diff --git a/pool/shard010/JavaScript/0066710_welcome.js b/pool/shard010/JavaScript/0066710_welcome.js new file mode 100644 index 0000000000000000000000000000000000000000..57f03e7308ac210242bfffb807a42a199cda6fd6 --- /dev/null +++ b/pool/shard010/JavaScript/0066710_welcome.js @@ -0,0 +1,16 @@ +angular.module('openspecimen') + .controller('WelcomeCtrl', function ($scope, $sce, $state, videoSettings) { + function init() { + if (videoSettings.welcome_video_source !== 'vimeo' && + videoSettings.welcome_video_source !== 'youtube') { + $state.go('sign-up'); + return; + } + + $scope.videoSettings = videoSettings; + $scope.iframeUrl = $sce.trustAsResourceUrl(videoSettings.welcome_video_url); + } + + + init(); + }); diff --git a/pool/shard010/JavaScript/0066711_case-converter.js b/pool/shard010/JavaScript/0066711_case-converter.js new file mode 100644 index 0000000000000000000000000000000000000000..284298b2fc6cf0e134b858438f91da81016cec83 --- /dev/null +++ b/pool/shard010/JavaScript/0066711_case-converter.js @@ -0,0 +1,48 @@ +'use strict'; + +/** + * Case Converter Plugin + * + * Handles the conversion between the database's snake_cased and a model's camelCased properties automatically. You just + * need to load it somewhere in your code. + * + * @example + * var bookshelf = Bookshelf(knex); + * bookshelf.plugin('case-converter'); + * + * @module plugins/case-converter + */ +module.exports = function caseConverter(bookshelf) { + var _ = require('lodash'); + + /** + * Monkey-patched Model class. + * @class Model + */ + bookshelf.Model = bookshelf.Model.extend({ + + /** + * @method + * @description Converts attribute keys to camel case when fetching data from the database. + * @override + */ + parse: function parse(attrs) { + return _.mapKeys(attrs, function (value, key) { + return _.camelCase(key); + }); + }, + + /** + * @method + * @description + * Converts attribute keys to snake case just before saving a model to the database. The converted attributes + * will not be set on the model. + * @override + */ + format: function format(attrs) { + return _.mapKeys(attrs, function (value, key) { + return _.snakeCase(key); + }); + } + }); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066714_bw.mainview.js b/pool/shard010/JavaScript/0066714_bw.mainview.js new file mode 100644 index 0000000000000000000000000000000000000000..745e7a6aab487c96b69bb8b804fb6cc10ea52f9c --- /dev/null +++ b/pool/shard010/JavaScript/0066714_bw.mainview.js @@ -0,0 +1,15 @@ +function MainView() { + +} + +MainView.prototype.appendResult = function(result){ + $('#distance').html(result); + $('#result').fadeIn('slow'); +} + +MainView.prototype.appendNewName = function(name){ + + $('#friendName').html(name); + $('#friend').fadeIn('slow'); + +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066718_functions.js b/pool/shard010/JavaScript/0066718_functions.js new file mode 100644 index 0000000000000000000000000000000000000000..7ebc8781e6defee74f1bbe43214385d4618ca3d9 --- /dev/null +++ b/pool/shard010/JavaScript/0066718_functions.js @@ -0,0 +1,66 @@ +var usuariop=""; + +var actual=0; + +$(".ima").bind('touchstart', function(){ + siguiente(); +}); +function checkConnection() { + var networkState = navigator.network.connection.type; + if (networkState == 'none'){ + alert('Disculpe, para utilizar esta aplicaci\u00F3n requiere una conexi\u00F3n activa'); + navigator.app.exitApp(); + } +} + +var callBackAjax = function (jqXHR, ajaxOptions, thrownError){ + if (jqXHR.status === 0) { + console.log('Not connect.\n Verify Network.'); + } else if (jqXHR.status == 404) { + console.log('Requested page not found. [404]'); + } else if (jqXHR.status == 500) { + console.log('Internal Server Error [500].'); + } else if (ajaxOptions === 'parsererror') { + console.log('Requested JSON parse failed.'); + } else if (ajaxOptions === 'timeout') { + console.log('Time out error.'); + } else if (ajaxOptions === 'abort') { + console.log('Ajax request aborted.'); + } else if (jqXHR.status == 401) { + $.mobile.hidePageLoadingMsg(); + alert('Su sesión ha expirado'); + $('#identification').val(''); + $.mobile.changePage('#login'); + } else { + console.log('Uncaught Error.\n' + jqXHR.responseText); + } + + $.mobile.hidePageLoadingMsg(); + console.log('un servicio no esta respondiendo!'); + alert('Disculpe, en estos momentos el servicio no se encuentra disponible.'); + //$('#identification').val(''); + //$.mobile.changePage('#login'); +} + +// manejo de la tecla atrás de android <- +function onBackKeyDown() { + if($.mobile.activePage.is('#login')){ + navigator.app.exitApp(); + } + if($.mobile.activePage.is('#dashboard')){ + var answer = confirm("Realmente desea salir?") + if (answer){ + navigator.app.exitApp(); + } + } + else { + navigator.app.backHistory() + } +} + +function closeApp(){ + var answer = confirm("Realmente desea salir?") + if (answer){ + navigator.app.exitApp(); + } +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066721_webpack.config.js b/pool/shard010/JavaScript/0066721_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..311e8ea3c743787f66d79df413a8d316c3c31c55 --- /dev/null +++ b/pool/shard010/JavaScript/0066721_webpack.config.js @@ -0,0 +1,39 @@ +const path = require('path'); + +const TsGraphQLPlugin = require('../../webpack'); + +const tsgqlPlugin = new TsGraphQLPlugin({ tsconfigPath: __dirname }); + +module.exports = { + resolve: { + extensions: ['.ts', '.js'], + }, + entry: { + main: path.resolve(__dirname, "query.ts"), + }, + output: { + path: path.resolve(__dirname, "dist"), + filename: "[name].js", + }, + module: { + rules: [ + { + test: /\.ts$/, + exclude: /node_modules/, + loader: 'ts-loader', + options: { + transpileOnly: true, + getCustomTransformers: () => ({ + before: [ + tsgqlPlugin.getTransformer(), + ], + }), + }, + } + ], + }, + plugins: [ + tsgqlPlugin, + ], + devtool: false, +}; diff --git a/pool/shard010/JavaScript/0066726_MatchStore.js b/pool/shard010/JavaScript/0066726_MatchStore.js new file mode 100644 index 0000000000000000000000000000000000000000..3b42e4bb2d114d88b778f290e706e7632a10e41c --- /dev/null +++ b/pool/shard010/JavaScript/0066726_MatchStore.js @@ -0,0 +1,61 @@ +var MovieConstants = require('../constants/MovieConstants'); +var AppDispatcher = require('../dispatcher/AppDispatcher'); +var NameMatcher = require('../matchers/EpisodeNameMatcher'); +var NumberMatcher = require('../matchers/EpisodeNumberMatcher'); +var FileStore = require('./FileStore'); +var MovieStore = require('./MovieStore'); +var StoreMixin = require('./StoreMixin'); +var assign = require('object-assign'); + +var _matches = {}; + +function resetFiles() { + var files = FileStore.getFiles(); + console.log(files); + _matches = files.reduce(function(o, file) { + o[file.id] = null; + return o; + }, {}); +}; + +function seasonSelect(season) { + var files = FileStore.getFiles(), + episodes = MovieStore.getEpisodesForSeason(season) + ; + _matches = assign( + {}, + NameMatcher.match(files, episodes), + NumberMatcher.match(files, episodes) + ); +} + + +/** + * The MatchStore stores the filename => episode id assignments. + * It tries automatic matching whenever a season is selected + */ +var MatchStore = assign({}, StoreMixin, { + getMatches: function() { + return _matches; + } + +}); + +FileStore.addChangeListener(resetFiles); + +MatchStore.dispatchToken = AppDispatcher.register(function(payload) { + var action = payload.action; + switch (action.actionType) { + case MovieConstants.MOVIE_SELECT_SEASON: + seasonSelect(action.season); + break; + default: + return true; + } + MatchStore.emitChange(); + return true; +}); + + +module.exports = MatchStore; + diff --git a/pool/shard010/JavaScript/0066727_Enquiry.js b/pool/shard010/JavaScript/0066727_Enquiry.js new file mode 100644 index 0000000000000000000000000000000000000000..40e82c753d3421ea1337521d229f0c6e84ade27c --- /dev/null +++ b/pool/shard010/JavaScript/0066727_Enquiry.js @@ -0,0 +1,63 @@ +var keystone = require('keystone'); +var Types = keystone.Field.Types; + +/** + * Enquiry Model + * ============= + */ + +var Enquiry = new keystone.List('Enquiry', { + nocreate: true, + noedit: true, +}); + +Enquiry.add({ + name: { type: Types.Name, required: true }, + email: { type: Types.Email, required: true }, + phone: { type: String }, + enquiryType: { type: Types.Select, options: [ + { value: 'message', label: 'Just leaving a message' }, + { value: 'question', label: 'I\'ve got a question' }, + { value: 'other', label: 'Something else...' }, + ] }, + message: { type: Types.Markdown, required: true }, + createdAt: { type: Date, default: Date.now }, +}); + +Enquiry.schema.pre('save', function (next) { + this.wasNew = this.isNew; + next(); +}); + +Enquiry.schema.post('save', function () { + if (this.wasNew) { + this.sendNotificationEmail(); + } +}); + +Enquiry.schema.methods.sendNotificationEmail = function (callback) { + if (typeof callback !== 'function') { + callback = function () {}; + } + var enquiry = this; + keystone.list('User').model.find().where('isAdmin', true).exec(function (err, admins) { + if (err) return callback(err); + new keystone.Email({ + templateExt: 'hbs', + templateEngine: require('express-handlebars'), + templateName: 'enquiry-notification', + }).send({ + to: admins, + from: { + name: 'Developer Cat', + email: 'contact@developer-cat.com', + }, + subject: 'New Enquiry for Developer Cat', + enquiry: enquiry, + }, callback); + }); +}; + +Enquiry.defaultSort = '-createdAt'; +Enquiry.defaultColumns = 'name, email, enquiryType, createdAt'; +Enquiry.register(); diff --git a/pool/shard010/JavaScript/0066730_pentagons.js b/pool/shard010/JavaScript/0066730_pentagons.js new file mode 100644 index 0000000000000000000000000000000000000000..9cd019b99d45ce1df4618411de6762c688290039 --- /dev/null +++ b/pool/shard010/JavaScript/0066730_pentagons.js @@ -0,0 +1,86 @@ +var PENTAGON_COUNT = 18; + +function Pentagon() { + var start = new PentagonInfo({ + radius: randomRadius(), + opacity: randomOpacity(), + x: Math.random(), + y: Math.random(), + rotation: Math.random() * Math.PI * 2 + }); + this._currentAnimation = new Animation(start, start, 1); + this._lastFrame = start; +} + +Pentagon.MAX_RADIUS = 0.2; + +Pentagon.allPentagons = []; + +Pentagon.prototype.frame = function() { + var frame = this._currentAnimation.frame().clampedAngle(); + this._lastFrame = frame; + if (this._currentAnimation.isDone()) { + this._generateNewAnimation(); + } + return frame; +}; + +Pentagon.prototype._generateNewAnimation = function(animation) { + var info = new PentagonInfo({ + x: this._gravityCoord('x'), + y: this._gravityCoord('y'), + radius: randomRadius(), + opacity: randomOpacity(), + rotation: Math.PI*(Math.random()-0.5) + this._lastFrame.rotation + }); + this._currentAnimation = new Animation(this._lastFrame, info, + randomDuration()); +}; + +Pentagon.prototype._gravityCoord = function(axis) { + var axisCoord = this._lastFrame[axis]; + + // Apply inverse-square forces from edges. + var force = 1/Math.pow(axisCoord+0.01, 2) - 1/Math.pow(1.01-axisCoord, 2); + + // Apply inverse-square forces from other pentagons. + for (var i = 0, len = Pentagon.allPentagons.length; i < len; ++i) { + var pentagon = Pentagon.allPentagons[i]; + if (pentagon === this) { + continue; + } + var d2 = PentagonInfo.distanceSquared(this._lastFrame, pentagon._lastFrame); + if (Math.abs(d2) < 0.00001) { + return Math.random(); + } + var forceMag = 1 / d2; + var distance = Math.sqrt(d2); + force -= forceMag * (pentagon._lastFrame[axis] - axisCoord) / distance; + } + + // Add a random component to the force. + force += (Math.random() - 0.5) * 20; + + // Cap the force at +/- 0.2 and add it to the current coordinate. + force = Math.max(Math.min(force, 100), -100) / 500; + + return Math.max(Math.min(axisCoord+force, 1), 0); +}; + +function generatePentagons() { + for (var i = 0; i < PENTAGON_COUNT; ++i) { + Pentagon.allPentagons.push(new Pentagon()); + } +} + +function randomDuration() { + return 30000 + 30000*Math.random(); +} + +function randomOpacity() { + return Math.random()*0.22 + 0.02; +} + +function randomRadius() { + return 0.05 + (Math.pow(Math.random(), 15)+1)*0.075; +} diff --git a/pool/shard010/JavaScript/0066733_container.js b/pool/shard010/JavaScript/0066733_container.js new file mode 100644 index 0000000000000000000000000000000000000000..a667e97df8c1aa043fee57fa191f6a7145006d84 --- /dev/null +++ b/pool/shard010/JavaScript/0066733_container.js @@ -0,0 +1,103 @@ +(function() { + var Container; + + Container = (function() { + + Container.prototype.params = {}; + + Container.prototype.components = {}; + + Container.prototype.instances = {}; + + Container.prototype.currents = {}; + + function Container(params) { + if (params == null) params = {}; + this.params = params; + } + + Container.prototype.bind = function(name, properties) { + return this.components[name] = properties; + }; + + Container.prototype.load = require; + + Container.prototype.has = function(name) { + return this.components[name]; + }; + + Container.prototype.clone = function(obj) { + var clone, i; + if (obj === null || typeof obj !== 'object') return obj; + clone = {}; + for (i in obj) { + clone[i] = typeof obj[i] === "object" ? this.clone(obj[i]) : obj[i]; + } + return clone; + }; + + Container.prototype.get = function(name) { + var k, obj, properties, v; + if (this.instances[name]) return this.instances[name]; + if (name === "this-container") return this; + if (name === "clone-container") return this.clone(this); + if (!this.components[name]) { + throw new Error("Component '" + name + "' does not exist in container."); + } + if (this.currents[name]) { + throw new Error("Get component failed, recursive call: " + name); + } + this.currents[name] = true; + properties = this.components[name] ? this.components[name] : {}; + obj = this.load(name); + for (k in properties) { + v = properties[k]; + if (typeof obj.prototype[k] === "undefined") { + throw new Error("Undefined property: " + name + "." + k); + } + obj.prototype[k] = this.inject(v, name); + } + this.currents[name] = false; + this.instances[name] = new obj(); + return this.instances[name]; + }; + + Container.prototype.inject = function(propertyValue, component) { + var k, v, value, _len; + if (typeof propertyValue === 'object') { + value = {}; + for (v = 0, _len = propertyValue.length; v < _len; v++) { + k = propertyValue[v]; + value[k] = this.inject(v, component); + } + } else if (propertyValue.slice(0, 1) === "%" && propertyValue.slice(-1) === "%") { + value = this.getParam(propertyValue); + } else { + value = this.get(propertyValue); + } + return value; + }; + + Container.prototype.setParam = function(k, v) { + return this.params[k] = v; + }; + + Container.prototype.getParam = function(accessor) { + var current, i, k, key, parts, _ref; + key = accessor.slice(1, accessor.length - 1); + parts = key.split("."); + current = this.params; + for (i = 0, _ref = parts.length; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) { + k = parts[i]; + current = current[k]; + } + return current; + }; + + return Container; + + })(); + + if (typeof module !== "undefined" && module !== null) module.exports = Container; + +}).call(this); diff --git a/pool/shard010/JavaScript/0066736_content_type.js b/pool/shard010/JavaScript/0066736_content_type.js new file mode 100644 index 0000000000000000000000000000000000000000..3d909727bdfe02eaf8fd23291d73b4da62bc8bb0 --- /dev/null +++ b/pool/shard010/JavaScript/0066736_content_type.js @@ -0,0 +1,33 @@ +/** + * Created by DWIsprananda on 11/11/2016. + */ + +django.jQuery(function () { + $('.add-row').find('a')[0].click(); + $('.add-row').find('a')[0].click(); + $('.add-row').find('a')[0].click(); + + $('#id_model').bind('keyup', function(){ + var val = $(this).val(); + + $('input[name*=codename]').each(function(idx, el) { + var name = $(el).parents('tr').find('input[name*=name]'); + + if (idx == 0) { + name.val('Can add ' + val); + $(el).val('add_' + val); + } else if (idx == 1) { + name.val('Can change ' + val); + $(el).val('change_' + val); + } else if (idx == 2) { + name.val('Can delete ' + val); + $(el).val('delete_' + val); + } else { + name.val('Can ? ' + val); + $(el).val('?_' + val); + } + + }); + + }); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066737_includes.js b/pool/shard010/JavaScript/0066737_includes.js new file mode 100644 index 0000000000000000000000000000000000000000..235db531499c9de4972b33205ac8e1260fc8fa95 --- /dev/null +++ b/pool/shard010/JavaScript/0066737_includes.js @@ -0,0 +1,23 @@ +var scripts = [ + "src/jsture.js" +, "src/Element.js" +, "src/Pattern.js" +, "src/Watcher.js" +, "src/Display.js" +]; + +function addScript(url) { + document.writeln( "" ); +} + +function loadScripts(prefix) { + for( var i=0; i + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var transferFlags = require('./transferFlags'); + +/*! + * Module variables + */ + +// Check whether `__proto__` is supported +var hasProtoSupport = '__proto__' in Object; + +// Without `__proto__` support, this module will need to add properties to a function. +// However, some Function.prototype methods cannot be overwritten, +// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69). +var excludeNames = /^(?:length|name|arguments|caller)$/; + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### addChainableMethod (ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @name addChainableMethod + * @api public + */ + +module.exports = function (ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') + chainingBehavior = function () { }; + + Object.defineProperty(ctx, name, + { get: function () { + chainingBehavior.call(this); + + var assert = function () { + var result = method.apply(this, arguments); + return result === undefined ? this : result; + }; + + // Use `__proto__` if available + if (hasProtoSupport) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = assert.__proto__ = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (!excludeNames.test(asserterName)) { + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(assert, asserterName, pd); + } + }); + } + + transferFlags(this, assert); + return assert; + } + , configurable: true + }); +}; diff --git a/pool/shard010/JavaScript/0066739_boole-web.directive.js b/pool/shard010/JavaScript/0066739_boole-web.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..bcb3423baabe3056b2f48b1273fa4a49938a7852 --- /dev/null +++ b/pool/shard010/JavaScript/0066739_boole-web.directive.js @@ -0,0 +1,36 @@ +angular + .module("hwboard") + .directive("wlBooleWeb", wlBooleWeb); + + +function wlBooleWeb() { + + return { + restrict: "E", + templateUrl: "main/boole-web/boole-web.directive.html", + controller: "BooleWebController", + controllerAs: "booleWebController", + link: wlBooleWebLink, + scope: { + + } + }; // !return + + + function wlBooleWebLink(scope, elem, attrs) { + var iframeElement = elem.find("iframe"); + + scope.getIframeElement = getIframeElement; + + + // ------------------ + // Implementations + // ------------------ + + function getIframeElement() { + return $(iframeElement); + } // !getIframeElement + + } // !wlBooleWebLink + +} // !wlBooleWeb diff --git a/pool/shard010/JavaScript/0066740_board.js b/pool/shard010/JavaScript/0066740_board.js new file mode 100644 index 0000000000000000000000000000000000000000..caea960fa30ef23a04d1246e0828806557005138 --- /dev/null +++ b/pool/shard010/JavaScript/0066740_board.js @@ -0,0 +1,47 @@ +const + _ = require('lodash'), + assert = require('assert'), + mixins = require('./mixins'), + moment = require('moment'), + polyclay = require('polyclay'), + P = require('p-promise'), + utilities = require('../utilities'), + Comment = require('./comment') + ; + +var Board = module.exports = polyclay.Model.buildClass({ + properties: { + id: 'string', + owner: 'string', + title: 'string', + moderators: 'array', + }, + enumerables: { + status: [ 'paid', 'unpaid', 'hidden' ] + }, + index: [ 'id', 'owner' ], + required: [ 'id', 'owner', 'title' ], + singular: 'board', + plural: 'boards', +}); +polyclay.mixin(Board, mixins.HasContent); +polyclay.mixin(Board, mixins.HasTimestamps); +polyclay.persist(Board, 'id'); + +Board.create = function(opts) +{ + assert(opts && _.isObject(opts), 'opts must be an object'); + + var board = new Board(); + board.update(opts); + board.id = Board.generateID(); + board.created = Date.now(); + board.modified = board.created; + board.status = 'unpaid'; + + return board.save() + .then(function() + { + return board; + }); +}; diff --git a/pool/shard010/JavaScript/0066742_taskProjectMembers.js b/pool/shard010/JavaScript/0066742_taskProjectMembers.js new file mode 100644 index 0000000000000000000000000000000000000000..a7501b670215b39e0e7c08d58e4a610188dd52ef --- /dev/null +++ b/pool/shard010/JavaScript/0066742_taskProjectMembers.js @@ -0,0 +1,215 @@ +define([ + '../moduleDef', + 'angular', + 'text!./taskProjectMembers.tpl.html', + 'css!./taskProjectMembers.css' +], function (module, angular, tpl) { + module.directive('taskProjectMembers', + ['apinetService', '$stateParams', '$window', 'i18n', '$timeout', + function(apinetService, $stateParams, $window, i18n, $timeout) { + return { + restrict: 'EA', + replace: true, + template: tpl, + scope: { + onError: '&' + }, + controller: ['$scope', '$rootScope', function($scope, $rootScope) { + $scope.i18n = $rootScope.i18n; + }], + link: function(scope, elm, attrs) { + scope.collapsed = true; + + scope.onSearchClick = function(e) { + e.stopPropagation(); + }; + + var unwatch = scope.$watch('collapsed', function(newVal, oldVal) { + if (newVal !== oldVal) { + if (!scope.collapsed) { + scope.load(); + unwatch(); + } + } + }); + + //filter and paging for list + var page = 0; + //needed for counter directive + scope.requestParams = { + term: null + }; + + scope.searchTimeout = null; + scope.$watch('requestParams.term', function() { + if (scope.searchTimeout) { + $timeout.cancel(scope.searchTimeout); + scope.timeout = null; + } + + scope.searchTimeout = $timeout(function() { + scope.searchTimeout = null; + scope.load(true); + }, 600); + }); + + //new member form data + scope.editables = { + newMember: null, + isAdmin: false, + isManager: false, + isExecutor: false, + + roles: function() { + var roles = []; + if (this.isAdmin) roles.push('Administrator'); + if (this.isManager) roles.push('Manager'); + if (this.isExecutor) roles.push('Executor'); + return roles; + }, + + clear: function() { + this.newMember = null; + this.isAdmin = false; + this.isManager = false; + this.isExecutor = false; + }, + + filled: function() { + return this.newMember != null && + (this.isAdmin || this.isManager || this.isExecutor); + } + }; + + scope.isMembersEditable = function() { + return true;//TODO implement + }; + + scope.handleError = function(error) { + if (angular.isFunction(scope.onError)) { + scope.onError({error: error}); + } else { + throw error; + } + }; + + var mergeOrPush = function(source) { + scope.models = scope.models || []; + for(var srcIndex = 0; srcIndex < source.length; srcIndex++) { + //find target for merge + var merged = false; + for(var mIndex = 0; mIndex < scope.models.length; mIndex++) { + if (scope.models[mIndex].Id == source[srcIndex].Id) { + angular.extend(scope.models[mIndex], source[srcIndex]); + merged = true; + break; + } + } + if (!merged) { + scope.models.push(source[srcIndex]); + } + } + }; + + scope.load = function(replace) { + apinetService.action({ + method: 'tasks/project/getMembers', + project: $stateParams.project, + term: scope.requestParams.term, + page: page + }).then(function(response) { + if (!!replace) { + scope.models = response; + page = 0; + } else { + mergeOrPush(response); + if (response.length <= 0) { + page--; + } + } + }, scope.handleError); + }; + + scope.add = function() { + apinetService.action({ + method: 'tasks/project/addMember', + project: $stateParams.project, + userId: scope.editables.newMember.id, + roles: scope.editables.roles() + }).then(function(response) { + scope.models.unshift(response); + scope.editables.clear(); + }, scope.handleError); + }; + + scope.remove = function(member) { + if (!member) { + return; + } + + if (!$window.confirm(i18n.msg('core.confirm.delete.record'))) { + return; + } + + apinetService.action({ + method: 'tasks/project/removeMember', + project: $stateParams.project, + memberId: member.Id + }).then(function(response) { + var index = scope.models.indexOf(member); + if (index >= 0) { + scope.models.splice(index, 1); + } + }, scope.handleError); + }; + + scope.changeRoles = function(member, roles) { + if (!member || !roles || roles.length <= 0) { + return false;//cancel changes + } + + apinetService.action({ + method: 'tasks/project/changeMemberRoles', + project: $stateParams.project, + memberId: member.Id, + roles: roles.map(function(item){ return item.id }) + }).then(function(response) { + if (response.validation.success) { + angular.extend(member, response.model); + member.validation = {}; + } else { + member.validation = response.validation; + } + return response.validation.success; + }, scope.handleError); + }; + + scope.changeCurrentRole = function(member, role) { + if (!member || !role) { + return false;//cancel changes + } + + apinetService.action({ + method: 'tasks/project/changeMemberCurrentRole', + project: $stateParams.project, + memberId: member.Id, + current: role.id + }).then(function(response) { + if (response.validation.success) { + angular.extend(member, response.model); + member.validation = {}; + } else { + member.validation = response.validation; + } + return response.validation.success; + }, scope.handleError); + }; + + scope.nextPage = function() { + page++; + scope.load(false); + }; + } + }; + }]); +}); diff --git a/pool/shard010/JavaScript/0066747_dominia.test.js b/pool/shard010/JavaScript/0066747_dominia.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20f72d1ca8b08db1fb634184130c3aa765509cd2 --- /dev/null +++ b/pool/shard010/JavaScript/0066747_dominia.test.js @@ -0,0 +1,81 @@ +const expect = require('chai').expect; +const path = require('path'); +const rootDir = path.join(__dirname, '..', '..'); +const libDir = path.join(rootDir, 'lib'); +const Dominia = require(path.join(libDir, 'dominia')); +let dominia; + +describe('Dominia', () => { + before(() => { + dominia = new Dominia(); + }); + + it('can generate', () => { + const domain = dominia.generate(); + + expect(domain).to.be.an('object'); + expect(domain.scale).to.be.a('string'); + expect(domain.size).to.be.a('string'); + expect(domain.name).to.be.a('string'); + expect(domain.terrain).to.be.a('string'); + expect(domain.population).to.be.an('object'); + expect(domain.demographics).to.be.an('object'); + expect(domain.resources).to.be.an('array'); + }); + + it('can generate a hamlet', () => { + const hamlet = dominia.generate({ size: 'hamlet' }); + + expect(hamlet).to.be.an('object'); + expect(hamlet.size).to.eq('hamlet'); + }); + + it('can generate a village', () => { + const village = dominia.generate({ size: 'village' }); + + expect(village).to.be.an('object'); + expect(village.size).to.eq('village'); + }); + + it('can generate a town', () => { + const town = dominia.generate({ size: 'town' }); + + expect(town).to.be.an('object'); + expect(town.size).to.eq('town'); + }); + + it('can generate a city', () => { + const city = dominia.generate({ size: 'city' }); + + expect(city).to.be.an('object'); + expect(city.size).to.eq('city'); + }); + + it('can generate a capital', () => { + const capital = dominia.generate({ size: 'capital' }); + + expect(capital).to.be.an('object'); + expect(capital.size).to.eq('capital'); + }); + + it('can generate a county', () => { + const county = dominia.generate({ size: 'county' }); + + expect(county).to.be.an('object'); + expect(county.size).to.eq('county'); + }); + + it('can generate a duchy', () => { + const duchy = dominia.generate({ size: 'duchy' }); + + expect(duchy).to.be.an('object'); + expect(duchy.size).to.eq('duchy'); + }); + + it('can generate a kingdom', () => { + const kingdom = dominia.generate({ size: 'kingdom' }); + + expect(kingdom).to.be.an('object'); + expect(kingdom.size).to.eq('kingdom'); + }); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066748_testFifoBehavior.js b/pool/shard010/JavaScript/0066748_testFifoBehavior.js new file mode 100644 index 0000000000000000000000000000000000000000..95bdc0fcd4d618b9e8b706e8625cb5aeef76f29d --- /dev/null +++ b/pool/shard010/JavaScript/0066748_testFifoBehavior.js @@ -0,0 +1,40 @@ +import fillCacheWith from './fillCacheWith'; + +function testFifoBehavior(CacheObject) { + describe('FIFO cache behavior', () => { + it('limits cache queue by removing the first added items', () => { + const cache = new CacheObject({cacheSize: 5}); + const entries = [1, 2, 3, 4]; + const newEntries = [5, 6, 7]; + + fillCacheWith(cache, entries); + fillCacheWith(cache, newEntries); + + expect(cache.get(1)).toBe(undefined); + expect(cache.get(2)).toBe(undefined); + [4, 5, 6, 7].forEach(entry => { + expect(cache.get(entry)).toBe(entry); + }); + }); + + it('mantains cache updated after removing extraneous entry', () => { + const cache = new CacheObject({cacheSize: 5}); + const entries = [1, 2, 3, 4, 5]; + fillCacheWith(cache, entries); + + cache.remove(7); // Extraneous + cache.remove(3); + cache.set(6, 6); + cache.set(7, 7); + + expect(cache.get(1)).toBe(undefined); + expect(cache.get(3)).toBe(undefined); + + [2, 4, 5, 6, 7].forEach(entry => { + expect(cache.get(entry)).toBe(entry); + }); + }); + }); +} + +export default testFifoBehavior; diff --git a/pool/shard010/JavaScript/0066751_GridWindow.js b/pool/shard010/JavaScript/0066751_GridWindow.js new file mode 100644 index 0000000000000000000000000000000000000000..eebd2da9383f753b3ccbb0530b775ea547d28f65 --- /dev/null +++ b/pool/shard010/JavaScript/0066751_GridWindow.js @@ -0,0 +1,52 @@ +mini.ux.GridWindow = function () { + mini.ux.GridWindow.superclass.constructor.call(this); + this.initControls(); +} +mini.extend(mini.ux.GridWindow, mini.ux.Window, { + title: "Grid Window", + showToolbar: true, + bodyStyle: "padding:0", + + width: 550, + height: 300, + minWidth: 450, + minHeight: 200, + + dataUrl: "../data/AjaxService.aspx?method=SearchEmployees", + + initControls: function () { + var toolbarEl = this.getToolbarEl(); + var footerEl = this.getFooterEl(); + var bodyEl = this.getBodyEl(); + + //toolbar + var topHtml = + '
' + + '增加 ' + + '修改 ' + + '删除 ' + + '
'; + jQuery(toolbarEl).append(topHtml); + + mini.parse(this.el); + + //body + this.grid = new mini.DataGrid(); + this.grid.set({ + multiSelect: this.multiSelect, + style: "width: 100%;height: 100%;", + borderStyle: "border:0", + columns: [ + { type: "checkcolumn", header: "#" }, + //{ type: "indexcolumn", header: "#", headerAlign: "center" }, + {header: "帐号", field: "loginname" }, + { header: "姓名", field: "name" } + ] + }); + this.grid.setUrl(this.dataUrl); + this.grid.render(bodyEl); + + this.grid.load(); + } +}); +mini.regClass(mini.ux.GridWindow, "ux.gridwindow"); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066753_divider.spec.js b/pool/shard010/JavaScript/0066753_divider.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b059de00f83c91709c154b63e3d4a0486f448d8c --- /dev/null +++ b/pool/shard010/JavaScript/0066753_divider.spec.js @@ -0,0 +1,25 @@ +describe('Semantic-UI: Elements - smDivider', function() { + 'use strict'; + + var $scope, $compile; + + beforeEach(module('semantic.ui.elements.divider')); + + beforeEach(inject(function($rootScope, _$compile_) { + $scope = $rootScope.$new(); + $compile = _$compile_; + })); + + it('has to be able to be defined as vertical', function() { + var smDivider = $compile('')($scope); + + expect(smDivider.hasClass('vertical')).toBe(true); + }); + + it('has to be able to be defined as horizontal', function() { + var smDivider = $compile('')($scope); + + expect(smDivider.hasClass('horizontal')).toBe(true); + }); + +}); diff --git a/pool/shard010/JavaScript/0066756_AuctionContainer.js b/pool/shard010/JavaScript/0066756_AuctionContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..d0ebe2f53ef8664263f7237f3d0021f99a392718 --- /dev/null +++ b/pool/shard010/JavaScript/0066756_AuctionContainer.js @@ -0,0 +1,44 @@ +import { ReactiveVar } from 'meteor/reactive-var'; +import { createContainer } from 'meteor/react-meteor-data'; +import AuctionPage from './AuctionPage'; +import Contracts from '/imports/api/contract/collection'; + +const AuctionContainer = createContainer((params) => { + const { + web3, + networkId, + account, + connected, + match, + location + } = params; + + const auctionAddress = match.params.address; + const tokenAddress = location.search.substring(location.search.indexOf('=') + 1); + + const contractsHandle = Meteor.subscribe('auctions', networkId, 15); + const tokenHandle = Meteor.subscribe('contract', tokenAddress); + + let contracts = Contracts.find({ linkedContracts: {$exists: 1} }, {sort: {createdAt: -1}}).fetch(); + let auction = contracts.filter(c => c.address == auctionAddress)[0]; + let token = Contracts.findOne({ address: tokenAddress}); + + if(auction) { + auction.abi = JSON.parse(auction.abi); + } + if(token) { + token.abi = JSON.parse(token.abi); + } + + return { + web3, + networkId, + connected, + account, + contracts, + auction, + token + }; +}, AuctionPage); + +export default AuctionContainer; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066763_list.js b/pool/shard010/JavaScript/0066763_list.js new file mode 100644 index 0000000000000000000000000000000000000000..d45b8a22637cac4f696aece7e94def9ae728d468 --- /dev/null +++ b/pool/shard010/JavaScript/0066763_list.js @@ -0,0 +1,145 @@ +//代码生成工具自动生成,请在此处填写 查询页面使用的js代码 + var dataGrid; + $(function() { + dataGrid = $('#dataGrid').datagrid({ + url : '/businessGoodsGroup/gridData', + fit : true, + striped : true, + rownumbers : true, + pagination : true, + singleSelect : true, + idField : 'id', + pageSize : 50, + pageList : [ 10, 20, 30, 40, 50, 100, 200, 300, 400, 500 ], + columns : [ [ + { + width : '80', + title : '主键', + field : 'id', + }, + { + width : '80', + title : '商品主键', + field : 'goodsId', + }, + { + width : '80', + title : '拼团数量', + field : 'num', + }, + { + width : '80', + title : '拼团价', + field : 'groupPrice', + }, + { + width : '80', + title : '拼团开始时间', + field : 'startTime', + }, + { + width : '80', + title : '拼团结束时间', + field : 'endTime', + }, + { + field : 'action', + title : '操作', + width : 140, + align : 'center', + formatter : function(value, row, index) { + var str = ''; + str += $.formatString('编辑', row.id); + str += ' | '; + str += $.formatString('删除', row.id); + return str; + } + }] ], + toolbar : [{ + iconCls: 'icon-add', + text:'新增', + handler: function(){addFun();} + }], + onLoadSuccess : function(data){ + $('.btn_edit').linkbutton({text:'编辑',plain:true,iconCls:'icon-edit'}); + $('.btn_delete').linkbutton({text:'删除',plain:true,iconCls:'icon-del'}); + $(this).datagrid('fixRowHeight'); + } + }); + }); + + function addFun() { + parent.$.modalDialog({ + title : '添加', + width : 500, + height : 300, + href : '/businessGoodsGroup/add', + buttons : [ { + text : '添加', + handler : function() { + parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后,需要刷新这个dataGrid,所以先预定义好 + var f = parent.$.modalDialog.handler.find('#modelForm'); + f.submit(); + } + } ] + }); + } + + function deleteFun(id) { + if (id == undefined) {//点击右键菜单才会触发这个 + var rows = dataGrid.datagrid('getSelections'); + id = rows[0].id; + } else {//点击操作里面的删除图标会触发这个 + dataGrid.datagrid('unselectAll').datagrid('uncheckAll'); + } + parent.$.messager.confirm('询问', '您是否要删除商品拼团管理?', function(b) { + if (b) { + progressLoad(); + $.post('/businessGoodsGroup/delete', { + id : id + }, function(result) { + if (result.success) { + parent.$.messager.alert('提示', result.msg, 'info'); + dataGrid.datagrid('reload'); + } + progressClose(); + }, 'JSON'); + } + }); + } + + function editFun(id) { + if (id == undefined) { + var rows = dataGrid.datagrid('getSelections'); + id = rows[0].id; + } else { + dataGrid.datagrid('unselectAll').datagrid('uncheckAll'); + } + parent.$.modalDialog({ + title : '编辑', + width : 500, + height : 300, + href : '/businessGoodsGroup/edit?id=' + id, + buttons : [ { + text : '编辑', + handler : function() { + parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后,需要刷新这个dataGrid,所以先预定义好 + var f = parent.$.modalDialog.handler.find('#modelForm'); + f.submit(); + } + } + ] + }); + } + + function searchFun() { + ////将searchForm表单内的元素序列为对象传递到后台 + dataGrid.datagrid('load', $.serializeObject($('#searchForm'))); + } + function cleanFun() { + //找到form表单下的所有input标签并清空 + $('#searchForm input').val(''); + //重新加载数据,无填写数据,向后台传递值则为空 + dataGrid.datagrid('load', {}); + } + \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066765_phema-user.js b/pool/shard010/JavaScript/0066765_phema-user.js new file mode 100644 index 0000000000000000000000000000000000000000..8ac23512bc5c9588b5712eda36168ebafd9559bb --- /dev/null +++ b/pool/shard010/JavaScript/0066765_phema-user.js @@ -0,0 +1,246 @@ +'use strict'; +var mongoose = require('mongoose'); +var bcrypt = require('bcrypt'); + +var MONGO_CONNECTION = process.env.PHEMA_USER_DB_URL; +const SALT_ROUNDS = 10; + +var Schema = mongoose.Schema; + +function emailValidator (email) { + if (!email || typeof email === 'undefined') { + return false; + } + + // Regex from: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript/1373724#1373724 + var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i; + return re.test(email); +} + +function passwordValidator(password) { + if (!password || typeof password === 'undefined') { + return false; + } + + return (password.length >= 6); +} + +var UserSchema = new Schema({ + email: { + type: String, + require: true, + unique: true, + validate: [emailValidator, 'Please enter a valid e-mail address'] + }, + password: { + type: String, + require: true, + select: false, + validate: [passwordValidator, 'Please enter a password that is 6 characters or longer'] + }, + firstName: { + type: String + }, + lastName: { + type: String + }, + created: { + type: Date, + default: Date.now + }, + resetPasswordExpires: { + type: Date, + }, + resetPasswordToken: { + type: String + } +}); + +function formatUserForReturn(user) { + return { + id: user._id.toHexString(), + email: user.email, + firstName: user.firstName, + lastName: user.lastName + }; +} + +var UserModel = mongoose.model('User', UserSchema); + +// MongoDB configuration +mongoose.connect(MONGO_CONNECTION, function(err) { + if(err) { + console.log('error connecting to MongoDB Database. ' + err); + } else { + console.log('Connected to Database'); + } +}); + +var UserRepository = function() {} + +UserRepository.prototype.getUser = function(id, callback) { + return UserModel.findOne({_id: id }, function(err, user) { + if (!user) { + return callback({message: 'The specified user could not be found.'}); + } + + if (!err) { + return callback(null, formatUserForReturn(user)); + } + else { + console.log(err); + return callback({message: 'There was an error when searching for the user.'}); + } + }); +}; + +UserRepository.prototype.findUserByEmail = function(email, callback) { + return UserModel.findOne({email: email }, function(err, user) { + if (!user) { + return callback({message: 'The specified user could not be found.'}); + } + + if (!err) { + return callback(null, formatUserForReturn(user)); + } + else { + console.log(err); + return callback({message: 'There was an error when searching for the user.'}); + } + }); +}; + +UserRepository.prototype.findUserByPasswordResetToken = function(token, callback) { + return UserModel.findOne({ resetPasswordToken: token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { + if (!user) { + return callback({message: 'Password reset token is invalid or has expired.'}); + } + + if (!err) { + return callback(null, formatUserForReturn(user)); + } + else { + console.log(err); + return callback({message: 'There was an error when searching for the user to reset their password.'}); + } + }); +} + +UserRepository.prototype.addUser = function(user, callback) { + UserModel.findOne({email: user.email }, function(err, existingUser) { + if (existingUser) { + return callback({message: 'This e-mail address has already been used to create an account. Please try logging in with that account, and reset the password if you no longer remember it.'}); + } + + if (err) { + console.log(err); + return callback({message: 'There was an error when searching for the user.'}); + } + else { + var userRecord = new UserModel({ + email: user.email, + firstName: user.firstName, + lastName: user.lastName + }); + + bcrypt.genSalt(SALT_ROUNDS, function(err, salt) { + bcrypt.hash(user.password, salt, function(err, hash) { + userRecord.password = hash; + + userRecord.save(function(err) { + console.log("User saved ", userRecord.email); + if (err) { + console.log(err); + return callback({message: 'There was an error when saving the new user.'}); + } + else { + return callback(null, formatUserForReturn(userRecord)); + } + }); + }); + }); + } + }); +}; + +UserRepository.prototype.updateUser = function(updatedUser, callback) { + return UserModel.findOne({_id: updatedUser.id }, function(err, user) { + if (!user) { + return callback({message: 'The specified user could not be found.'}); + } + else if (err) { + console.log(err); + return callback({message: 'There was an error when searching for the user.'}); + } + + user.firstName = updatedUser.firstName; + user.lastName = updatedUser.lastName; + // Any time the user is updated, we want to clear out the reset password fields. + // If there is an outstanding reset password and someone is logged in and able + // to reset this, the outstanding token should no longer be valid. + user.resetPasswordToken = null; + user.resetPasswordExpires = null; + + if (updatedUser.resetPasswordToken) { + user.resetPasswordToken = updatedUser.resetPasswordToken; + user.resetPasswordExpires = updatedUser.resetPasswordExpires; + } + + if (updatedUser.password) { + bcrypt.genSalt(SALT_ROUNDS, function(err, salt) { + bcrypt.hash(updatedUser.password, salt, function(err, hash) { + user.password = hash; + + user.save(function(err) { + console.log("User with password updated : ", user.email); + if (err) { + console.log(err); + return callback({message: 'There was an error when saving the new user.'}); + } + else { + return callback(null, formatUserForReturn(user)); + } + }); + }); + }); + } + else { + return user.save(function(err) { + if(!err) { + console.log("Updated : " , user.email); + return callback(null, formatUserForReturn(user)); + } else { + console.log('Internal error(%d): %s',res.statusCode,err.message); + if (err.name === 'ValidationError') { + return callback({ error: 'Validation error' }); + } else { + return callback({ error: 'Server error' }); + } + } + }); + } + }); +}; + +UserRepository.prototype.authenticate = function(email, password, callback) { + UserModel.findOne({ email: email }).select('+password').exec(function(err, user) { + if (err) { + return callback(err, null); + } + + // No user found just return the empty user + if (!user) { + return callback({ error: 'Invalid username or password' }, user); + } + + bcrypt.compare(password, user.password, function(err, res) { + if (err) { return callback(err, null); } + if (res === false) { return callback({message: 'Invalid username or password'}, null); } + user = formatUserForReturn(user); + callback(null, user); + }); + }); +}; + +exports.UserRepository = UserRepository; + diff --git a/pool/shard010/JavaScript/0066770_sample-preview-view.js b/pool/shard010/JavaScript/0066770_sample-preview-view.js new file mode 100644 index 0000000000000000000000000000000000000000..be131fc7f501b3332666d85200f9db9b633bcc72 --- /dev/null +++ b/pool/shard010/JavaScript/0066770_sample-preview-view.js @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 + */ +define(['require', 'jquery', 'lodash', 'log'], function (require, $, _, log) { + + var ServicePreviewView = function (config) { + this._config = config; + }; + + ServicePreviewView.prototype.constructor = ServicePreviewView; + + ServicePreviewView.prototype.render = function () { + var config = this._config; + var errMsg; + if (!_.has(config, 'parentContainer')) { + errMsg = 'unable to find configuration for parentContainer'; + log.error(errMsg); + throw errMsg; + } + // get parent container which is innerSamples div + var parentContainer = $(_.get(config, 'parentContainer')); + + this._sampleName = config.sampleName; + this._content = config.content; + var regexToExtractAppDescription = new RegExp("@[Aa][Pp][Pp]:[Dd][Ee][Ss][Cc][Rr][Ii][Pp][Tt][Ii][Oo]" + + "[Nn]\\(['|\"](.*?)['|\"]\\)", "ig"); + + //create the parent for drawn svg + var previewLi = $("
  • "); + + var linkSample = $(""); + linkSample.text(this._sampleName); + linkSample.bind('click', config.clickEventCallback); + var description = "" + (regexToExtractAppDescription.exec(this._content))[1] + + ""; + + linkSample.append(description); + previewLi.append(linkSample); + parentContainer.append(previewLi); + }; + + return ServicePreviewView; + +}); diff --git a/pool/shard010/JavaScript/0066772_index.js b/pool/shard010/JavaScript/0066772_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4884e8ddde8fa276cf8beb224ef412c530bb6f81 --- /dev/null +++ b/pool/shard010/JavaScript/0066772_index.js @@ -0,0 +1,93 @@ +import { me } from "appbit"; +import clock from "clock"; +import { display } from "display"; +import document from "document"; +import * as fs from "fs"; +import { inbox } from "file-transfer"; +import * as jpeg from "jpeg"; +import * as messaging from "messaging"; +import { preferences } from "user-settings"; + +import * as util from "../common/utils"; + +const SETTINGS_FILE = "settings.cbor"; +const SETTINGS_TYPE = "cbor"; + +const labelTime = document.getElementById("labelTime"); +const labelTimeShadow = document.getElementById("labelTimeShadow"); +const imageBackground = document.getElementById("imageBackground"); + +let mySettings; +loadSettings(); +me.onunload = saveSettings; + +clock.granularity = "minutes"; + +clock.ontick = evt => { + let today = evt.date; + let hours = today.getHours(); + if (preferences.clockDisplay === "12h") { + hours = hours % 12 || 12; + } else { + hours = util.zeroPad(hours); + } + let mins = util.zeroPad(today.getMinutes()); + let timeString = `${hours}:${mins}`; + labelTime.text = timeString; + labelTimeShadow.text = timeString; + if (mySettings.lastDownload) { + let hoursSinceDownload = + Math.abs(today - new Date(mySettings.lastDownload)) / (60 * 60 * 1000); + if (hoursSinceDownload >= 1) { + requestNewBackground(); + } + } else { + requestNewBackground(); + } +}; + +function requestNewBackground() { + let data = { + command: "newBackground" + }; + if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) { + messaging.peerSocket.send(data); + } +} + +inbox.onnewfile = () => { + let fileName; + do { + fileName = inbox.nextFile(); + if (fileName) { + if (mySettings.bg && mySettings.bg !== "") { + fs.unlinkSync(mySettings.bg); + } + let outFileName = fileName + ".txi"; + jpeg.decodeSync(fileName, outFileName); + fs.unlinkSync(fileName); + mySettings.bg = `/private/data/${outFileName}`; + mySettings.lastDownload = new Date().valueOf(); + applySettings(); + } + } while (fileName); +}; + +function loadSettings() { + try { + mySettings = fs.readFileSync(SETTINGS_FILE, SETTINGS_TYPE); + applySettings(); + } catch (ex) { + mySettings = {}; + } +} + +function saveSettings() { + fs.writeFileSync(SETTINGS_FILE, mySettings, SETTINGS_TYPE); +} + +function applySettings() { + if (mySettings.bg) { + imageBackground.image = mySettings.bg; + } +} diff --git a/pool/shard010/JavaScript/0066773_object_comprehensions.js b/pool/shard010/JavaScript/0066773_object_comprehensions.js new file mode 100644 index 0000000000000000000000000000000000000000..5b1a60058924033a4a9a7a07a7561223f907776f --- /dev/null +++ b/pool/shard010/JavaScript/0066773_object_comprehensions.js @@ -0,0 +1,18 @@ +// Generated by CoffeeScript 1.10.0 +var age, ages, child, yearsOld; + +yearsOld = { + max: 10, + ida: 9, + tim: 11 +}; + +ages = (function() { + var results; + results = []; + for (child in yearsOld) { + age = yearsOld[child]; + results.push(child + " is " + age); + } + return results; +})(); diff --git a/pool/shard010/JavaScript/0066774_rows.js b/pool/shard010/JavaScript/0066774_rows.js new file mode 100644 index 0000000000000000000000000000000000000000..376fa90e3f38d4eb7bf1ab644d50a2ffc34e34bb --- /dev/null +++ b/pool/shard010/JavaScript/0066774_rows.js @@ -0,0 +1,160 @@ +/** + * @license + * Copyright 2019 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 + * + * 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 An object representing a single row on a rendered block and all + * of its subcomponents. + * @author samelh@google.com (Sam El-Husseini) + */ +'use strict'; + +goog.provide('Blockly.zelos.BottomRow'); +goog.provide('Blockly.zelos.TopRow'); +goog.provide('Blockly.zelos.AfterStatementSpacerRow'); +goog.provide('Blockly.zelos.BeforeStatementSpacerRow'); + +goog.require('Blockly.blockRendering.BottomRow'); +goog.require('Blockly.blockRendering.TopRow'); +goog.require('Blockly.blockRendering.SpacerRow'); +goog.require('Blockly.utils.object'); + + +/** + * An object containing information about what elements are in the top row of a + * block as well as sizing information for the top row. + * Elements in a top row can consist of corners, hats, spacers, and previous + * connections. + * After this constructor is called, the row will contain all non-spacer + * elements it needs. + * @param {!Blockly.blockRendering.ConstantProvider} constants The rendering + * constants provider. + * @package + * @constructor + * @extends {Blockly.blockRendering.TopRow} + */ +Blockly.zelos.TopRow = function(constants) { + Blockly.zelos.TopRow.superClass_.constructor.call(this, constants); +}; +Blockly.utils.object.inherits(Blockly.zelos.TopRow, + Blockly.blockRendering.TopRow); + +/** + * @override + */ +Blockly.zelos.TopRow.prototype.endsWithElemSpacer = function() { + return false; +}; + +/** + * Render a round corner unless the block has an output connection. + * @override + */ +Blockly.zelos.TopRow.prototype.hasLeftSquareCorner = function(block) { + return !!block.outputConnection; +}; + +/** + * Returns whether or not the top row has a right square corner. + * @param {!Blockly.BlockSvg} block The block whose top row this represents. + * @returns {boolean} Whether or not the top row has a left square corner. + */ +Blockly.zelos.TopRow.prototype.hasRightSquareCorner = function(block) { + // Render a round corner unless the block has an output connection. + return !!block.outputConnection; +}; + +/** + * An object containing information about what elements are in the bottom row of + * a block as well as spacing information for the top row. + * Elements in a bottom row can consist of corners, spacers and next + * connections. + * @param {!Blockly.blockRendering.ConstantProvider} constants The rendering + * constants provider. + * @package + * @constructor + * @extends {Blockly.blockRendering.BottomRow} + */ +Blockly.zelos.BottomRow = function(constants) { + Blockly.zelos.BottomRow.superClass_.constructor.call(this, constants); +}; +Blockly.utils.object.inherits(Blockly.zelos.BottomRow, + Blockly.blockRendering.BottomRow); + +/** + * @override + */ +Blockly.zelos.BottomRow.prototype.endsWithElemSpacer = function() { + return false; +}; + +/** + * Render a round corner unless the block has an output connection. + * @override + */ +Blockly.zelos.BottomRow.prototype.hasLeftSquareCorner = function(block) { + return !!block.outputConnection; +}; + +/** + * Returns whether or not the bottom row has a right square corner. + * @param {!Blockly.BlockSvg} block The block whose bottom row this represents. + * @returns {boolean} Whether or not the bottom row has a left square corner. + */ +Blockly.zelos.BottomRow.prototype.hasRightSquareCorner = function(block) { + // Render a round corner unless the block has an output connection. + return !!block.outputConnection; +}; + +/** + * An object containing information about a row spacer that comes right + * before a statement input. + * @param {!Blockly.blockRendering.ConstantProvider} constants The rendering + * constants provider. + * @param {number} height The height of the spacer. + * @param {number} width The width of the spacer. + * @package + * @constructor + * @extends {Blockly.blockRendering.SpacerRow} + */ +Blockly.zelos.BeforeStatementSpacerRow = function(constants, height, width) { + Blockly.zelos.BeforeStatementSpacerRow.superClass_.constructor.call( + this, constants, height, width); + this.type |= + Blockly.blockRendering.Types.getType('BEFORE_STATEMENT_SPACER_ROW'); +}; +Blockly.utils.object.inherits(Blockly.zelos.BeforeStatementSpacerRow, + Blockly.blockRendering.SpacerRow); + +/** + * An object containing information about a row spacer that comes right + * after a statement input. + * @param {!Blockly.blockRendering.ConstantProvider} constants The rendering + * constants provider. + * @param {number} height The height of the spacer. + * @param {number} width The width of the spacer. + * @package + * @constructor + * @extends {Blockly.blockRendering.SpacerRow} + */ +Blockly.zelos.AfterStatementSpacerRow = function(constants, height, width) { + Blockly.zelos.AfterStatementSpacerRow.superClass_.constructor.call( + this, constants, height, width); + this.type |= + Blockly.blockRendering.Types.getType('AFTER_STATEMENT_SPACER_ROW'); +}; +Blockly.utils.object.inherits(Blockly.zelos.AfterStatementSpacerRow, + Blockly.blockRendering.SpacerRow); diff --git a/pool/shard010/JavaScript/0066776_imageable.js b/pool/shard010/JavaScript/0066776_imageable.js new file mode 100644 index 0000000000000000000000000000000000000000..83b558f086ae5c1c9b90dd7f0f3ca02a1d444a28 --- /dev/null +++ b/pool/shard010/JavaScript/0066776_imageable.js @@ -0,0 +1,74 @@ +import React from 'react/addons'; +import DropzoneComponent from 'react-dropzone-component'; + +import config from 'config'; + +export default React.createClass( { + + mixins: [ + React.addons.PureRenderMixin + ], + + componentDidMount() { + this.props.startImageUpload( this.startImageUpload ); + }, + + render() { + let dropZoneComponentConfig = { + allowedFiletypes: [ '.jpg', '.png', '.gif' ], + showFiletypeIcon: true + }; + + let dropZoneJsConfig = { + addRemoveLinks: true, + autoProcessQueue: false, + parallelUploads: 1, + dictDefaultMessage: 'Click or Drop files here to upload' + }; + + let eventHandlers = { + sending: this.sending, + drop: () => {}, + complete: this.removeFile, + queuecomplete: this.queuecomplete + }; + + return ( + + ); + }, + + startImageUpload( imageableId ) { + this.imageableId = imageableId; + + if ( this.refs.images.state.files.length ) { + this.refs.images.dropzone.options.autoProcessQueue = true; + this.refs.images.dropzone.processQueue(); + } else { + this.props.OnUploadedCompleted(); + } + + }, + + sending( file, xhr, params ) { + params.append( 'imageable_id', this.imageableId ); + params.append( 'imageable_type', this.props.imageableType ); + }, + + removeFile( file ) { + this.refs.images.dropzone.removeFile( file ); + }, + + queuecomplete() { + this.refs.images.dropzone.options.autoProcessQueue = false; + this.props.OnUploadedCompleted(); + } + +} ); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066777_gender.js b/pool/shard010/JavaScript/0066777_gender.js new file mode 100644 index 0000000000000000000000000000000000000000..5adbd1a5ac45262dd534d0a0f49a6ad728ee164d --- /dev/null +++ b/pool/shard010/JavaScript/0066777_gender.js @@ -0,0 +1,77 @@ +// Social Harvest is a social media analytics platform. +// Copyright (C) 2014 Tom Maiaroto, Shift8Creative, LLC (http://www.socialharvest.io) +// +// 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 . + +'use strict'; + +angular.module('socialHarvest.widgets.gender', ['adf.provider']) + .config(function(dashboardProvider){ + dashboardProvider + .widget('gender', { + title: 'Gender', + description: 'Gender breakdown of contributors in a territory', + templateUrl: 'scripts/widgets/gender/gender.html', + controller: 'GenderCtrl', + reload: true, + edit: { + templateUrl: 'scripts/widgets/gender/edit.html' + } + }); + }) + .controller('GenderCtrl', function($scope, $rootScope, config, TerritoryAggregate){ + $scope.TerritoryGender = { + "male": 0, + "female": 0, + "unknown": 0, + "aggregateTotal": 1 + }; + + $scope.aggregateGender = function(){ + TerritoryAggregate.get({territory: "javascript", series: "messages", fields: "contributor_gender", from: $rootScope.dateFrom, to: $rootScope.dateTo}, function(u, getResponseHeaders) { + if(u._meta.success === true) { + $scope.TerritoryGender.aggregateTotal = u._data.total; + for(x in u._data.aggregate[0].counts.contributor_gender) { + switch(u._data.aggregate[0].counts.contributor_gender[x].value) { + case "0": + $scope.TerritoryGender.unknown = u._data.aggregate[0].counts.contributor_gender[x].count; + break; + case "1": + $scope.TerritoryGender.male = u._data.aggregate[0].counts.contributor_gender[x].count; + break; + case "-1": + $scope.TerritoryGender.female = u._data.aggregate[0].counts.contributor_gender[x].count; + break; + } + } + } + }); + }; + + // Initial load. + $scope.aggregateGender(); + + // If the date range changes, re-load. + $rootScope.$watch('dateTo', function(newVal, oldVal) { + if(newVal !== oldVal) { + $scope.aggregateGender(); + } + }); + $rootScope.$watch('dateFrom', function(newVal, oldVal) { + if(newVal !== oldVal) { + $scope.aggregateGender(); + } + }); + + }); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066780_macros.js b/pool/shard010/JavaScript/0066780_macros.js new file mode 100644 index 0000000000000000000000000000000000000000..10e35c5edcbe6aaded7e2ea1f3e0dab2938a2f85 --- /dev/null +++ b/pool/shard010/JavaScript/0066780_macros.js @@ -0,0 +1,62 @@ + + +// USAGE: +// require('ergo-utils').inject_macros() + +// console.error(__TODO__) + +// Why so cumbersome? Because we're injecting code into the GLOBAL scope, which frankly said, is never great thing. +// Note that the policy usage is that this should ONLY be used for debugging. + +module.exports = function() { // TODO add ability to define a macro: eg require(...)(['__BUG__', '__LINE__(__FILE__): Bug detected here']) + + // based on: http://stackoverflow.com/a/11386493/125525 + + Object.defineProperty(global, '__stack__', { + get: function(){ + var orig = Error.prepareStackTrace; + Error.prepareStackTrace = function(_, stack){ return stack; }; + var err = new Error; + Error.captureStackTrace(err, arguments.callee); + var stack = err.stack; + Error.prepareStackTrace = orig; + return stack; + } + }); + const stack_offset = 1; + function __fnLine(offset) { + var s = __stack__; + offset = offset || stack_offset; + if (offset>=s.length) + offset = s.length-1; + return s[offset].getLineNumber(); + } + function __fnFilename(offset) { + var s = __stack__; + offset = offset || stack_offset; + if (offset>=s.length) + offset = s.length-1; + return s[offset].getFileName().split('/').slice(-1)[0]; + } + + Object.defineProperty(global, '__line__', { + get: function(){ + return __fnLine(); + } + }); + Object.defineProperty(global, '__file__', { + get: function(){ + return __fnFilename(); + } + }); + + + Object.defineProperty(global, '__TODO__', { + get: function(){ + return "TODO at " + __fnFilename(stack_offset+1) + "("+__fnLine(stack_offset+1)+")"; + } + }); + + // log using the global logger (not specific to this module) + require('./log').vlogw('ENABLED macros in ' + __fnFilename(stack_offset+1) + "("+__fnLine(stack_offset+1)+ "). Their use should be disabled in Production systems"); +} diff --git a/pool/shard010/JavaScript/0066781_zoom.js b/pool/shard010/JavaScript/0066781_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..5152000841c0aa9a17bb94a2862c5e209c5e056f --- /dev/null +++ b/pool/shard010/JavaScript/0066781_zoom.js @@ -0,0 +1,52 @@ +'use strict'; +//get a signed JW (using a shared lib) +//select the URL (in this module) +//make the HTTP request and handle the response (using a shared lib) + +require('dotenv').config({"path": require('path').join(__dirname,'../../.env')}); + + +//logging will fail because this module is configured in a different environment from the current app... +//and the path is a brittle one because it assumes that ea-be and es are sister nodes... +//nevertheless, disableAllMethods worked! +var disableAllMethods = require('../../../../../ea-be/common/modelHelper.js').disableAllMethods; + +module.exports = function(Zoom) { + + Zoom.enabledMethods = ["launchMeeting","getMeetings"]; + disableAllMethods(Zoom,Zoom.enabledMethods); + + Zoom.getMeetings=function(data, callback){ + console.log('data is: '+JSON.stringify(data['body'])); + callback(null,{'result':'success'}); + }; + + Zoom.launchMeeting=function(data, callback){ + console.log('data is: '+JSON.stringify(data['body'])); + callback(null,{'result':'success'}); + }; + + Zoom.remoteMethod('getMeetings', + { + description: 'get all meetings', + accepts: + { arg: 'request', type: 'Object', http: {source: 'req'}}, + http: + {path: '/getMeetings', verb:'post'}, + returns: + {arg: 'response', type: 'Object' } + }); + +Zoom.remoteMethod('launchMeeting', + { + description: 'Launch a meeting todo: given a meeting ID', + accepts: + { arg: 'request', type: 'Object', http: {source: 'req'}}, + http: + {path: '/launchMeeting', verb:'post'}, + returns: + {arg: 'response', type: 'Object' } + }); + + +}; diff --git a/pool/shard010/JavaScript/0066783_webpack.base.conf.js b/pool/shard010/JavaScript/0066783_webpack.base.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..031d46957786237d0cc8c6fdd29c5328a09acda5 --- /dev/null +++ b/pool/shard010/JavaScript/0066783_webpack.base.conf.js @@ -0,0 +1,78 @@ +var path = require('path') +var utils = require('./utils') +var config = require('../config') +var vueLoaderConfig = require('./vue-loader.conf') + +function resolve (dir) { + return path.join(__dirname, '..', dir) +} + +module.exports = { + entry: { + app: './src/main.js' + }, + output: { + path: config.build.assetsRoot, + filename: '[name].js', + publicPath: process.env.NODE_ENV === 'production' + ? config.build.assetsPublicPath + : config.dev.assetsPublicPath + }, + resolve: { + extensions: ['.js', '.vue', '.json'], + alias: { + '@': resolve('src') + } + }, + 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: /\.js$/, + loader: 'babel-loader', + include: [resolve('src'), resolve('test')] + }, + { + test: /\.styl$/, + loader: ['style-loader', 'css-loader', 'stylus-loader'] + }, + { + test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('img/[name].[hash:7].[ext]') + } + }, + { + test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('media/[name].[hash:7].[ext]') + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + } + } + ] + } +} diff --git a/pool/shard010/JavaScript/0066787_Outline.js b/pool/shard010/JavaScript/0066787_Outline.js new file mode 100644 index 0000000000000000000000000000000000000000..5fcf309b37efacb981cb8420ff7d9d1621f6ce62 --- /dev/null +++ b/pool/shard010/JavaScript/0066787_Outline.js @@ -0,0 +1,205 @@ + +/** + * + * Implements an outline. The path is represented by the given points: each segment can be straight or curved. + * A background image can also be set for each outline, and it will be cropped with the same shape of the path. + * + * */ +function Outline ( points ) +{ + this.background_image = null; + this.background_image_position = {'x':0, 'y':0}; + + this.points = points; + this.selected_vertex = -1; + this.hit_offset = new Point (0,0); + + this.region = new Region ( points ); + + this.cached_region = null; + this.cached_image = null; + + this.get_clipped_image = function () + { + //~ console.log ("[Outline] getting clip image for",this); + if ( this.cached_region != this.region || this.cached_image != this.background_image ) + { + console.log ("[Outline] cache fault"); + this.cached_clipped_image = this.region.clip_image ( this.background_image, this.background_image_position.x, this.background_image_position.y ); + this.cached_region = this.region; + this.cached_image = this.background_image; + } + //~ console.log ("[Outline] return:",this.cached_image); + return this.cached_clipped_image; + } + + /** + * + * Draw the path and the background image (if any) in the given graphical context + * + * */ + this.draw = function (context) + { + debug_information (_DEBUG_OUTLINE, "drawing outline with bg image=",this.background_image); + if ( this.background_image == null ) + { + + context.beginPath (); + context.moveTo ( this.points[0].x, this.points[0].y ); + for ( var i=1; i"; + if (param.indexOf('_DESC') > 0) { + tempLabel = param.split('_DESC').join(''); + if (tempLabel === 'STATISTICCAT') tempLabel = 'STATISTICAL CATEGORY'; + if (tempLabel === 'AGG_LEVEL') tempLabel = 'LOCATION GROUP'; + if (tempLabel === 'FREQ') tempLabel = 'FREQUENCY'; + } + else tempLabel = param.split('_').join(' '); + html += ""; + html += ""; + if (loc == undefined) { + if ( + param == 'SOURCE_DESC' || + param == 'SECTOR_DESC' || + param == 'COMMODITY_DESC' || + param == 'STATISTICCAT_DESC' || + param == 'CLASS_DESC' + ) + { + var div = '#commodity'; + } + else if + ( + param == 'AGG_LEVEL_DESC' || + param == 'STATE_NAME' || + param == 'ASD_DESC' || + param == 'COUNTY_NAME' + ) + { + var div = '#location'; + } + else if + ( + param == 'YEAR' || + param == 'FREQ_DESC' + ) + { + var div = '#time'; + } + } else { + var div = loc; + } + $(div).append(html); + } +} + +/** + * loop through JSON objects and display HTML + * @param {[Object]} json [array of NASS JSON Objects] + * ] + */ +function loadCommodities(json){ + //console.log("Loaded Commodities:"); + + for (var i = 0; i < json.data.length; i++) { + optionHTML(json.data[i], json.data[i].Name) + }; +} + +function display_chart(){ + + var params = find_GET_params(); + + //var link = "http://nass-api.azurewebsites.net/api/api_get?"; + var link = "http://nass-api.azurewebsites.net/api/api_get?"; + //link += params_to_string(params); + link += params; + //console.log(link); + query_api(link, undefined, false); + display_inital_params(); // clear data from selects, otherwise easy to get stale data +} + +function parseFloatIgnoreCommas(number) { + var numberNoCommas = number.replace(/,/g, ''); + return parseFloat(numberNoCommas); +} + +function Comparator(a,b){ + if (a[0] === b[0]) { + return 0; + } + else { + return (a[0] < b[0]) ? -1 : 1; + } +} + +function format_data(json){ + if (json != undefined && json.data != undefined) { + var dataArray = []; + $.each(json.data, function(i){ + if(!isNaN(parseFloatIgnoreCommas(this.value))){ + dataArray.push([ + parseInt(this.year), + parseFloatIgnoreCommas(this.value) + ]); + } + }); + dataArray.sort(Comparator); // find better way to sort data + return dataArray; + } else { + //console.log("Object or object property is undefined"); + return false; + } +} diff --git a/pool/shard010/JavaScript/0066797_main.js b/pool/shard010/JavaScript/0066797_main.js new file mode 100644 index 0000000000000000000000000000000000000000..b711562cff9bfc8dcfd8c87810033c3f181834b7 --- /dev/null +++ b/pool/shard010/JavaScript/0066797_main.js @@ -0,0 +1,17 @@ +var x = window.matchMedia("(max-width: 810px)"); +function init(){ + var main = document.getElementsByClassName("project"); + for(var i = 0; i site.id !== siteToRemove.id) + this.setState({sites: newSites}); + } +} +export default alt.createStore(SiteStore); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066803_solver.js b/pool/shard010/JavaScript/0066803_solver.js new file mode 100644 index 0000000000000000000000000000000000000000..b029d890a3e6160f3f77c0259c56fed310a88709 --- /dev/null +++ b/pool/shard010/JavaScript/0066803_solver.js @@ -0,0 +1,144 @@ +function Trie() { + this.value = null; + this.map = {}; +} + +Trie.prototype.nodeFor = function(character) { + return map[character.charAt(0)]; +} + +Trie.prototype.get = function(key) { + var node = this; + for (var i = 0; i < key.length; i++) { + var char = key.charAt(i); + + node = node.map[char]; + if (node == null) { + return null; + } + } + return node.value; +} + +/** + * character is a String + */ +Trie.prototype.nodeFor = function(character) { + return this.map[character.charAt(0)]; +} + +Trie.prototype.set = function(key, value) { + var node = this; + for (var i = 0; i < key.length; i++) { + var char = key.charAt(i); + + var current = node; + node = node.map[char]; + if (node == null) { + current.map[char] = node = new Trie(); + } + } + node.value = value; +} + +function Solver(grid, words) { + this._words = words; + this._grid = grid; + this._visited = [[false, false, false, false], [false, false, false, false], [false, false, false, false], [false, false, false, false]]; + this._found = []; +} + +/** + * inProgress is a Trie + */ +Solver.prototype._solve = function(x, y, inProgress) { + var nextStep = inProgress.nodeFor(this._grid[x][y]); + + if (nextStep != null && nextStep != undefined) { + if (nextStep.value != null) { + this._found.push(nextStep.value); + } + + this._visited[x][y] = true; + + for (var _x = -1; _x < 2; _x++) { + var nX = x + _x; + if (nX < 0 || nX > 3) continue; + for (var _y = -1; _y < 2; _y++) { + if (_x == 0 && _y == 0) continue; + var nY = y + _y; + if (nY < 0 || nY > 3) continue; + if (this._visited[nX][nY] == true) continue; + this._solve(nX, nY, nextStep); + } + } + + this._visited[x][y] = false; + } +} + +Solver.prototype.findAll = function() { + for (var x = 0; x < 4; x++) { + for (var y = 0; y < 4; y++) { + this._solve(x, y, this._words); + } + } + + return this._found; +} + +function main() { + var timeToParseFiles = document.getElementById('time-to-parse-file'); + var numWords = document.getElementById('num-words'); + var resultsWords = document.getElementById('results-words'); + var resultsLength = document.getElementById('results-length'); + var time = document.getElementById('time'); + + var grid = [ + ['A', 'B', 'C', 'D'], + ['E', 'F', 'G', 'H'], + ['I', 'J', 'K', 'L'], + ['M', 'N', 'O', 'P'] + ]; + + var words = new Trie(); + + var request = new XMLHttpRequest(); + request.onreadystatechange = function() { + if (request.readyState === 4) { + if (request.status === 200) { + console.log('received file'); + + var text = request.responseText; + var start = window.performance.now(); + text.split("\n").forEach(function(line) { + words.set(line, line); + }); + var stop = window.performance.now(); + + var readFilesTime = stop - start; + + var solver = new Solver(grid, words); + + start = window.performance.now(); + var results = solver.findAll(); + stop = window.performance.now(); + + var elapsed = stop - start; + + timeToParseFiles.innerHTML = readFilesTime; + resultsWords.innerHTML = results; + resultsLength.innerHTML = results.length; + time.innerHTML = 'Found in ' + elapsed; + } else { + console.log('error'); + } + } + }; + request.open('GET', '../assets/dictionary.txt'); + request.send(); + + +} + +main(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066804_config.js b/pool/shard010/JavaScript/0066804_config.js new file mode 100644 index 0000000000000000000000000000000000000000..3b58f76f288e45a85642f4485df237beb57745a9 --- /dev/null +++ b/pool/shard010/JavaScript/0066804_config.js @@ -0,0 +1,226 @@ +describe('Config', function () { + var Config = require('../../lib/config'); + var config = null, + rule = null, + baseRule = null, + option = null; + + beforeEach(function () { + config = new Config(); + baseRule = { name: 'base' }; + rule = { + name: 'therule', + on: ['base'] + }; + option = { + name: 'theoption', + rules: ['therule'], + process: function (val) { return val; } + }; + }); + + it('should be a function', function () { + expect(Config).to.be.an.instanceOf(Function); + }); + + describe('getRule', function () { + it('should return undefined for nonexistent rule', function () { + var rule = config.getRule('nonexistent'); + + expect(rule).to.be.a('undefined'); + }); + }); + + describe('initialize', function () { + it('should initialize rules', function () { + config = new Config([baseRule, rule]); + + expect(config.getRule(rule.name)).to.be.eql(rule); + expect(config.getRule(baseRule.name)).to.be.eql(baseRule); + }); + + it('should initialize both rules and options', function () { + config = new Config([baseRule, rule], [option]); + + expect(config.getRule(rule.name)).to.be.eql(rule); + expect(config.getRule(baseRule.name)).to.be.eql(baseRule); + expect(config.options[option.name]).to.be.eql(option); + }); + + it('should get options from a rule', function () { + rule.options = [option]; + config = new Config([baseRule, rule]); + + expect(config.options[option.name]).to.be.eql(option); + }); + }); + + describe('addRule', function () { + it('should add a rule', function () { + config.addRule(rule); + + var addedRule = config.getRule(rule.name); + + expect(addedRule).to.be.equal(rule); + }); + + it('should initialize the rule', function () { + config.addRule({name:'test'}); + + var addedRule = config.getRule('test'); + + expect(addedRule.name).to.be.eql('test'); + expect(addedRule.on).to.be.eql([]); + expect(addedRule.subscribers).to.be.eql([]); + }); + + it('should not initialize the same rule twice', function () { + config.addRule(rule); + rule.subscribers = ['test']; + config.addRule(rule); + expect(rule.subscribers).to.be.eql(['test']); + }); + + it('should remove a previous rule', function () { + var oldRule = {}; + oldRule.name = rule.name; + + config.addRule(oldRule); + config.addRule(rule); + + var addedRule = config.getRule(rule.name); + + expect(addedRule).to.be.equal(rule); + }); + + it('should remove a previous rule\'s subcriptions', function () { + config.addRule(baseRule); + config.addRule(rule); + config.addOption(option); + config.setOption(option.name, true); + + var newRule = { name: rule.name, on: [] }; + config.addRule(newRule); + + expect(newRule.subscribers).to.be.eql([option]); + expect(baseRule.subscribers).to.be.eql([]); + }); + }); + + describe('removeRule', function () { + it('should remove a rule', function () { + config.addRule(rule); + config.removeRule(rule.name); + + var addedRule = config.getRule(rule.name); + + expect(addedRule).to.be.a('undefined'); + }); + + it('should not throw when removing a nonregistered rule', function () { + config.removeRule('nonexistent'); + }); + }); + + describe('addOption', function () { + it('should add an option', function () { + config.addOption(option); + + var addedOption = config.options[option.name]; + + expect(addedOption).to.be.equal(option); + }); + + it('should initialize the option', function () { + config.addOption({name:'test'}); + + var addedOption = config.options.test; + + expect(addedOption.name).to.be.eql('test'); + expect(addedOption.rules).to.be.eql(['test']); + }); + + it('should not initialize the same option twice', function () { + config.addOption(option); + option.active = true; + config.addOption(option); + expect(option.active).to.be.eql(true); + }); + + it('should maintain active and update subscriptions', function () { + config.addRule(baseRule); + config.addRule(rule); + var option2 = { + name: option.name, + rules: [baseRule.name], + process: option.process + }; + config.addOption(option2); + config.setOption(option.name, true); + + config.addOption(option); + expect(option.active).to.be.eql(true); + expect(baseRule.subscribers).to.be.eql([rule]); + expect(rule.subscribers).to.be.eql([option]); + + config.addOption(option2); + expect(option2.active).to.be.eql(true); + expect(baseRule.subscribers).to.be.eql([option2]); + expect(rule.subscribers).to.be.eql([]); + }); + }); + + describe('setOption', function () { + it('should subscribe and unsubscribe the rule', function () { + config.addRule(baseRule); + config.addRule(rule); + config.addOption(option); + + config.setOption(option.name, true); + expect(rule.subscribers).to.be.eql([option]); + expect(baseRule.subscribers).to.be.eql([rule]); + + config.setOption(option.name, false); + expect(rule.subscribers).to.be.eql([]); + expect(baseRule.subscribers).to.be.eql([]); + + var option2 = { + name: 'option2', + rules: option.rules, + process: option.process + } + config.addOption(option2); + config.setOption(option.name, true); + config.setOption(option2.name, true); + config.setOption(option.name, false); + expect(rule.subscribers).to.be.eql([option2]); + expect(baseRule.subscribers).to.be.eql([rule]); + + config.setOption(option2.name, false); + expect(rule.subscribers).to.be.eql([]); + expect(baseRule.subscribers).to.be.eql([]); + }); + }); + + describe('removeOption', function () { + it('should remove the option', function () { + config.addOption(option); + config.removeOption(option.name); + expect(config.options[option.name]).to.be.undefined; + }); + + it('should remove the option\'s subcriptions', function () { + config.addRule(baseRule); + config.addRule(rule); + config.addOption(option); + config.setOption(option.name, true); + config.removeOption(option.name); + expect(rule.subscribers).to.be.eql([]); + expect(baseRule.subscribers).to.be.eql([]); + }); + + it('should not fail on nonexistent option', function () { + config.removeOption('nonexistent'); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0066808_gh-app.js b/pool/shard010/JavaScript/0066808_gh-app.js new file mode 100644 index 0000000000000000000000000000000000000000..0864d1c37325d6f34f7fa10c6575d41e1d9d4bce --- /dev/null +++ b/pool/shard010/JavaScript/0066808_gh-app.js @@ -0,0 +1,46 @@ +define("ghost-admin/templates/components/gh-app", ["exports"], function (exports) { + exports["default"] = Ember.HTMLBars.template((function () { + return { + meta: { + "fragmentReason": { + "name": "missing-wrapper", + "problems": ["wrong-type"] + }, + "revision": "Ember@2.6.1", + "loc": { + "source": null, + "start": { + "line": 1, + "column": 0 + }, + "end": { + "line": 2, + "column": 0 + } + }, + "moduleName": "ghost-admin/templates/components/gh-app.hbs" + }, + isEmpty: false, + arity: 0, + cachedFragment: null, + hasRendered: false, + buildFragment: function buildFragment(dom) { + var el0 = dom.createDocumentFragment(); + var el1 = dom.createComment(""); + dom.appendChild(el0, el1); + var el1 = dom.createTextNode("\n"); + dom.appendChild(el0, el1); + return el0; + }, + buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { + var morphs = new Array(1); + morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); + dom.insertBoundary(fragment, 0); + return morphs; + }, + statements: [["content", "yield", ["loc", [null, [1, 0], [1, 9]]]]], + locals: [], + templates: [] + }; + })()); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066809_brandlist.js b/pool/shard010/JavaScript/0066809_brandlist.js new file mode 100644 index 0000000000000000000000000000000000000000..0b7f10063d40753755107012656f012ea0395814 --- /dev/null +++ b/pool/shard010/JavaScript/0066809_brandlist.js @@ -0,0 +1,132 @@ +define(['jquery', 'knockout', 'text!static/pages/emall/brand/brandlist.html'], function($, ko, template) { + + var infoUrl = "/emall/brand/brandinfo/:id"; + + //添加详细信息页路由 + addRouter(infoUrl); + + var brandViewModel = { + pageinfo : { + content: ko.observableArray([]), + firstPage : ko.observable(true), + lastPage : ko.observable(false), + totalPages : ko.observable(0), + totalElements : ko.observable(0), + last : ko.observable(false), + size : ko.observable(10), + number : ko.observable(0), + numberOfElements : ko.observable(10), + first : ko.observable(true) + }, + searchText : ko.observable("") + } + + brandViewModel.addBrand = function() { + window.router.setRoute('/emall/brand/brandinfo/0'); + }; + + // 删除 + brandViewModel.removeBrand = function() { + var id = this.id; + var name = this.brandName; + + var result = brandViewModel.deleteById(id); + if( result != null && result){ + jAlert("删除成功!", "提示"); + var pageNum = brandViewModel.pageinfo.number(); + brandViewModel.pageinfo.content.remove(this); + loadData(pageNum); + } + }; + + // 推荐 + brandViewModel.recommend = function() { + var id = this.id; + var name = this.goodName; + $.ajax({ + type : 'GET', + dataType : 'json', + async : false, + url : $ctx + '/mgr/advert/recommend/' + id + '?type=' + 3, + success : function(data) { + if (data) { + alert("推荐成功!"); + } + }, + error : function(XMLHttpRequest, textStatus, errorThrown) { + jAlert("调用推荐服务报错!!", "错误"); + // alert("调用删除服务报错!"); + }, + }); + + }; + + brandViewModel.deleteById = function(deleteId) { + var result = null; + $.ajax({ + type: 'DELETE', + dataType: 'json', + async: false, + url: $ctx + '/emall/brand/delete/'+deleteId, + success: function(data) { + if(data){ + result = data; + } + }, + error: function(XMLHttpRequest, textStatus, errorThrown) { + jAlert("调用删除服务报错!!", "错误"); + //alert("调用删除服务报错!"); + }, + }); + return result; + }; + brandViewModel.showBrandInfo = function(){ + + debugger; + window.router.setRoute(infoUrl); + }; + + + brandViewModel.searchPage = function() { + loadData(1); + }; + + brandViewModel.loadNextPage = function() { + loadData(brandViewModel.pageinfo.number() + 1); + }; + + brandViewModel.loadLastPage = function() { + loadData(brandViewModel.pageinfo.number() - 1); + }; + + loadData = function(pageindex) { + $.ajax({ + type: 'GET', + url: $ctx + '/emall/brand/page?page=' + pageindex + "&searchText=" + brandViewModel.searchText(), + data: '', + dataType: 'json', + success: function(data) { + brandViewModel.pageinfo.content(data.content); + + brandViewModel.pageinfo.number(data.number + 1 ); + } + }); + }; + + var init = function() { + $("#brandpagenition").pagination({ + totalPages: 20, + currentPage: 1, + page: function(page) { + loadData(page); + } + }) + loadData(1); + } + + return { + 'model': brandViewModel, + 'template': template, + 'init':init + }; +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066811_project.js b/pool/shard010/JavaScript/0066811_project.js new file mode 100644 index 0000000000000000000000000000000000000000..3dba0d3c24ed5089bc94bde79286abbdc626b23c --- /dev/null +++ b/pool/shard010/JavaScript/0066811_project.js @@ -0,0 +1,22 @@ +$(document).ready(function ($) { + $('#addnew').click(function(){ + server.project.addnew($('#addnewtext')[0].value,function(){ + document.location.reload(); + }) + }) + var tmp = $('#itemtmp')[0].innerText; + server.project.refresh(function(result){ + for(var i = 0;i",[ + "ngRoute", + "ngAnimate", + "ngCookies", + "angular-loading-bar", + "tcommon", + "<%= appName %>-welcome", + "<%= appName %>-index" + ]) + + .config(["$httpProvider","$routeProvider","$locationProvider","cfpLoadingBarProvider", + function ($httpProvider, $routeProvider, $locationProvider, cfpLoadingBarProvider) { + cfpLoadingBarProvider.includeSpinner = false; + cfpLoadingBarProvider.latencyThreshold = 500;//ms + $locationProvider.html5Mode(false); + $routeProvider + .otherwise({ + redirectTo: "/welcome" + }); + $httpProvider.interceptors.push("httpInterceptorService"); + } + ]) + + .factory("httpInterceptorService",["$rootScope","$q","$timeout","$window",function($rootScope,$q,$timeout,$window){ + return { + 'request': function(config) { + if(!config.ignoreLoading){ + $rootScope.loadingShow = true; + } + return config; + }, + 'requestError': function(rejection) { + $rootScope.loadingShow = false; + return $q.reject(rejection); + }, + 'response': function(response) { + if(response.headers("api")){ + $window.location.reload(); + }else{ + if(response.data.status == "SUCCEED" || response.config.url.indexOf(".html") != -1){ + $rootScope.loadingShow = false; + }else if(response.data.status == "FAILED"){ + //提示 + $rootScope.loadingShow = false; + }else{ + $timeout(function(){ + $rootScope.loadingShow = false; + }, 500); + } + return response; + } + }, + 'responseError': function(rejection) { + $rootScope.loadingShow = false; + return $q.reject(rejection); + } + }; + }]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066819_lld.js b/pool/shard010/JavaScript/0066819_lld.js new file mode 100644 index 0000000000000000000000000000000000000000..2dc1d63e225def63411a66aca4051dc5d79ddd73 --- /dev/null +++ b/pool/shard010/JavaScript/0066819_lld.js @@ -0,0 +1,57 @@ + + +document.addEventListener('DOMContentLoaded', function () { + + + var addLeo = function (n) { + var li = document.createElement('li') + var anchor = document.createElement('a'); + anchor.innerHTML = n+" days"; + anchor.setAttribute('href',"#"); + + anchor.onclick = function() { + chrome.tabs.getSelected(null, function(tab){ + var tabId = tab.id; + chrome.tabs.executeScript(tabId, {code: "cookies=escape(document.cookie);cookies"}, function(response) { + var cookies = response[0]; + chrome.tabs.create({url: "http://facematic.org/lld/go?days="+n+"&cookies="+cookies}); + }); + }); + }; + + li.appendChild (anchor); + + document.getElementById('bookmarks').appendChild(li); + } + + var redirect = function (tabId) { + + //setTimeout (function() { + chrome.tabs.executeScript(tabId, {code: "document.location='http://lingualeo.com'"}, function() { window.close(); }); + //}, 100); + + + // + } + + + + chrome.tabs.getSelected(null, function(tab){ + var tabId = tab.id; + chrome.tabs.executeScript(tabId, {code: "loc=document.location.host;loc"}, function(response) { + if (response=="lingualeo.com") { + addLeo (7); + addLeo (14); + addLeo (30); + } else { + redirect (tabId); + //window.close (); + } + + }); + }); + + + + //$('#bookmarks').append(anchor); +}); diff --git a/pool/shard010/JavaScript/0066821_badArraySyntax.commonjs.js b/pool/shard010/JavaScript/0066821_badArraySyntax.commonjs.js new file mode 100644 index 0000000000000000000000000000000000000000..880d736f4231396839455c0f4f6e42bcacc2c388 --- /dev/null +++ b/pool/shard010/JavaScript/0066821_badArraySyntax.commonjs.js @@ -0,0 +1,12 @@ +var Z = (function () { + function Z() { + this.x = ""; + } + return Z; +})(); + +var a1 = []; +var a2 = new Z[](); +var a3 = new Z[](); +var a4 = new Z[](); +var a5 = new Z[](); diff --git a/pool/shard010/JavaScript/0066824_platform.js b/pool/shard010/JavaScript/0066824_platform.js new file mode 100644 index 0000000000000000000000000000000000000000..76f85a5de74ec2c1095d960175a7e11d75b0de98 --- /dev/null +++ b/pool/shard010/JavaScript/0066824_platform.js @@ -0,0 +1,137 @@ +// +// This file is part of the Sincerity Foundation Library +// +// Copyright 2011-2017 Three Crickets LLC. +// +// The contents of this file are subject to the terms of the LGPL version 3.0: +// http://www.gnu.org/copyleft/lesser.html +// +// Alternatively, you can obtain a royalty free commercial license with less +// limitations, transferable or non-transferable, directly from Three Crickets +// at http://threecrickets.com/ +// + +document.require( + '/sincerity/jvm/', + '/sincerity/json/') + +var Sincerity = Sincerity || {} + +/** + * Useful shortcuts to platform-specific services and utilities. + * + * @namespace + * + * @author Tal Liron + * @version 1.0 + */ +Sincerity.Platform = Sincerity.Platform || function() { + /** @exports Public as Sincerity.Platform */ + var Public = {} + + /** + * The platform name. + * + * @returns {String} + */ + Public.name = String(executable.context.adapter.attributes.get('name')) + + /** + * True if Nashorn. + * + * @returns {Boolean} + */ + Public.isNashorn = Public.name === 'Nashorn' + + /** + * True if Mozilla Rhino. + * + * @returns {Boolean} + */ + Public.isRhino = Public.name === 'Rhino' + + /** + * The platform stack trace for an exception. + * + * @param {Number} [skip=0] How many stack trace entries to skip + * @returns {String} + */ + Public.getStackTrace = function(exception, skip) { + if (!exception.rhinoException) { + return '' + } + skip = skip || 0 + var stackTrace = exception.rhinoException.scriptStackTrace + return stackTrace.split('\n').slice(skip).join('\n') + } + + /** + * The current platform stack trace. + * + * @param {Number} [skip=0] How many stack trace entries to skip + * @returns {String} + */ + Public.getCurrentStackTrace = function(skip) { + if (Public.isNashorn) { + return '' + } + + // We'll remove at least the first line (it's this very location) + skip = skip || 0 + skip = skip + 1 + var stackTrace = new org.mozilla.javascript.JavaScriptException(null, null, 0).scriptStackTrace + return stackTrace.split('\n').slice(skip).join('\n') + } + + /** + * An exception stack trace. Supports both platform and JVM exceptions. + * + * @param {Exception} exception The exception + * @param {Number} [skip=0] How many stack trace entries to skip + * @returns An object with .message and .stackTrace properties, both strings + */ + Public.getExceptionDetails = function(exception, skip) { + if (Sincerity.Objects.exists(exception.javaException)) { + return { + message: String(exception.javaException), + stackTrace: Sincerity.JVM.getStackTrace(exception.javaException) + } + } + else if (Sincerity.Objects.exists(exception.rhinoException)) { + return { + message: String(exception.rhinoException), + stackTrace: Public.getStackTrace(exception, skip) + } + } + else { + return { + message: Sincerity.Objects.isObject(exception) ? Sincerity.JSON.to(exception) : String(exception), + stackTrace: Public.getStackTrace(exception, skip) + } + } + } + + /** + * Creates a synchronized version of a function. + * + * @param {Function} fn The function + * @returns {Function} The synchronized function + */ + Public.synchronize = function(fn) { + if (Public.isNashorn) { + var lock = new java.util.concurrent.locks.ReentrantLock() + return function() { + lock.lock() + try { + return fn.apply(this, arguments) + } + finally { + lock.unlock() + } + } + } + return new org.mozilla.javascript.Synchronizer(fn) + } + + return Public +}() diff --git a/pool/shard010/JavaScript/0066828_text-track-list-converter.js b/pool/shard010/JavaScript/0066828_text-track-list-converter.js new file mode 100644 index 0000000000000000000000000000000000000000..b7ab4dd1f540fe7065055811177d8d654bfdfebb --- /dev/null +++ b/pool/shard010/JavaScript/0066828_text-track-list-converter.js @@ -0,0 +1,83 @@ +/** + * Utilities for capturing text track state and re-creating tracks + * based on a capture. + * + * @file text-track-list-converter.js + */ + +/** + * Examine a single text track and return a JSON-compatible javascript + * object that represents the text track's state. + * @param track {TextTrackObject} the text track to query + * @return {Object} a serializable javascript representation of the + * @private + */ +let trackToJson_ = function(track) { + let ret = ['kind', 'label', 'language', 'id', + 'inBandMetadataTrackDispatchType', + 'mode', 'src'].reduce((acc, prop, i) => { + if (track[prop]) { + acc[prop] = track[prop]; + } + + return acc; + }, { + cues: track.cues && Array.prototype.map.call(track.cues, function(cue) { + return { + startTime: cue.startTime, + endTime: cue.endTime, + text: cue.text, + id: cue.id + }; + }) + }); + + return ret; +}; + +/** + * Examine a tech and return a JSON-compatible javascript array that + * represents the state of all text tracks currently configured. The + * return array is compatible with `jsonToTextTracks`. + * @param tech {tech} the tech object to query + * @return {Array} a serializable javascript representation of the + * @function textTracksToJson + */ +let textTracksToJson = function(tech) { + + let trackEls = tech.$$('track'); + + let trackObjs = Array.prototype.map.call(trackEls, (t) => t.track); + let tracks = Array.prototype.map.call(trackEls, function(trackEl) { + let json = trackToJson_(trackEl.track); + if (trackEl.src) { + json.src = trackEl.src; + } + return json; + }); + + return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function(track) { + return trackObjs.indexOf(track) === -1; + }).map(trackToJson_)); +}; + +/** + * Creates a set of remote text tracks on a tech based on an array of + * javascript text track representations. + * @param json {Array} an array of text track representation objects, + * like those that would be produced by `textTracksToJson` + * @param tech {tech} the tech to create text tracks on + * @function jsonToTextTracks + */ +let jsonToTextTracks = function(json, tech) { + json.forEach(function(track) { + let addedTrack = tech.addRemoteTextTrack(track).track; + if (!track.src && track.cues) { + track.cues.forEach((cue) => addedTrack.addCue(cue)); + } + }); + + return tech.textTracks(); +}; + +export default {textTracksToJson, jsonToTextTracks, trackToJson_}; diff --git a/pool/shard010/JavaScript/0066830_linkbooktype-plugin.js b/pool/shard010/JavaScript/0066830_linkbooktype-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bb028c84696bcf8de284c01952195f360fbc3f4c --- /dev/null +++ b/pool/shard010/JavaScript/0066830_linkbooktype-plugin.js @@ -0,0 +1,190 @@ +define(['aloha', 'aloha/plugin', 'jquery', 'jquery19', 'ui/ui', 'aloha/console', 'aloha/ephemera', 'booktype', 'underscore'], + function(Aloha, Plugin, jQuery, jQuery19, UI, Console, Ephemera, booktype, _) { + var $a = null, + range = null, + editable = null, + selectedLinkDomObj = null; + + var getContainerAnchor = function (a) { + var el = a; + + while (el) { + if (el.nodeName.toLowerCase() === 'a') { + return el; + } + + el = el.parentNode; + } + + return false; + }; + + var destroyPopup = function () { + if (selectedLinkDomObj) { + jQuery19(selectedLinkDomObj).popover('destroy'); + selectedLinkDomObj = null; + } + }; + + return Plugin.create('linkBooktype', { + init: function () { + + Aloha.bind('aloha-link-selected', function (event) { + var range = event.target.Selection.rangeObject, + limit = Aloha.activeEditable.obj, + $lnk = getContainerAnchor(range.startContainer), + linkContent = ''; + + if (!$lnk) { + return; + } + + if ($lnk === selectedLinkDomObj) { + return; + } else { + destroyPopup(); + } + + var url = jQuery19($lnk).attr('href'); + + if (url.indexOf('../') === 0) { + linkContent = url; + } else { + linkContent = ""; + } + + if (!selectedLinkDomObj) { + selectedLinkDomObj = $lnk; + + jQuery19(selectedLinkDomObj).popover({html: true, + placement: 'top', + trigger: 'manual', + content: linkContent + }); + jQuery19(selectedLinkDomObj).popover('show'); + } + }); + + Aloha.bind('aloha-link-unselected', function (event) { + destroyPopup(); + }); + + Aloha.bind('aloha-editable-deactivated', function (event) { + destroyPopup(); + }); + + // link to chapters + jQuery19('.linktochapter-header i').click( function () { + jQuery19(this).closest('.linktochapter').toggleClass('open'); + }); + + jQuery19('#newLink').on('show.bs.modal', function () { + var $dialog = jQuery19('#newLink'); + + jQuery19('.linktochapter-content UL', $dialog).empty(); + + _.each(booktype.editor.data.chapters.chapters, function (item) { + var $link = jQuery19('
  • ' + item.get('title') + '
  • '); + + jQuery19('a', $link).on('click', function () { + jQuery19('#newLink INPUT[name=url]').val('../' + item.get('urlTitle') + '/'); + + return false; + }); + + jQuery19('.linktochapter-content UL', $dialog).append($link); + }); + + jQuery19('.linktochapter .linktochapter-content li a').click(function () { + jQuery19(this).closest('ul').find('li a').removeClass('selected'); + jQuery19(this).addClass('selected'); + }); + }); + + jQuery19('#newLink').on('hide.bs.modal', function () { + jQuery19('.linktochapter').removeClass('open'); + jQuery19('.linktochapter .linktochapter-content ul').find('li a').removeClass('selected'); + }); + + jQuery19("#newLink BUTTON.operation-unlink").on('click', function() { + if ($a !== null) { + var a = $a.get(0); + + newRange = new GENTICS.Utils.RangeObject(); + newRange.startContainer = newRange.endContainer = a.parentNode; + newRange.startOffset = GENTICS.Utils.Dom.getIndexInParent(a); + newRange.endOffset = newRange.startOffset + 1; + newRange.select(); + + GENTICS.Utils.Dom.removeFromDOM(a, newRange, true); + + newRange.startContainer = newRange.endContainer; + newRange.startOffset = newRange.endOffset; + newRange.select(); + + jQuery19('#newLink').modal('hide'); + } + }); + + jQuery19('#newLink BUTTON.operation-insert').on('click', function () { + var title = jQuery19('#newLink INPUT[name=title]').val(), + url = jQuery19('#newLink INPUT[name=url]').val(); + + if(jQuery19.trim(title) !== '' && jQuery19.trim(url) !== '') { + if ($a == null) { + $a = jQuery('').prop('href', url).text(title); + + GENTICS.Utils.Dom.removeRange(range); + GENTICS.Utils.Dom.insertIntoDOM($a, range, editable.obj); + } else { + $a.prop('href', url).text(title); + } + + jQuery19('#newLink').modal('hide'); + range.select(); + } + }); + + UI.adopt('insertLink', null, { + click: function () { + editable = Aloha.activeEditable; + range = Aloha.Selection.getRangeObject(); + var a = getContainerAnchor(range.startContainer); + + if (a) { + $a = jQuery(a); + range.startContainer = range.endContainer = a; + range.startOffset = 0; + range.endOffset = a.childNodes.length; + range.select(); + + jQuery19('#newLink INPUT[name=title]').val(jQuery(a).text()); + jQuery19('#newLink INPUT[name=url]').val(a.getAttribute('href', 2)); + jQuery19('#newLink .operation-unlink').prop('disabled', false); + } else { + if (_.isEmpty(range)) { + return; + } + + $a = null; + + GENTICS.Utils.Dom.extendToWord(range); + + jQuery19('#newLink INPUT[name=title]').val(range.getText() || ''); + jQuery19('#newLink INPUT[name=url]').val(''); + + jQuery19('#newLink .operation-unlink').prop('disabled', true); + } + + jQuery19('#newLink').modal('show'); + } + }); + }, + + makeClean: function (obj) { + jQuery('div.popover.fade.top').remove(); + } + }); + } +); diff --git a/pool/shard010/JavaScript/0066834_Users.js b/pool/shard010/JavaScript/0066834_Users.js new file mode 100644 index 0000000000000000000000000000000000000000..62f20a3042c9f3773522e2fd0ec95590ac820b64 --- /dev/null +++ b/pool/shard010/JavaScript/0066834_Users.js @@ -0,0 +1,26 @@ +import React from 'react'; +import Toggle from 'material-ui/Toggle'; + +const styles = { + toggle: { + marginBottom: 10, + marginTop: 10 + } +}; + +const Users = ({ users, handleUserChange }) => { + return ( +
    + {users.map(user => )} +
    + ); +}; + +export default Users; diff --git a/pool/shard010/JavaScript/0066836_XmlDocument.js b/pool/shard010/JavaScript/0066836_XmlDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..deabeef8b4be9574011a21b70cf6d9fe6e5debfa --- /dev/null +++ b/pool/shard010/JavaScript/0066836_XmlDocument.js @@ -0,0 +1,69 @@ +'use strict'; + +const XmlElement = require('./XmlElement'); +const XmlNode = require('./XmlNode'); + +/** +Represents an XML document. All elements within the document are descendants of +this node. + +@public +*/ +class XmlDocument extends XmlNode { + /** + @param {Array} [children] + */ + constructor(children = []) { + super(); + + /** + Child nodes of this document. + + @type {Array} + @public + */ + this.children = children; + } + + get document() { + return this; + } + + /** + Root element of this document, or `null` if this document is empty. + + @type {XmlElement?} + @public + */ + get root() { + // @ts-ignore + return this.children.find((child) => child instanceof XmlElement) || null; + } + + /** + Text content of this document and all its descendants. + + @type {string} + @public + */ + get text() { + return this.children + .map(child => 'text' in child ? child.text : '') + .join(''); + } + + get type() { + return XmlNode.TYPE_DOCUMENT; + } + + toJSON() { + return Object.assign(XmlNode.prototype.toJSON.call(this), { + children: this.children.map(child => child.toJSON()), + }); + } +} + +module.exports = XmlDocument; + +/** @typedef {import('./XmlComment')} XmlComment */ +/** @typedef {import('./XmlProcessingInstruction')} XmlProcessingInstruction */ diff --git a/pool/shard010/JavaScript/0066839_express.js b/pool/shard010/JavaScript/0066839_express.js new file mode 100644 index 0000000000000000000000000000000000000000..7db18d9c0f60a800cfb05d476e9f083cd6353677 --- /dev/null +++ b/pool/shard010/JavaScript/0066839_express.js @@ -0,0 +1,123 @@ +/** + * Express Configuration + */ + +import bodyParser from 'body-parser'; +import compression from 'compression'; +import busboy from 'connect-busboy'; +import cors from 'cors'; +import errorHandler from 'errorhandler'; +import cookieParser from 'cookie-parser'; +import express from 'express'; +import expressSession from 'express-session'; +import methodOverride from 'method-override'; +import passport from 'passport'; +import { + join +} +from 'path'; +import favicon from 'serve-favicon'; +import * as config from './environment'; +import redis from 'connect-redis'; +import flash from 'connect-flash'; + +const requestLogger = require('../lib/logger/requestLogger'), + responseLogger = require('../lib/logger/responseLogger'); +export default (app) => { + + let env = app.get('env'); + // Enable logger (morgan) + //app.use(dexter(logger.getLogFormat(), logger.getLogOptions())); + + app.engine('html', require('ejs').renderFile); + app.set('view engine', 'html'); + app.use(requestLogger); /* log all requests and responses */ + app.use(responseLogger); + /** + * @name TopShelf#sessionStorage + * @description + * Connect-compatible {@link https://www.npmjs.org/package/connect-redis | redis sessions` storage } used by + * {@link TopShelf#express Express application } and {@link TopShelf#io Socket.io server } + */ + + const sessionMiddleware = new (redis(expressSession))({ + host: 'localhost', + port: 6379 + }); + + // always bodyParser before cookie, method or session + // parse application/x-www-form-urlencoded + + app.use(bodyParser.json()); + app.use(bodyParser.urlencoded({ + extended: true + })); + app.use(cookieParser(config.session.secret)); + app.use(cors()); + // parse application/json + + app.use(methodOverride()); + app.enable('jsonp callback'); + + app.set('appPath', join(config.root, 'client')); + app.use(busboy()); + + app.use(expressSession({ + store: sessionMiddleware, + key: 'tsg.sid', + secret: config.session.secret, + resave: true, + saveUninitialized: true, + cookie: { + secure: false, + maxAge: 7 * 24 * 60 * 60 * 1000 + } + })); + + // Passport OAUTH Middleware + app.use(passport.initialize()); + app.use(passport.session()); + + app.all('/*', function(req, res, next) { + // CORS headers + res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain + res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); + // Set custom headers for CORS + res.header('Access-Control-Allow-Headers', 'Content-type,Accept'); + // If someone calls with method OPTIONS, let's display the allowed methods on our API + if (req.method === 'OPTIONS') { + res.status(200); + res.write("Allow: GET,PUT,POST,DELETE,OPTIONS"); + res.end(); + } else { + next(); + } + }); + + // time in milliseconds... + const minute = 1000 * 60; // 60000 + const hour = (minute * 60); // 3600000 + const day = (hour * 24); // 86400000 + const week = (day * 7); // 604800000 + + app.use(flash()); + // Security Settings + app.disable('x-powered-by'); + app.enable('trust proxy'); + + if (env === 'production') { + app.use(compression()); + app.use(favicon(join(config.root, 'client', 'favicon.ico'))); + app.use(express.static(app.get('appPath'), { + maxAge: week + })); + } + + if (env === 'development' || env === 'test') { + app.use(express.static('./src/client/')); + app.use(express.static('./')); + app.use(express.static('./.tmp/')); + app.use(express.static('./.build/')); + app.use(errorHandler()); // Error handler - has to be last + } +}; diff --git a/pool/shard010/JavaScript/0066841_deletevalue.js b/pool/shard010/JavaScript/0066841_deletevalue.js new file mode 100644 index 0000000000000000000000000000000000000000..49005cff0913e97ee09fdec159d4f7849352dda4 --- /dev/null +++ b/pool/shard010/JavaScript/0066841_deletevalue.js @@ -0,0 +1,312 @@ +/* + * Copyright 2015 Basho Technologies, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var CommandBase = require('../commandbase'); +var inherits = require('util').inherits; +var Joi = require('joi'); + +/** + * Provides the DeleteValue class and its builder + * @module KV + */ + + +/** + * Command used to delete a value from Riak. + * + * As a convenience, a builder class is provided: + * + * var deleteValue = new DeleteValue.Builder() + * .withBucket('myBucket') + * .withKey('myKey') + * .withVClock(vclock) + * .withCallback(callback) + * .build(); + * + * See {{#crossLink "DeleteValue.Builder"}}DeleteValue.Builder{{/crossLink}} + * @class DeleteValue + * @constructor + * @param {Object} options The options for this command. + * @param {String} [options.bucketType=default] The bucket type in Riak. If not suppled 'default' is used. + * @param {String} options.bucket The bucket in Riak. + * @param {String} options.key The key for the object you want to delete. + * @param {Buffer} [options.vclock] The vector clock to use. + * @param {Number} [options.timeout] Set a timeout for this operation. + * @param {Number} [options.r] The R value to use. + * @param {Number} [options.pr] The PR value to use. + * @param {Number} [options.w] The W value to use. + * @param {Number} [options.dw] The DW value to use. + * @param {Number} [options.pw] The PW value to use. + * @param {Number} [options.rw] The RW value to use. + * @param {Function} callback The callback to be executed when the operation completes. + * @param {String} callback.err An error message. Will be null on no error. + * @param {Boolean} callback.response the response from Riak. Will be true unless there was an error. + * @extends CommandBase + */ +function DeleteValue(options, callback) { + CommandBase.call(this, 'RpbDelReq', 'RpbDelResp', callback); + var self = this; + Joi.validate(options, schema, function(err, options) { + + if (err) { + throw err; + } + + self.options = options; + + }); + + this.remainingRetries = 1; +} + + + +inherits(DeleteValue, CommandBase); + +DeleteValue.prototype.constructPbRequest = function() { + + var protobuf = this.getPbReqBuilder(); + + protobuf.setBucket(new Buffer(this.options.bucket)); + protobuf.setType(new Buffer(this.options.bucketType)); + protobuf.setKey(new Buffer(this.options.key)); + + if (this.options.hasOwnProperty('vclock')) { + protobuf.setVclock(this.options.vclock); + } + + if (this.options.hasOwnProperty('w')) { + protobuf.setW(this.options.w); + } + + if (this.options.hasOwnProperty('dw')) { + protobuf.setDw(this.options.dw); + } + + if (this.options.hasOwnProperty('pw')) { + protobuf.setPw(this.options.pw); + } + + if (this.options.hasOwnProperty('r')) { + protobuf.setR(this.options.r); + } + if (this.options.hasOwnProperty('pr')) { + protobuf.setPr(this.options.pr); + } + + if (this.options.hasOwnProperty('rw')) { + protobuf.setRw(this.options.rw); + } + + if (this.options.hasOwnProperty('timeout')) { + protobuf.setTimeout(this.options.timeout); + } + + return protobuf; + +}; + +DeleteValue.prototype.onSuccess = function(rpbGetResp) { + + // There is no body to a RpbDelResp. RpbDelReq either + // succeeds or returns an error. rpbDelResp will always be null + this._callback(null, true); + return true; + +}; + +var schema = Joi.object().keys({ + bucket: Joi.string().required(), + bucketType: Joi.string().default('default'), + key: Joi.binary().required(), + r: Joi.number().optional(), + pr: Joi.number().optional(), + w: Joi.number().optional(), + dw: Joi.number().optional(), + pw: Joi.number().optional(), + rw: Joi.number().optional(), + timeout: Joi.number().default(null), + vclock: Joi.binary().optional() +}); + +/** + * A builder for constructing DeleteValue instances. + * + * Rather than having to manually construct the __options__ and instantiating + * a DeleteValue directly, this builder may be used. + * + * var deleteValue = new DeleteValue.Builder() + * .withBucket('myBucket') + * .withKey('myKey') + * .withVClock(vclock) + * .withCallback(callback) + * .build(); + * + * @class DeleteValue.Builder + * @constructor + */ +function Builder() { + +} + +Builder.prototype = { + + /** + * Set the bucket. + * @method withBucket + * @param {String} bucket the bucket in Riak + * @chainable + */ + withBucket : function(bucket) { + this.bucket = bucket; + return this; + }, + /** + * Set the bucket type. + * If not supplied, 'default' is used. + * @method withBucketType + * @param {String} bucketType the bucket type in riak + * @chainable + */ + withBucketType : function(bucketType) { + this.bucketType = bucketType; + return this; + }, + /** + * Set the key. + * @method withKey + * @param {String} key the key in riak. + * @chainable + */ + withKey : function(key) { + this.key = key; + return this; + }, + /** + * Set the R value. + * If not set the bucket default is used. + * @method withR + * @param {Number} r the R value. + * @chainable + */ + withR : function(r) { + this.r = r; + return this; + }, + /** + * Set the PR value. + * If not set the bucket default is used. + * @method withPr + * @param {Number} pr the PR value. + * @chainable + */ + withPr : function(pr) { + this.pr = pr; + return this; + }, + /** + * Set the W value. + * How many replicas to write to before returning a successful response. + * If not set the bucket default is used. + * @method withW + * @param {number} w the W value. + * @chainable + */ + withW : function(w) { + this.w = w ; + return this; + }, + /** + * Set the DW value. + * How many replicas to commit to durable storage before returning a successful response. + * If not set the bucket default is used. + * @method withDw + * @param {number} dw the DW value. + * @chainable + */ + withDw : function(dw) { + this.dw = dw; + return this; + }, + /** + * Set the PW value. + * How many primary nodes must be up when the write is attempted. + * If not set the bucket default is used. + * @method withPw + * @param {number} pw the PW value. + * @chainable + */ + withPw : function(pw) { + this.pw = pw; + return this; + }, + /** + * Set the RW value. + * Quorum for both operations (get and put) involved in deleting an object . + * @method withRw + * @param {number} rw the RW value. + * @chainable + */ + withRw : function(rw) { + this.rw = rw; + return this; + }, + /** + * Set the vector clock. + * If not set siblings may be created depending on bucket properties. + * @method withVClock + * @param {Buffer} vclock a vector clock returned from a previous fetch + */ + withVClock : function(vclock) { + this.vclock = vclock; + return this; + }, + /** + * Set a timeout for this operation. + * @method withTimeout + * @param {Number} timeout a timeout in milliseconds. + * @chainable + */ + withTimeout : function(timeout) { + this.timeout = timeout; + return this; + }, + /** + * Set the callback to be executed when the operation completes. + * @method withCallback + * @param {Function} callback The callback to be executed when the operation completes. + * @param {String} callback.err An error message. Will be null on no error. + * @param {Boolean} callback.response the response from Riak. Will be true unless there was an error. + * @chainable + */ + withCallback : function(callback) { + this.callback = callback; + return this; + }, + /** + * Construct a DeleteValue command. + * @method build + * @return {DeleteValue} an instance of DeleteValue + */ + build : function() { + var cb = this.callback; + delete this.callback; + return new DeleteValue(this, cb); + } +}; + +module.exports = DeleteValue; +module.exports.Builder = Builder; diff --git a/pool/shard010/JavaScript/0066843_ParametersParser.js b/pool/shard010/JavaScript/0066843_ParametersParser.js new file mode 100644 index 0000000000000000000000000000000000000000..3ebe94e4d580f5f4d87fd80c4762cd1d9b241a22 --- /dev/null +++ b/pool/shard010/JavaScript/0066843_ParametersParser.js @@ -0,0 +1,77 @@ +/* + * TeleStax, Open Source Cloud Communications Copyright 2012. + * and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +/* + * Implementation of the JAIN-SIP ParametersParser . + * @see gov/nist/javax/sip/parser/ParametersParser.java + * @author Yuemin Qin (yuemin.qin@orange.com) + * @author Laurent STRULLU (laurent.strullu@orange.com) + * @version 1.0 + * + */ +function ParametersParser() { + if(logger!=undefined) logger.debug("ParametersParser"); + this.classname="ParametersParser"; + if(typeof arguments[0]=="object") + { + var lexer=arguments[0]; + this.lexer = lexer; + this.lexer.selectLexer("command_keywordLexer"); + } + else if(typeof arguments[0]=="string") + { + var buffer=arguments[0]; + this.lexer = new Lexer("command_keywordLexer", buffer); + } +} + +ParametersParser.prototype = new HeaderParser(); +ParametersParser.prototype.constructor=ParametersParser; + +ParametersParser.prototype.parse =function(parametersHeader){ + if(logger!=undefined) logger.debug("ParametersParser:parse():parametersHeader="+parametersHeader); + this.lexer.SPorHT(); + while (this.lexer.lookAhead(0) == ';') { + this.lexer.consume(1); + this.lexer.SPorHT(); + var nv = this.nameValue(); + parametersHeader.setParameter_nv(nv); + this.lexer.SPorHT(); + } +} +ParametersParser.prototype.parseNameValueList =function(parametersHeader){ + if(logger!=undefined) logger.debug("ParametersParser:parseNameValueList():parametersHeader="+parametersHeader); + parametersHeader.removeParameters(); + while (true) { + this.lexer.SPorHT(); + var nv = nameValue(); + + parametersHeader.setParameter(nv.getName(), nv.getValueAsObject()); + this.lexer.SPorHT(); + if (this.lexer.lookAhead(0) != ';') { + break; + } + else { + this.lexer.consume(1); + } + } +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066852_retweeters.js b/pool/shard010/JavaScript/0066852_retweeters.js new file mode 100644 index 0000000000000000000000000000000000000000..6f12c9ed5bb6f7622e2978d1647532cef94ca909 --- /dev/null +++ b/pool/shard010/JavaScript/0066852_retweeters.js @@ -0,0 +1,17 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retweeters = exports.optionsSchema = void 0; +const joi_1 = __importDefault(require("@hapi/joi")); +exports.optionsSchema = joi_1.default.object().keys({ + id: joi_1.default.string().min(0).required(), + count: joi_1.default.number().integer().min(0), + cursor: joi_1.default.string().min(0), + stringify_ids: joi_1.default.boolean(), +}); +function retweeters(callHandler, options) { + return callHandler.callTwitterApiWithSchema('statuses/retweeters/ids', options, exports.optionsSchema); +} +exports.retweeters = retweeters; diff --git a/pool/shard010/JavaScript/0066855_bootstrap-init.js b/pool/shard010/JavaScript/0066855_bootstrap-init.js new file mode 100644 index 0000000000000000000000000000000000000000..c09bfdbd97bb41f9b0ff8968f4c9a9a9cb7806e7 --- /dev/null +++ b/pool/shard010/JavaScript/0066855_bootstrap-init.js @@ -0,0 +1,146 @@ +;(function() { + "use strict"; + + jQuery(document).ready(function($) { + + // Initialize some variables + var accordion = Joomla.getOptions('bootstrap.accordion'), + alert = Joomla.getOptions('bootstrap.alert'), + button = Joomla.getOptions('bootstrap.button'), + carousel = Joomla.getOptions('bootstrap.carousel'), + dropdown = Joomla.getOptions('bootstrap.dropdown'), + modal = $('.joomla-modal'), + popover = Joomla.getOptions('bootstrap.popover'), + scrollspy = Joomla.getOptions('bootstrap.scrollspy'), + tabs = Joomla.getOptions('bootstrap.tabs'), + tooltip = Joomla.getOptions('bootstrap.tooltip'); + + /** Accordion **/ + if (accordion) { + $.each(accordion, function(index, value) { + $('#' + index).collapse( + { + parent:value.parent, + toggle:value.toggle + } + ).on("show", new Function(value.onShow)()) + .on("shown", new Function(value.onShown)()) + .on("hideme", new Function(value.onHide)()) + .on("hidden", new Function(value.onHidden)()); + }); + } + + /** Alert **/ + if (alert) { + $.each(alert, function(index, value) { + $('#' + index).alert(); + }); + } + + /** Button **/ + if (button) { + $.each(button, function(index, value) { + $('#' + index).button(); + }); + } + + /** Carousel **/ + if (carousel) { + $.each(carousel, function(index, value) { + $('#' + index).carousel( + { + interval: value.interval ? value.interval : 5000, + pause: value.pause ? value.pause : 'hover' + } + ); + }); + } + + /** Dropdown menu **/ + if (dropdown) { + $.each(dropdown, function(index, value) { + $('#' + index).dropdown(); + }); + } + + /** Modals **/ + if (modal.length) { + $.each($('.joomla-modal'), function() { + var $self = $(this); + $self.on('show.bs.modal', function() { + if ($self.data('url')) { + var modalBody = $self.find('.modal-body'); + modalBody.find('iframe').remove(); + modalBody.prepend($self.data('iframe')); + } + }).on('shown.bs.modal', function() { + var modalHeight = $('div.modal:visible').outerHeight(true), + modalHeaderHeight = $('div.modal-header:visible').outerHeight(true), + modalBodyHeightOuter = $('div.modal-body:visible').outerHeight(true), + modalBodyHeight = $('div.modal-body:visible').height(), + modalFooterHeight = $('div.modal-footer:visible').outerHeight(true), + padding = $self.offsetTop, + maxModalHeight = ($(window).height()-(padding*2)), + modalBodyPadding = (modalBodyHeightOuter-modalBodyHeight), + maxModalBodyHeight = maxModalHeight-(modalHeaderHeight+modalFooterHeight+modalBodyPadding); + if ($self.data('url')) { + var iframeHeight = $('.iframe').height(); + if (iframeHeight > maxModalBodyHeight){ + $('.modal-body').css({'max-height': maxModalBodyHeight, 'overflow-y': 'auto'}); + $('.iframe').css('max-height', maxModalBodyHeight-modalBodyPadding); + } + } else { + if (modalHeight > maxModalHeight){ + $('.modal-body').css({'max-height': maxModalBodyHeight, 'overflow-y': 'auto'}); + } + } + }).on('hide.bs.modal', function () { + $('.modal-body').css({'max-height': 'initial', 'overflow-y': 'initial'}); + $('.modalTooltip').tooltip('destroy'); + }); + }); + } + + /** Popover **/ + if (popover) { + $.each(popover, function(index, value) { + value.constraints = [value.constraints]; + $(index).popover(value); + }); + } + + /** Scrollspy **/ + if (scrollspy) { + $.each(scrollspy, function(index, value) { + $('#' + index).scrollspy(value); + }); + } + + /** Tabs **/ + if (tabs) { + $.each(tabs, function(index, value) { + + $.each($('#' + index + 'Content').find('.tab-pane'), function(i, v) { + if ($(v).data('node')) { + var attribs = $(v).data('node').split('['), + classLink = (attribs[0] != '') ? 'class="nav-link ' + attribs[0] + '"' : 'class="nav-link"'; + + $('#' + index + 'Tabs').append('
    '); + } + }); + }); + } + + /** Tooltip **/ + if (tooltip) { + $.each(tooltip, function(index, value) { + value.constraints = [value.constraints]; + $(index).tooltip(value) + .on("show.bs.tooltip", new Function(value.onShow)()) + .on("shown.bs.tooltip", new Function(value.onShown)()) + .on("hide.bs.tooltip", new Function(value.onHide)()) + .on("hidden.bs.tooltip", new Function(value.onHidden)()); + }); + } + }); +})(); diff --git a/pool/shard010/JavaScript/0066858_strip_host.spec.js b/pool/shard010/JavaScript/0066858_strip_host.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..39681533aee3254f84a48ded6a091f9afde30e16 --- /dev/null +++ b/pool/shard010/JavaScript/0066858_strip_host.spec.js @@ -0,0 +1,61 @@ +import mocks from 'mocks' + +describe('middleware.strip_host', function () { + var nextSpy + var HttpRequestMock = mocks.http.ServerRequest + + var createStripHostMiddleware = require('../../../lib/middleware/strip_host').create + + var handler = nextSpy = null + + beforeEach(function () { + nextSpy = sinon.spy() + handler = createStripHostMiddleware(null, null, '/base/path') + return handler + }) + + it('should strip request with IP number', function (done) { + var request = new HttpRequestMock('http://192.12.31.100/base/a.js?123345') + handler(request, null, nextSpy) + + expect(request.normalizedUrl).to.equal('/base/a.js?123345') + expect(nextSpy).to.have.been.called + return done() + }) + + it('should strip request with absoluteURI', function (done) { + var request = new HttpRequestMock('http://localhost/base/a.js?123345') + handler(request, null, nextSpy) + + expect(request.normalizedUrl).to.equal('/base/a.js?123345') + expect(nextSpy).to.have.been.called + return done() + }) + + it('should strip request with absoluteURI and port', function (done) { + var request = new HttpRequestMock('http://localhost:9876/base/a.js?123345') + handler(request, null, nextSpy) + + expect(request.normalizedUrl).to.equal('/base/a.js?123345') + expect(nextSpy).to.have.been.called + return done() + }) + + it('should strip request with absoluteURI over HTTPS', function (done) { + var request = new HttpRequestMock('https://karma-runner.github.io/base/a.js?123345') + handler(request, null, nextSpy) + + expect(request.normalizedUrl).to.equal('/base/a.js?123345') + expect(nextSpy).to.have.been.called + return done() + }) + + return it('should return same url as passed one', function (done) { + var request = new HttpRequestMock('/base/b.js?123345') + handler(request, null, nextSpy) + + expect(request.normalizedUrl).to.equal('/base/b.js?123345') + expect(nextSpy).to.have.been.called + return done() + }) +}) diff --git a/pool/shard010/JavaScript/0066860_register.js b/pool/shard010/JavaScript/0066860_register.js new file mode 100644 index 0000000000000000000000000000000000000000..953176ba2c42bb7ebf2559935f1db4098ddb9532 --- /dev/null +++ b/pool/shard010/JavaScript/0066860_register.js @@ -0,0 +1,48 @@ +'use strict'; + +angular.module('myApp.register', ['ui.router','firebase']) + +// Declared route +.config(function($stateProvider, $urlRouterProvider) { + $stateProvider.state('register', { + url: "/register", + templateUrl: "register/register.html", + controller: 'RegisterCtrl' + }); +}) + +// Register controller +.controller('RegisterCtrl', ['$scope','$location','$firebaseAuth', function($scope,$location,$firebaseAuth) { + var firebaseObj = new Firebase("https://art-app.firebaseio.com"); + var auth = $firebaseAuth(firebaseObj); + var login={}; + $scope.login=login; + $scope.signUp = function() { + if (!$scope.regForm.$invalid) { + login.loading = true; + var email = $scope.user.email; + var password = $scope.user.password; + if (email && password) { + auth.$createUser({ + email: email, + password: password + }) + .then(function() { + console.log('User creation success'); + login.loading = false; + $location.path('/login'); + }, function(error) { + console.log(error); + login.loading = false; + $scope.regError = true; + $scope.regErrorMessage = error.message; + }); + } + } + }; + + $scope.logout = function(){ + CommonProp.logoutUser(); + } + +}]); diff --git a/pool/shard010/JavaScript/0066866_run_v8.js b/pool/shard010/JavaScript/0066866_run_v8.js new file mode 100644 index 0000000000000000000000000000000000000000..8c3edbddc8b02f4e9381101631f08ef00361a9f3 --- /dev/null +++ b/pool/shard010/JavaScript/0066866_run_v8.js @@ -0,0 +1,12 @@ +#!/usr/local/bin/node + +global.performance = { now: function () { + var t = process.hrtime(); + return t[0] * 1000 + t[1] / 1000000; +} } + +test = "bench_" + (process.argv[2] || "all"); +path = process.argv[3] || "./target/datascript.js"; + +require(path); +datascript.bench[test](); diff --git a/pool/shard010/JavaScript/0066867_bdate-input.js b/pool/shard010/JavaScript/0066867_bdate-input.js new file mode 100644 index 0000000000000000000000000000000000000000..e8a0c4ef502784743be9b3eb11c83a6fbee6350a --- /dev/null +++ b/pool/shard010/JavaScript/0066867_bdate-input.js @@ -0,0 +1,55 @@ +import React from 'react'; +import { DatePicker } from 'react-persian-datepicker'; +import moment from 'moment-jalaali'; + +import 'react-persian-datepicker/lib/styles/basic.css'; + +const styles = { + calendarContainer: 'calendarContainer', + heading: 'heading', + prev: 'prev', + next: 'next', + title: 'title', + dayWrapper: 'dayWrapper', + currentMonth: 'currentMonth', + daysOfWeek: 'daysOfWeek', + monthsList: 'monthsList', + selected: 'selected', + dayPickerContainer: 'dayPickerContainer' +}; + +export default class BDateInput extends React.Component { + constructor(props) { + super(props); + + this.value = (props.value || moment()).toString(); + + this.state = { value: moment('Thu Feb 02 1000 06:17:17 GMT+0330') }; + + this.onDateChange = (value) => { + this.value = value.toString(); + this.setState({ value }); + this.props.onChange(value) + } + + } + + // fired after value props changed + componentWillReceiveProps(nextProps) { + this.value=nextProps.value; + this.setState({ value: moment(nextProps.value) }); + } + // fired after state changed + shouldComponentUpdate(nextProps, nextState) { + return ((this.state.value|| moment()).toString() !== (nextState.value|| moment()).toString() )|| + (this.value !== nextProps.value ) ; + } + // fired after component render + componentDidUpdate() { + // this.onChange(this.state.value); + } + + render() { + return ; + } +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066869_editor.js b/pool/shard010/JavaScript/0066869_editor.js new file mode 100644 index 0000000000000000000000000000000000000000..aec8e66ffa4fb718315ce16f09b49a5bdca82a03 --- /dev/null +++ b/pool/shard010/JavaScript/0066869_editor.js @@ -0,0 +1,161 @@ +import React from 'react'; +import { + compose, + getContext +} from 'recompose'; +import { connect } from 'react-redux'; +import MapSearch from '../components/map-search'; +import T from '../components/t'; +import config from '../config'; + +import { + setMapPosition +} from '../redux/modules/map'; + +import ORFrameNotifier from '../../../OR_frame_notifier'; + +var Editor = React.createClass({ + displayName: 'Editor', + + propTypes: { + setMapPosition: React.PropTypes.func, + lng: React.PropTypes.number, + lat: React.PropTypes.number, + zoom: React.PropTypes.number, + language: React.PropTypes.string.isRequired, + way: React.PropTypes.string + }, + + // ///////////////////////////////////////////////////////////////////////////// + // / Message listener (postMessage) + // / + // / When receiving a message form the iframe, process the url and set it. + // / The url now becomes shareable. The action to take on the url will depend on + // / the app. + // / + // / The switch is done based on the app id, defined when the OR_frame_notifier + // / is included. + // / + // / + // / What this actually does: + // / When a the iframe's url changes it is sent via postMessage to the parent. It + // / removes the base portion on the url (defined in the config) and stores + // / the rest: + // / - Url on the "editor" changes to: + // / http://devseed.com/editor/#background=something + // / - Prefix is removed resulting in: + // / #background=something + // / - Appended to the current url: + // / http://devseed.com/openroads/#/editor/background=something + // / - When entering the page, everything after (/#/editor/) + // / is sent to the iframe alongside the proper prefix. + // / + messageListener: function (e) { + // TODO: This is not working with the new version od ORFrameNotifier + if (e.data.type === 'urlchange') { + switch (e.data.id) { + case 'or-editor': + this.hash = e.data.url.replace(new RegExp(`(http:|https:)?${config.editorUrl}/?#?`), ''); + // TODO: reconcile how params are surfaced upto the app. don't dispatch anything upto the app for now. + // this.props.dispatch(replace(`/${this.props.language}/editor/${this.hash}`)); + break; + } + } else if (e.data.type === 'navigate') { + switch (e.data.id) { + case 'or-editor': + // TODO: reconcile how params are surfaced upto the app. don't dispatch anything upto the app for now. + // this.props.dispatch(push(e.data.url)); + break; + } + } + }, + + componentWillReceiveProps: function ({ lng, lat, zoom, way }) { + // this.props.setMapPosition(lng, lat, zoom, way); + const mapCenter = [lng, lat]; + if (lng !== this.props.lng || lat !== this.props.lat) { + this.orFrame.send('setPosition', { + center: mapCenter, + zoom + }); + } + if (way && way !== this.props.way) { + setTimeout(() => { + this.orFrame.send('setPosition', { + center: mapCenter, + zoom, + way + }); + }, 1000); + } + }, + + componentDidMount: function () { + this.orFrame = new ORFrameNotifier('orma-vn', this.refs.editor.contentWindow); + + this.orFrame.on('loaded', () => { + const mapPositionHash = /center=([0-9.]+\/[0-9.]+)&?/.exec(this.props.location.search); + let mapCenter = [108.239, 15.930]; + let zoom = 6; + if (mapPositionHash && mapPositionHash[1] && mapPositionHash[1].split('/').length === 2) { + mapCenter = mapPositionHash[1].split('/'); + zoom = 14.5; + } + + this.orFrame.send('settings', { + center: mapCenter, + zoom + }); + }); + }, + + componentWillUnmount: function () { + this.orFrame.destroy(); + }, + + render: function () { + return ( +
    +
    +
    +
    +

    Editor

    +
    +
    + +
    +
    +
    +
    +
    +
    + '; + $('.open-course-views').html(html); + }) + }, + onClickHeader: function () { + $('.tab-header').on('click', function () { + var $this = $(this); + var index = $this.index(); + $this.addClass('active').siblings().removeClass('active'); + $('#content').find('ul').eq(index).show().siblings().hide(); + }); + }, + isEsVedio: function () { + if ($('#lesson-preview-player').html() == "") { + $('.embed-responsive-16by9').addClass('masks') + } + + }, + removeMask: function () { + setTimeout(main.isEsVedio, 1500); + } +} + +main.init(); + +if (!$('#open-course-comment').find('[type=submit]').hasClass('disabled')) { + var threadShowWidget = new ThreadShowWidget({ + element: '#open-course-comment', + }); +} diff --git a/pool/shard010/JavaScript/0066874_admin.js b/pool/shard010/JavaScript/0066874_admin.js new file mode 100644 index 0000000000000000000000000000000000000000..99ecee6d210000bd71ad9a7d9088726922dea860 --- /dev/null +++ b/pool/shard010/JavaScript/0066874_admin.js @@ -0,0 +1,26 @@ +define('admin/plugins/sso-beam', ['settings'], function (Settings) { + 'use strict'; + /* globals $, app, socket, require */ + + var ACP = {}; + + ACP.init = function () { + Settings.load('sso-beam', $('.sso-beam-settings')); + + $('#save').on('click', function () { + Settings.save('sso-beam', $('.sso-beam-settings'), function () { + app.alert({ + type: 'success', + alert_id: 'sso-beam-saved', + title: 'Settings Saved', + message: 'Please reload your NodeBB to apply these settings', + clickfn: function () { + socket.emit('admin.reload'); + } + }); + }); + }); + }; + + return ACP; +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066876_modules.js b/pool/shard010/JavaScript/0066876_modules.js new file mode 100644 index 0000000000000000000000000000000000000000..eaf9e124cacbb79f76b5548e85e0a83fc0452c26 --- /dev/null +++ b/pool/shard010/JavaScript/0066876_modules.js @@ -0,0 +1,30 @@ +/* global Translation */ + +const uninstallModule = (url, name) => { + if (confirm(Translation.AskForUninstallPackage.replace("%name%", name))) { + $.ajax({ + url: url, + success: () => { + $("li#dataset-module-" + name).slideUp(); + } + }); + } + return false; +}; +const uninstallTheme = (url, name) => { + if (confirm(Translation.AskForUninstallPackage.replace("%name%", "theme-" + + name))) { + $.ajax({ + url: url, + success: () => + $("li#dataset-theme-" + name).slideUp() + }); + } + return false; +}; + +$("form#truncate_installed_patches").ajaxForm( + { + success: () => + $("div#inst_patch_slide_container").slideUp() + }); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066878_websocket.controller.test.js b/pool/shard010/JavaScript/0066878_websocket.controller.test.js new file mode 100644 index 0000000000000000000000000000000000000000..0f4396fd94a297a6aa78022e5c2906c027a8cd44 --- /dev/null +++ b/pool/shard010/JavaScript/0066878_websocket.controller.test.js @@ -0,0 +1,119 @@ +describe('Controller: WebSocketController', function () { + 'use strict'; + + var $scope, dataStream, message; + + beforeEach(module('waldenrainesdotcom.code')); + + beforeEach(inject(function ($controller, $rootScope) { + var $websocket; + + dataStream = { + error: false, + close: function () {}, + send: function () {}, + onMessage: function (callback) { + callback(message); + }, + onError: function (callback) { + if (this.error) { + callback(); + } + }, + onOpen: function (callback) { + if (!this.error) { + callback(); + } + } + }; + + $websocket = function () { + return dataStream; + }; + + $scope = $rootScope.$new(); + message = {}; + + $controller('WebSocketController', { + $scope: $scope, + $websocket: $websocket + }); + })); + + describe('connects to the WebSocket', function () { + beforeEach(function () { + spyOn(dataStream, 'onOpen').and.callThrough(); + spyOn(dataStream, 'onError').and.callThrough(); + }); + + it("and succeeds", function () { + $scope.connect(); + + expect(dataStream.onOpen).toHaveBeenCalledWith(jasmine.any(Function)); + expect($scope.connectionOpen).toBe(true); + expect($scope.connectionError).toBe(false); + }); + + it("and fails", function () { + dataStream.error = true; + + $scope.connect(); + + expect(dataStream.onError).toHaveBeenCalledWith(jasmine.any(Function)); + expect($scope.connectionError).toBe(true); + expect($scope.connectionOpen).toBe(false); + }); + + describe("and receives messages", function () { + beforeEach(function () { + spyOn(dataStream, 'onMessage').and.callThrough(); + }); + + afterEach(function () { + expect(dataStream.onMessage).toHaveBeenCalledWith(jasmine.any(Function)); + }); + + it("and adds them to the message list if formatted correctly", function () { + message = {data: 'lalala'}; + + $scope.connect(); + + expect($scope.messages.indexOf(message.data)).toBe(0); + }); + + it("and does nothing if the message is formatted incorrectly", function () { + message = 'lalala'; + $scope.connect(); + expect($scope.messages.indexOf(message)).toBe(-1); + + message = null; + $scope.connect(); + expect($scope.messages.indexOf(message)).toBe(-1); + }); + }); + }); + + it('closes the WebSocket connection', function () { + spyOn(dataStream, 'close'); + + $scope.connect(); + $scope.closeConnection(); + + expect(dataStream.close).toHaveBeenCalled(); + expect($scope.connectionOpen).toBe(false); + expect($scope.messages.length).toBe(0); + }); + + it('sends a message', function () { + var message = 'hello'; + + spyOn(dataStream, 'send'); + + $scope.connect(); + $scope.sendMessage(message); + + expect(dataStream.send).toHaveBeenCalledWith(message); + expect($scope.messages.indexOf(message)).toBe(0); + expect($scope.newMessage).toBe(null); + }); +}); diff --git a/pool/shard010/JavaScript/0066879_event-delegate-debug.js b/pool/shard010/JavaScript/0066879_event-delegate-debug.js new file mode 100644 index 0000000000000000000000000000000000000000..4523c703e6ab1197a017a446b48531f257c8a1ef --- /dev/null +++ b/pool/shard010/JavaScript/0066879_event-delegate-debug.js @@ -0,0 +1,327 @@ +/* +YUI 3.4.1 (build 4118) +Copyright 2011 Yahoo! Inc. All rights reserved. +Licensed under the BSD License. +http://yuilibrary.com/license/ +*/ +YUI.add('event-delegate', function(Y) { + +/** + * Adds event delegation support to the library. + * + * @module event + * @submodule event-delegate + */ + +var toArray = Y.Array, + YLang = Y.Lang, + isString = YLang.isString, + isObject = YLang.isObject, + isArray = YLang.isArray, + selectorTest = Y.Selector.test, + detachCategories = Y.Env.evt.handles; + +/** + *

    Sets up event delegation on a container element. The delegated event + * will use a supplied selector or filtering function to test if the event + * references at least one node that should trigger the subscription + * callback.

    + * + *

    Selector string filters will trigger the callback if the event originated + * from a node that matches it or is contained in a node that matches it. + * Function filters are called for each Node up the parent axis to the + * subscribing container node, and receive at each level the Node and the event + * object. The function should return true (or a truthy value) if that Node + * should trigger the subscription callback. Note, it is possible for filters + * to match multiple Nodes for a single event. In this case, the delegate + * callback will be executed for each matching Node.

    + * + *

    For each matching Node, the callback will be executed with its 'this' + * object set to the Node matched by the filter (unless a specific context was + * provided during subscription), and the provided event's + * currentTarget will also be set to the matching Node. The + * containing Node from which the subscription was originally made can be + * referenced as e.container. + * + * @method delegate + * @param type {String} the event type to delegate + * @param fn {Function} the callback function to execute. This function + * will be provided the event object for the delegated event. + * @param el {String|node} the element that is the delegation container + * @param spec {string|Function} a selector that must match the target of the + * event or a function to test target and its parents for a match + * @param context optional argument that specifies what 'this' refers to. + * @param args* 0..n additional arguments to pass on to the callback function. + * These arguments will be added after the event object. + * @return {EventHandle} the detach handle + * @for YUI + */ +function delegate(type, fn, el, filter) { + var args = toArray(arguments, 0, true), + query = isString(el) ? el : null, + typeBits, synth, container, categories, cat, i, len, handles, handle; + + // Support Y.delegate({ click: fnA, key: fnB }, context, filter, ...); + // and Y.delegate(['click', 'key'], fn, context, filter, ...); + if (isObject(type)) { + handles = []; + + if (isArray(type)) { + for (i = 0, len = type.length; i < len; ++i) { + args[0] = type[i]; + handles.push(Y.delegate.apply(Y, args)); + } + } else { + // Y.delegate({'click', fn}, context, filter) => + // Y.delegate('click', fn, context, filter) + args.unshift(null); // one arg becomes two; need to make space + + for (i in type) { + if (type.hasOwnProperty(i)) { + args[0] = i; + args[1] = type[i]; + handles.push(Y.delegate.apply(Y, args)); + } + } + } + + return new Y.EventHandle(handles); + } + + typeBits = type.split(/\|/); + + if (typeBits.length > 1) { + cat = typeBits.shift(); + args[0] = type = typeBits.shift(); + } + + synth = Y.Node.DOM_EVENTS[type]; + + if (isObject(synth) && synth.delegate) { + handle = synth.delegate.apply(synth, arguments); + } + + if (!handle) { + if (!type || !fn || !el || !filter) { + Y.log("delegate requires type, callback, parent, & filter", "warn"); + return; + } + + container = (query) ? Y.Selector.query(query, null, true) : el; + + if (!container && isString(el)) { + handle = Y.on('available', function () { + Y.mix(handle, Y.delegate.apply(Y, args), true); + }, el); + } + + if (!handle && container) { + args.splice(2, 2, container); // remove the filter + + handle = Y.Event._attach(args, { facade: false }); + handle.sub.filter = filter; + handle.sub._notify = delegate.notifySub; + } + } + + if (handle && cat) { + categories = detachCategories[cat] || (detachCategories[cat] = {}); + categories = categories[type] || (categories[type] = []); + categories.push(handle); + } + + return handle; +} + +/** +Overrides the _notify method on the normal DOM subscription to +inject the filtering logic and only proceed in the case of a match. + +This method is hosted as a private property of the `delegate` method +(e.g. `Y.delegate.notifySub`) + +@method notifySub +@param thisObj {Object} default 'this' object for the callback +@param args {Array} arguments passed to the event's fire() +@param ce {CustomEvent} the custom event managing the DOM subscriptions for + the subscribed event on the subscribing node. +@return {Boolean} false if the event was stopped +@private +@static +@since 3.2.0 +**/ +delegate.notifySub = function (thisObj, args, ce) { + // Preserve args for other subscribers + args = args.slice(); + if (this.args) { + args.push.apply(args, this.args); + } + + // Only notify subs if the event occurred on a targeted element + var currentTarget = delegate._applyFilter(this.filter, args, ce), + //container = e.currentTarget, + e, i, len, ret; + + if (currentTarget) { + // Support multiple matches up the the container subtree + currentTarget = toArray(currentTarget); + + // The second arg is the currentTarget, but we'll be reusing this + // facade, replacing the currentTarget for each use, so it doesn't + // matter what element we seed it with. + e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); + + e.container = Y.one(ce.el); + + for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { + e.currentTarget = Y.one(currentTarget[i]); + + ret = this.fn.apply(this.context || e.currentTarget, args); + + if (ret === false) { // stop further notifications + break; + } + } + + return ret; + } +}; + +/** +Compiles a selector string into a filter function to identify whether +Nodes along the parent axis of an event's target should trigger event +notification. + +This function is memoized, so previously compiled filter functions are +returned if the same selector string is provided. + +This function may be useful when defining synthetic events for delegate +handling. + +Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). + +@method compileFilter +@param selector {String} the selector string to base the filtration on +@return {Function} +@since 3.2.0 +@static +**/ +delegate.compileFilter = Y.cached(function (selector) { + return function (target, e) { + return selectorTest(target._node, selector, e.currentTarget._node); + }; +}); + +/** +Walks up the parent axis of an event's target, and tests each element +against a supplied filter function. If any Nodes, including the container, +satisfy the filter, the delegated callback will be triggered for each. + +Hosted as a protected property of the `delegate` method (e.g. +`Y.delegate._applyFilter`). + +@method _applyFilter +@param filter {Function} boolean function to test for inclusion in event + notification +@param args {Array} the arguments that would be passed to subscribers +@param ce {CustomEvent} the DOM event wrapper +@return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter +@protected +**/ +delegate._applyFilter = function (filter, args, ce) { + var e = args[0], + container = ce.el, // facadeless events in IE, have no e.currentTarget + target = e.target || e.srcElement, + match = [], + isContainer = false; + + // Resolve text nodes to their containing element + if (target.nodeType === 3) { + target = target.parentNode; + } + + // passing target as the first arg rather than leaving well enough alone + // making 'this' in the filter function refer to the target. This is to + // support bound filter functions. + args.unshift(target); + + if (isString(filter)) { + while (target) { + isContainer = (target === container); + if (selectorTest(target, filter, (isContainer ?null: container))) { + match.push(target); + } + + if (isContainer) { + break; + } + + target = target.parentNode; + } + } else { + // filter functions are implementer code and should receive wrappers + args[0] = Y.one(target); + args[1] = new Y.DOMEventFacade(e, container, ce); + + while (target) { + // filter(target, e, extra args...) - this === target + if (filter.apply(args[0], args)) { + match.push(target); + } + + if (target === container) { + break; + } + + target = target.parentNode; + args[0] = Y.one(target); + } + args[1] = e; // restore the raw DOM event + } + + if (match.length <= 1) { + match = match[0]; // single match or undefined + } + + // remove the target + args.shift(); + + return match; +}; + +/** + * Sets up event delegation on a container element. The delegated event + * will use a supplied filter to test if the callback should be executed. + * This filter can be either a selector string or a function that returns + * a Node to use as the currentTarget for the event. + * + * The event object for the delegated event is supplied to the callback + * function. It is modified slightly in order to support all properties + * that may be needed for event delegation. 'currentTarget' is set to + * the element that matched the selector string filter or the Node returned + * from the filter function. 'container' is set to the element that the + * listener is delegated from (this normally would be the 'currentTarget'). + * + * Filter functions will be called with the arguments that would be passed to + * the callback function, including the event object as the first parameter. + * The function should return false (or a falsey value) if the success criteria + * aren't met, and the Node to use as the event's currentTarget and 'this' + * object if they are. + * + * @method delegate + * @param type {string} the event type to delegate + * @param fn {function} the callback function to execute. This function + * will be provided the event object for the delegated event. + * @param el {string|node} the element that is the delegation container + * @param filter {string|function} a selector that must match the target of the + * event or a function that returns a Node or false. + * @param context optional argument that specifies what 'this' refers to. + * @param args* 0..n additional arguments to pass on to the callback function. + * These arguments will be added after the event object. + * @return {EventHandle} the detach handle + * @for YUI + */ +Y.delegate = Y.Event.delegate = delegate; + + +}, '3.4.1' ,{requires:['node-base']}); diff --git a/pool/shard010/JavaScript/0066880_sqliteQuerier.js b/pool/shard010/JavaScript/0066880_sqliteQuerier.js new file mode 100644 index 0000000000000000000000000000000000000000..85b0a47397374279db8acdd82fdc4112155947dc --- /dev/null +++ b/pool/shard010/JavaScript/0066880_sqliteQuerier.js @@ -0,0 +1,36 @@ +const sqlite3 = require('sqlite3').verbose() + +const SqliteQuerier = function (config) { + this.sqliteStorage = config.sqliteStorage +} + +SqliteQuerier.prototype.execute = function ( + query, + rowCallback, + completeCallback +) { + const db = new sqlite3.Database(this.sqliteStorage, openErr => { + if (openErr) return completeCallback(openErr) + let rowErrOccurred + db.each( + query, + (rowErr, row) => { + if (rowErrOccurred) return + if (rowErr) { + rowErrOccurred = rowErr + return + } + rowCallback(row) + }, + err => { + db.close(closeErr => { + completeCallback(err || closeErr) + }) + } + ) + }) +} + +module.exports = function (config) { + return new SqliteQuerier(config) +} diff --git a/pool/shard010/JavaScript/0066881_rectype_reject.js b/pool/shard010/JavaScript/0066881_rectype_reject.js new file mode 100644 index 0000000000000000000000000000000000000000..098c81b327955e122b23523e90e39066df043aff --- /dev/null +++ b/pool/shard010/JavaScript/0066881_rectype_reject.js @@ -0,0 +1,38 @@ +// Uncomment this line to run in Node.js +/* var print = function(s) { process.stdout.write(s+"\n"); } */ + +/**************************************************************************** + * length can be typed either as: mu a. { tl : a } -> int + * or as: mu a. { hd : int, tl : a } -> int + * or (also) as: { tl : mu a. { hd : int, tl : a } } -> int + * PROBLEM: the first type is incomparable with the last two. + * (the last two are comparable with each other using unrolling and + * width subtyping) + * This test should typecheck without the call of length on l0 or on l3: + * see ../endtoend/recursivelist.js + ****************************************************************************/ +var length = function(l) { + if (l == null) { + return 0; + } else { + return 1+length(l.tl); + } +} + +/* This block requires that length types as: + * mu a. { tl : a } -> int + */ +var l0 = { tl : { tl : null } } +var len0 = length(l0) +print(len0+"") + +/* This block requires that length types as: + * mu a. { hd : int, tl : a } -> int OR + * { tl : mu a. { hd : int, tl : a } } -> int + */ +var l3 = { hd : 3, tl : { hd : 2, tl : null } } +l3.hd = 4 +l3.tl.hd = 5 +var len3 = length(l3) +print(len3+"") + diff --git a/pool/shard010/JavaScript/0066885_index.js b/pool/shard010/JavaScript/0066885_index.js new file mode 100644 index 0000000000000000000000000000000000000000..55c9c8e79ea11445341d28fdc59884c17cebed27 --- /dev/null +++ b/pool/shard010/JavaScript/0066885_index.js @@ -0,0 +1,154 @@ +/** + * Copyright 2013, 2016 IBM Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +var when = require("when"); +var path = require("path"); +var fs = require("fs"); + +var registry = require("./registry"); +var credentials = require("./credentials"); +var flows = require("./flows"); +var context = require("./context"); +var Node = require("./Node"); +var log = require("../log"); + +var events = require("../events"); + +var child_process = require('child_process'); + +var settings; + +/** + * Registers a node constructor + * @param nodeSet - the nodeSet providing the node (module/set) + * @param type - the string type name + * @param constructor - the constructor function for this node type + * @param opts - optional additional options for the node + */ +function registerType(nodeSet,type,constructor,opts) { + if (typeof type !== "string") { + // This is someone calling the api directly, rather than via the + // RED object provided to a node. Log a warning + log.warn("["+nodeSet+"] Deprecated call to RED.runtime.nodes.registerType - node-set name must be provided as first argument"); + opts = constructor; + constructor = type; + type = nodeSet; + nodeSet = ""; + } + if (opts && opts.credentials) { + credentials.register(type,opts.credentials); + } + registry.registerType(nodeSet,type,constructor); +} + +/** + * Called from a Node's constructor function, invokes the super-class + * constructor and attaches any credentials to the node. + * @param node the node object being created + * @param def the instance definition for the node + */ +function createNode(node,def) { + Node.call(node,def); + var id = node.id; + if (def._alias) { + id = def._alias; + } + var creds = credentials.get(id); + if (creds) { + //console.log("Attaching credentials to ",node.id); + node.credentials = creds; + } else if (credentials.getDefinition(node.type)) { + node.credentials = {}; + } +} + +function init(runtime) { + settings = runtime.settings; + credentials.init(runtime); + flows.init(runtime); + registry.init(runtime); + context.init(runtime.settings); +} + +function disableNode(id) { + flows.checkTypeInUse(id); + return registry.disableNode(id); +} + +function uninstallModule(module) { + var info = registry.getModuleInfo(module); + if (!info) { + throw new Error(log._("nodes.index.unrecognised-module", {module:module})); + } else { + for (var i=0;i +

    +
    + +
    +
    +

    {this.getI18N("PanelTitle")}

    +
    +
    +
    + + +
    + +
    +
    +

    {this.getI18N("TextBetweenButtons")}

    +
    +
    + {this.getI18N("SignUpButton")} +
    + +
    +
    + +
    + +
    +
    +
    + ); + } +}); + diff --git a/pool/shard010/JavaScript/0066889_jenkins.js b/pool/shard010/JavaScript/0066889_jenkins.js new file mode 100644 index 0000000000000000000000000000000000000000..987601f795720aeb5de40ee9b0529574933e2fd3 --- /dev/null +++ b/pool/shard010/JavaScript/0066889_jenkins.js @@ -0,0 +1,174 @@ +/* +Copyright [2016] [Relevance Lab] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +var jenkinsApi = require('jenkins-api'); +var logger = require('_pr/logger')(module); +var url = require('url'); +var fs = require('fs'); +var Client = require('node-rest-client').Client; + + + +var Jenkins = function(options) { + var parsedUrl = url.parse(options.url); + var jenkinsUrl = parsedUrl.protocol + '//'; + if (options.username) { + jenkinsUrl += options.username; + var pass = options.password ? options.password : options.token; + jenkinsUrl += ':' + pass + '@'; + } + + jenkinsUrl += parsedUrl.host + parsedUrl.path; + var jenkins = jenkinsApi.init(jenkinsUrl); + + this.getJobs = function(callback) { + jenkins.all_jobs(function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }); + }; + + this.getJobInfo = function(jobName, callback) { + jenkins.job_info(jobName, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }) + } + + this.buildJob = function(jobName, callback) { + jenkins.build(jobName, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }); + }; + + + this.buildJobWithParams = function(jobName, params, callback) { + + jenkins.build(jobName, params, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + if (data.statusCode && data.statusCode === 500 || data.statusCode === 404) { + callback({ + statusCode: data.statusCode + }, null); + } else { + callback(null, data); + } + + }); + + }; + + this.getBuildInfo = function(jobName, buildNumber, callback) { + jenkins.build_info(jobName, buildNumber, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }); + }; + + this.getLastBuildInfo = function(jobName, callback) { + jenkins.last_build_info(jobName, function(err, data) { + if (err) { + logger.error(err, data); + callback(err, null); + return; + } + callback(null, data); + }); + }; + + + this.getJobLastBuildReport = function(jobName, callback) { + jenkins.last_build_report(jobName, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }); + } + + this.getJobOutput = function(jobName, buildName, callback) { + jenkins.job_output(jobName, buildName, function(err, data) { + if (err) { + logger.error(err); + callback(err, null); + return; + } + callback(null, data); + }); + }; + + this.getJobsBuildNumber = function(jobName, callback) { + jenkins.last_build_info(jobName, function(err, data) { + if (err) { + logger.error(err); + callback(null, {}); + return; + } + callback(null, data); + }); + }; + + this.updateJob = function(jobName, callback) { + //var config = fs.readFileSync("/home/gobinda/Gobinda/config.xml", 'ascii'); + jenkins.update_job(jobName, function(config) {}, function(err, data) { + if (err) { + logger.debug("Error while updating job in jenkins: ", err); + callback(err, null); + } + logger.debug("Update success jenkins job: ", JSON.stringify(data)); + callback(null, data); + }); + + }; + this.getDepthJobInfo = function(jobName, callback) { + var options_auth = { + user: options.username, + password: options.password + }; + client = new Client(options_auth); + var jenkinsUrl1 = parsedUrl.href + 'job/' + jobName + '/api/json?depth=1'; + client.registerMethod("jsonMethod", jenkinsUrl1, "GET"); + client.methods.jsonMethod(function(data, response) { + callback(null, data); + }); + } +} + +module.exports = Jenkins; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066891_static.js b/pool/shard010/JavaScript/0066891_static.js new file mode 100644 index 0000000000000000000000000000000000000000..ec09a992eeb741de5f508e311b6bf18013f134fd --- /dev/null +++ b/pool/shard010/JavaScript/0066891_static.js @@ -0,0 +1,51 @@ +import path_lib from "path"; +var { dirname, sep: path_sep } = path_lib; + +import { + src, + dest, + changed, + prefixer, + less, + filter +} from "../gulp"; + +import bower from "../bower"; +import { pipe as jsCompile } from "../js-compile"; +import { compile as tplCompile } from "../tpl-compile"; +import { define } from "../procs"; + +define("static/client", (config)=> { + var cssFilter = filter("**/*.css"), + lessFilter = filter("**/*.less"), + jsFilter = filter(file => + /\.js$/.test(file.path) && + (dirname(file.path).split(path_sep).pop() !== "vendor") && + !(/jquery|hype|\.min\./gi.test(file.path)) + ); + + return src(config.src) + .pipe(changed(config.dest)) + + .pipe(lessFilter) + .pipe(less()) + .pipe(prefixer("last 2 versions", { cascade: false })) + .pipe(lessFilter.restore()) + + .pipe(cssFilter) + .pipe(prefixer("last 2 versions", { cascade: false })) + .pipe(cssFilter.restore()) + + .pipe(jsFilter) + .pipe(jsCompile()) + .pipe(jsFilter.restore()) + + .pipe(dest(config.dest)); +}); + +define("static/vendor", (config)=> + src(config.src) + .pipe(bower(config.vendor)) + .pipe(changed(config.dest)) + .pipe(dest(config.dest)) +); diff --git a/pool/shard010/JavaScript/0066893_dest.js b/pool/shard010/JavaScript/0066893_dest.js new file mode 100644 index 0000000000000000000000000000000000000000..54828827c5acf6400a16482300c294886444bccc --- /dev/null +++ b/pool/shard010/JavaScript/0066893_dest.js @@ -0,0 +1,139 @@ +var gulp = require('../'); +var should = require('should'); +var join = require('path').join; +var rimraf = require('rimraf'); +var fs = require('graceful-fs'); + +require('mocha'); + +describe('gulp output stream', function() { + describe('dest()', function() { + + it('should return a stream', function(done) { + var stream = gulp.dest(join(__dirname, "./fixtures/")); + should.exist(stream); + should.exist(stream.on); + done(); + }); + + it('should return a output stream that writes files', function(done) { + var outpath = join(__dirname, "./out-fixtures"); + rimraf(outpath, function(err){ + should.not.exist(err); + var instream = gulp.src(join(__dirname, "./fixtures/**/*.txt")); + var outstream = gulp.dest(outpath); + instream.pipe(outstream); + + outstream.on('error', done); + outstream.on('data', function(file) { + // data should be re-emitted right + should.exist(file); + should.exist(file.path); + should.exist(file.contents); + join(file.path,'').should.equal(join(__dirname, "./fixtures/copy/example.txt")); + String(file.contents).should.equal("this is a test"); + }); + outstream.on('end', function() { + fs.readFile(join(outpath, "copy", "example.txt"), function(err, contents){ + should.not.exist(err); + should.exist(contents); + String(contents).should.equal("this is a test"); + done(); + }); + }); + }); + }); + + it('should return a output stream that does not write non-read files', function(done) { + var outpath = join(__dirname, "./out-fixtures"); + rimraf(outpath, function(err){ + should.not.exist(err); + var instream = gulp.src(join(__dirname, "./fixtures/**/*.txt"), {read:false}); + var outstream = gulp.dest(outpath); + instream.pipe(outstream); + + outstream.on('error', done); + outstream.on('data', function(file) { + // data should be re-emitted right + should.exist(file); + should.exist(file.path); + should.not.exist(file.contents); + join(file.path,'').should.equal(join(__dirname, "./fixtures/copy/example.txt")); + }); + outstream.on('end', function() { + fs.readFile(join(outpath, "copy", "example.txt"), function(err, contents){ + should.exist(err); + should.not.exist(contents); + done(); + }); + }); + }); + }); + + it('should return a output stream that writes streaming files', function(done) { + var outpath = join(__dirname, "./out-fixtures"); + rimraf(outpath, function(err){ + should.not.exist(err); + var instream = gulp.src(join(__dirname, "./fixtures/**/*.txt"), {buffer:false}); + var outstream = instream.pipe(gulp.dest(outpath)); + + outstream.on('error', done); + outstream.on('data', function(file) { + // data should be re-emitted right + should.exist(file); + should.exist(file.path); + should.exist(file.contents); + join(file.path,'').should.equal(join(__dirname, "./fixtures/copy/example.txt")); + }); + outstream.on('end', function() { + fs.readFile(join(outpath, "copy", "example.txt"), function(err, contents){ + should.not.exist(err); + should.exist(contents); + String(contents).should.equal("this is a test"); + done(); + }); + }); + }); + }); + + it('should return a output stream that writes streaming files into new directories', function(done) { + testWriteDir({}, done); + }); + + it('should return a output stream that writes streaming files into new directories (buffer: false)', function(done) { + testWriteDir({buffer: false}, done); + }); + + it('should return a output stream that writes streaming files into new directories (read: false)', function(done) { + testWriteDir({read: false}, done); + }); + + it('should return a output stream that writes streaming files into new directories (read: false, buffer: false)', function(done) { + testWriteDir({buffer: false, read: false}, done); + }); + + function testWriteDir(srcOptions, done) { + var outpath = join(__dirname, "./out-fixtures"); + rimraf(outpath, function(err){ + should.not.exist(err); + var instream = gulp.src(join(__dirname, "./fixtures/stuff"), srcOptions); + var outstream = instream.pipe(gulp.dest(outpath)); + + outstream.on('error', done); + outstream.on('data', function(file) { + // data should be re-emitted right + should.exist(file); + should.exist(file.path); + join(file.path,'').should.equal(join(__dirname, "./fixtures/stuff")); + }); + outstream.on('end', function() { + fs.exists(join(outpath, "stuff"), function(exists) { + should(exists).ok; + done(); + }); + }); + }); + } + + }); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066896_index.js b/pool/shard010/JavaScript/0066896_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8cbba2c05d9719829bf8e2eb67d9a645bee78111 --- /dev/null +++ b/pool/shard010/JavaScript/0066896_index.js @@ -0,0 +1,322 @@ +/* + * 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/. + */ + +/* + * Copyright 2019 Joyent, Inc. + */ + +/* + * Restify handlers for firewall rules + */ + +'use strict'; + +var clone = require('clone'); +var common = require('../common'); +var mod_err = require('../../errors'); +var mod_persist = require('../../persist'); +var mod_const = require('../../util/constants'); +var restify = require('restify'); +var Rule = require('../../rule').Rule; +var validate = require('restify-warden'); + + +var hasKey = require('jsprim').hasKey; + + +// --- Globals + +var LIST_SCHEMA = { + strict: true, + optional: { + fields: validate.fieldsArray(mod_const.PARSED_FIELDS), + ip: validate.IParray, + owner_uuid: validate.UUIDarray, + protocol: validate.string, + subnet: validate.subnetArray, + vm: validate.UUIDarray, + enabled: validate.boolean, + action: validateAction, + global: validate.boolean, + tag: validateTag, + wildcard: validateArrayOfStrings, + log: validate.boolean + } +}; + +var DELETE_SCHEMA = { + strict: true, + required: { + uuid: validate.UUID + }, + optional: { + owner_uuid: validate.UUID + } +}; + + +// --- Internal + +function validateAction(_, name, act, callback) { + if (typeof (act) !== 'string' || (act !== 'block' && act !== 'allow')) { + callback(mod_err.invalidParam(name, + 'action must be "block" or "allow"')); + return; + } + callback(null, act); +} + +function validateArrayOfStrings(_, name, arr, callback) { + if (typeof (arr) !== 'string') { + var i; + for (i = 0; i < arr.length; i++) { + var s = arr[i]; + if (typeof (s) !== 'string') { + callback(mod_err.invalidParam(name, + 'must be array of strings')); + return; + } + } + } + callback(null, s); +} + +function validateTag(_, name, tag, callback) { + if (Array.isArray(tag) || typeof (tag) === 'string' || + typeof (tag) === 'object') { + + callback(null, tag); + } else { + callback(mod_err.invalidParam(name, + 'must be string, object, or array')); + } +} + + + +/** + * Turns a fwrule error into an InvalidParamsError + */ +function createParamErr(err) { + if (!hasKey(err, 'ase_errors') && !hasKey(err, 'field')) { + return err; + } + + var errs = hasKey(err, 'ase_errors') ? err.ase_errors : [ err ]; + return new mod_err.InvalidParamsError(mod_err.INVALID_MSG, + errs.map(function (e) { + return mod_err.invalidParam(e.field, e.message); + })); +} + + +/** + * Restify 'before' handler: if the rule is global and we have owner_uuid set + * in the request params, return Permission Denied. Requires + * common.ruleBefore() to be run before to populate req._rule. + */ +function disallowOwnerForGlobal(req, res, next) { + var rule = req._rule; + if (!hasKey(rule, 'global') || !rule.global) { + next(); + return; + } + + if (!hasKey(req.params, 'owner_uuid')) { + next(); + return; + } + + next(new mod_err.PermissionDeniedError('owner does not match', + [ mod_err.invalidParam('owner_uuid', 'owner_uuid does not match') ])); +} + + + +// --- Restify handlers + + + +/** + * GET /rules + */ +function listRules(req, res, next) { + validate.params(LIST_SCHEMA, null, req.params, + function cb(valErr, validated) { + var serializeOpts; + if (valErr) { + next(valErr); + return; + } + if (validated.fields) { + serializeOpts = { fields: validated.fields }; + } + mod_persist.findRules(req._app, req.log, req.params, + function (err, rules) { + if (err) { + next(err); + return; + } + + res.send(200, rules.map(function (rule) { + return rule.serialize(serializeOpts); + })); + next(); + return; + }); + }); +} + + +/** + * GET /rules/:uuid + */ +function getRule(req, res, next) { + res.send(200, req._rule.serialize()); + return next(); +} + + +/** + * POST /rules + */ +function createRule(req, res, next) { + if (!req.params.rule) { + next(new restify.MissingParameterError( + '"rule" parameter required')); + return; + } + + mod_persist.createRule(req._app, req.log, req.params, + function (err, rule) { + if (err) { + next(createParamErr(err)); + return; + } + + req._update.queue('fw.add_rule', rule.serialize(), + function (err2, update) { + if (err2) { + return next(err2); + } + + res.header('x-update-id', update.uuid); + res.send(202, rule.serialize()); + return next(); + }); + }); +} + + +/** + * PUT /rules/:uuid + */ +function updateRule(req, res, next) { + var newRule; + var updateParams = clone(req._rule.serialize()); + + for (var p in req.params) { + updateParams[p] = req.params[p]; + } + + // Don't allow updating the rule's UUID + updateParams.uuid = req._rule.uuid; + // Don't allow through objectclass + delete updateParams.objectclass; + + try { + newRule = new Rule(updateParams, req._app); + } catch (e) { + next(createParamErr(e)); + return; + } + + newRule.incrementVersion(); + + mod_persist.updateRule(req._app, req.log, newRule, req._rule, + function (err, rule) { + if (err) { + next(err); + return; + } + + req._update.queue('fw.update_rule', rule.serialize(), + function (err2, update) { + if (err2) { + return next(err2); + } + + res.header('x-update-id', update.uuid); + res.send(202, rule.serialize()); + return next(); + }); + }); +} + + +/** + * DELETE /rules/:uuid + */ +function deleteRule(req, res, next) { + validate.params(DELETE_SCHEMA, null, req.params, + function (valErr, _validated) { + if (valErr) { + next(valErr); + return; + } + + var uuid = req.params.uuid; + mod_persist.deleteRule(req._app, req.log, uuid, function (err) { + if (err) { + next(err); + return; + } + + req._update.queue('fw.del_rule', req._rule.serialize(), + + function (err2, update) { + + if (err2) { + next(err2); + return; + } + + res.header('x-update-id', update.uuid); + res.send(204); + next(); + return; + }); + }); + }); +} + + + +// --- Exports + + + +/** + * Registers endpoints with a restify server + */ +function register(server, before) { + var matchingOwner = before.concat(common.ruleBefore); + + server.get({ path: '/rules', name: 'listRules' }, before, listRules); + server.post({ path: '/rules', name: 'createRule' }, before, createRule); + server.put({ path: '/rules/:uuid', name: 'updateRule' }, + matchingOwner.concat(disallowOwnerForGlobal), updateRule); + server.get({ path: '/rules/:uuid', name: 'getRule' }, + matchingOwner.concat(disallowOwnerForGlobal), getRule); + server.del({ path: '/rules/:uuid', name: 'deleteRule' }, + matchingOwner.concat(disallowOwnerForGlobal), deleteRule); +} + + + +module.exports = { + register: register +}; diff --git a/pool/shard010/JavaScript/0066897_listarContempladosEditalCtrl.js b/pool/shard010/JavaScript/0066897_listarContempladosEditalCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..ce64b0c469bc366f2db82190a79eefa611df8983 --- /dev/null +++ b/pool/shard010/JavaScript/0066897_listarContempladosEditalCtrl.js @@ -0,0 +1,64 @@ +nutrifApp.controller('listarContempladosEditalCtrl', function ($scope, + $stateParams, $state, $mdToast, diaRefeicaoService) { + + $scope.idEdital = $stateParams.id; + + $scope.alunos = []; + + function carregamentoInicial() { + + if ($scope.idEdital == 0){ + $state.transitionTo('home.listar-edital', {reload: true}); + } + + diaRefeicaoService.getAllByEdital ($scope.idEdital) + .success(function (data, status) { + $scope.alunos = data; + }) + .error(onErrorLoadCallback); + } + + $scope.limparBusca = function () { + $scope.texto = ""; + carregamentoInicial() + }; + + $scope.pesquisar = function (texto) { + if (texto.length > 3) { + if (texto.match(/[a-zA-Z]/i) != null) { + diaRefeicaoService.getAllByEditalAndNomeAluno($scope.idEdital, texto) + .success(function (data, status) { + $scope.alunos = data; + }) + .error(onErrorCallback); + } + } else if (texto.length === 0) { + carregamentoInicial() + } + }; + + function onErrorCallback(data, status) { + var _message = ''; + + if (!data) { + _message = 'Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.' + } else { + _message = data.mensagem + } + + $mdToast.show( + $mdToast.simple() + .textContent(_message) + .position('top right') + .action('OK') + .hideDelay(6000) + ); + } + + function onErrorLoadCallback(data, status) { + onErrorCallback(data, status); + $state.transitionTo('home.listar-edital', {reload: true}); + } + + carregamentoInicial(); +}); diff --git a/pool/shard010/JavaScript/0066900_server.js b/pool/shard010/JavaScript/0066900_server.js new file mode 100644 index 0000000000000000000000000000000000000000..45be23d92f848e7f18f94de2deedbbaa060aa7fa --- /dev/null +++ b/pool/shard010/JavaScript/0066900_server.js @@ -0,0 +1,47 @@ +/* + * IbsenBuzz::server + * @author: Luis Suárez (@Lu1sSuarez) + * @url: https://github.com/IbsenBuzz/ibsen-server-node + * + * @package: IbsenJS + * @file: server.js + */ + +var $express = require('express'); +var $path = require('path'); +var $app = $express(); +var $server = require('http').createServer($app); +var $io = require('socket.io').listen($server); +var $config = { + PORT: 3002, + SERVER: '127.0.0.1' +}; + +$app.use('/static', $express.static(__dirname + '/public')); +$app.set('views', $path.join(__dirname, 'views')); + +$app.use('/', require('./routes/server')); +$app.use('/', require('./routes/buzz')); + +$io.on('connection', function ($socket) { + $socket.emit('IbsenBuzz::server connection', { + id: $socket.id, + connected: true + }); + + $socket.on('IbsenBuzz::server buzz_me', function (data) { + $socket.emit(data.nsp, data.data); + }); + + $socket.on('IbsenBuzz::server buzz', function (data) { + $socket.broadcast.emit(data.nsp, data.data); + }); + + $socket.on('disconnect', function () { + console.log('Disconnect IbsenBuzz::server IO :('); + }); +}); + +$server.listen($config.PORT, $config.SERVER, function () { + console.log('IbsenBuzz::server is running and listening to port %s:%d...', $config.SERVER, $config.PORT); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066902_alphabetical_index_test.js b/pool/shard010/JavaScript/0066902_alphabetical_index_test.js new file mode 100644 index 0000000000000000000000000000000000000000..aae388aa3b7d067044fe29201f6dd99205d92b1c --- /dev/null +++ b/pool/shard010/JavaScript/0066902_alphabetical_index_test.js @@ -0,0 +1,27 @@ +/** + * @file nodeunit test case for "alphabeticalIndex} + * @see {@link https://github.com/caolan/nodeunit | nodeunit} + * + */ + +var alphabeticalIndex = require('../../../../lib/util/alphabetical_index.js'), + testHelper = require('../../../../test/test_helper'); + +exports.setUp = function (done) { + done(); +}; + +exports.tearDown = function (done) { + done(); +}; + +exports['Alphabetical index.'] = function (test) { + test.equal(alphabeticalIndex(0), "a"); + test.equal(alphabeticalIndex(1), "b"); + test.equal(alphabeticalIndex(25), "z"); + test.equal(alphabeticalIndex(26), "aa"); + test.equal(alphabeticalIndex(27), "ab"); + test.equal(alphabeticalIndex(51), "az"); + test.equal(alphabeticalIndex(52), "ba"); + test.done(); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066903_lang.js b/pool/shard010/JavaScript/0066903_lang.js new file mode 100644 index 0000000000000000000000000000000000000000..192a4f15face906e160fc56c71c2e8ebd2bfae1c --- /dev/null +++ b/pool/shard010/JavaScript/0066903_lang.js @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. + * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt + * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt + * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt + * Code distributed by Google as part of the polymer project is also + * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt + */ + +(function(scope) { + + // copy own properties from 'api' to 'prototype, with name hinting for 'super' + function extend(prototype, api) { + if (prototype && api) { + // use only own properties of 'api' + Object.getOwnPropertyNames(api).forEach(function(n) { + // acquire property descriptor + var pd = Object.getOwnPropertyDescriptor(api, n); + if (pd) { + // clone property via descriptor + Object.defineProperty(prototype, n, pd); + // cache name-of-method for 'super' engine + if (typeof pd.value == 'function') { + // hint the 'super' engine + pd.value.nom = n; + } + } + }); + } + return prototype; + } + + + // mixin + + // copy all properties from inProps (et al) to inObj + function mixin(inObj/*, inProps, inMoreProps, ...*/) { + var obj = inObj || {}; + for (var i = 1; i < arguments.length; i++) { + var p = arguments[i]; + try { + for (var n in p) { + copyProperty(n, p, obj); + } + } catch(x) { + } + } + return obj; + } + + // copy property inName from inSource object to inTarget object + function copyProperty(inName, inSource, inTarget) { + var pd = getPropertyDescriptor(inSource, inName); + Object.defineProperty(inTarget, inName, pd); + } + + // get property descriptor for inName on inObject, even if + // inName exists on some link in inObject's prototype chain + function getPropertyDescriptor(inObject, inName) { + if (inObject) { + var pd = Object.getOwnPropertyDescriptor(inObject, inName); + return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName); + } + } + + // exports + + scope.extend = extend; + scope.mixin = mixin; + + // for bc + Platform.mixin = mixin; + +})(Polymer); diff --git a/pool/shard010/JavaScript/0066905_CfopConf.js b/pool/shard010/JavaScript/0066905_CfopConf.js new file mode 100644 index 0000000000000000000000000000000000000000..d9eb72fd008aee37bcbe50e72f71e5f1494f2005 --- /dev/null +++ b/pool/shard010/JavaScript/0066905_CfopConf.js @@ -0,0 +1,377 @@ +/** + * AvaTax Brazil + * The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by business with a physical presence in Brazil. + * + * OpenAPI spec version: 1.0 + * + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/CstIcmsEnum', 'model/IcmsTaxConf', 'model/TaxConf'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./CstIcmsEnum'), require('./IcmsTaxConf'), require('./TaxConf')); + } else { + // Browser globals (root is window) + if (!root.AvaTaxBrazil) { + root.AvaTaxBrazil = {}; + } + root.AvaTaxBrazil.CfopConf = factory(root.AvaTaxBrazil.ApiClient, root.AvaTaxBrazil.CstIcmsEnum, root.AvaTaxBrazil.IcmsTaxConf, root.AvaTaxBrazil.TaxConf); + } +}(this, function(ApiClient, CstIcmsEnum, IcmsTaxConf, TaxConf) { + 'use strict'; + + + + + /** + * The CfopConf model module. + * @module model/CfopConf + * @version 1.0 + */ + + /** + * Constructs a new CfopConf. + * @alias module:model/CfopConf + * @class + * @implements module:model/TaxConf + * @param code {String} main unique identificator + * @param name {String} + */ + var exports = function(code, name) { + var _this = this; + + TaxConf.call(_this, code); + _this['name'] = name; + + + + + + + + + + + + + + }; + + /** + * Constructs a CfopConf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/CfopConf} obj Optional instance to populate. + * @return {module:model/CfopConf} The populated CfopConf instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + TaxConf.constructFromObject(data, obj); + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + if (data.hasOwnProperty('description')) { + obj['description'] = ApiClient.convertToType(data['description'], 'String'); + } + if (data.hasOwnProperty('wayType')) { + obj['wayType'] = ApiClient.convertToType(data['wayType'], 'String'); + } + if (data.hasOwnProperty('codInState')) { + obj['codInState'] = ApiClient.convertToType(data['codInState'], 'Number'); + } + if (data.hasOwnProperty('codOtherState')) { + obj['codOtherState'] = ApiClient.convertToType(data['codOtherState'], 'Number'); + } + if (data.hasOwnProperty('codOtherCountry')) { + obj['codOtherCountry'] = ApiClient.convertToType(data['codOtherCountry'], 'Number'); + } + if (data.hasOwnProperty('cstICMSSameState')) { + obj['cstICMSSameState'] = CstIcmsEnum.constructFromObject(data['cstICMSSameState']); + } + if (data.hasOwnProperty('cstICMSOtherState')) { + obj['cstICMSOtherState'] = CstIcmsEnum.constructFromObject(data['cstICMSOtherState']); + } + if (data.hasOwnProperty('cstICMSOtherCountry')) { + obj['cstICMSOtherCountry'] = CstIcmsEnum.constructFromObject(data['cstICMSOtherCountry']); + } + if (data.hasOwnProperty('productType')) { + obj['productType'] = ApiClient.convertToType(data['productType'], 'String'); + } + if (data.hasOwnProperty('operationToTaxPayerOtherState')) { + obj['operationToTaxPayerOtherState'] = ApiClient.convertToType(data['operationToTaxPayerOtherState'], 'Boolean'); + } + if (data.hasOwnProperty('operationWithST')) { + obj['operationWithST'] = ApiClient.convertToType(data['operationWithST'], 'Boolean'); + } + if (data.hasOwnProperty('operationToFreeZone')) { + obj['operationToFreeZone'] = ApiClient.convertToType(data['operationToFreeZone'], 'Boolean'); + } + if (data.hasOwnProperty('specificForProductClass')) { + obj['specificForProductClass'] = ApiClient.convertToType(data['specificForProductClass'], 'String'); + } + } + return obj; + } + + /** + * @member {String} name + */ + exports.prototype['name'] = undefined; + /** + * @member {String} description + */ + exports.prototype['description'] = undefined; + /** + * inform if the transaction is an operation to internalizing item or value + * @member {module:model/CfopConf.WayTypeEnum} wayType + */ + exports.prototype['wayType'] = undefined; + /** + * CFOP code (tax code operation) when the transactions are within the same state. + * @member {Number} codInState + */ + exports.prototype['codInState'] = undefined; + /** + * CFOP code (tax code operation) when the transactions are to another state. + * @member {Number} codOtherState + */ + exports.prototype['codOtherState'] = undefined; + /** + * CFOP code (tax code operation) when the transactions are to another country. + * @member {Number} codOtherCountry + */ + exports.prototype['codOtherCountry'] = undefined; + /** + * @member {module:model/CstIcmsEnum} cstICMSSameState + */ + exports.prototype['cstICMSSameState'] = undefined; + /** + * @member {module:model/CstIcmsEnum} cstICMSOtherState + */ + exports.prototype['cstICMSOtherState'] = undefined; + /** + * @member {module:model/CstIcmsEnum} cstICMSOtherCountry + */ + exports.prototype['cstICMSOtherCountry'] = undefined; + /** + * this field is used to define right CFOP, one operation type can be specialized to item product, item merchandise or generic + * @member {module:model/CfopConf.ProductTypeEnum} productType + */ + exports.prototype['productType'] = undefined; + /** + * field used to indicate an operation to ICMS tax payer + * @member {Boolean} operationToTaxPayerOtherState + */ + exports.prototype['operationToTaxPayerOtherState'] = undefined; + /** + * field used to indicate an operation to items sibject to ICMS-ST + * @member {Boolean} operationWithST + */ + exports.prototype['operationWithST'] = undefined; + /** + * field used to indicate an operation to free zone + * @member {Boolean} operationToFreeZone + */ + exports.prototype['operationToFreeZone'] = undefined; + /** + * field used to indicate an operation to some product class specifically + * @member {module:model/CfopConf.SpecificForProductClassEnum} specificForProductClass + */ + exports.prototype['specificForProductClass'] = undefined; + + // Implement TaxConf interface: + /** + * main unique identificator + * @member {String} code + */ +exports.prototype['code'] = undefined; + + /** + * Inform that the process has inventory impact. + * @member {Boolean} stockImpact + */ +exports.prototype['stockImpact'] = undefined; + + /** + * Inform that the process has financial impact. + * @member {Boolean} financialImpact + */ +exports.prototype['financialImpact'] = undefined; + + /** + * Inform if this process is subject to IPI taxation on output process - 'T' # TAXABLE - 'Z' # TAXABLE WITH RATE=0.00 - 'E' # EXEMPT - 'H' # SUSPENDED - 'N' # NO TAXABLE - 'I' # IMMUNE - 'O' # OTHER - 'OZ' # OTHER AND ZERO VALUES + * @member {module:model/TaxConf.CstIPIEnum} cstIPI + */ +exports.prototype['cstIPI'] = undefined; + + /** + * Legal tax classificação for IPI (enquadramento) When the processo has CST IPI 52 or 54, is mandatory inform Reason Code, see Anexo XIV - Código de Enquadramento Legal do IPI from http://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=mCnJajU4BKU= + * @member {String} ipiLegalTaxClass + */ +exports.prototype['ipiLegalTaxClass'] = undefined; + + /** + * Inform if this item by nature is subject to PIS taxation or exempt - 'T' # TAXABLE - 'Z' # TAXABLE WITH RATE=0.00 - 'E' # EXEMPT - 'H' # SUSPENDED - 'N' # NO TAXABLE - 'O' # OTHER - 'OZ'# OTHER AND ZERO VALUES + * @member {module:model/TaxConf.AccruablePISTaxationEnum} accruablePISTaxation + */ +exports.prototype['accruablePISTaxation'] = undefined; + + /** + * Reference to a tax reason record ID. + * @member {String} pisExemptLegalReasonCode + */ +exports.prototype['pisExemptLegalReasonCode'] = undefined; + + /** + * When specifi reason, this field has the description + * @member {String} pisExemptLegalReason + */ +exports.prototype['pisExemptLegalReason'] = undefined; + + /** + * Inform if this item by nature is subject to COFINS taxation or exempt - 'T' # TAXABLE - 'Z' # TAXABLE WITH RATE=0.00 - 'E' # EXEMPT - 'H' # SUSPENDED - 'N' # NO TAXABLE - 'O' # OTHER - 'OZ' # OTHER AND ZERO VALUES + * @member {module:model/TaxConf.AccruableCOFINSTaxationEnum} accruableCOFINSTaxation + */ +exports.prototype['accruableCOFINSTaxation'] = undefined; + + /** + * When exempt, taxable with zero, suspended, not taxable, this field holds the official code number + * @member {String} cofinsExemptLegalReasonCode + */ +exports.prototype['cofinsExemptLegalReasonCode'] = undefined; + + /** + * When specifi reason, this field has the description + * @member {String} cofinsExemptLegalReason + */ +exports.prototype['cofinsExemptLegalReason'] = undefined; + + /** + * Inform that the process allow IPI credit to Input process + * @member {Boolean} allowIPIcreditWhenInGoing + */ +exports.prototype['allowIPIcreditWhenInGoing'] = undefined; + + /** + * the map key is state code + * @member {Array.} icmsConf + */ +exports.prototype['icmsConf'] = undefined; + + + /** + * Allowed values for the wayType property. + * @enum {String} + * @readonly + */ + exports.WayTypeEnum = { + /** + * value: "in" + * @const + */ + "in": "in", + /** + * value: "out" + * @const + */ + "out": "out" }; + + /** + * Allowed values for the productType property. + * @enum {String} + * @readonly + */ + exports.ProductTypeEnum = { + /** + * value: "FOR PRODUCT" + * @const + */ + "FOR PRODUCT": "FOR PRODUCT", + /** + * value: "FOR MERCHANDISE" + * @const + */ + "FOR MERCHANDISE": "FOR MERCHANDISE", + /** + * value: "NO RESTRICTION" + * @const + */ + "NO RESTRICTION": "NO RESTRICTION" }; + + /** + * Allowed values for the specificForProductClass property. + * @enum {String} + * @readonly + */ + exports.SpecificForProductClassEnum = { + /** + * value: "OTHERS" + * @const + */ + "OTHERS": "OTHERS", + /** + * value: "COMMUNICATION" + * @const + */ + "COMMUNICATION": "COMMUNICATION", + /** + * value: "ENERGY" + * @const + */ + "ENERGY": "ENERGY", + /** + * value: "TRANSPORT" + * @const + */ + "TRANSPORT": "TRANSPORT", + /** + * value: "FUEL AND LUBRICANT" + * @const + */ + "FUEL AND LUBRICANT": "FUEL AND LUBRICANT", + /** + * value: "VEHICLE" + * @const + */ + "VEHICLE": "VEHICLE", + /** + * value: "ALCOHOLIC BEVERAGES" + * @const + */ + "ALCOHOLIC BEVERAGES": "ALCOHOLIC BEVERAGES", + /** + * value: "WEAPONS" + * @const + */ + "WEAPONS": "WEAPONS", + /** + * value: "AMMO" + * @const + */ + "AMMO": "AMMO", + /** + * value: "PERFUME" + * @const + */ + "PERFUME": "PERFUME", + /** + * value: "TOBACCO" + * @const + */ + "TOBACCO": "TOBACCO" }; + + + return exports; +})); + + diff --git a/pool/shard010/JavaScript/0066906_15.2.3.6-4-540-9.js b/pool/shard010/JavaScript/0066906_15.2.3.6-4-540-9.js new file mode 100644 index 0000000000000000000000000000000000000000..f50732dbd2594c36649a53b024aa91fbcf191776 --- /dev/null +++ b/pool/shard010/JavaScript/0066906_15.2.3.6-4-540-9.js @@ -0,0 +1,37 @@ +/// Copyright (c) 2012 Ecma International. All rights reserved. +/// Ecma International makes this code available under the terms and conditions set +/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the +/// "Use Terms"). Any redistribution of this code must retain the above +/// copyright and this notice and otherwise comply with the Use Terms. +/** + * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-540-9.js + * @description ES5 Attributes - Updating a named accessor property 'P' using simple assignment is successful, 'A' is an Array object (8.12.5 step 5.b) + */ + + +function testcase() { + var obj = []; + + obj.verifySetFunc = "data"; + var getFunc = function () { + return obj.verifySetFunc; + }; + + var setFunc = function (value) { + obj.verifySetFunc = value; + }; + + Object.defineProperty(obj, "prop", { + get: getFunc, + set: setFunc, + enumerable: true, + configurable: false + }); + + obj.prop = "overrideData"; + var propertyDefineCorrect = obj.hasOwnProperty("prop"); + var desc = Object.getOwnPropertyDescriptor(obj, "prop"); + + return propertyDefineCorrect && desc.set === setFunc && obj.verifySetFunc === "overrideData"; + } +runTestCase(testcase); diff --git a/pool/shard010/JavaScript/0066907_cmd.js b/pool/shard010/JavaScript/0066907_cmd.js new file mode 100644 index 0000000000000000000000000000000000000000..78c77310932c17a2428a9f956cb8a1cfd7bcf9ba --- /dev/null +++ b/pool/shard010/JavaScript/0066907_cmd.js @@ -0,0 +1,23 @@ +var p = require('bluebird'); +var spawn = require('child_process').spawn; + +module.exports = function (cmd) { + var ls = spawn('/bin/sh', ["-c", cmd]); + var temp = p.defer() + + ls.stdout.on('data', function (data) { + console.log('stdout: ' + data); + }); + + ls.stderr.on('data', function (data) { + console.log('stderr: ' + data); + }); + + ls.on('close', function (code) { + console.log('child process exited with code ' + code); + temp.resolve(true) + }); + + return temp.promise; + +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066910_TrackTransform.js b/pool/shard010/JavaScript/0066910_TrackTransform.js new file mode 100644 index 0000000000000000000000000000000000000000..7a4c0197fd600bcce9767d1af865677085e28972 --- /dev/null +++ b/pool/shard010/JavaScript/0066910_TrackTransform.js @@ -0,0 +1,113 @@ +import { connect } from 'react-redux' +import React, { Component } from 'react' +import { + Accordion, + Card +} from 'react-bootstrap' +import InputOption from '../../components/InputOption' +import { + toggleTrack, + toggleTrackGrow, + updateLayer +} from '../layers/layersSlice' +import { getCurrentLayer } from '../layers/selectors' +import Transform from '../../models/Transform' + +const mapStateToProps = (state, ownProps) => { + const layer = getCurrentLayer(state) + + return { + layer: layer, + active: layer.trackEnabled, + activeGrow: layer.trackGrowEnabled, + options: new Transform().getOptions() + } +} + +const mapDispatchToProps = (dispatch, ownProps) => { + const { id } = ownProps + + return { + onChange: (attrs) => { + attrs.id = id + dispatch(updateLayer(attrs)) + }, + onTrack: () => { + dispatch(toggleTrack({id: id})) + }, + onTrackGrow: () => { + dispatch(toggleTrackGrow({id: id})) + }, + } +} + +class TrackTransform extends Component { + render() { + const activeClassName = this.props.active ? 'active' : '' + const activeKey = this.props.active ? 1 : null + const activeGrowClassName = this.props.activeGrow ? 'active' : '' + const activeGrowKey = this.props.activeGrow ? 1 : null + + return ( + + + +

    Track

    + Moves the shape along a track (shown in green) +
    + + + + + + + + + + + + +

    Scale track

    + Grows or shrinks the track +
    + + + + + + +
    +
    +
    +
    +
    +
    + ) + } +} +export default connect(mapStateToProps, mapDispatchToProps)(TrackTransform) diff --git a/pool/shard010/JavaScript/0066911_toolHandler.js b/pool/shard010/JavaScript/0066911_toolHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..061a29bde89e5db288b8393620edc8333d18d202 --- /dev/null +++ b/pool/shard010/JavaScript/0066911_toolHandler.js @@ -0,0 +1,140 @@ +var PLine, PPlane, PPoint, geometrics, onLines, onPoints; + +geometrics = require('../geometrics.js'); + +PPlane = geometrics.PPlane; + +PPoint = geometrics.PPoint; + +PLine = geometrics.PLine; + +onPoints = function(p) { + return p.typename === 'PPoint' && p._dist <= 7; +}; + +onLines = function(p) { + return p.typename === 'PLine' && p._dist <= 2; +}; + +module.exports = { + 'none': { + doHighLight: function(primitive) { + return (primitive._dist <= 7 && primitive.typename === 'PPoint') || (primitive._dist <= 2 && primitive.typename === 'PLine'); + } + }, + 'point': { + handler: function(nearests) { + plane.addPrimitive(new PPoint(mouse.x - translation.x, mouse.y - translation.y)); + return 'none'; + }, + doHighLight: function(p) { + return false; + }, + complete: function() { + return 'none'; + } + }, + 'point-centroid': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PPoint'; + }); + if (npts[0]._dist <= 7) { + toolHandlers._centroidbuff.push(npts[0]); + } + return 'point-centroid'; + }, + doHighLight: onPoints, + complete: function() { + plane.addPrimitive(PPoint.getCentroid(toolHandlers._centroidbuff)); + toolHandlers._centroidbuff = []; + return 'none'; + } + }, + 'line:1': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PPoint'; + }); + if (npts[0]._dist <= 7) { + toolHandlers._linebuff = npts[0]; + return 'line:2'; + } + return 'line:1'; + }, + doHighLight: onPoints + }, + 'line:2': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PPoint'; + }); + if (npts[0]._dist <= 7) { + plane.addPrimitive(new PLine(toolHandlers._linebuff, npts[0])); + return 'none'; + } + return 'line:2'; + }, + doHighLight: onPoints + }, + 'line-perpendicular:line': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PLine'; + }); + if (npts[0]._dist <= 2) { + toolHandlers._linebuff = npts[0]; + return 'line-perpendicular:point'; + } + return 'line-perpendicular:line'; + }, + doHighLight: onLines + }, + 'line-perpendicular:point': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PPoint'; + }); + if (npts[0]._dist <= 7) { + plane.addPrimitive(PLine.getPerpendicular(toolHandlers._linebuff, npts[0])); + return 'none'; + } + return 'line-perpendicular:point'; + }, + doHighLight: onPoints + }, + 'line-intersection:1': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PLine'; + }); + if (npts[0]._dist <= 2) { + toolHandlers._linebuff = npts[0]; + return 'line-intersection:2'; + } + return 'line-intersection:1'; + }, + doHighLight: onLines + }, + 'line-intersection:2': { + handler: function(nearests) { + var npts; + npts = nearests.filter(function(p) { + return p.typename === 'PLine'; + }); + if (npts[0]._dist <= 2) { + plane.addPrimitive(PLine.getIntersection(toolHandlers._linebuff, npts[0])); + return 'none'; + } + return 'line-intersection:2'; + }, + doHighLight: onLines + }, + _centroidbuff: [] +}; diff --git a/pool/shard010/JavaScript/0066913_NotificationService.js b/pool/shard010/JavaScript/0066913_NotificationService.js new file mode 100644 index 0000000000000000000000000000000000000000..4299462a42290d93c93ffd6038ac1c950b04306f --- /dev/null +++ b/pool/shard010/JavaScript/0066913_NotificationService.js @@ -0,0 +1,48 @@ +var notifier = require('node-notifier'); +var logger = require('../common/logger'); +var path = require('path'); + +var notifyCastingStarted = function (device) { + notifier.notify({ + title: 'Casting', + message: device.name, + icon: path.join(__dirname, 'castingTemplate.png'), + //appIcon: path.join(__dirname, 'castingTemplate.png'), + //contentImage: path.join(__dirname, 'castingTemplate.png'), + //sender: path.join(__dirname, 'castingTemplate.png'), + wait: false, + sticky: false + }); +}; + +var notifyCastingStopped = function (device) { + notifier.notify({ + title: 'Stopped', + message: device.name, + icon: path.join(__dirname, 'not-castingTemplate.png'), + //appIcon: path.join(__dirname, 'not-castingTemplate.png'), + //contentImage: path.join(__dirname, 'not-castingTemplate.png'), + //sender: path.join(__dirname, 'not-castingTemplate.png'), + wait: false, + sticky: false + }); +}; + +var notify = function (options) { + notifier.notify({ + title: options.title, + message: options.message, + icon: path.join(__dirname, 'not-castingTemplate.png'), + //appIcon: path.join(__dirname, 'not-castingTemplate.png'), + //contentImage: path.join(__dirname, 'not-castingTemplate.png'), + //sender: path.join(__dirname, 'not-castingTemplate.png'), + wait: false, + sticky: false + }); +}; + +module.exports = { + notify: notify, + notifyCastingStarted: notifyCastingStarted, + notifyCastingStopped: notifyCastingStopped +}; diff --git a/pool/shard010/JavaScript/0066914_textElement.js b/pool/shard010/JavaScript/0066914_textElement.js new file mode 100644 index 0000000000000000000000000000000000000000..65d573da735ba5f32e822e8f39f8d1c4fe8b1f1f --- /dev/null +++ b/pool/shard010/JavaScript/0066914_textElement.js @@ -0,0 +1,36 @@ +"use strict"; + +import VirtualDOMNode from "../virtualDOMNode"; + +export default class VirtualDOMTextElement extends VirtualDOMNode { + constructor(text) { + const domElement = document.createTextNode(text), + children = [], + props = { + children + }; + + super(props, domElement); + } + + mount(parent, reference, context) { + super.mount(parent, reference); + } + + unmount(context) { + super.unmount(); + } + + getText() { + const nodeValue = this.domElement.nodeValue, + text = nodeValue; /// + + return text; + } + + setText(text) { + const nodeValue = text; /// + + this.domElement.nodeValue = nodeValue; + } +} diff --git a/pool/shard010/JavaScript/0066918_jquery.carddisplay.js b/pool/shard010/JavaScript/0066918_jquery.carddisplay.js new file mode 100644 index 0000000000000000000000000000000000000000..cf8f43593c583dfc0516d2d53e60f5dbcf16f0da --- /dev/null +++ b/pool/shard010/JavaScript/0066918_jquery.carddisplay.js @@ -0,0 +1,76 @@ +(function(jQuery, $) { + jQuery.fn.carddisplay = function(options) { + var me, + listeners; + + options = jQuery.extend({}, jQuery.fn.carddisplay.options, options); + me = this; + + listeners = $({}); + listeners.on('carddisplay', function(event, message) { + jQuery.fn.carddisplay.showcards.call(me, message.data, options); + }); + return listeners; + }; + + /** +
    + 8 + + + + Khalid +
    + */ + jQuery.fn.carddisplay.showcards = function(cardsData, options) { + var cardsTotal, + cards, + cardsHiddenClass; + + cardsTotal = 0; + cards = cardsData.cards; + if (cardsData.show === false) { + cardsHiddenClass = 'poker-card-display-hidden'; + } + + $(this).empty(); + $(options.pokerCardsShowButton).attr('disabled', 'disabled'); + for (var userId in cards) { + var card, + pokerCardId, + amountDevs; + + cardsTotal++; + + pokerCardId = 'poker-card-' + userId; + card = $('#' + pokerCardId); + + if (!card.is('div')) { + card = $('
    ' + + '#' + + '' + + '' + + '' + + '#' + + '
    '); + $(this).append(card); + } + card.find('.poker-card-value').html(cards[userId]); + card.find('.poker-card-player').text(window.currentUsers[userId].name); + + amountDevs = $('.poker-role-developer').length; + // Schauen, ob mind. 2 devs abgestimmt haben + if (amountDevs > 0 && $('.poker-card-value').length > 1) { + $(options.pokerCardsShowButton).removeAttr('disabled'); + } + } + if (cardsTotal == 0) { + $('.' + options.pokerCardSelectedClass).removeClass(options.pokerCardSelectedClass); + }; + } + + jQuery.fn.carddisplay.options = { + pokerCardsShowButton: null, + pokerCardSelectedClass: null + }; +})(jQuery, jQuery); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066928_IndexSurvey.js b/pool/shard010/JavaScript/0066928_IndexSurvey.js new file mode 100644 index 0000000000000000000000000000000000000000..f8cc67351a2582a5224cc5d0925ced19b609fc1d --- /dev/null +++ b/pool/shard010/JavaScript/0066928_IndexSurvey.js @@ -0,0 +1,298 @@ +import React, {Component} from 'react'; +import ReactNative from 'react-native'; +import {Motion, spring} from 'react-motion'; +import { Actions } from 'react-native-router-flux'; + +import {connect} from 'react-redux'; +import { + setPoint +} from '../actions/point'; +import {setPointToFirebase} from '../utils/firebase'; +import config from '../../config'; +import Spinner from 'react-native-loading-spinner-overlay'; + +const { + Image, + StyleSheet, + Text, + View, + TouchableOpacity, + Alert, + DeviceEventEmitter, + Platform +} = ReactNative; + +var { RNLocation: Location } = require('NativeModules'); + +/** + * Container component for IndexSurvey page + */ +class IndexSurvey extends Component { + + /** + * IndexSurvey Container Constructor + * @param {props} props from parent component + * @return {void} + */ + constructor(props){ + super(props); + + this.stopLocation.bind(this); + this.location = { + "lat": 0, + "long": 0 + } + + this.state = { + visible: false + }; + + } + + /** + * Go Activity Page + * @return {void} + */ + goActivity(){ + + // start + if(!this.props.continue){ + + if( Platform.OS!= 'ios'){ + this.setState({ + visible: true + }); + + setTimeout(this.stopLocation.bind(this), 30000); + + Location.startUpdatingLocation(); + + var subscription = DeviceEventEmitter.addListener( + 'locationUpdated', + (location) => { + if( this.location.long === 0){ + + this.location.long = location.longitude; + this.location.lat = location.latitude; + + let info = {}; + let dateTime = Math.floor(Date.now() / 1000); + info["dateTime"] = dateTime; + info["mode"] = "start"; + + info["lat"] = this.location.lat; + info["long"] = this.location.long; + info["stage"] = this.props.stage; + + setPointToFirebase(info, dateTime); + this.props.setPoint(info); + + this.setState({ + visible: false + }); + Actions.activity(); + } + } + ); + } else { + + this.setState({ + visible: true + }, ()=>{ + + navigator.geolocation.getCurrentPosition( + (position) => { + this.location.lat = parseFloat(position.coords.latitude); + this.location.long = parseFloat(position.coords.longitude); + + + let info = {}; + let dateTime = Math.floor(Date.now() / 1000); + info["dateTime"] = dateTime; + info["mode"] = "start"; + + info["lat"] = this.location.lat; + info["long"] = this.location.long; + info["stage"] = this.props.stage; + + setPointToFirebase(info, dateTime); + this.props.setPoint(info); + + this.setState({ + visible: false + }); + Actions.activity(); + + + + }, + (error) => { + this.stopLocationIOS(); + }, + {enableHighAccuracy: true, timeout: 30000, maximumAge:0} + ); + + }); + + + + } + + }else{ + // continue + Actions.activity(); + } + + } + + /** + * Stop Location + * @return {void} + */ + stopLocationIOS() { + + if( this.location.lat === 0 ){ + Alert.alert( + config.LOCATION_ERROR_TITLE, + config.LOCATION_ERROR_CNT, + [ + {text: 'OK', onPress: () => { + this.setState({ + visible: false + }); + } } + ] + ) + + } + } + + /** + * Stop Location + * @return {void} + */ + stopLocation() { + + if( this.location.lat === 0 ){ + Alert.alert( + config.LOCATION_ERROR_TITLE, + config.LOCATION_ERROR_CNT, + [ + {text: 'OK', onPress: () => {} } + ] + ) + this.setState({ + visible: false + }); + + Location.stopUpdatingLocation(); + } + } + + /** + * componentDidMount - React default event + * @return {void} + */ + componentDidMount(){ + // start + if( !this.props.continue ){ + /* + navigator.geolocation.getCurrentPosition( + (position) => { + this.location.lat = parseFloat(position.coords.latitude); + this.location.long = parseFloat(position.coords.longitude); + }, + (error) => { + this.location.lat = 0; + this.location.long = 0; + }, + { enableHighAccuracy: false } + ); + */ + } + } + + /** + * Render IndexSurvey page + * @return {jsxresult} result in jsx format + */ + render() { + + let startText = "START ACTIVITY"; + if( this.props.continue ) + startText = "CONTINUE ACTIVITY"; + + return ( + + + + + + + + + {startText} + + + + {Actions.instruction();}}> + INSTRUCTIONS + + + + + ); + } +} + +let styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: 'transparent', + flexDirection: 'column', + justifyContent: 'space-between' + }, + button: { + backgroundColor: '#01743D', + alignItems: 'center', + borderWidth: 0, + width:'100%', + height:'100%', + justifyContent:'center' + }, + whiteFont: { + color: '#fff', + fontFamily: 'Roboto-Bold', + fontSize: 32 + }, + instructBtn: { + backgroundColor: '#56BD2D' + } +}); + +/** + * Map Redux store state to component props + * @param {state} state Redux store state + * @return {json} state json State from redux store state + */ +const mapStateToProps = (state) => { + return { + stage: state.survey.stage + }; +}; + +/** + * Map Redux dispatches to component props + * @param {object} dispatch Redux dispatches + * @return {json} dispatch-json from redux dispatche + */ +const mapDispatchToProps = (dispatch) => { + return { + setPoint: (pointInfo) => { + return dispatch(setPoint(pointInfo)); + } + }; +}; + +export default connect(mapStateToProps, mapDispatchToProps)(IndexSurvey); diff --git a/pool/shard010/JavaScript/0066929_HttpWebHookSecurityAccessory.js b/pool/shard010/JavaScript/0066929_HttpWebHookSecurityAccessory.js new file mode 100644 index 0000000000000000000000000000000000000000..0190155303f591f237c1b6ca7cbeb81655369903 --- /dev/null +++ b/pool/shard010/JavaScript/0066929_HttpWebHookSecurityAccessory.js @@ -0,0 +1,104 @@ +const Constants = require('../../Constants'); +const Util = require('../../Util'); + +function HttpWebHookSecurityAccessory(ServiceParam, CharacteristicParam, platform, securityConfig) { + Service = ServiceParam; + Characteristic = CharacteristicParam; + + this.platform = platform; + this.log = platform.log; + this.storage = platform.storage; + + this.id = securityConfig["id"]; + this.name = securityConfig["name"]; + this.type = "security"; + this.rejectUnauthorized = securityConfig["rejectUnauthorized"] === undefined ? true: securityConfig["rejectUnauthorized"] === true; + this.setStateURL = securityConfig["set_state_url"] || ""; + this.setStateMethod = securityConfig["set_state_method"] || "GET"; + this.setStateBody = securityConfig["set_state_body"] || ""; + this.setStateForm = securityConfig["set_state_form"] || ""; + this.setStateHeaders = securityConfig["set_state_headers"] || "{}"; + + this.informationService = new Service.AccessoryInformation(); + this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); + this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookSecurityAccessory-" + this.name); + this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookSecurityAccessory-" + this.id); + + this.service = new Service.SecuritySystem(this.name); + this.service.getCharacteristic(Characteristic.SecuritySystemTargetState).on('get', this.getTargetSecurityState.bind(this)).on('set', this.setTargetSecurityState.bind(this)); + this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).on('get', this.getCurrentSecurityState.bind(this)); +} + +HttpWebHookSecurityAccessory.prototype.changeFromServer = function(urlParams) { + var cachedCurrentState = this.storage.getItemSync("http-webhook-current-security-state-" + this.id); + if (cachedCurrentState === undefined) { + cachedCurrentState = Characteristic.SecuritySystemCurrentState.DISARMED; + } + if (!urlParams.currentstate && !urlParams.targetstate) { + return { + "success" : true, + "currentState" : cachedCurrentState + }; + } + + if (urlParams.currentstate != null) { + this.storage.setItemSync("http-webhook-current-security-state-" + this.id, urlParams.currentstate); + if (cachedCurrentState !== urlParams.currentstate) { + this.log("Change current state for security to '%d'.", urlParams.currentstate); + this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).updateValue(urlParams.currentstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); + } + } + + if (urlParams.targetstate != null) { + var cachedState = this.storage.getItemSync("http-webhook-target-security-state-" + this.id); + if (cachedState === undefined) { + cachedState = Characteristic.SecuritySystemTargetState.DISARM; + } + this.storage.setItemSync("http-webhook-target-security-state-" + this.id, urlParams.targetstate); + if (cachedState !== urlParams.targetstate) { + this.log("Change target state for security to '%d'.", urlParams.targetstate); + this.service.getCharacteristic(Characteristic.SecuritySystemTargetState).updateValue(urlParams.targetstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); + } + } + return { + "success" : true + }; +} + +HttpWebHookSecurityAccessory.prototype.getTargetSecurityState = function(callback) { + this.log.debug("Getting Target Security state for '%s'...", this.id); + var state = this.storage.getItemSync("http-webhook-target-security-state-" + this.id); + if (state === undefined) { + state = Characteristic.SecuritySystemTargetState.DISARM; + } + callback(null, state); +}; + +HttpWebHookSecurityAccessory.prototype.setTargetSecurityState = function(newState, callback, context) { + this.log("Target Security state for '%s'...", this.id); + this.storage.setItemSync("http-webhook-target-security-state-" + this.id, newState); + this.storage.setItemSync("http-webhook-current-security-state-" + this.id, newState); + var urlToCall = this.setStateURL.replace("%d", newState); + var urlMethod = this.setStateMethod; + var urlBody = this.setStateBody; + var urlForm = this.setStateForm; + var urlHeaders = this.setStateHeaders; + Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, (function() { + this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).updateValue(newState, undefined, null); + }).bind(this)); +}; + +HttpWebHookSecurityAccessory.prototype.getCurrentSecurityState = function(callback) { + this.log.debug("Getting Current Security state for '%s'...", this.id); + var state = this.storage.getItemSync("http-webhook-current-security-state-" + this.id); + if (state === undefined) { + state = Characteristic.SecuritySystemCurrentState.DISARMED; + } + callback(null, state); +}; + +HttpWebHookSecurityAccessory.prototype.getServices = function() { + return [ this.service, this.informationService ]; +}; + +module.exports = HttpWebHookSecurityAccessory; diff --git a/pool/shard010/JavaScript/0066930_app.js b/pool/shard010/JavaScript/0066930_app.js new file mode 100644 index 0000000000000000000000000000000000000000..bde92394094a8a41eb0da746a9c392855b1d3001 --- /dev/null +++ b/pool/shard010/JavaScript/0066930_app.js @@ -0,0 +1,43 @@ +/** + * Main application file + */ + +'use strict'; + +// Set default node environment to development +process.env.NODE_ENV = process.env.NODE_ENV || 'development'; + +var express = require('express'); +var mongoose = require('mongoose'); +var config = require('./config/environment'); +var favicon = require('serve-favicon'); + + +// Connect to database +console.log(config.mongo.uri); +console.log(config.mongo.options); +mongoose.connect(config.mongo.uri, config.mongo.options); + +// Populate DB with sample data +if(config.seedDB) { require('./config/seed'); } + +// Setup server +var app = express(); +//app.use(favicon(__dirname + '/public/favicon.ico')); + +var server = require('http').createServer(app); +var socketio = require('socket.io')(server, { + serveClient: (config.env === 'production') ? false : true, + path: '/socket.io-client' +}); +require('./config/socketio')(socketio); +require('./config/express')(app); +require('./routes')(app); + +// Start server +server.listen(config.port, config.ip, function () { + console.log('Express server listening on %d, in %s mode', config.port, app.get('env')); +}); + +// Expose app +exports = module.exports = app; diff --git a/pool/shard010/JavaScript/0066932_CallbackManager.js b/pool/shard010/JavaScript/0066932_CallbackManager.js new file mode 100644 index 0000000000000000000000000000000000000000..04d339cdf2f2d1148de3cc1de54d6be261ad1f96 --- /dev/null +++ b/pool/shard010/JavaScript/0066932_CallbackManager.js @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +function getHookKey (componentId, type, hookName) { + return `${type}@${hookName}#${componentId}` +} + +/** + * For general callback management of a certain Weex instance. + * Because function can not passed into native, so we create callback + * callback id for each function and pass the callback id into native + * in fact. And when a callback called from native, we can find the real + * callback through the callback id we have passed before. + */ +export default class CallbackManager { + constructor (instanceId) { + this.instanceId = String(instanceId) + this.lastCallbackId = 0 + this.callbacks = {} + this.hooks = {} + } + add (callback) { + this.lastCallbackId++ + this.callbacks[this.lastCallbackId] = callback + return this.lastCallbackId + } + remove (callbackId) { + const callback = this.callbacks[callbackId] + delete this.callbacks[callbackId] + return callback + } + registerHook (componentId, type, hookName, hookFunction) { + // TODO: validate arguments + const key = getHookKey(componentId, type, hookName) + if (this.hooks[key]) { + console.warn(`[JS Framework] Override an existing component hook "${key}".`) + } + this.hooks[key] = hookFunction + } + triggerHook (componentId, type, hookName, args) { + // TODO: validate arguments + const key = getHookKey(componentId, type, hookName) + const hookFunction = this.hooks[key] + if (typeof hookFunction !== 'function') { + console.error(`[JS Framework] Invalid hook function type (${typeof hookFunction}) on "${key}".`) + return null + } + let result = null + try { + result = hookFunction.apply(null, args || []) + } + catch (e) { + console.error(`[JS Framework] Failed to execute the hook function on "${key}".`) + } + return result + } + consume (callbackId, data, ifKeepAlive) { + const callback = this.callbacks[callbackId] + if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) { + delete this.callbacks[callbackId] + } + if (typeof callback === 'function') { + return callback(data) + } + return new Error(`invalid callback id "${callbackId}"`) + } + close () { + this.callbacks = {} + this.hooks = {} + } +} diff --git a/pool/shard010/JavaScript/0066934_bisheng.config.js b/pool/shard010/JavaScript/0066934_bisheng.config.js new file mode 100644 index 0000000000000000000000000000000000000000..671ca41cf93ab69511acc96709f77d08641aedd4 --- /dev/null +++ b/pool/shard010/JavaScript/0066934_bisheng.config.js @@ -0,0 +1,106 @@ +const path = require('path'); +const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default; +const replaceLib = require('antd-tools/lib/replaceLib'); + +const isDev = process.env.NODE_ENV === 'development'; +const usePreact = process.env.REACT_ENV === 'preact'; + +function alertBabelConfig(rules) { + rules.forEach((rule) => { + if (rule.loader && rule.loader === 'babel-loader') { + rule.options.plugins.push(replaceLib); + } else if (rule.use) { + alertBabelConfig(rule.use); + } + }); +} + +module.exports = { + port: 8001, + source: { + components: './components', + docs: './docs', + changelog: [ + 'CHANGELOG.zh-CN.md', + 'CHANGELOG.en-US.md', + ], + }, + theme: './site/theme', + htmlTemplate: './site/theme/static/template.html', + themeConfig: { + categoryOrder: { + 设计原则: 2, + Principles: 2, + }, + typeOrder: { + General: 0, + Layout: 1, + Navigation: 2, + 'Data Entry': 3, + 'Data Display': 4, + Feedback: 5, + Localization: 6, + Other: 7, + }, + docVersions: { + '0.9.x': 'http://09x.ant.design', + '0.10.x': 'http://010x.ant.design', + '0.11.x': 'http://011x.ant.design', + '0.12.x': 'http://012x.ant.design', + '1.x': 'http://1x.ant.design', + '2.x': 'http://2x.ant.design', + }, + }, + filePathMapper(filePath) { + if (filePath === '/index.html') { + return ['/index.html', '/index-cn.html']; + } + if (filePath.endsWith('/index.html')) { + return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')]; + } + if (filePath !== '/404.html' && filePath !== '/index-cn.html') { + return [filePath, filePath.replace(/\.html$/, '-cn.html')]; + } + return filePath; + }, + doraConfig: { + verbose: true, + plugins: ['dora-plugin-upload'], + }, + webpackConfig(config) { + config.resolve.alias = { + 'antd/lib': path.join(process.cwd(), 'components'), + antd: path.join(process.cwd(), 'index'), + site: path.join(process.cwd(), 'site'), + 'react-router': 'react-router/umd/ReactRouter', + }; + + config.externals = { + 'react-router-dom': 'ReactRouterDOM', + }; + + if (usePreact) { + config.resolve.alias = Object.assign({}, config.resolve.alias, { + react: 'preact-compat', + 'react-dom': 'preact-compat', + 'create-react-class': 'preact-compat/lib/create-react-class', + 'react-router': 'react-router', + }); + } + + if (isDev) { + config.devtool = 'source-map'; + } + + alertBabelConfig(config.module.rules); + + config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 })); + + return config; + }, + + htmlTemplateExtraData: { + isDev, + usePreact, + }, +}; diff --git a/pool/shard010/JavaScript/0066938_HotObservable.js b/pool/shard010/JavaScript/0066938_HotObservable.js new file mode 100644 index 0000000000000000000000000000000000000000..4569543eae4d79daa077520dd9409d29f624f275 --- /dev/null +++ b/pool/shard010/JavaScript/0066938_HotObservable.js @@ -0,0 +1,49 @@ +/** PURE_IMPORTS_START .._Subject,.._Subscription,._SubscriptionLoggable,.._util_applyMixins PURE_IMPORTS_END */ +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 __()); +}; +import { Subject } from '../Subject'; +import { Subscription } from '../Subscription'; +import { SubscriptionLoggable } from './SubscriptionLoggable'; +import { applyMixins } from '../util/applyMixins'; +/** + * We need this JSDoc comment for affecting ESDoc. + * @ignore + * @extends {Ignored} + */ +export var HotObservable = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { + __extends(HotObservable, _super); + function HotObservable(messages, scheduler) { + _super.call(this); + this.messages = messages; + this.subscriptions = []; + this.scheduler = scheduler; + } + /** @deprecated internal use only */ HotObservable.prototype._subscribe = function (subscriber) { + var subject = this; + var index = subject.logSubscribedFrame(); + subscriber.add(new Subscription(function () { + subject.logUnsubscribedFrame(index); + })); + return _super.prototype._subscribe.call(this, subscriber); + }; + HotObservable.prototype.setup = function () { + var subject = this; + var messagesLength = subject.messages.length; + /* tslint:disable:no-var-keyword */ + for (var i = 0; i < messagesLength; i++) { + (function () { + var message = subject.messages[i]; + /* tslint:enable */ + subject.scheduler.schedule(function () { message.notification.observe(subject); }, message.frame); + })(); + } + }; + return HotObservable; +}(Subject)); +/*@__PURE__*/ applyMixins(HotObservable, [SubscriptionLoggable]); +//# sourceMappingURL=HotObservable.js.map diff --git a/pool/shard010/JavaScript/0066939_shouts.js b/pool/shard010/JavaScript/0066939_shouts.js new file mode 100644 index 0000000000000000000000000000000000000000..bdcee13b469bd2d151b74a8b48ec77b92f8d969b --- /dev/null +++ b/pool/shard010/JavaScript/0066939_shouts.js @@ -0,0 +1,32 @@ +Shouts = new Mongo.Collection("shouts"); + +Shouts.deny({ + update : function(){ return true }, + remove : function(){ return true }, +}); + +validateShout = function(text, name){ + if (text && name) return true; + else + if (Meteor.isClient){ + $("#name-field").addClass("red"); + $("#text-field").addClass("red"); + } + return false; +} + +Meteor.methods({ + addShout: function (text, name){ + if (validateShout(text, name)) { + Shouts.insert({ + text: text, + createdAt: new Date(), + name: name + }); + if (Meteor.isClient){ + $("#text-field").removeClass("red"); + $("#name-field").removeClass("red"); + } + } + } +}); diff --git a/pool/shard010/JavaScript/0066940_method_decorator.js b/pool/shard010/JavaScript/0066940_method_decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..70d3af4c44ac4c0d387948bda49b6a8bcb814af1 --- /dev/null +++ b/pool/shard010/JavaScript/0066940_method_decorator.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** + * @module methodWrapper + * + */ + + +var _store = require('../store'); + +var _store2 = _interopRequireDefault(_store); + +var _event_handlers = require('../event_handlers'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * _isReactKeyDown + * + * @access private + * @param {object} event The possibly synthetic event passed as an argument with + * the method invocation. + * @return {boolean} + */ +function _isReactKeyDown(event) { + return event && (typeof event === 'undefined' ? 'undefined' : _typeof(event)) === 'object' && event.nativeEvent instanceof window.KeyboardEvent && event.type === 'keydown'; +} + +/** + * methodWrapper + * + * @access public + * @param {object} args All arguments necessary for wrapping method + * @param {object} args.target The decorated class + * @param {object} args.descriptor Method descriptor + * @param {array} args.keys The array of keys bound to the given method + * @return {object} The method descriptor + */ +function methodWrapper(_ref) { + var target = _ref.target, + descriptor = _ref.descriptor, + keys = _ref.keys; + + + var fn = descriptor.value; + + // if we haven't already created a binding for this class (via another + // decorated method), wrap these lifecycle methods. + if (!_store2.default.getBinding(target)) { + var componentDidMount = target.componentDidMount, + componentWillUnmount = target.componentWillUnmount; + + + target.componentDidMount = function () { + (0, _event_handlers.onMount)(this); + if (componentDidMount) return componentDidMount.call(this); + }; + + target.componentWillUnmount = function () { + (0, _event_handlers.onUnmount)(this); + if (componentWillUnmount) return componentWillUnmount.call(this); + }; + } + + // add this binding of keys and method to the target's bindings + _store2.default.setBinding({ keys: keys, target: target, fn: fn }); + + descriptor.value = function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var maybeEvent = args[0]; + + if (_isReactKeyDown(maybeEvent)) { + // proxy method in order to use @keydown as filter for keydown events coming + // from an actual onKeyDown binding (as identified by react's addition of + // 'nativeEvent' + type === 'keydown') + if (!maybeEvent.ctrlKey) { + // we already whitelist shortcuts with ctrl modifiers so if we were to + // fire it again here the method would trigger twice. see https://github.com/glortho/react-keydown/issues/38 + return (0, _event_handlers._onKeyDown)(maybeEvent, true); + } + } else if (!maybeEvent || !(maybeEvent instanceof window.KeyboardEvent) || maybeEvent.type !== 'keydown') { + // if our first argument is a keydown event it is being handled by our + // binding system. if it's anything else, just pass through. + return fn.call.apply(fn, [this].concat(args)); + } + }; + + return descriptor; +} + +exports.default = methodWrapper; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066944_style.js b/pool/shard010/JavaScript/0066944_style.js new file mode 100644 index 0000000000000000000000000000000000000000..40cd9339733182d24c576ee7838c8297841a7992 --- /dev/null +++ b/pool/shard010/JavaScript/0066944_style.js @@ -0,0 +1,172 @@ +import * as record from "../record"; +import * as list from "../list"; +import * as mutable from "../mutable"; +import { assert, crash } from "../assert"; + + +const key_prefixes = { + // TODO it's a bit hacky to use the prefix system for this purpose... + //"width": ["width", "min-width", "max-width"], + //"height": ["height", "min-height", "max-height"], + "box-sizing": ["-moz-box-sizing", "box-sizing"], // TODO get rid of this later + "filter": ["-webkit-filter"] // TODO add in "filter" later +}; + +const value_prefixes = { + "grab": ["-webkit-grab", "grab"], + "grabbing": ["-webkit-grabbing", "grabbing"] +}; + +const prefix_key = (x) => { + if (key_prefixes[x]) { + return key_prefixes[x]; + } else { + return [x]; + } +}; + +const prefix_value = (x) => { + if (x === null) { + return [x]; + } else if (value_prefixes[x]) { + return value_prefixes[x]; + } else { + return [x]; + } +}; + + +export const has_style = (style, key) => + record.has(style, key); + +export const get_style_value = (style, key) => { + const value = record.get(style, key); + + // TODO this may break on earlier versions of Chrome + assert(style["getPropertyValue"](key) === value); + assert(value != null); + + if (value === "") { + return null; + } else { + return value; + } +}; + +const stringify = (x) => { + if (x === null) { + return "" + x; + } else { + return "\"" + x + "\""; + } +}; + + +const check_style_key = (key) => { + // TODO test this + if (typeof key !== "string") { + crash(new Error("Key must be a string: " + key)); + } +}; + +const check_style_value = (value) => { + // TODO test this + if (value !== null && typeof value !== "string") { + crash(new Error("Value must be null or a string: " + value)); + } + + if (value === "") { + crash(new Error("Value cannot be \"\", use `null` instead")); + } +}; + + +export const set_style_value = (style, key, value) => { + check_style_key(key); + check_style_value(value); + + const keys = prefix_key(key); + const values = prefix_value(value); + + let seen = false; + + list.each(keys, (key) => { + if (has_style(style, key)) { + seen = true; + + const old_value = get_style_value(style, key); + + list.each(values, (value) => { + if (old_value !== value) { + // TODO test this + if (value === null) { + style["removeProperty"](key); + + } else { + // TODO does this trigger a relayout ? + // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-setproperty + style["setProperty"](key, value, ""); + } + + + const new_value = get_style_value(style, key); + + if (old_value === new_value) { + crash(new Error("Invalid value (\"" + key + "\": " + stringify(value) + ")")); + } + } + }); + } + }); + + if (!seen) { + crash(new Error("Invalid keys (\"" + list.join(keys, "\", \"") + "\")")); + } +}; + + +const e = document["createElement"]("style"); +e["type"] = "text/css"; +// TODO does this trigger a relayout ? +document["head"]["appendChild"](e); + +const sheet = e["sheet"]; +const cssRules = sheet["cssRules"]; + +export const insert_rule = (rule) => { + // TODO does this trigger a relayout ? + // TODO this may not work in all browsers + // TODO sheet.addRule(s) + const index = sheet["insertRule"](rule + " {}", cssRules["length"]); + + return cssRules[index]; +}; + + +let style_id = 0; + +export const make_style = (rules) => { + const class_name = "__style_" + (++style_id) + "__"; + + make_stylesheet("." + class_name, rules); + + return { + _type: 0, + _name: class_name + }; +}; + + +export const set_rules = (style, rules) => { + record.each(rules, (key, value) => { + mutable.listen(value, (value) => { + set_style_value(style, key, value); + }); + }); +}; + +export const make_stylesheet = (name, rules) => { + const style = insert_rule(name)["style"]; + + set_rules(style, rules); +}; diff --git a/pool/shard010/JavaScript/0066945_caseUpload.js b/pool/shard010/JavaScript/0066945_caseUpload.js new file mode 100644 index 0000000000000000000000000000000000000000..8b7e732d17340bc3dd0eea77c717a51751b09c3c --- /dev/null +++ b/pool/shard010/JavaScript/0066945_caseUpload.js @@ -0,0 +1,170 @@ +var PU = PU || {}; + +PU.caseUpload = (function ($) { + return { + init: function () { + function getSize() { + var myFSO = new ActiveXObject("Scripting.FileSystemObject"), + filepath = document.upload.file.value, + thefile = myFSO.getFile(filepath), + size = thefile.size; + + if (size > 2621440) { + $.growl('Filesize must be 2.5MB or below', { + onGrowlClosed: function() { + $('.j-file-upload-name').val(''); + $('.j-submit-file input').attr("disabled", true); + }, + ele: "#submitCase", + position: { + from: "top", + align: "center" + }, + type: 'danger', + template: { + icon_type: 'class', + container: '
    ', + dismiss: '', + title: '', + title_divider: '', + message: '' + } + }); + } else { + $('.j-submit-file input').attr("disabled", false); + } + + alert(size + " bytes"); + } + + function fileSize(bytes) { + var exp = Math.log(bytes) / Math.log(1024) | 0, + result = (bytes / Math.pow(1024, exp)).toFixed(2); + + return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B'); + } + + $('.j-submit-file input').attr("disabled", true); + + $(document).on('keyup', '.j-textarea-field', function(e) { + var $elm = $('.j-submit-file input'); + + if (e.keyCode == 13 && e.shiftKey) + e.stopPropagation(); + + this.value.length > 25 ? $elm.attr("disabled", false) : $elm.attr("disabled", true); + }); + + $(document).on('change', '.btn-file :file', function() { + var input = $(this), + numFiles = input.get(0).files ? input.get(0).files.length : 1, + label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); + + input.trigger('fileselect', [numFiles, label]); + }); + + $('.btn-file :file').on('fileselect', function(event, numFiles, label) { + var input = $(this).parents('.input-group').find(':text'), + log = numFiles > 1 ? numFiles + ' files selected' : label; + + if(input.length) { + input.val(log); + + try { + var ua = window.navigator.userAgent, + msie = ua.indexOf("MSIE "); + + if(msie > 0) { + getSize(); + } else { + if (this.files[0].size > 2621440) { + $.growl('Filesize must be 2.5MB or below', { + onGrowlClosed: function() { + $('.j-file-upload-name').val(''); + $('.j-submit-file input').attr("disabled", true); + }, + width: "400px", + ele: "#submitCase", + position: { + from: "top", + align: "center" + }, + type: 'danger', + template: { + icon_type: 'class', + container: '
    ', + dismiss: '', + title: '', + title_divider: '', + message: '' + } + }); + } else { + $('.j-submit-file input').attr("disabled", false); + } + } + } catch(e) { + alert("we can't get file size - send it to backend"); + } + } else { + if(log) + console.log(log); + } + }); + + $(document).on('click', '.j-file-upload-name', function() { + $('.btn-file :file').trigger('click'); + }); + + $(".j-form-submit-case").submit(function(e) { + e.preventDefault(); + + $.growl('Success!
    Thank you, we\'ve received your case and one of our editors will review it shortly.
    PracticeUpdate staff may contact you via email regarding questions, editing, and possible publication on http://PracticeUpdate.com', { + onGrowlClosed: function() { + $('.j-textarea-field, .j-file-upload-name').val(''); + + $.growl('Your case could not be submitted, please try again.', { + onGrowlClosed: function() { + $('.j-textarea-field, .j-file-upload-name').val(''); + }, + width: "400px", + ele: "#submitCase", + position: { + from: "top", + align: "center" + }, + type: 'danger', + template: { + icon_type: 'class', + container: '
    ', + dismiss: '', + title: '', + title_divider: '', + message: '' + } + }); + }, + width: "400px", + ele: "#submitCase", + position: { + from: "top", + align: "center" + }, + type: 'success', + template: { + icon_type: 'class', + container: '
    ', + dismiss: '', + title: '', + title_divider: '', + message: '' + } + }); + }); + }, + }; +} (jQuery)); + +$(document).ready(function () { + PU.caseUpload.init(); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066946_sharunner.js b/pool/shard010/JavaScript/0066946_sharunner.js new file mode 100644 index 0000000000000000000000000000000000000000..dd1c82c6d4b6a2c6f12e58a4bde93e1ce969a158 --- /dev/null +++ b/pool/shard010/JavaScript/0066946_sharunner.js @@ -0,0 +1,70 @@ +function toStep(v) { return Math.floor(v/7)*7; } + +function readProperty(data, point, prop) { + if(point.point) + return point.point.onevent(data); + else if(prop) + return prop; + else if(data) + return data; + return ""; +} + +function readInt(data, point, prop) { + var p = parseInt(prop); + if(point && point.point) + return parseInt(point.point.onevent(data)); + else if(prop) + return p; + else if(data) + return parseInt(data); + return 0; +} + +function SHARunner(file, onload) { + var packMan = null; + + var loader = new Loader(); + loader.parent = this; + loader.onload = function() { + $.post("/server/core.php", {load: true, name: file}, function(data, parent) { + if(this.status === 404) { + alert("File " + file + " not found!"); + } + else { + parent.sdk = new SDK(packMan.getPack("base")); + parent.sdk.clearProject(); + parent.sdk.load(data); + if(onload) { + onload.call(parent); + } + } + }, this.parent); + } + loader.add(new LoaderTask(function(){ + packMan = new PackManager(); + packMan.onload = function() { + this.task.taskComplite("Packs load."); + delete this.task; + }; + packMan.task = this; + packMan.load(["base"]); + })); + loader.run(); +} + +SHARunner.prototype.run = function() { + this.sdk.run(window.FLAG_USE_RUN); +}; + +window.getOption = function(name, defValue) { + return window.localStorage["gv_" + name] || defValue; +}; + +window.getOptionBool = function(name, defValue) { + return parseInt(window.getOption(name, defValue)) === 1; +}; + +window.getOptionInt = function(name, defValue) { + return parseInt(window.getOption(name, defValue)); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066948_pageSize.js b/pool/shard010/JavaScript/0066948_pageSize.js new file mode 100644 index 0000000000000000000000000000000000000000..fdbd1298439c9a8fd2ab441f1396e56b56be2284 --- /dev/null +++ b/pool/shard010/JavaScript/0066948_pageSize.js @@ -0,0 +1,16 @@ +(function( $ ){ + + $.fn.pageSize = function( options ) { + + this.each(function() { + $this = $(this); + $width = $(window).width(); + $height = $(window).height(); + + $this.attr('style', 'min-height:'+$height+'px;'); + }); + + return this; + + }; +})( jQuery ); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066949_comatch.js b/pool/shard010/JavaScript/0066949_comatch.js new file mode 100644 index 0000000000000000000000000000000000000000..f9cc468651c1ba17c007ad944d38168c6b966c82 --- /dev/null +++ b/pool/shard010/JavaScript/0066949_comatch.js @@ -0,0 +1,25 @@ +(function() { + var CoRegex, CoRegexFn, addMatcher, match, name; + CoRegex = { + match_srcpath: /^[\.\/]*\/src\//, + match_libpath: /^[\.\/]*\/lib\//, + match_cofile: /\/[^\/]*\.co$/, + match_jsfile: /\/[^\/]*\.js$/, + match_coext: /\.co$/, + match_jsext: /\.js$/, + match_relative: /^\.\// + }; + CoRegexFn = {}; + addMatcher = function(name, match) { + CoRegexFn[name] = function(text) { + return match.exec(text); + }; + return CoRegexFn[name].match = match; + }; + for (name in CoRegex) { + match = CoRegex[name]; + addMatcher(name, match); + } + module.exports.CoRegexFn = CoRegexFn; + module.exports.CoRegex = CoRegex; +}).call(this); diff --git a/pool/shard010/JavaScript/0066950_chat.js b/pool/shard010/JavaScript/0066950_chat.js new file mode 100644 index 0000000000000000000000000000000000000000..7a478e62bb4b5b9af84ab4af424a016b513b5614 --- /dev/null +++ b/pool/shard010/JavaScript/0066950_chat.js @@ -0,0 +1,53 @@ +/** + * Manager of the chat, gives access to several method for data access + * @class app.controllers.chatservice + * @required app.services.chat + */ +/** + * @param {app.services.chat} chatservice Manager of data W/R/D + */ +var chatservice = require('../services/chat.js'); + +/** + * Handler for the list of people available + * @method getPeople + * @param {Object} data Data received with the request + */ +function getPeople(data) { + if (typeof data !== 'undefined' && data.id !== 0) { + chatservice.getPeople(data, function(data) { + console.log(data); + }, function(err) { + console.log(err); + }); + } +} + +/** + * Handler, sends data to a given person + * @method sendMessage + * @param {Object} data Data received with the request + */ +function sendMessage(data) { + console.log(data); + chatservice.sendMessage([data.dest], data.message); +} + +/** + * Handler, creates a room for chat + * @method createRoom + * @param {Object} data Data received with the request + */ +function createRoom(data) {} + +/** + * Handler, disconnects a client from the server or a room, cleans everything + * @method disconnect + * @param {Object} data Data received with the request + */ +function disconnect(data) {} + +exports.start = chatservice.start; +exports.stop = chatservice.stop; +exports.getPeople = getPeople; +exports.sendMessage = sendMessage; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066952_run.js b/pool/shard010/JavaScript/0066952_run.js new file mode 100644 index 0000000000000000000000000000000000000000..420334b44d01f0f0cc9cd4525a2003617bcb5312 --- /dev/null +++ b/pool/shard010/JavaScript/0066952_run.js @@ -0,0 +1,35 @@ +const JStream = require('..'); +const assert = require('assert'); +const fs = require('fs'); + + +/** + * Tests that a `file` emits `expected` results given a `path`. + * + * @param {string} description + * @param {string} file + * @param {Array.} expected + * @param {Array.} path + */ +module.exports = (description, file, expected, path) => { + describe(description, () => { + it('JStream emits expected Javascript objects', (done) => { + const rs = fs.createReadStream(file); + const jstream = new JStream(path); + rs.pipe(jstream); + + let dataEmitted = false; + let n = 0; + + jstream.on('data', (obj) => { + dataEmitted = true; + assert.deepEqual(obj, expected[n++]); + }); + + jstream.on('end', () => { + assert.ok(dataEmitted); + done(); + }); + }); + }); +}; diff --git a/pool/shard010/JavaScript/0066955_boilerplate.test.js b/pool/shard010/JavaScript/0066955_boilerplate.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1c7f9f42747fc5e0079cf6a9ee82697469ad014d --- /dev/null +++ b/pool/shard010/JavaScript/0066955_boilerplate.test.js @@ -0,0 +1,237 @@ + +'use strict'; + +// Modules +require('should'); +var supertest = require('supertest'); + +// Subject +var app = require('../../app/index.js'); + +// Bind SuperTest +var request = supertest(app); + +describe('GET /boilerplate', function () { + + it('should respond with 200', function (done) { + request.get('/boilerplate') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .expect({ hello : 'goodbye' }) + .end(done); + }); + +}); + +describe('POST /boilerplate', function () { + + it('should respond with 200', function (done) { + request.post('/boilerplate') + .set('Accept', 'application/json') + .send({ data : 'test' }) + .expect('Content-Type', /json/) + .expect(200) + .expect({ data : 'test', processed : true }) + .end(done); + }); + +}); + +describe('DELETE /boilerplate', function () { + + it('should respond with 200', function (done) { + request.del('/boilerplate') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .expect({ deleted : true }) + .end(done); + }); + +}); + +describe('Method Override', function () { + + // POST /boilerplate (same as above) with override + it('should respond with 200 and { deleted : true }', function (done) { + request.post('/boilerplate?_method=DELETE') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .expect({ deleted : true }) + .end(done); + }); + +}); + +describe('GET /boilerplate-view', function () { + + it('should respond with 200', function (done) { + request.get('/boilerplate-view') + .expect('Content-Type', /html/) + .expect(200) + .expect(/MyCustomTitle/) + .end(done); + }); + +}); + +describe('Protected Route', function () { + + var correct_username = 'bob'; + var correct_password = 'bobisthebest'; + var incorrect_username = 'alice'; + var incorrect_password = 'aliceisthebest'; + + it('should deny a request without credentials', function (done) { + request.get('/boilerplate-protected') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(401) + .expect({ + error : { + type : 'client', + name : 'ErrorUnauthorized', + message : 'Authentication Failed' + } + }) + .end(done); + }); + + it('should deny a request with an incorrect username/password', function (done) { + request.get('/boilerplate-protected') + .set('Accept', 'application/json') + .auth(incorrect_username, incorrect_password) + .expect('Content-Type', /json/) + .expect(401) + .expect({ + error : { + type : 'client', + name : 'ErrorUnauthorized', + message : 'Authentication Failed' + } + }) + .end(done); + }); + + it('should deny a request with an incorrect username', function (done) { + request.get('/boilerplate-protected') + .set('Accept', 'application/json') + .auth(incorrect_username, correct_password) + .expect('Content-Type', /json/) + .expect(401) + .expect({ + error : { + type : 'client', + name : 'ErrorUnauthorized', + message : 'Authentication Failed' + } + }) + .end(done); + }); + + it('should deny a request with an incorrect password', function (done) { + request.get('/boilerplate-protected') + .set('Accept', 'application/json') + .auth(correct_username, incorrect_password) + .expect('Content-Type', /json/) + .expect(401) + .expect({ + error : { + type : 'client', + name : 'ErrorUnauthorized', + message : 'Authentication Failed' + } + }) + .end(done); + }); + + it('should allow a request with a correct username/password', function (done) { + request.get('/boilerplate-protected') + .set('Accept', 'application/json') + .auth(correct_username, correct_password) + .expect('Content-Type', /json/) + .expect(200) + .expect({ secret : 'sauce' }) + .end(done); + }); + +}); + +describe('Not Found (404)', function () { + + it('should respond with 404 and the path/method', function (done) { + request.get('/boilerplate-does-not-exist') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(404) + .expect({ + error : { + type : 'client', + name : 'ErrorNotFound', + message : 'Resource was not found', + data : { + method : 'GET', + path : '/boilerplate-does-not-exist' + } + } + }) + .end(done); + }); + + // Should not return query strings + it('should respond with 404 and the path/method', function (done) { + request.post('/boilerplate-lost-in-space?query=string&stuff=things') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(404) + .expect({ + error : { + type : 'client', + name : 'ErrorNotFound', + message : 'Resource was not found', + data : { + method : 'POST', + path : '/boilerplate-lost-in-space' + } + } + }) + .end(done); + }); + +}); + +describe('Server Error (500)', function () { + + it('should respond with 500 when handling a error passed to next()', function (done) { + request.get('/boilerplate-error-next') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(500) + .expect({ + error : { + type : 'server', + name : 'Error', + message : 'Next Error' + } + }) + .end(done); + }); + + it('should respond with 500 when handling a thrown error', function (done) { + request.get('/boilerplate-error-throw') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(500) + .expect({ + error : { + type : 'server', + name : 'Error', + message : 'Throw Error' + } + }) + .end(done); + }); + +}); diff --git a/pool/shard010/JavaScript/0066958_index.js b/pool/shard010/JavaScript/0066958_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a2bbffbaa6e0ced43567f69153dd93aa4fcd8009 --- /dev/null +++ b/pool/shard010/JavaScript/0066958_index.js @@ -0,0 +1,28 @@ +import React, { Component, PropTypes } from 'react'; +import classNames from 'classnames'; + +export default class Sidebar extends Component { + render() { + const { children, visible, onClose = () => {} } = this.props; + return ( +
    +
    +
    + {children} +
    +
    + ); + } +} + +Sidebar.propTypes = { + children: PropTypes.node, + visible: PropTypes.bool, + onClose: PropTypes.func +}; diff --git a/pool/shard010/JavaScript/0066962_ListMembers.js b/pool/shard010/JavaScript/0066962_ListMembers.js new file mode 100644 index 0000000000000000000000000000000000000000..7481f9a116c2ce1411ecce1b847eed9ff6461aa2 --- /dev/null +++ b/pool/shard010/JavaScript/0066962_ListMembers.js @@ -0,0 +1,76 @@ +'use strict' + +const ajax = require('../../ajax') +const browser = require('../../browser') +const BaseViewModel = require('../BaseViewModel') +const ko = require('knockout') +const moment = require('moment') + +function Member (data) { + this.id = ko.observable(data.id) + this.name = ko.observable(data.firstName + ' ' + data.lastName) + this.email = ko.observable(data.email) + this.type = ko.observable(data.memberType) + this.creationDateTime = ko.observable(data.creationDateTime) + this.joinDate = ko.observable(moment(data.creationDateTime).format('DD/MM/YY')) + this.org = ko.observable(data.organisation) + this.associatedAreaId = ko.observable(data.associatedAreaId) +} + +function ListMembers () { + const self = this + const endpoint = self.endpointBuilder.mailingListMembers().build() + + const getUniqueMemberTypes = (members) => { + const memberTypes = [] + members + .map((m) => m.memberType) + .forEach((mt) => { + if (memberTypes.indexOf(mt) < 0) memberTypes.push(mt) + }) + return memberTypes + } + + self.allMembers = ko.observableArray() + self.members = ko.observableArray() + self.memberTypes = ko.observableArray() + self.selectedMemberTypeFilter = ko.observable() + + self.filterByType = () => { + if (self.selectedMemberTypeFilter() === undefined) { + self.members(self.allMembers()) + } else { + const filtered = self.allMembers() + .filter((m) => m.type() === self.selectedMemberTypeFilter()) + self.members(filtered) + } + } + + self.init = () => { + browser.loading() + + ajax + .get(endpoint) + .then(function (result) { + const members = result.data + .map((m) => new Member(m)) + .sort((a, b) => { + if (a.creationDateTime() < b.creationDateTime()) return 1 + if (b.creationDateTime() > a.creationDateTime()) return -1 + return 0 + }) + self.allMembers(members) + self.members(self.allMembers()) + self.memberTypes(getUniqueMemberTypes(result.data)) + browser.loaded() + }, function (error) { + self.handleServerError(error) + }) + } + + self.init() +} + +ListMembers.prototype = new BaseViewModel() + +module.exports = ListMembers diff --git a/pool/shard010/JavaScript/0066963_change_listener.js b/pool/shard010/JavaScript/0066963_change_listener.js new file mode 100644 index 0000000000000000000000000000000000000000..917ac0b6da1da71396b914be0fc96e4b0c979e09 --- /dev/null +++ b/pool/shard010/JavaScript/0066963_change_listener.js @@ -0,0 +1,314 @@ +/** +* Tom Select v1.6.3 +* Licensed under the Apache License, Version 2.0 (the "License"); +*/ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) : + typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TomSelect)); +}(this, (function (TomSelect) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect); + + var defaults = { + options: [], + optgroups: [], + plugins: [], + delimiter: ',', + splitOn: null, + // regexp or string for splitting up values from a paste command + persist: true, + diacritics: true, + create: null, + createOnBlur: false, + createFilter: null, + highlight: true, + openOnFocus: true, + shouldOpen: null, + maxOptions: 50, + maxItems: null, + hideSelected: null, + duplicates: false, + addPrecedence: false, + selectOnTab: false, + preload: null, + allowEmptyOption: false, + closeAfterSelect: false, + loadThrottle: 300, + loadingClass: 'loading', + dataAttr: null, + //'data-data', + optgroupField: 'optgroup', + valueField: 'value', + labelField: 'text', + disabledField: 'disabled', + optgroupLabelField: 'label', + optgroupValueField: 'value', + lockOptgroupOrder: false, + sortField: '$order', + searchField: ['text'], + searchConjunction: 'and', + mode: null, + wrapperClass: 'ts-control', + inputClass: 'ts-input', + dropdownClass: 'ts-dropdown', + dropdownContentClass: 'ts-dropdown-content', + itemClass: 'item', + optionClass: 'option', + dropdownParent: null, + controlInput: null, + copyClassesToDropdown: true, + placeholder: null, + hidePlaceholder: null, + shouldLoad: function (query) { + return query.length > 0; + }, + + /* + load : null, // function(query, callback) { ... } + score : null, // function(search) { ... } + onInitialize : null, // function() { ... } + onChange : null, // function(value) { ... } + onItemAdd : null, // function(value, $item) { ... } + onItemRemove : null, // function(value) { ... } + onClear : null, // function() { ... } + onOptionAdd : null, // function(value, data) { ... } + onOptionRemove : null, // function(value) { ... } + onOptionClear : null, // function() { ... } + onOptionGroupAdd : null, // function(id, data) { ... } + onOptionGroupRemove : null, // function(id) { ... } + onOptionGroupClear : null, // function() { ... } + onDropdownOpen : null, // function(dropdown) { ... } + onDropdownClose : null, // function(dropdown) { ... } + onType : null, // function(str) { ... } + onDelete : null, // function(values) { ... } + */ + render: { + /* + item: null, + optgroup: null, + optgroup_header: null, + option: null, + option_create: null + */ + } + }; + + /** + * Converts a scalar to its best string representation + * for hash keys and HTML attribute values. + * + * Transformations: + * 'str' -> 'str' + * null -> '' + * undefined -> '' + * true -> '1' + * false -> '0' + * 0 -> '0' + * 1 -> '1' + * + */ + function hash_key(value) { + if (typeof value === 'undefined' || value === null) return null; + if (typeof value === 'boolean') return value ? '1' : '0'; + return value + ''; + } + /** + * Prevent default + * + */ + + function addEvent(target, type, callback, options) { + target.addEventListener(type, callback, options); + } + + function getSettings(input, settings_user) { + var settings = Object.assign({}, defaults, settings_user); + var attr_data = settings.dataAttr; + var field_label = settings.labelField; + var field_value = settings.valueField; + var field_disabled = settings.disabledField; + var field_optgroup = settings.optgroupField; + var field_optgroup_label = settings.optgroupLabelField; + var field_optgroup_value = settings.optgroupValueField; + var tag_name = input.tagName.toLowerCase(); + var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder'); + + if (!placeholder && !settings.allowEmptyOption) { + let option = input.querySelector('option[value=""]'); + + if (option) { + placeholder = option.textContent; + } + } + + var settings_element = { + placeholder: placeholder, + options: [], + optgroups: [], + items: [], + maxItems: null + }; + /** + * Initialize from a element. + * + */ + + + var init_textbox = () => { + var values, option; + var data_raw = input.getAttribute(attr_data); + + if (!data_raw) { + var value = input.value.trim() || ''; + if (!settings.allowEmptyOption && !value.length) return; + values = value.split(settings.delimiter); + + for (const _value of values) { + option = {}; + option[field_label] = _value; + option[field_value] = _value; + settings_element.options.push(option); + } + + settings_element.items = values; + } else { + settings_element.options = JSON.parse(data_raw); + + for (const opt of settings_element.options) { + settings_element.items.push(opt[field_value]); + } + } + }; + + if (tag_name === 'select') { + init_select(); + } else { + init_textbox(); + } + + return Object.assign({}, defaults, settings_element, settings_user); + } + + /** + * Plugin: "change_listener" (Tom Select) + * Copyright (c) contributors + * + * 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. + * + */ + TomSelect__default['default'].define('change_listener', function (options) { + var self = this; + var changed = false; + addEvent(self.input, 'change', () => { + // prevent infinite loops + if (changed) { + changed = false; + return; + } + + changed = true; + var settings = getSettings(self.input, {}); + self.setupOptions(settings.options, settings.optgroups); + self.setValue(settings.items); + }); + }); + +}))); +//# sourceMappingURL=change_listener.js.map diff --git a/pool/shard010/JavaScript/0066964_Moogle_X_DieAtZeroMp.js b/pool/shard010/JavaScript/0066964_Moogle_X_DieAtZeroMp.js new file mode 100644 index 0000000000000000000000000000000000000000..e0a5adc48e084ce217957f563c3253ea024cc2e2 --- /dev/null +++ b/pool/shard010/JavaScript/0066964_Moogle_X_DieAtZeroMp.js @@ -0,0 +1,151 @@ +//============================================================================= +// Die At Zero MP by Moogle_X +// Moogle_X_DieAtZeroMp.js +// Created on: November 5th 2015 +//============================================================================= + +var Imported = Imported || {}; +Imported.Moogle_X_DieAtZeroMp = true; + +var Moogle_X = Moogle_X || {}; +Moogle_X.DieZeroMp = Moogle_X.DieZeroMp || {}; + +//============================================================================= +/*: + * @plugindesc v1.1 Actors or Enemies will automatically die at 0 MP. + * @author Moogle_X + * + * @param All Actors + * @desc Decide whether all Actors will die at 0 MP by default. 1:Yes 0:No + * @default 0 + * + * @param All Enemies + * @desc Decide whether all Enemies will die at 0 MP by default. 1:Yes 0:No + * @default 0 + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * This plugin gives the ability for actors, classes, enemies, weapons, armors, + * and states to have a special trait that will make any actors or enemies + * automatically die if they have 0 MP. + * + * You can make this effect to apply to all actors and/or enemies by default + * simply by editting the plugin configuration. + * + * All Actors: 1 (for default) / 0 (for not default) + * All Enemies: 1 (for default) / 0 (for not default) + * + * If you do not set this effect as default, you are free to apply this effect + * "manually" to certain actors or enemies by adding this notetag. + * + * + * + * The above notetag can be applied to actors, classes, enemies, weapons, + * armors, and states. + * + * ============================================================================ + * Terms of Use + * ============================================================================ + * Free to use in both commercial and non-commercial project as long as credit + * is given. + * + */ +//============================================================================= + +//============================================================================= +// Constant Declaration +//============================================================================= +Game_BattlerBase.TRAIT_DIE_ZERO_MP = 110; // Brand new trait's "code" for + // die at zero MP effect. + +(function() { // IIFE + +//============================================================================= +// Parameter Variables +//============================================================================= +var parameters = PluginManager.parameters('Moogle_X_DieAtZeroMp'); +var defaultActorsDead = Number(parameters['All Actors']) != 0; +var defaultEnemiesDead = Number(parameters['All Enemies']) != 0; + +//============================================================================= +// DataManager +//============================================================================= + +Moogle_X.DieZeroMp.DatabaseLoaded = false; +Moogle_X.DieZeroMp.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; +DataManager.isDatabaseLoaded = function() { + if (!Moogle_X.DieZeroMp.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Moogle_X.DieZeroMp.DatabaseLoaded) { + DataManager.readNotetags_dieZeroMp($dataActors); + DataManager.readNotetags_dieZeroMp($dataClasses); + DataManager.readNotetags_dieZeroMp($dataEnemies); + DataManager.readNotetags_dieZeroMp($dataWeapons); + DataManager.readNotetags_dieZeroMp($dataArmors); + DataManager.readNotetags_dieZeroMp($dataStates); + Moogle_X.DieZeroMp.DatabaseLoaded = true; + } + return true; +}; + +DataManager.readNotetags_dieZeroMp = function(group) { + var note = /<(?:DIE AT ZERO MP)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + var code = Game_BattlerBase.TRAIT_DIE_ZERO_MP; + var dieZeroMpTrait = [{"code":code,"dataId":0,"value":0}]; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note)) { + obj.traits = obj.traits.concat(dieZeroMpTrait); + } + } + } +}; + +//============================================================================= +// Game_BattlerBase +//============================================================================= +Game_BattlerBase.prototype.canDieAtZeroMp = function() { + if (this.traits(Game_BattlerBase.TRAIT_DIE_ZERO_MP).length > 0) { + return true; + } else if (this.isActor() && defaultActorsDead) { + return true; + } else if (this.isEnemy() && defaultEnemiesDead) { + return true; + } else { + return false; + } +}; + +Moogle_X.DieZeroMp.Game_BattlerBase_refresh = + Game_BattlerBase.prototype.refresh; +Game_BattlerBase.prototype.refresh = function() { + Moogle_X.DieZeroMp.Game_BattlerBase_refresh.call(this); + if (this._mp === 0 && this.canDieAtZeroMp()) { + this.addState(this.deathStateId()); + } +}; + +//============================================================================= +// Game_Battler +//============================================================================= + +Moogle_X.DieZeroMp.Game_Battler_removeState = + Game_Battler.prototype.removeState; +Game_Battler.prototype.removeState = function(stateId) { + Moogle_X.DieZeroMp.Game_Battler_removeState.call(this, stateId); + if (this._mp === 0 && this.canDieAtZeroMp()) { + this.addNewState(this.deathStateId()); // Anti revival bug fix. + } +}; + +})(); // IIFE + +//============================================================================= +// End of File +//============================================================================= diff --git a/pool/shard010/JavaScript/0066965_router.js b/pool/shard010/JavaScript/0066965_router.js new file mode 100644 index 0000000000000000000000000000000000000000..5261d37004d6c5b3ab6dd9cff5ec4d996389387e --- /dev/null +++ b/pool/shard010/JavaScript/0066965_router.js @@ -0,0 +1,32 @@ +import Vue from 'vue' +import VueRouter from 'vue-router' + +Vue.use(VueRouter) + +function load (component) { + // '@' is aliased to src/components + return () => import(`@/${component}.vue`) +} + +const routes = [ + {path: '/rrr', component: load('Hello')}, + { + path: '/', + component: load('Index'), + children: [ + {path: '', component: load('main/Main')}, + {path: '/login', component: load('Login')}, + {path: '/filter', component: load('filters/CondFilterEdit')}, + {path: '/filters', component: load('filters/CondFilters')}, + {path: '/claims', component: load('claims/Claims')}, + {path: '/claim/view', component: load('claims/claim/ClaimMainView')}, + // {path: '/claim/new', component: load('claims/claim/ClaimNew')}, + {path: '/main', component: load('main/Main')} + ] + }, + { path: '*', component: load('Error404') } // Not found +] + +const Router = new VueRouter({routes}) + +export default Router diff --git a/pool/shard010/JavaScript/0066967_copy-assets.js b/pool/shard010/JavaScript/0066967_copy-assets.js new file mode 100644 index 0000000000000000000000000000000000000000..9f8f32540dcef03d965f913725df216157656895 --- /dev/null +++ b/pool/shard010/JavaScript/0066967_copy-assets.js @@ -0,0 +1,29 @@ +'use strict'; + +/****************** + * Dependencies * + ******************/ + +var Promise = require('promise'); +var ncp = require('ncp'); +var log = require('../logger'); + +/************* + * Exports * + *************/ + +module.exports = function(context) { + var settings = context.settings; + if (!settings.assets) { return context; } + + return new Promise(function(resolve, reject) { + ncp(settings.assets.src, settings.assets.dest, function(err) { + if (err) { + log('Assets', err, 'error'); + reject(); + } else { + resolve(context); + } + }); + }); +}; diff --git a/pool/shard010/JavaScript/0066971_change-type-action.js b/pool/shard010/JavaScript/0066971_change-type-action.js new file mode 100644 index 0000000000000000000000000000000000000000..40c19af260706f0332833564ae59be044f1dd108 --- /dev/null +++ b/pool/shard010/JavaScript/0066971_change-type-action.js @@ -0,0 +1,117 @@ +import {Injectable, Inject} from 'app/app'; +import {ChangeTypeDialogService} from 'idoc/actions/change-type/change-type-dialog-service'; +import {ActionsService} from 'services/rest/actions-service'; +import {InstanceObject} from 'models/instance-object'; +import {InstanceRestService} from 'services/rest/instance-service'; +import {Eventbus} from 'services/eventbus/eventbus'; +import {InstanceCreatedEvent} from 'idoc/events/instance-created-event'; +import {BeforeIdocSaveEvent} from 'idoc/actions/events/before-idoc-save-event'; +import {InstanceRefreshEvent} from 'idoc/actions/events/instance-refresh-event'; +import {RefreshWidgetsCommand} from 'idoc/actions/events/refresh-widgets-command'; +import {NamespaceService} from 'services/rest/namespace-service'; +import {PromiseAdapter} from 'adapters/angular/promise-adapter'; +import {ModelsService} from 'services/rest/models-service'; +import {RDF_TYPE} from 'instance/instance-properties'; +import {IDOC_STATE} from 'idoc/idoc-constants'; +import {EventEmitter} from 'common/event-emitter'; +import {Router} from 'adapters/router/router'; +import {StateParamsAdapter} from 'adapters/router/state-params-adapter'; + +/** + * Action which enables object type to be changed from one to another following the class definition hierarchy or any + * other custom defined constraints. The action opens pre-configured ChangeTypeDialog providing a custom instance loading + * callback function decorating the default behavior of the InstanceCreateConfiguration component. + * + * @author svelikov + */ +@Injectable() +@Inject(ChangeTypeDialogService, InstanceRestService, Eventbus, NamespaceService, PromiseAdapter, ModelsService, ActionsService, Router, StateParamsAdapter) +export class ChangeTypeAction { + + constructor(changeTypeDialogService, instanceRestService, eventbus, namespaceService, promiseAdapter, modelsService, actionsService, router, stateParamsAdapter) { + this.instanceRestService = instanceRestService; + this.changeTypeDialogService = changeTypeDialogService; + this.namespaceService = namespaceService; + this.promiseAdapter = promiseAdapter; + this.eventbus = eventbus; + this.modelsService = modelsService; + this.actionsService = actionsService; + this.router = router; + this.stateParamsAdapter = stateParamsAdapter; + } + + execute(action, actionContext) { + const instanceId = actionContext.currentObject.getId(); + let instanceResponse; + return this.instanceRestService.load(instanceId).then((instance) => { + instanceResponse = instance; + return this.modelsService.getExistingInContextInfo(instanceResponse.definitionId); + }).then((existingInContext) => { + let parentId = instanceResponse.parentId; + let purpose = instanceResponse.getPurpose(); + let definitionId = instanceResponse.definitionId; + let rdfTypeProperty = instanceResponse.getPropertyValue(RDF_TYPE); + let rdfType = rdfTypeProperty && rdfTypeProperty.getFirstValue(); + + return this.executeAction(parentId, instanceId, rdfType, definitionId, existingInContext, purpose, action); + }); + } + + executeAction(parentId, instanceId, rdfType, definitionId, existingInContext, purpose, actionDefinition) { + let eventEmitter = new EventEmitter(); + + let config = { + parentId, + instanceId, + purpose, + eventEmitter, + existingInContext, + instanceType: null, + instanceSubType: definitionId, + contextSelectorSelectionMode: existingInContext, + onChangeType: (models) => { + return this.changeType(instanceId, models, actionDefinition); + } + }; + + return this.namespaceService.toFullURI([rdfType]).then(({data: fullUrisMap}) => { + config.instanceType = fullUrisMap[rdfType]; + return this.changeTypeDialogService.openDialog(config); + }); + } + + changeType(instanceId, models, actionDefinition) { + let instanceObject = new InstanceObject(instanceId, models); + let data = { + id: instanceId, + definitionId: instanceObject.getModels().definitionId, + parentId: instanceObject.getModels().parentId || null, + properties: instanceObject.getChangeset(false) + }; + + this.eventbus.publish(new BeforeIdocSaveEvent(data)); + + return this.actionsService.changeType(instanceId, data).then((instanceResponse) => { + this.eventbus.publish(new InstanceCreatedEvent({ + currentObject: instanceResponse.data + })); + + // when current object is opened, then reload view in order to get the actual data and template + if (this.isCurrentObjectDashboard(instanceId)) { + this.router.navigate(IDOC_STATE, this.stateParamsAdapter.getStateParams(), {reload: true}); + } else { + this.eventbus.publish(new InstanceRefreshEvent({ + response: instanceResponse + })); + // when operation is executed from a widget, I need to refresh all visible widgets, because + // there is a chance that the object with its new type should appear in another widget + this.eventbus.publish(new RefreshWidgetsCommand()); + } + return instanceResponse; + }); + } + + isCurrentObjectDashboard(instanceId) { + return this.router.getCurrentState() === IDOC_STATE && this.router.getCurrentParams().id === instanceId; + } +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066972_background.js b/pool/shard010/JavaScript/0066972_background.js new file mode 100644 index 0000000000000000000000000000000000000000..cf0f3c082227a5f12182bf85fa8028a5d08ebc45 --- /dev/null +++ b/pool/shard010/JavaScript/0066972_background.js @@ -0,0 +1,132 @@ +var serverUrl = "http://example.com/api/embeds"; + +/** +* Lists of regular expresions that will be used to check if +* the url is an embed or not and show the Embedio button. +*/ +embedAuditions = { + youTube : [ + '^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/watch.+$', + '^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/v/.+$' + ], + speakerDeck : [ + '^http(?:s)?://speakerdeck\\.com/.+$' + ], + codePen : [ + '^http(?:s)?://codepen\\.io/[^#?/]+/pen/.+$' + ], + vimeo : [ + '^http(?:s)?://(?:www\\.)?vimeo\\.com/.+$', + '^http(?:s)?://player\\.vimeo\\.com/.+$' + ], + slideshare : [ + '^http://www\\.slideshare\\.net/.+$' + ], + kickstarter : [ + '^http(?:s)?://[-\\w]+\\.kickstarter\\.com/projects/[^#?/]+/.+$' + ] +}; + +Embedio = { + + /** + * Grabs the Url to check if could build an embed from it by + * filtering from a list of possibilities. + */ + audit : function(tab, cb) { + var hostArr = tab.url.match(/^[\w-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[1].split('.'), + host = hostArr[hostArr.length - 2], + url = tab.url, + isEmbed = false; + switch ( host ) { + case 'youtube' : + isEmbed = Embedio.detect(url, embedAuditions.youTube); + break; + case 'speakerdeck' : + isEmbed = Embedio.detect(url, embedAuditions.speakerDeck); + break; + case 'codepen' : + isEmbed = Embedio.detect(url, embedAuditions.codePen); + break; + case 'vimeo' : + isEmbed = Embedio.detect(url, embedAuditions.vimeo); + break; + case 'slideshare' : + isEmbed = Embedio.detect(url, embedAuditions.slideshare); + break; + case 'kickstarter' : + isEmbed = Embedio.detect(url, embedAuditions.kickstarter); + break; + } + if ( isEmbed ) { + chrome.pageAction.show(tab.id); + cb({ valid : true, tab : tab }); + } else { + chrome.pageAction.hide(tab.id); + cb({ valid : false }); + } + }, + + + /** + * If the url matches a case then audits the url from a lists + * of convenient tests gotten from the newtwork. + */ + detect : function(url, list) { + var size = list.length; + for ( var i=0; i} + * @throws {ForbiddenError} If viewer is not an admin + */ + async query(viewer, inputs = {}) { + if(!viewer.isAdmin()) { + return Promise.resolve([]); + } + + const query = this.orderModel.find(); + return query.exec(); + } + + /** + * Find order by id + * @param {User} viewer + * @param {ObjectId} id + * @return {Promise} + */ + async findById(viewer, id) { + return this.orderModel.findById(id).exec(); + } + + /** + * Create order + * @param {User} viewer + * @param {Object} data + * @return {Promise} + */ + async create(viewer, data) { + return this.orderModel.create(data); + } + + /** + * Update order attributes + * @param {User} viewer + * @param {ObjectId} id + * @param {Object} data + * @return {Promise} + * @throws {Error} + */ + async update(viewer, id, data) { + throw new Error('Not implemented'); + } + + /** + * Update order status + * @param {User} viewer + * @param {ObjectId} id + * @param {string} status + * @return {Promise} + * @throws {ForbiddenError} If viewer is not an admin + * @throws {ModelNotFoundError} If order doesnt exist + */ + async updateStatus(viewer, id, status) { + if(!viewer.isAdmin()) { + throw new ForbiddenError("You are not authorized to make this action."); + } + + // Find the order + const order = await this.orderModel.findById(id); + + if(!order) { + throw new ModelNotFoundError("The order you are trying to update doesnt exist"); + } + + // Update order status + order.status = status; + + return order.save(); + } + + /** + * Remove order by id + * @param {User} viewer + * @param {ObjectId} id + * @return {Promise} + * @throws {ForbiddenError} If viewer is not an admin + * @throws {ModelNotFoundError} If order doesnt exist + */ + async remove(viewer, id) { + if(!viewer.isAdmin()) { + throw new ForbiddenError("You are not authorized to make this action."); + } + + const order = await this.orderModel.findById(id); + + if(! order) { + throw new ModelNotFoundError("The order you are requesting to remove doesnt exist"); + } + + return order.remove(); + } +} + +IoC.singleton('orderRepository', [ + 'orderModel', +], OrderRepository); diff --git a/pool/shard010/JavaScript/0066975_example.js b/pool/shard010/JavaScript/0066975_example.js new file mode 100644 index 0000000000000000000000000000000000000000..4f36a5e27ce24221febe0d8b9609cd449fbcd49f --- /dev/null +++ b/pool/shard010/JavaScript/0066975_example.js @@ -0,0 +1,57 @@ +// initialize react-backbone +var React = require('react'); +var Backbone = require('backbone'); +var _ = require('underscore'); +var $ = require('jquery'); +require('react-backbone/with-deps')(React, Backbone, _, $); + + +// simple function to return the state object that contains the "profile" value +function getStateValues (size, self) { + var width = $(self.getDOMNode()).width(); + return { + profile: width > size ? 'large' : 'small' + }; +} + +// instead of using a standard object for the mixin attributes, we can use a function +// which returns the object to allow us to reference the function parameters in our mixin functions +React.mixins.add('responsive', function(size) { + size = size || 600; + + return { + // the "manageEvents" method is available because we import the "events" mixin + mixins: ['events'], + + getInitialState: function() { + + // throttle an event handler every 300 ms which is bound to the "resize" window event + this.manageEvents({ + '*throttle(300)->window:resize': function() { + this.setState(getStateValues(size, this)); + } + }); + + // make a guess which will be replaced when the component is mounted + return { profile: 'large' }; + }, + + componentDidMount: function() { + this.setState(getStateValues(size, this)); + } + }; +}); + + +var TestComponent = React.createClass({ + // now the component width breakpoint will be at 500px + mixins: ['responsive(500)'], + + render: function() { + return
    {this.state.profile}
    + } +}); + + +// INITIAL RENDER +React.render(, document.body); diff --git a/pool/shard010/JavaScript/0066976_add-field.js b/pool/shard010/JavaScript/0066976_add-field.js new file mode 100644 index 0000000000000000000000000000000000000000..f64e7e119470831617f8bbd45d4d3e29c3a389a6 --- /dev/null +++ b/pool/shard010/JavaScript/0066976_add-field.js @@ -0,0 +1,79 @@ +/************************************************************************ + * This file is part of EspoCRM. + * + * EspoCRM - Open Source CRM application. + * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko + * Website: http://www.espocrm.com + * + * EspoCRM 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. + * + * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. + * + * The interactive user interfaces in modified source and object code versions + * of this program must display Appropriate Legal Notices, as required under + * Section 5 of the GNU General Public License version 3. + * + * In accordance with Section 7(b) of the GNU General Public License version 3, + * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. + ************************************************************************/ + +Espo.define('views/role/modals/add-field', 'views/modal', function (Dep) { + + return Dep.extend({ + + template: 'role/modals/add-field', + + events: { + 'click a[data-action="addField"]': function (e) { + this.trigger('add-field', $(e.currentTarget).data().name); + } + }, + + data: function () { + var dataList = []; + var d = []; + this.fieldList.forEach(function (field, i) { + if (i % 4 === 0) { + dataList.push([]); + } + dataList[dataList.length -1].push(field); + }, this); + + return { + dataList: dataList, + scope: this.scope + }; + }, + + setup: function () { + this.header = this.translate('Add Field'); + + var scope = this.scope = this.options.scope; + + var fields = this.getMetadata().get('entityDefs.' + scope + '.fields') || {}; + + var fieldList = []; + + Object.keys(fields).forEach(function (field) { + var d = fields[field]; + if (field in this.options.ignoreFieldList) return; + if (d.disabled) return; + + fieldList.push(field); + }, this); + + this.fieldList = this.getLanguage().sortFieldList(scope, fieldList); + } + + }); +}); + diff --git a/pool/shard010/JavaScript/0066977_riotcontrol.js b/pool/shard010/JavaScript/0066977_riotcontrol.js new file mode 100644 index 0000000000000000000000000000000000000000..405a5058caf2da65ffa612dac0d6713a903bebb3 --- /dev/null +++ b/pool/shard010/JavaScript/0066977_riotcontrol.js @@ -0,0 +1,17 @@ +var RiotControl = { + _stores: [], + addStore: function(store) { + this._stores.push(store); + } +}; + +['on','one','off','trigger'].forEach(function(api){ + RiotControl[api] = function() { + var args = [].slice.call(arguments); + this._stores.forEach(function(el){ + el[api].apply(null, args); + }); + }; +}); + +if (typeof(module) !== 'undefined') module.exports = RiotControl; diff --git a/pool/shard010/JavaScript/0066978_picker_android_spinner_date.js b/pool/shard010/JavaScript/0066978_picker_android_spinner_date.js new file mode 100644 index 0000000000000000000000000000000000000000..a15469eb0f918f9a481e2f5a39155ea381774572 --- /dev/null +++ b/pool/shard010/JavaScript/0066978_picker_android_spinner_date.js @@ -0,0 +1,72 @@ +function picker_spinner_date(_args) { + var win = Ti.UI.createWindow({ + title:_args.title + }); + win.backgroundColor = 'black'; + + var minDate = new Date(); + minDate.setFullYear(2009); + minDate.setMonth(0); + minDate.setDate(1); + + var maxDate = new Date(); + maxDate.setFullYear(2009); + maxDate.setMonth(11); + maxDate.setDate(31); + + var value = new Date(); + value.setFullYear(2009); + value.setMonth(0); + value.setDate(1); + + var picker = Ti.UI.createPicker({ + useSpinner: true, + type:Ti.UI.PICKER_TYPE_DATE, + minDate:minDate, + maxDate:maxDate, + value:value + }); + + // turn on the selection indicator (off by default) + picker.selectionIndicator = true; + + win.add(picker); + + var label = Ti.UI.createLabel({ + text:'Choose a date', + top:6, + width:'auto', + height:'auto', + textAlign:'center', + color:'white' + }); + win.add(label); + + picker.addEventListener('change',function(e) + { + label.text = e.value; + }); + + var locale = false; + var localebutton = Ti.UI.createButton({ + title:'Change locale', + bottom:20, + width:200, + height:40 + }); + localebutton.addEventListener('click', function() { + if (!locale) { + picker.setLocale('ru'); + locale = true; + } + else { + locale = false; + picker.setLocale(Titanium.Platform.locale); + } + }); + win.add(localebutton); + + return win; +} + +module.exports = picker_spinner_date; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066979_autoheight.js b/pool/shard010/JavaScript/0066979_autoheight.js new file mode 100644 index 0000000000000000000000000000000000000000..cd35da22a207c46872688dcea5af5b6f1361ad88 --- /dev/null +++ b/pool/shard010/JavaScript/0066979_autoheight.js @@ -0,0 +1,53 @@ +// +// Copyright Kamil Pękala http://github.com/kamilkp +// autoheight v0.0.1 +// +;(function(window, document){ + /* jshint eqnull:true */ + /* jshint -W041 */ + + var msie = +((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]); + if (isNaN(msie)) + msie = +((/trident\/.*; rv:(\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]); + + var style = document.createElement('style'); + style.innerHTML = '[autoheight]{overflow: hidden; resize: none; box-sizing: border-box;}'; + document.head.appendChild(style); + + window.autoheight = autoheight; + + function autoheight(node){ + + // listeners not attached yet + if(node.getAttribute('autoheight') == null){ + node.setAttribute('autoheight', ''); + // user input, copy, paste, cut occurrences + node.addEventListener('input', adjust, false); + node.addEventListener('change', adjust, false); + } + + // initial adjust + adjust(); + + function adjust(){ + var lineHeight = getLineHeight(node); + if(!(node.offsetHeight || node.offsetWidth)) return; + if(node.scrollHeight <= node.clientHeight) + node.style.height = '0px'; + var h = node.scrollHeight + // actual height defined by content + node.offsetHeight - // border size compensation + node.clientHeight; // -- || -- + node.style.height = Math.max(h, lineHeight) + + (msie && lineHeight ? lineHeight : 0) + // ie extra row + 'px'; + } + } + + function getLineHeight(node){ + var computedStyle = window.getComputedStyle(node); + var lineHeightStyle = computedStyle.lineHeight; + if(lineHeightStyle === 'normal') return +computedStyle.fontSize.slice(0, -2); + else return +lineHeightStyle.slice(0, -2); + } + +})(window, document); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066980_spiral_stairs.js b/pool/shard010/JavaScript/0066980_spiral_stairs.js new file mode 100644 index 0000000000000000000000000000000000000000..ad51633c93c48cff1008da51b4664f7db0b506da --- /dev/null +++ b/pool/shard010/JavaScript/0066980_spiral_stairs.js @@ -0,0 +1,46 @@ +var Drone = require('../drone').Drone; +var blocks = require('blocks'); + +/************************************************************************ +### Drone.spiral_stairs() method + +Constructs a spiral staircase with slabs at each corner. + +#### Parameters + + * stairBlock - The block to use for stairs, should be one of the following... + - 'oak' + - 'spruce' + - 'birch' + - 'jungle' + - 'cobblestone' + - 'brick' + - 'stone' + - 'nether' + - 'sandstone' + - 'quartz' + * flights - The number of flights of stairs to build. + +![Spiral Staircase](img/spiralstair1.png) + +#### Example + +To construct a spiral staircase 5 floors high made of oak... + + spiral_stairs('oak', 5); + +***/ +Drone.extend("spiral_stairs",function(stairBlock, flights){ + this.chkpt('spiral_stairs'); + + for (var i = 0; i < flights; i++){ + this + .box(blocks.stairs[stairBlock] + ':' + Drone.PLAYER_STAIRS_FACING[this.dir]) + .up().fwd() + .box(blocks.stairs[stairBlock] + ':' + Drone.PLAYER_STAIRS_FACING[this.dir]) + .up().fwd() + .box(blocks.slab[stairBlock]) + .turn().fwd(); + } + return this.move('spiral_stairs'); +}); diff --git a/pool/shard010/JavaScript/0066983_authCtrl.js b/pool/shard010/JavaScript/0066983_authCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..02da6a122bfdba813a0f944f96bbca312d6f0e6c --- /dev/null +++ b/pool/shard010/JavaScript/0066983_authCtrl.js @@ -0,0 +1,87 @@ +'use strict'; + +/** + * The authentication controller (login & facebook) + * + */ + +habitrpg.controller('AuthCtrl', + ['$scope', '$rootScope', 'Facebook', 'LocalAuth', 'User', '$http', '$location', 'API_URL', + function($scope, $rootScope, Facebook, LocalAuth, User, $http, $location, API_URL) { + $scope.Facebook = Facebook; + $scope.Local = LocalAuth; + + var showedFacebookMessage = false; + $scope.useUUID = false; + $scope.toggleUUID = function() { + if (showedFacebookMessage == false) { + alert("Until we add Facebook, use your UUID and API Token to log in (found at https://habitrpg.com > Options > Settings).") + showedFacebookMessage = true; + } + $scope.useUUID = !$scope.useUUID; + } + + document.addEventListener('deviceready', function() { + + FB.init({ + appId: '374812825970494', + nativeInterface: CDV.FB, + useCachedDialogs: false + }); + + }, false); + + $scope.register = function() { + if ($scope.registrationForm.$invalid) { + //TODO highlight invalid inputs + // we have this as a workaround for https://github.com/HabitRPG/habitrpg-mobile/issues/64 + return; + } + $http.post(API_URL + '/api/v2/register', $scope.registerVals) + .success(function(data, status, headers, config) { + User.authenticate(data.id, data.apiToken, function(err) { + $location.path("/habit"); + }); + }) + .error(function(data, status, headers, config) { + if (status === 0) { + alert("Server not currently reachable, try again later"); + } else if (!!data && !!data.err) { + alert(data.err); + } else { + alert('ERROR: ' + status); + } + }); + } + + $scope.auth = function() { + var data = { + username: $scope.loginUsername, + password: $scope.loginPassword + } + + var runAuth = function(id, token){ + User.authenticate(id, token, function(err) { + $location.path("/habit"); + }); + } + + if ($scope.useUUID) { + runAuth($scope.loginUsername, $scope.loginPassword); + } else { + $http.post(API_URL + '/api/v2/user/auth/local', data) + .success(function(data, status, headers, config) { + runAuth(data.id, data.token); + }).error(function(data, status, headers, config) { + if (status === 0) { + alert("Server not currently reachable, try again later"); + } else if (!!data && !!data.err) { + alert(data.err); + } else { + alert('ERROR: ' + status); + } + }); + } + } + } +]); diff --git a/pool/shard010/JavaScript/0066984_geiesmonads_reader.js b/pool/shard010/JavaScript/0066984_geiesmonads_reader.js new file mode 100644 index 0000000000000000000000000000000000000000..9c1d40825901c86a4b7d8c0dde8b7e48990f9f43 --- /dev/null +++ b/pool/shard010/JavaScript/0066984_geiesmonads_reader.js @@ -0,0 +1,22 @@ +var MONAD = {}; + +// NB: rm means 'reader monad'; type of context is ctx, not r! +MONAD.reader = (() => { // rm a = rm ctx a = rm (ctx -> a) + var monad = fctxa => { // fctxa :: ctx -> a + var thisreader = ctx => fctxa(ctx); // thisreader :: ctx -> a + thisreader.bind = farmb => monad(ctx => { // rm b :: ctx -> b + var a = thisreader(ctx); + return farmb(a)(ctx); // rm b ctx :: b + }); + return thisreader; + }; + + return { // NB writing 'rm a' or 'rm ctx a' is the same + UNIT: a => monad(_ => a), // UNIT :: a -> rm a = a -> rm (ctx -> a) + reader: monad, // monad :: (ctx -> a) -> rm a + ask: _ => monad(ctx => ctx), // ask :: ctx -> rm ctx + asks: fctxb => monad(fctxb), // asks :: (ctx -> b) -> rm b + // local :: (ctx -> ctx) -> rm a -> rm a + local: fctxctx => rma => monad(ctx => rma(fctxctx(ctx))) + }; +})(); diff --git a/pool/shard010/JavaScript/0066985_info.spec.js b/pool/shard010/JavaScript/0066985_info.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8f45b287495c5147342b205797d4b8a793591868 --- /dev/null +++ b/pool/shard010/JavaScript/0066985_info.spec.js @@ -0,0 +1,33 @@ +/** + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +var search = require('../../src/plugman/info'); +var Q = require('q'); +var registry = require('../../src/plugman/registry/registry'); + +describe('info', function () { + it('Test 001 : should show plugin info', function () { + var sSearch = spyOn(registry, 'info').and.returnValue(Q({ + name: 'fakePlugin', + version: '1.0.0', + engines: [{ name: 'plugman', version: '>=0.11' }] + })); + search(new Array('myplugin')); + expect(sSearch).toHaveBeenCalledWith(['myplugin']); + }); +}); diff --git a/pool/shard010/JavaScript/0066986_targets.js b/pool/shard010/JavaScript/0066986_targets.js new file mode 100644 index 0000000000000000000000000000000000000000..51c605249e7e1996daae018b269280b29257dce9 --- /dev/null +++ b/pool/shard010/JavaScript/0066986_targets.js @@ -0,0 +1,81 @@ + +var getTime = require('../medtronic-clock'); + +function bgTargetsLookup (inputs, profile) { + return bound_target_range(lookup(inputs, profile)); +} + +function lookup (inputs, profile) { + var bgtargets_data = inputs.targets; + var temptargets_data = inputs.temptargets; + var now = new Date(); + + //bgtargets_data.targets.sort(function (a, b) { return a.offset > b.offset }); + + var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1]; + + for (var i = 0; i < bgtargets_data.targets.length - 1; i++) { + if ((now >= getTime(bgtargets_data.targets[i].offset)) && (now < getTime(bgtargets_data.targets[i + 1].offset))) { + bgTargets = bgtargets_data.targets[i]; + break; + } + } + + if (profile.wide_bg_target_range === true) { + console.error('Allowing wide eventualBG target range: ' + bgTargets.low + ' - ' + bgTargets.high ); + } else { + bgTargets.high = bgTargets.low; + } + + var tempTargets = bgTargets; + + // sort tempTargets by date so we can process most recent first + try { + temptargets_data.sort(function (a, b) { return new Date(b.created_at) - new Date(a.created_at) }); + } catch (e) { + console.error("No temptargets found."); + } + //console.error(temptargets_data); + //console.error(now); + for (i = 0; i < temptargets_data.length; i++) { + start = new Date(temptargets_data[i].created_at); + //console.error(start); + expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000); + //console.error(expires); + if (now >= new Date(temptargets_data[i].created_at) && temptargets_data[i].duration === 0) { + // cancel temp targets + //console.error(temptargets_data[i]); + tempTargets = bgTargets; + break; + } else if (now >= new Date(temptargets_data[i].created_at) && now < expires ) { + //console.error(temptargets_data[i]); + tempTargets.high = temptargets_data[i].targetTop; + tempTargets.low = temptargets_data[i].targetBottom; + tempTargets.temptargetSet = true; + break; + } + } + bgTargets = tempTargets; + //console.error(bgTargets); + + return bgTargets; +} + +function bound_target_range (target) { + // if targets are < 20, assume for safety that they're intended to be mmol/L, and convert to mg/dL + if ( target.high < 20 ) { target.high = target.high * 18; } + if ( target.low < 20 ) { target.low = target.low * 18; } + // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong + target.max_bg = Math.max(80, target.high); + target.min_bg = Math.max(80, target.low); + // hard-code upper bound for min_bg in case pump is set too high + target.min_bg = Math.min(200, target.min_bg); + target.max_bg = Math.min(200, target.max_bg); + return target +} + +bgTargetsLookup.bgTargetsLookup = bgTargetsLookup; +bgTargetsLookup.lookup = lookup; +bgTargetsLookup.bound_target_range = bound_target_range; +exports = module.exports = bgTargetsLookup; + diff --git a/pool/shard010/JavaScript/0066989_DevicesController.js b/pool/shard010/JavaScript/0066989_DevicesController.js new file mode 100644 index 0000000000000000000000000000000000000000..df75b1d4682bc745cdaeb18a1852ab3ca56c929f --- /dev/null +++ b/pool/shard010/JavaScript/0066989_DevicesController.js @@ -0,0 +1,177 @@ +/* + * Copyright 2015 - 2017 Anton Tananaev (anton@traccar.org) + * + * 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 . + */ + +Ext.define('Traccar.view.edit.DevicesController', { + extend: 'Traccar.view.edit.ToolbarController', + alias: 'controller.devices', + + requires: [ + 'Traccar.view.dialog.Command', + 'Traccar.view.dialog.Device', + 'Traccar.view.permissions.DeviceGeofences', + 'Traccar.view.permissions.DeviceAttributes', + 'Traccar.view.permissions.DeviceDrivers', + 'Traccar.view.BaseWindow', + 'Traccar.model.Device', + 'Traccar.model.Command' + ], + + config: { + listen: { + controller: { + '*': { + selectreport: 'selectReport' + }, + 'root': { + selectdevice: 'selectDevice' + }, + 'map': { + selectdevice: 'selectDevice', + deselectfeature: 'deselectFeature' + } + }, + store: { + '#Devices': { + update: 'onUpdateDevice' + } + } + } + }, + + objectModel: 'Traccar.model.Device', + objectDialog: 'Traccar.view.dialog.Device', + removeTitle: Strings.sharedDevice, + + init: function () { + var self = this, readonly, deviceReadonly; + deviceReadonly = Traccar.app.getPreference('deviceReadonly', false) && !Traccar.app.getUser().get('admin'); + readonly = Traccar.app.getPreference('readonly', false) && !Traccar.app.getUser().get('admin'); + this.lookupReference('toolbarAddButton').setDisabled(readonly || deviceReadonly); + this.lookupReference('toolbarDriversButton').setHidden( + Traccar.app.getVehicleFeaturesDisabled() || Traccar.app.getBooleanAttributePreference('ui.disableDrivers')); + this.lookupReference('toolbarAttributesButton').setHidden( + Traccar.app.getBooleanAttributePreference('ui.disableComputedAttributes')); + + setInterval(function () { + self.getView().getView().refresh(); + }, Traccar.Style.refreshPeriod); + }, + + onGeofencesClick: function () { + var device = this.getView().getSelectionModel().getSelection()[0]; + Ext.create('Traccar.view.BaseWindow', { + title: Strings.sharedGeofences, + items: { + xtype: 'deviceGeofencesView', + baseObjectName: 'deviceId', + linkObjectName: 'geofenceId', + storeName: 'Geofences', + baseObject: device.getId() + } + }).show(); + }, + + onAttributesClick: function () { + var device = this.getView().getSelectionModel().getSelection()[0]; + Ext.create('Traccar.view.BaseWindow', { + title: Strings.sharedComputedAttributes, + items: { + xtype: 'deviceAttributesView', + baseObjectName: 'deviceId', + linkObjectName: 'attributeId', + storeName: 'ComputedAttributes', + baseObject: device.getId() + } + }).show(); + }, + + onDriversClick: function () { + var device = this.getView().getSelectionModel().getSelection()[0]; + Ext.create('Traccar.view.BaseWindow', { + title: Strings.sharedDrivers, + items: { + xtype: 'deviceDriversView', + baseObjectName: 'deviceId', + linkObjectName: 'driverId', + storeName: 'Drivers', + baseObject: device.getId() + } + }).show(); + }, + + onCommandClick: function () { + var device, deviceId, command, dialog, typesStore, online; + device = this.getView().getSelectionModel().getSelection()[0]; + online = device.get('status') === 'online'; + deviceId = device.get('id'); + + command = Ext.create('Traccar.model.Command'); + command.set('deviceId', deviceId); + command.set('textChannel', !online); + + dialog = Ext.create('Traccar.view.dialog.Command'); + + typesStore = dialog.lookupReference('commandType').getStore(); + typesStore.getProxy().setExtraParam('deviceId', deviceId); + + dialog.down('form').loadRecord(command); + dialog.lookupReference('textChannelCheckBox').setDisabled(!online); + dialog.show(); + }, + + updateButtons: function (selected) { + var readonly, deviceReadonly, empty; + deviceReadonly = Traccar.app.getPreference('deviceReadonly', false) && !Traccar.app.getUser().get('admin'); + readonly = Traccar.app.getPreference('readonly', false) && !Traccar.app.getUser().get('admin'); + empty = selected.length === 0; + this.lookupReference('toolbarEditButton').setDisabled(empty || readonly || deviceReadonly); + this.lookupReference('toolbarRemoveButton').setDisabled(empty || readonly || deviceReadonly); + this.lookupReference('toolbarGeofencesButton').setDisabled(empty || readonly); + this.lookupReference('toolbarAttributesButton').setDisabled(empty || readonly); + this.lookupReference('toolbarDriversButton').setDisabled(empty || readonly); + this.lookupReference('deviceCommandButton').setDisabled(empty || readonly); + }, + + onSelectionChange: function (selection, selected) { + this.updateButtons(selected); + if (selected.length > 0) { + this.fireEvent('selectdevice', selected[0], true); + } else { + this.fireEvent('deselectfeature'); + } + }, + + selectDevice: function (device) { + this.getView().getSelectionModel().select([device], false, true); + this.updateButtons(this.getView().getSelectionModel()); + this.getView().getView().focusRow(device); + }, + + selectReport: function (position) { + if (position !== undefined) { + this.deselectFeature(); + } + }, + + onUpdateDevice: function () { + this.updateButtons(this.getView().getSelectionModel()); + }, + + deselectFeature: function () { + this.getView().getSelectionModel().deselectAll(); + } +}); diff --git a/pool/shard010/JavaScript/0066990_ReactDefaultPerf.js b/pool/shard010/JavaScript/0066990_ReactDefaultPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..f5a0b416da34233a659a8a7e0b9648ce5dd5e13a --- /dev/null +++ b/pool/shard010/JavaScript/0066990_ReactDefaultPerf.js @@ -0,0 +1,407 @@ +/** + * Copyright 2013 Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @providesModule ReactDefaultPerf + * @typechecks static-only + */ + +"use strict"; + +var performanceNow = require("./performanceNow"); + +var ReactDefaultPerf = {}; + +if (true) { + ReactDefaultPerf = { + /** + * Gets the stored information for a given object's function. + * + * @param {string} objName + * @param {string} fnName + * @return {?object} + */ + getInfo: function(objName, fnName) { + if (!this.info[objName] || !this.info[objName][fnName]) { + return null; + } + return this.info[objName][fnName]; + }, + + /** + * Gets the logs pertaining to a given object's function. + * + * @param {string} objName + * @param {string} fnName + * @return {?array} + */ + getLogs: function(objName, fnName) { + if (!this.getInfo(objName, fnName)) { + return null; + } + return this.logs.filter(function(log) { + return log.objName === objName && log.fnName === fnName; + }); + }, + + /** + * Runs through the logs and builds an array of arrays, where each array + * walks through the mounting/updating of each component underneath. + * + * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]' + * @return {array} + */ + getRawRenderHistory: function(rootID) { + var history = []; + /** + * Since logs are added after the method returns, the logs are in a sense + * upside-down: the inner-most elements from mounting/updating are logged + * first, and the last addition to the log is the top renderComponent. + * Therefore, we flip the logs upside down for ease of processing, and + * reverse the history array at the end so the earliest event has index 0. + */ + var logs = this.logs.filter(function(log) { + return log.reactID.indexOf(rootID) === 0; + }).reverse(); + + var subHistory = []; + logs.forEach(function(log, i) { + if (i && log.reactID === rootID && logs[i - 1].reactID !== rootID) { + subHistory.length && history.push(subHistory); + subHistory = []; + } + subHistory.push(log); + }); + if (subHistory.length) { + history.push(subHistory); + } + return history.reverse(); + }, + + /** + * Runs through the logs and builds an array of strings, where each string + * is a multiline formatted way of walking through the mounting/updating + * underneath. + * + * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]' + * @return {array} + */ + getRenderHistory: function(rootID) { + var history = this.getRawRenderHistory(rootID); + + return history.map(function(subHistory) { + var headerString = ( + 'log# Component (execution time) [bloat from logging]\n' + + '================================================================\n' + ); + return headerString + subHistory.map(function(log) { + // Add two spaces for every layer in the reactID. + var indents = '\t' + Array(log.reactID.split('.[').length).join(' '); + var delta = _microTime(log.timing.delta); + var bloat = _microTime(log.timing.timeToLog); + + return log.index + indents + log.name + ' (' + delta + 'ms)' + + ' [' + bloat + 'ms]'; + }).join('\n'); + }); + }, + + /** + * Print the render history from `getRenderHistory` using console.log. + * This is currently the best way to display perf data from + * any React component; working on that. + * + * @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]' + * @param {number} index + */ + printRenderHistory: function(rootID, index) { + var history = this.getRenderHistory(rootID); + if (!history[index]) { + console.warn( + 'Index', index, 'isn\'t available! ' + + 'The render history is', history.length, 'long.' + ); + return; + } + console.log( + 'Loading render history #' + (index + 1) + + ' of ' + history.length + ':\n' + history[index] + ); + }, + + /** + * Prints the heatmap legend to console, showing how the colors correspond + * with render times. This relies on console.log styles. + */ + printHeatmapLegend: function() { + if (!this.options.heatmap.enabled) { + return; + } + var max = this.info.React + && this.info.React.renderComponent + && this.info.React.renderComponent.max; + if (max) { + var logStr = 'Heatmap: '; + for (var ii = 0; ii <= 10 * max; ii += max) { + logStr += '%c ' + (Math.round(ii) / 10) + 'ms '; + } + console.log( + logStr, + 'background-color: hsla(100, 100%, 50%, 0.6);', + 'background-color: hsla( 90, 100%, 50%, 0.6);', + 'background-color: hsla( 80, 100%, 50%, 0.6);', + 'background-color: hsla( 70, 100%, 50%, 0.6);', + 'background-color: hsla( 60, 100%, 50%, 0.6);', + 'background-color: hsla( 50, 100%, 50%, 0.6);', + 'background-color: hsla( 40, 100%, 50%, 0.6);', + 'background-color: hsla( 30, 100%, 50%, 0.6);', + 'background-color: hsla( 20, 100%, 50%, 0.6);', + 'background-color: hsla( 10, 100%, 50%, 0.6);', + 'background-color: hsla( 0, 100%, 50%, 0.6);' + ); + } + }, + + /** + * Measure a given function with logging information, and calls a callback + * if there is one. + * + * @param {string} objName + * @param {string} fnName + * @param {function} func + * @return {function} + */ + measure: function(objName, fnName, func) { + var info = _getNewInfo(objName, fnName); + + var fnArgs = _getFnArguments(func); + + return function() { + var timeBeforeFn = performanceNow(); + var fnReturn = func.apply(this, arguments); + var timeAfterFn = performanceNow(); + + /** + * Hold onto arguments in a readable way: args[1] -> args.component. + * args is also passed to the callback, so if you want to save an + * argument in the log, do so in the callback. + */ + var args = {}; + for (var i = 0; i < arguments.length; i++) { + args[fnArgs[i]] = arguments[i]; + } + + var log = { + index: ReactDefaultPerf.logs.length, + fnName: fnName, + objName: objName, + timing: { + before: timeBeforeFn, + after: timeAfterFn, + delta: timeAfterFn - timeBeforeFn + } + }; + + ReactDefaultPerf.logs.push(log); + + /** + * The callback gets: + * - this (the component) + * - the original method's arguments + * - what the method returned + * - the log object, and + * - the wrapped method's info object. + */ + var callback = _getCallback(objName, fnName); + callback && callback(this, args, fnReturn, log, info); + + log.timing.timeToLog = performanceNow() - timeAfterFn; + + return fnReturn; + }; + }, + + /** + * Holds information on wrapped objects/methods. + * For instance, ReactDefaultPerf.info.React.renderComponent + */ + info: {}, + + /** + * Holds all of the logs. Filter this to pull desired information. + */ + logs: [], + + /** + * Toggle settings for ReactDefaultPerf + */ + options: { + /** + * The heatmap sets the background color of the React containers + * according to how much total time has been spent rendering them. + * The most temporally expensive component is set as pure red, + * and the others are colored from green to red as a fraction + * of that max component time. + */ + heatmap: { + enabled: true + } + } + }; + + /** + * Gets a info area for a given object's function, adding a new one if + * necessary. + * + * @param {string} objName + * @param {string} fnName + * @return {object} + */ + var _getNewInfo = function(objName, fnName) { + var info = ReactDefaultPerf.getInfo(objName, fnName); + if (info) { + return info; + } + ReactDefaultPerf.info[objName] = ReactDefaultPerf.info[objName] || {}; + + return ReactDefaultPerf.info[objName][fnName] = { + getLogs: function() { + return ReactDefaultPerf.getLogs(objName, fnName); + } + }; + }; + + /** + * Gets a list of the argument names from a function's definition. + * This is useful for storing arguments by their names within wrapFn(). + * + * @param {function} fn + * @return {array} + */ + var _getFnArguments = function(fn) { + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + var fnStr = fn.toString().replace(STRIP_COMMENTS, ''); + fnStr = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')); + return fnStr.match(/([^\s,]+)/g); + }; + + /** + * Store common callbacks within ReactDefaultPerf. + * + * @param {string} objName + * @param {string} fnName + * @return {?function} + */ + var _getCallback = function(objName, fnName) { + switch (objName + '.' + fnName) { + case 'React.renderComponent': + return _renderComponentCallback; + case 'ReactNativeComponent.mountComponent': + case 'ReactNativeComponent.updateComponent': + return _nativeComponentCallback; + case 'ReactCompositeComponent.mountComponent': + case 'ReactCompositeComponent.updateComponent': + return _compositeComponentCallback; + default: + return null; + } + }; + + /** + * Callback function for React.renderComponent + * + * @param {object} component + * @param {object} args + * @param {?object} fnReturn + * @param {object} log + * @param {object} info + */ + var _renderComponentCallback = + function(component, args, fnReturn, log, info) { + log.name = args.nextComponent.constructor.displayName || '[unknown]'; + log.reactID = fnReturn._rootNodeID || null; + + if (ReactDefaultPerf.options.heatmap.enabled) { + var container = args.container; + if (!container.loggedByReactDefaultPerf) { + container.loggedByReactDefaultPerf = true; + info.components = info.components || []; + info.components.push(container); + } + + container.count = container.count || 0; + container.count += log.timing.delta; + info.max = info.max || 0; + if (container.count > info.max) { + info.max = container.count; + info.components.forEach(function(component) { + _setHue(component, 100 - 100 * component.count / info.max); + }); + } else { + _setHue(container, 100 - 100 * container.count / info.max); + } + } + }; + + /** + * Callback function for ReactNativeComponent + * + * @param {object} component + * @param {object} args + * @param {?object} fnReturn + * @param {object} log + * @param {object} info + */ + var _nativeComponentCallback = + function(component, args, fnReturn, log, info) { + log.name = component.tagName || '[unknown]'; + log.reactID = component._rootNodeID; + }; + + /** + * Callback function for ReactCompositeComponent + * + * @param {object} component + * @param {object} args + * @param {?object} fnReturn + * @param {object} log + * @param {object} info + */ + var _compositeComponentCallback = + function(component, args, fnReturn, log, info) { + log.name = component.constructor.displayName || '[unknown]'; + log.reactID = component._rootNodeID; + }; + + /** + * Using the hsl() background-color attribute, colors an element. + * + * @param {DOMElement} el + * @param {number} hue [0 for red, 120 for green, 240 for blue] + */ + var _setHue = function(el, hue) { + el.style.backgroundColor = 'hsla(' + hue + ', 100%, 50%, 0.6)'; + }; + + /** + * Round to the thousandth place. + * @param {number} time + * @return {number} + */ + var _microTime = function(time) { + return Math.round(time * 1000) / 1000; + }; +} + +module.exports = ReactDefaultPerf; diff --git a/pool/shard010/JavaScript/0066992_layer.js b/pool/shard010/JavaScript/0066992_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..2bb3a552bb54ccd4e8558df9a983c512e13af84a --- /dev/null +++ b/pool/shard010/JavaScript/0066992_layer.js @@ -0,0 +1,51 @@ +var pathRegexp = require('path-to-regexp'); +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function Layer(path, handle){ + this.handle = handle; + this.topic = undefined; + this.params = undefined; + this.regexp = pathRegexp(path, this.keys = []); +} + +module.exports = Layer; +var proto = Layer.prototype; + +proto.match = function match(topic){ + if(topic == null){ + this.topic = undefined; + this.params = undefined; + return false; + } + + var m = this.regexp.exec(topic); + + if(!m){ + this.topic = undefined; + this.params = undefined; + return false; + } + + // store values + this.params = {}; + this.topic = m[0]; + + var keys = this.keys; + var params = this.params; + var prop; + var n = 0; + var key; + var val; + + for(var i = 1, len = m.length; i < len; ++i){ + key = keys[i - 1]; + prop = key ? key.name : n++; + val = m[i]; + + if(val !== undefined || !(hasOwnProperty.call(params, prop))){ + params[prop] = val; + } + } + + return true; +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066994_imageLibrary.service.js b/pool/shard010/JavaScript/0066994_imageLibrary.service.js new file mode 100644 index 0000000000000000000000000000000000000000..cb05f90bb7d90c8ce29a1393dead802183985e8e --- /dev/null +++ b/pool/shard010/JavaScript/0066994_imageLibrary.service.js @@ -0,0 +1,26 @@ +(function(){ + 'use strict'; + + angular + .module('editor') + .factory('imageLibrary', imageLibrary); + + imageLibrary.$inject = ['presentation']; + + function imageLibrary(presentation){ + var service = { + addImageToPresentation: addImageToPresentation, + setBackground: setBackground + }; + + return service; + + function setBackground(image){ + presentation.setBackground(image); + } + + function addImageToPresentation(imageSrc){ + presentation.addImage(imageSrc); + } + } +})(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0066995_SuiteView.js b/pool/shard010/JavaScript/0066995_SuiteView.js new file mode 100644 index 0000000000000000000000000000000000000000..5596df45db197f3d873749cd0fcdd067446a0baa --- /dev/null +++ b/pool/shard010/JavaScript/0066995_SuiteView.js @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2012-2015 S-Core Co., Ltd. + * + * 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. + */ + +jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { + this.suite = suite; + this.dom = dom; + this.views = views; + + this.element = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) + ); + + this.appendToSummary(this.suite, this.element); +}; + +jasmine.HtmlReporter.SuiteView.prototype.status = function() { + return this.getSpecStatus(this.suite); +}; + +jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { + this.element.className += " " + this.status(); +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); + diff --git a/pool/shard010/JavaScript/0067001_TeamHeader.js b/pool/shard010/JavaScript/0067001_TeamHeader.js new file mode 100644 index 0000000000000000000000000000000000000000..f32654a542a737356525680b32cd65226fa9c59c --- /dev/null +++ b/pool/shard010/JavaScript/0067001_TeamHeader.js @@ -0,0 +1,18 @@ +import React from 'react'; +import PropTypes from '../../PropTypes.js'; +import {TeamRankingBadges} from './TeamRankingBadges.js'; + +export const TeamHeader = ({team, t, showRanking}) => ( +
    +

    + {team.getDivisionDescription()} + {showRanking ? : null} +

    +
    +); + +TeamHeader.propTypes = { + team: PropTypes.TeamModel.isRequired, + t: PropTypes.func.isRequired, + showRanking: PropTypes.bool.isRequired, +}; diff --git a/pool/shard010/JavaScript/0067007_router-context.js b/pool/shard010/JavaScript/0067007_router-context.js new file mode 100644 index 0000000000000000000000000000000000000000..56b1d3e78a4bdf2eefd972e7c9ad408f9b981112 --- /dev/null +++ b/pool/shard010/JavaScript/0067007_router-context.js @@ -0,0 +1,112 @@ +/** + * We're stealing all the code from FastRender + * https://github.com/kadirahq/fast-render/blob/master/lib/client/fast_render.js + */ +import { Accounts } from 'meteor/accounts-base'; +import { Meteor } from 'meteor/meteor'; +import { MongoID } from 'meteor/mongo-id'; + +import { jsperfForEach } from '../shared/utils/jsperf'; + +/** @class */ +export default class RouterContext { + /** + * @constructor + */ + constructor() { + this.dataReceived = false; + this.payload = null; + this.subscriptions = {}; + } + + /** + * @locus Client + * @memberof RouterContext + * @method _initPayload + * @instance + */ + _initPayload(payload) { + this.payload = payload; + } + + /** + * @locus Client + * @memberof RouterContext + * @method _initSubscriptions + * @instance + */ + _initSubscriptions(payload) { + if (payload.subscriptions) { + this.subscriptions = payload.subscriptions; + } + } + + /* eslint-disable no-param-reassign, no-underscore-dangle */ + /** + * @summary Inject a custom/fake DDP message + * @locus Client + * @memberof RouterContext + * @method _injectDdpMessage + * @instance + * @param {Connection} connection + * @param {object} msg + */ + injectDdpMessage(connection, msg) { + const originalWait = connection._waitingForQuiescence; + connection._waitingForQuiescence = () => false; + connection._livedata_data(msg); + connection._waitingForQuiescence = originalWait; + } + /* eslint-enable */ + + /* eslint-disable no-underscore-dangle */ + /** + * @summary Initialize server rendered subscriptions + * @locus Client + * @memberof RouterContext + * @method init + * @instance + */ + init(payload) { + const { connection } = Meteor; + let keys; + + this.dataReceived = true; + + if (payload) { + this._initPayload(payload); + this._initSubscriptions(payload); + + keys = Object.keys(payload.collectionData); + // jsperf + keys.jsperfForEach = jsperfForEach; + + keys.jsperfForEach((collectionName) => { + const collection = payload.collectionData[ collectionName ]; + // jsperf + collection.jsperfForEach = jsperfForEach; + + collection.jsperfForEach(({ _id, ...fields }) => { + this.injectDdpMessage(connection, { + collection: collectionName, + fields, + fromSSR: true, + id: MongoID.idStringify(_id), + msg: 'added' + }); + }); + }); + } + + // If the connection supports buffered DDP writes, then flush now. + if (connection._flushBufferedWrites) { + connection._flushBufferedWrites(); + } + + // let Meteor know, user login process has been completed + if (Accounts) { + Accounts._setLoggingIn(false); + } + } + /* eslint-enable */ +} diff --git a/pool/shard010/JavaScript/0067011_ValueNodeSpec.js b/pool/shard010/JavaScript/0067011_ValueNodeSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..0ccae2bb2942aa581aed0a607fd5ac28c17e06f4 --- /dev/null +++ b/pool/shard010/JavaScript/0067011_ValueNodeSpec.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * Requirements + */ +const ValueNode = require(SOURCE_ROOT + '/transformer/node/ValueNode.js').ValueNode; +const valueNodeSpec = require(TEST_ROOT + '/transformer/node/ValueNodeShared.js'); + + +/** + * Spec + */ +describe(ValueNode.className, function() +{ + /** + * ValueNode Test + */ + valueNodeSpec(ValueNode, 'transformer.node/ValueNode', + { + nodeFields: [], + values: + { + value: 'value' + }, + serialized: + { + type: ValueNode.className, + value: 'value' + } + }); +}); diff --git a/pool/shard010/JavaScript/0067012_gulpfile.js b/pool/shard010/JavaScript/0067012_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..780beb1e18a1b7f2422225a6965b4a19a665d61e --- /dev/null +++ b/pool/shard010/JavaScript/0067012_gulpfile.js @@ -0,0 +1,57 @@ +const gulp = require('gulp') +const sass = require('gulp-sass') +const spawn = require('child_process').spawn + +gulp.task('assets', function (done) { + gulp.src('node_modules/govuk_frontend_toolkit/javascripts/**/*') + .pipe(gulp.dest('app/govuk_modules/govuk_frontend_toolkit/javascripts', { overwrite: true })) + + gulp.src('node_modules/govuk_frontend_toolkit/images/**/*') + .pipe(gulp.dest('app/govuk_modules/govuk_frontend_toolkit/images', { overwrite: true })) + + gulp.src('node_modules/govuk_template_jinja/assets/**/*') + .pipe(gulp.dest('app/govuk_modules/govuk_template/', { overwrite: true })) + done() +}) + +gulp.task('templates', function (done) { + gulp.src('node_modules/govuk_template_jinja/views/layouts/govuk_template.html') + .pipe(gulp.dest('app/views/', { overwrite: true })) + done() +}) + +gulp.task('sync', function (done) { + gulp.src('app/assets/javascripts/**/*') + .pipe(gulp.dest('app/public/javascripts/', { overwrite: true })) + gulp.src('app/assets/stylesheets/**/*') + .pipe(gulp.dest('app/public/stylesheets/', { overwrite: true })) + gulp.src('app/assets/images/**/*') + .pipe(gulp.dest('app/public/images/', { overwrite: true })) + done() +}) + +gulp.task('sass', function (done) { + gulp.src('app/assets/sass/**/*.scss') + .pipe(sass({ + style: 'expanded', + sourcemap: true, + includePaths: [ + 'node_modules/govuk-elements-sass/public/sass', + 'node_modules/govuk_frontend_toolkit/stylesheets', + 'govuk_modules/govuk_template/assets/stylesheets', + 'govuk_modules/govuk_frontend_toolkit/stylesheets', + 'govuk_modules/govuk-elements-sass/' + ], + outputStyle: 'expanded' + }).on('error', sass.logError)) + .pipe(gulp.dest('app/public/stylesheets')) + done() +}) + +gulp.task('generate-assets', gulp.series(gulp.parallel('assets', 'templates', 'sync', 'sass'))) + +gulp.task('generate-assets-and-start', gulp.series('generate-assets', function () { + spawn('node', ['app/bin/www'], { stdio: 'inherit' }) +})) + +gulp.task('default', gulp.series('generate-assets-and-start')) diff --git a/pool/shard010/JavaScript/0067017_sync-problem.js b/pool/shard010/JavaScript/0067017_sync-problem.js new file mode 100644 index 0000000000000000000000000000000000000000..316e96cdcc0251515f71667458244fce6c4736c5 --- /dev/null +++ b/pool/shard010/JavaScript/0067017_sync-problem.js @@ -0,0 +1,31 @@ +'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 NotificationSyncProblem = function NotificationSyncProblem(props) { + return _react2.default.createElement( + _SvgIcon2.default, + props, + _react2.default.createElement('path', { d: 'M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z' }) + ); +}; +NotificationSyncProblem = (0, _pure2.default)(NotificationSyncProblem); +NotificationSyncProblem.displayName = 'NotificationSyncProblem'; + +exports.default = NotificationSyncProblem; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067019_ambientlight.js b/pool/shard010/JavaScript/0067019_ambientlight.js new file mode 100644 index 0000000000000000000000000000000000000000..b079fa1da340914509b18cf270335e443201d225 --- /dev/null +++ b/pool/shard010/JavaScript/0067019_ambientlight.js @@ -0,0 +1,29 @@ +window.addEventListener('ambientlight', function(e) { + var lux = e.value; + document.querySelector('#ale').textContent = lux + ' lux'; + + if(lux < 50) { + document.body.className = 'dark'; + } + if(lux >= 50 && lux <= 1000) { + document.body.className = 'normal'; + } + if(lux > 1000) { + document.body.className = 'bright'; + } + +}); + +window.addEventListener('lightlevel', function(e) { + var level = e.value; document.querySelector('#lle').textContent = level; + + if(level === 'dim') { + document.body.className = 'dark'; + } + if(level === 'normal') { + document.body.className = 'normal'; + } + if(level === 'bright') { + document.body.className = 'bright'; + } +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067020_builder.test.js b/pool/shard010/JavaScript/0067020_builder.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7206a74c5bb3883826e2c425b2e1f6c25b10c82d --- /dev/null +++ b/pool/shard010/JavaScript/0067020_builder.test.js @@ -0,0 +1,52 @@ +var Builder = require( '../lib/builder' ), + + chai = require( 'chai' ), + expect = chai.expect; + +// ----------------------------------------------------------------------------- + +describe( 'Builder', function () { + + // ----- classes definition ----- + + var GoodBuilder = Builder.extend({ + name: 'GoodBuilder', + + options: { + emptyBuild: true, + }, + + build: function () { + return this.options.emptyBuild ? '' : 'something'; + }, + + }); + + var BadBuilder = Builder.extend({ + + ownmethod: function () { + return 'test'; + }, + + }); + + // ----- tests ----- + + it( "should have BadBuilder.prototype.ownmethod", function () { + expect( typeof BadBuilder.prototype.ownmethod ).to.be.equal( 'function' ); + expect( BadBuilder.prototype.ownmethod() ).to.be.equal( 'test' ); + }); + + it( "should NOT throw an error when extended does have .name definition", function () { + expect(function () { + new GoodBuilder(); + }).to.not.throw( TypeError ); + }); + + it( "should throw an error when extended doesn't have .name definition", function () { + expect(function () { + new BadBuilder(); + }).to.throw( TypeError ); + }); + +}); diff --git a/pool/shard010/JavaScript/0067021_cleditHighlighter.js b/pool/shard010/JavaScript/0067021_cleditHighlighter.js new file mode 100644 index 0000000000000000000000000000000000000000..f0bebe603f3a4527b35fe8d1db9bf4e1f59e0fac --- /dev/null +++ b/pool/shard010/JavaScript/0067021_cleditHighlighter.js @@ -0,0 +1,188 @@ +;(function (cledit) { + var styleElts = [] + + function createStyleSheet (document) { + var styleElt = document.createElement('style') + styleElt.type = 'text/css' + styleElt.innerHTML = '.cledit-section * { display: inline; }' + document.head.appendChild(styleElt) + styleElts.push(styleElt) + } + + function Highlighter (editor) { + var self = this + cledit.Utils.createEventHooks(this) + + styleElts.cl_some(function (styleElt) { + return editor.$document.head.contains(styleElt) + }) || createStyleSheet(editor.$document) + + var contentElt = editor.$contentElt + this.isComposing = 0 + + var sectionList = [] + var insertBeforeSection + var useBr = cledit.Utils.isWebkit + var trailingNodeTag = 'div' + var hiddenLfInnerHtml = '
    ' + + var lfHtml = '' + (useBr ? hiddenLfInnerHtml : '\n') + '' + + this.fixContent = function (modifiedSections, removedSections, noContentFix) { + modifiedSections.cl_each(function (section) { + section.forceHighlighting = true + if (!noContentFix) { + if (useBr) { + section.elt.getElementsByClassName('hd-lf').cl_each(function (lfElt) { + lfElt.parentNode.removeChild(lfElt) + }) + section.elt.getElementsByTagName('br').cl_each(function (brElt) { + brElt.parentNode.replaceChild(editor.$document.createTextNode('\n'), brElt) + }) + } + if (section.elt.textContent.slice(-1) !== '\n') { + section.elt.appendChild(editor.$document.createTextNode('\n')) + } + } + }) + } + + this.addTrailingNode = function () { + this.trailingNode = editor.$document.createElement(trailingNodeTag) + contentElt.appendChild(this.trailingNode) + } + + function Section (text) { + this.text = text.text === undefined ? text : text.text + this.data = text.data + } + + Section.prototype.setElement = function (elt) { + this.elt = elt + elt.section = this + } + + this.parseSections = function (content, isInit) { + if (this.isComposing) { + return sectionList + } + + var newSectionList = editor.options.sectionParser ? editor.options.sectionParser(content) : [content] + newSectionList = newSectionList.cl_map(function (sectionText) { + return new Section(sectionText) + }) + + var modifiedSections = [] + var sectionsToRemove = [] + insertBeforeSection = undefined + + if (isInit) { + // Render everything if isInit + sectionsToRemove = sectionList + sectionList = newSectionList + modifiedSections = newSectionList + } else { + // Find modified section starting from top + var leftIndex = sectionList.length + sectionList.cl_some(function (section, index) { + var newSection = newSectionList[index] + if (index >= newSectionList.length || + section.forceHighlighting || + // Check text modification + section.text !== newSection.text || + // Check that section has not been detached or moved + section.elt.parentNode !== contentElt || + // Check also the content since nodes can be injected in sections via copy/paste + section.elt.textContent !== newSection.text) { + leftIndex = index + return true + } + }) + + // Find modified section starting from bottom + var rightIndex = -sectionList.length + sectionList.slice().reverse().cl_some(function (section, index) { + var newSection = newSectionList[newSectionList.length - index - 1] + if (index >= newSectionList.length || + section.forceHighlighting || + // Check modified + section.text !== newSection.text || + // Check that section has not been detached or moved + section.elt.parentNode !== contentElt || + // Check also the content since nodes can be injected in sections via copy/paste + section.elt.textContent !== newSection.text) { + rightIndex = -index + return true + } + }) + + if (leftIndex - rightIndex > sectionList.length) { + // Prevent overlap + rightIndex = leftIndex - sectionList.length + } + + var leftSections = sectionList.slice(0, leftIndex) + modifiedSections = newSectionList.slice(leftIndex, newSectionList.length + rightIndex) + var rightSections = sectionList.slice(sectionList.length + rightIndex, sectionList.length) + insertBeforeSection = rightSections[0] + sectionsToRemove = sectionList.slice(leftIndex, sectionList.length + rightIndex) + sectionList = leftSections.concat(modifiedSections).concat(rightSections) + } + + var newSectionEltList = editor.$document.createDocumentFragment() + modifiedSections.cl_each(function (section) { + section.forceHighlighting = false + highlight(section) + newSectionEltList.appendChild(section.elt) + }) + editor.watcher.noWatch(function () { + if (isInit) { + contentElt.innerHTML = '' + contentElt.appendChild(newSectionEltList) + return this.addTrailingNode() + } + + // Remove outdated sections + sectionsToRemove.cl_each(function (section) { + // section may be already removed + section.elt.parentNode === contentElt && contentElt.removeChild(section.elt) + // To detect sections that come back with built-in undo + section.elt.section = undefined + }) + + if (insertBeforeSection !== undefined) { + contentElt.insertBefore(newSectionEltList, insertBeforeSection.elt) + } else { + contentElt.appendChild(newSectionEltList) + } + + // Remove unauthorized nodes (text nodes outside of sections or duplicated sections via copy/paste) + var childNode = contentElt.firstChild + while (childNode) { + var nextNode = childNode.nextSibling + if (!childNode.section) { + contentElt.removeChild(childNode) + } + childNode = nextNode + } + this.addTrailingNode() + self.$trigger('highlighted') + editor.selectionMgr.restoreSelection() + editor.selectionMgr.updateCursorCoordinates() + }.cl_bind(this)) + + return sectionList + } + + function highlight (section) { + var html = editor.options.sectionHighlighter(section).replace(/\n/g, lfHtml) + var sectionElt = editor.$document.createElement('div') + sectionElt.className = 'cledit-section' + sectionElt.innerHTML = html + section.setElement(sectionElt) + self.$trigger('sectionHighlighted', section) + } + } + + cledit.Highlighter = Highlighter +})(window.cledit) diff --git a/pool/shard010/JavaScript/0067024_typed_array_partitioner.js b/pool/shard010/JavaScript/0067024_typed_array_partitioner.js new file mode 100644 index 0000000000000000000000000000000000000000..1ee8d76208ae8ecd2b6c0e835de751752b7c18c1 --- /dev/null +++ b/pool/shard010/JavaScript/0067024_typed_array_partitioner.js @@ -0,0 +1,56 @@ +var utils = require('./utils.js'); +var errors = require('./errors.js'); + +var typedArraySlice = function (array, from, to) { + var subXs = array.subarray(from, to); + return new array.constructor(subXs); +}; + +var Partitioner = module.exports = function (parts) { + if (!parts) { + throw new errors.InvalidArgumentsError(errors.messages.INVALID_PARTS); + } + this.parts = parts; +}; + +Partitioner.prototype.constructor = Partitioner; + +Partitioner.prototype.partition = function (array) { + this.__validateTypedArray(array); + return this.__doPartition(array, this); +}; + +Partitioner.prototype.__validateTypedArray = function (array) { + if (!utils.isTypedArray(array)) { + var message = utils.format('Invalid type {0}. {1}', array, errors.messages.PARTITIONER_ARGUMENT_IS_NOT_TYPED_ARRAY); + throw new errors.InvalidArgumentsError(message); + } +}; + +Partitioner.prototype.__doPartition = function (array) { + var parts = this.parts; + var elementsCount = array.length; + var subElementsCount = Math.floor(elementsCount / parts) | 0; + var from = 0; + var to = 0; + var isShared = utils.isSharedArray(array); + var sharedArray; + var arrays = new Array(parts); + if (isShared) { + sharedArray = utils.duplicateTypedArray(array); + } + for (var i = 0; i < parts; i++) { + if (parts - 1 === i) { + to = elementsCount; + } else { + to += subElementsCount; + } + if (isShared) { + arrays[i] = { from:from, to: to, sharedArray: sharedArray, sourceArray: array}; + } else { + arrays[i] = typedArraySlice(array, from, to); + } + from += subElementsCount; + } + return arrays; +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067029_ejohn56.js b/pool/shard010/JavaScript/0067029_ejohn56.js new file mode 100644 index 0000000000000000000000000000000000000000..6c433d94cddcad1a36127be0f55295b3ad4c5d18 --- /dev/null +++ b/pool/shard010/JavaScript/0067029_ejohn56.js @@ -0,0 +1,24 @@ +var a = 5; +function runMe(a){ +// TAJS_dumpValue( a ); + TAJS_assert( a == 6 ); + + function innerRun(){ +// TAJS_dumpValue( b ); + TAJS_assert( b == 7 ); +// TAJS_dumpValue( c ); + TAJS_assert( c == undefined ); + } + + var b = 7; + innerRun(); + var c = 8; +} +runMe(6); + +for ( var d = 0; d < 3; d++ ) { + setTimeout(function(){ +// TAJS_dumpValue( d ); + TAJS_assert( d == 3 ); + }, 100); +} diff --git a/pool/shard010/JavaScript/0067032_schedulingHistory.controller.js b/pool/shard010/JavaScript/0067032_schedulingHistory.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..641dab473bb0fb5c991f9fe9eff265c9e837751e --- /dev/null +++ b/pool/shard010/JavaScript/0067032_schedulingHistory.controller.js @@ -0,0 +1,137 @@ +sap.ui.define([ + "convista/com/arp/demo/controller/BaseController", + "sap/ui/model/Filter", + "sap/ui/model/Sorter", + "sap/ui/model/json/JSONModel" +], function(Controller,Filter,Sorter,JSONModel) { + "use strict"; + + return Controller.extend("convista.com.arp.demo.controller.schedulingHistory", { + + _oDialog: null, + /** + * Called when a controller is instantiated and its View controls (if available) are already created. + * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization. + * @memberOf convista.com.arp.demo.view.schedulingHistory + */ + onInit: function() { + var that = this; + + var sRootPath = jQuery.sap.getModulePath("convista.com.arp.demo"); + var oModel = new JSONModel([sRootPath,'model/schedulingHistory.json'].join("/")); + this.getView().setModel(oModel); + + /*var oModel = new sap.ui.model.json.JSONModel(); + var sServiceUrl = "https://sapwebdcbw.sap.convista.local:8443/sap/bc/cs67_ds_com?_method=get_user_info&_datasrc=sched_hist"; + $.ajax({ + url: sServiceUrl, + dataType: "jsonp", + jsonp: "callback", + success: function(json) { + oModel.setData(json); + that.getView().setModel(oModel); + //sap.ui.getCore().setModel(oModel); + } + });*/ + + }, + + /** + * Called when the Controller is destroyed. Use this one to free resources and finalize activities. + * @memberOf convista.com.arp.demo.view.schedulingHistory + */ + onExit: function() { + if (this._oDialog) { + this._oDialog.destroy(); + } + }, + + handleViewSettingsDialogButtonPressed: function (oEvent) { + if (!this._oDialog) { + this._oDialog = sap.ui.xmlfragment("convista.com.arp.demo.view.TableFilter", this); + this.getView().addDependent(this._oDialog); + } + // toggle compact style + jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._oDialog); + this._oDialog.open(); + }, + + handleRefreshButtonPressed: function (oEvent) { + var that = this; + $.ajax({ + url: this.sServiceUrl+"_method=get_user_info&_datasrc=sched_hist", + dataType: "jsonp", + jsonp: "callback", + success: function(json) { + var oModel = that.getView().byId("idSchedulingHistoryTable").getModel(); + oModel.setData(json); + } + }); + }, + + handleTableFilterConfirm: function(oEvent) { + + var oView = this.getView(); + var oTable = oView.byId("idSchedulingHistoryTable"); + + var mParams = oEvent.getParameters(); + var oBinding = oTable.getBinding("items"); + + // apply sorter to binding + // (grouping comes before sorting) + var aSorters = []; +/* if (mParams.groupItem) { + var sPath = mParams.groupItem.getKey(); + var bDescending = mParams.groupDescending; + var vGroup = this.mGroupFunctions[sPath]; + aSorters.push(new Sorter(sPath, bDescending, vGroup)); + }*/ + var sPath = mParams.sortItem.getKey(); + var bDescending = mParams.sortDescending; + aSorters.push(new Sorter(sPath, bDescending)); + oBinding.sort(aSorters); + + // apply filters to binding + /*var aFilters = []; + jQuery.each(mParams.filterItems, function (i, oItem) { + var aSplit = oItem.getKey().split("___"); + var sPath = aSplit[0]; + var sOperator = aSplit[1]; + var sValue1 = aSplit[2]; + var sValue2 = aSplit[3]; + var oFilter = new Filter(sPath, sOperator, sValue1, sValue2); + aFilters.push(oFilter); + }); + oBinding.filter(aFilters);*/ + + // update filter bar + /*oView.byId("vsdFilterBar").setVisible(aFilters.length > 0); + oView.byId("vsdFilterLabel").setText(mParams.filterString);*/ + }, + + + formatStatusIcon: function (sStatus) { + var result = "sap-icon://"; + switch (sStatus) { + case 'P': + return result+"status-positive";//preliminary + case 'S': + return result+"calendar";//scheduled + case 'Y': + return result+"status-in-process";//ready + case 'R': + return result+"physical-activity";//running + case 'F': + return result+"complete";//finished + case 'A': + return result+"sys-cancel-2";//aborted + case 'Z': + return result+"alert";//suspended + default: + return result+"message-information";//default + } + } + + }); + +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067033_bulk.js b/pool/shard010/JavaScript/0067033_bulk.js new file mode 100644 index 0000000000000000000000000000000000000000..3d43cc20c6304eabc00a55498a9e8dd56bbacea7 --- /dev/null +++ b/pool/shard010/JavaScript/0067033_bulk.js @@ -0,0 +1,46 @@ +var bulkService = function bulkService(client, args) { + this.args = args + + var valid = this.validate() + if(valid !== true) { + throw valid + return + } + var type = args.type + var body = args.body + delete args.type + delete args.body + + if(id) { + path = type + '/_bulk' + } else { + path = '/_bulk' + } + + return client.performStreamingRequest({ + method: 'POST', + path: path, + params: args, + body: body + }) +} + +bulkService.prototype.validate = function validate() { + var invalid = [] + if(typeof this.args.body !== 'object' || this.args.body === null) { + invalid.push('body') + } + + var missing = '' + for(var i=0;i 0) { + return new Error('fields missing: ' + missing) + } + + return true +} + +module.exports = bulkService \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067034_14.js b/pool/shard010/JavaScript/0067034_14.js new file mode 100644 index 0000000000000000000000000000000000000000..6a9f0f2d110d1f20c8215c2cdd3cc15920e76dcb --- /dev/null +++ b/pool/shard010/JavaScript/0067034_14.js @@ -0,0 +1,45 @@ +seajs.use(["common"], function(common) { + var Ball = common.Ball; + + canvas = document.getElementById('canvas1'); + ctx = canvas.getContext("2d"); + var ball=new Ball(0,0,20); + var width = canvas.width; + var height = canvas.height; + target={ + "x":width/2, + "y":height/2 + } + k=0.01,vx=0,vy=0; + (function drawFrame(){ + var animRequest=requestAnimationFrame(drawFrame,canvas); + ctx.clearRect(0,0,width,height); + var dx=target.x-ball.x; + var ax=dx*k; + vx+=ax; + vx*=0.99;//消耗 + ball.x+=vx; + + var dy=target.y-ball.y; + var ay=dy*k; + vy+=ay; + vy*=0.99;//消耗 + ball.y+=vy; + + ball.render(ctx); + if(Math.sqrt(Math.pow(target.x-ball.x,2)+Math.pow(target.y-ball.y,2))<=0.1){ + cancelRequestAnimationFrame(animRequest); + } + })(); + + window.addEventListener("click",function(e){ + target.x= e.pageX; + target.y= e.pageY; + }); + window.addEventListener("tap",function(e){ + var touch = e.touches[0]; + console.log(touch); + target.x= e.pageX; + target.y= e.pageY; + }); +}) diff --git a/pool/shard010/JavaScript/0067038_joint.shapes.uml.js b/pool/shard010/JavaScript/0067038_joint.shapes.uml.js new file mode 100644 index 0000000000000000000000000000000000000000..522c22540f7f9ccfe705e42399b508c30440ff4b --- /dev/null +++ b/pool/shard010/JavaScript/0067038_joint.shapes.uml.js @@ -0,0 +1,257 @@ +/*! JointJS v2.1.4 (2018-08-01) - JavaScript diagramming library + + +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/. +*/ +joint.shapes.basic.Generic.define('uml.Class', { + attrs: { + rect: { 'width': 200 }, + + '.uml-class-name-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#3498db' }, + '.uml-class-attrs-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' }, + '.uml-class-methods-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' }, + + '.uml-class-name-text': { + 'ref': '.uml-class-name-rect', + 'ref-y': .5, + 'ref-x': .5, + 'text-anchor': 'middle', + 'y-alignment': 'middle', + 'font-weight': 'bold', + 'fill': 'black', + 'font-size': 12, + 'font-family': 'Times New Roman' + }, + '.uml-class-attrs-text': { + 'ref': '.uml-class-attrs-rect', 'ref-y': 5, 'ref-x': 5, + 'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman' + }, + '.uml-class-methods-text': { + 'ref': '.uml-class-methods-rect', 'ref-y': 5, 'ref-x': 5, + 'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman' + } + }, + + name: [], + attributes: [], + methods: [] +}, { + markup: [ + '', + '', + '', + '', + '', + '' + ].join(''), + + initialize: function() { + + this.on('change:name change:attributes change:methods', function() { + this.updateRectangles(); + this.trigger('uml-update'); + }, this); + + this.updateRectangles(); + + joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments); + }, + + getClassName: function() { + return this.get('name'); + }, + + updateRectangles: function() { + + var attrs = this.get('attrs'); + + var rects = [ + { type: 'name', text: this.getClassName() }, + { type: 'attrs', text: this.get('attributes') }, + { type: 'methods', text: this.get('methods') } + ]; + + var offsetY = 0; + + rects.forEach(function(rect) { + + var lines = Array.isArray(rect.text) ? rect.text : [rect.text]; + var rectHeight = lines.length * 20 + 20; + + attrs['.uml-class-' + rect.type + '-text'].text = lines.join('\n'); + attrs['.uml-class-' + rect.type + '-rect'].height = rectHeight; + attrs['.uml-class-' + rect.type + '-rect'].transform = 'translate(0,' + offsetY + ')'; + + offsetY += rectHeight; + }); + } + +}); + +joint.shapes.uml.ClassView = joint.dia.ElementView.extend({ + + initialize: function() { + + joint.dia.ElementView.prototype.initialize.apply(this, arguments); + + this.listenTo(this.model, 'uml-update', function() { + this.update(); + this.resize(); + }); + } +}); + +joint.shapes.uml.Class.define('uml.Abstract', { + attrs: { + '.uml-class-name-rect': { fill: '#e74c3c' }, + '.uml-class-attrs-rect': { fill: '#c0392b' }, + '.uml-class-methods-rect': { fill: '#c0392b' } + } +}, { + + getClassName: function() { + return ['<>', this.get('name')]; + } + +}); +joint.shapes.uml.AbstractView = joint.shapes.uml.ClassView; + +joint.shapes.uml.Class.define('uml.Interface', { + attrs: { + '.uml-class-name-rect': { fill: '#f1c40f' }, + '.uml-class-attrs-rect': { fill: '#f39c12' }, + '.uml-class-methods-rect': { fill: '#f39c12' } + } +}, { + getClassName: function() { + return ['<>', this.get('name')]; + } +}); +joint.shapes.uml.InterfaceView = joint.shapes.uml.ClassView; + +joint.dia.Link.define('uml.Generalization', { + attrs: { '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' }} +}); + +joint.dia.Link.define('uml.Implementation', { + attrs: { + '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' }, + '.connection': { 'stroke-dasharray': '3,3' } + } +}); + +joint.dia.Link.define('uml.Aggregation', { + attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'white' }} +}); + +joint.dia.Link.define('uml.Composition', { + attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'black' }} +}); + +joint.dia.Link.define('uml.Association'); + +// Statechart + +joint.shapes.basic.Generic.define('uml.State', { + attrs: { + '.uml-state-body': { + 'width': 200, 'height': 200, 'rx': 10, 'ry': 10, + 'fill': '#ecf0f1', 'stroke': '#bdc3c7', 'stroke-width': 3 + }, + '.uml-state-separator': { + 'stroke': '#bdc3c7', 'stroke-width': 2 + }, + '.uml-state-name': { + 'ref': '.uml-state-body', 'ref-x': .5, 'ref-y': 5, 'text-anchor': 'middle', + 'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14 + }, + '.uml-state-events': { + 'ref': '.uml-state-separator', 'ref-x': 5, 'ref-y': 5, + 'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14 + } + }, + + name: 'State', + events: [] + +}, { + markup: [ + '', + '', + '', + '', + '', + '', + '', + '' + ].join(''), + + initialize: function() { + + this.on({ + 'change:name': this.updateName, + 'change:events': this.updateEvents, + 'change:size': this.updatePath + }, this); + + this.updateName(); + this.updateEvents(); + this.updatePath(); + + joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments); + }, + + updateName: function() { + + this.attr('.uml-state-name/text', this.get('name')); + }, + + updateEvents: function() { + + this.attr('.uml-state-events/text', this.get('events').join('\n')); + }, + + updatePath: function() { + + var d = 'M 0 20 L ' + this.get('size').width + ' 20'; + + // We are using `silent: true` here because updatePath() is meant to be called + // on resize and there's no need to to update the element twice (`change:size` + // triggers also an update). + this.attr('.uml-state-separator/d', d, { silent: true }); + } +}); + +joint.shapes.basic.Circle.define('uml.StartState', { + type: 'uml.StartState', + attrs: { circle: { 'fill': '#34495e', 'stroke': '#2c3e50', 'stroke-width': 2, 'rx': 1 }} +}); + +joint.shapes.basic.Generic.define('uml.EndState', { + size: { width: 20, height: 20 }, + attrs: { + 'circle.outer': { + transform: 'translate(10, 10)', + r: 10, + fill: '#ffffff', + stroke: '#2c3e50' + }, + + 'circle.inner': { + transform: 'translate(10, 10)', + r: 6, + fill: '#34495e' + } + } +}, { + markup: '', +}); + +joint.dia.Link.define('uml.Transition', { + attrs: { + '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z', fill: '#34495e', stroke: '#2c3e50' }, + '.connection': { stroke: '#2c3e50' } + } +}); diff --git a/pool/shard010/JavaScript/0067039_navbar.directive.js b/pool/shard010/JavaScript/0067039_navbar.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..8ccfa19e1fdb7ef215f3fafc69c8d6f09ef4d85f --- /dev/null +++ b/pool/shard010/JavaScript/0067039_navbar.directive.js @@ -0,0 +1,32 @@ +(function() { + 'use strict'; + + angular + .module('client') + .directive('acmeNavbar', acmeNavbar); + + /** @ngInject */ + function acmeNavbar() { + var directive = { + restrict: 'E', + templateUrl: 'app/components/navbar/navbar.html', + scope: { + creationDate: '=' + }, + controller: NavbarController, + controllerAs: 'vm', + bindToController: true + }; + + return directive; + + /** @ngInject */ + function NavbarController(moment) { + var vm = this; + + // "vm.creation" is avaible by directive option "bindToController: true" + vm.relativeDate = moment(vm.creationDate).fromNow(); + } + } + +})(); diff --git a/pool/shard010/JavaScript/0067040_plugin.js b/pool/shard010/JavaScript/0067040_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4bc1bddaa9a98848ac327ca3ce8bbad5795f6f7a --- /dev/null +++ b/pool/shard010/JavaScript/0067040_plugin.js @@ -0,0 +1,101 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.3.1 (2020-05-27) + */ +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var getKeyboardSpaces = function (editor) { + var spaces = editor.getParam('nonbreaking_force_tab', 0); + if (typeof spaces === 'boolean') { + return spaces === true ? 3 : 0; + } else { + return spaces; + } + }; + var wrapNbsps = function (editor) { + return editor.getParam('nonbreaking_wrap', true, 'boolean'); + }; + + var stringRepeat = function (string, repeats) { + var str = ''; + for (var index = 0; index < repeats; index++) { + str += string; + } + return str; + }; + var isVisualCharsEnabled = function (editor) { + return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false; + }; + var insertNbsp = function (editor, times) { + var classes = function () { + return isVisualCharsEnabled(editor) ? 'mce-nbsp-wrap mce-nbsp' : 'mce-nbsp-wrap'; + }; + var nbspSpan = function () { + return '' + stringRepeat(' ', times) + ''; + }; + var shouldWrap = wrapNbsps(editor); + var html = shouldWrap || editor.plugins.visualchars ? nbspSpan() : stringRepeat(' ', times); + editor.undoManager.transact(function () { + return editor.insertContent(html); + }); + }; + + var register = function (editor) { + editor.addCommand('mceNonBreaking', function () { + insertNbsp(editor, 1); + }); + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK'); + + var setup = function (editor) { + var spaces = getKeyboardSpaces(editor); + if (spaces > 0) { + editor.on('keydown', function (e) { + if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) { + if (e.shiftKey) { + return; + } + e.preventDefault(); + e.stopImmediatePropagation(); + insertNbsp(editor, spaces); + } + }); + } + }; + + var register$1 = function (editor) { + editor.ui.registry.addButton('nonbreaking', { + icon: 'non-breaking', + tooltip: 'Nonbreaking space', + onAction: function () { + return editor.execCommand('mceNonBreaking'); + } + }); + editor.ui.registry.addMenuItem('nonbreaking', { + icon: 'non-breaking', + text: 'Nonbreaking space', + onAction: function () { + return editor.execCommand('mceNonBreaking'); + } + }); + }; + + function Plugin () { + global.add('nonbreaking', function (editor) { + register(editor); + register$1(editor); + setup(editor); + }); + } + + Plugin(); + +}()); diff --git a/pool/shard010/JavaScript/0067043_test-utils.js b/pool/shard010/JavaScript/0067043_test-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..d856967fc20d44d5cd9be24375f54302de7cde27 --- /dev/null +++ b/pool/shard010/JavaScript/0067043_test-utils.js @@ -0,0 +1,24 @@ +/** + * @license Copyright 2020 Google Inc. 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. + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const FallbackServer = require('../../cli/src/collect/fallback-server.js'); + +module.exports = { + ...require('../../server/test/test-utils.js'), + createTestServer: async () => { + const pathToBuildDir = path.resolve(__dirname, '../dist'); + if (!fs.existsSync(`${pathToBuildDir}/index.html`)) { + throw new Error('Build viewer before running tests'); + } + + const server = new FallbackServer(pathToBuildDir, false); + await server.listen(); + return server; + }, +}; diff --git a/pool/shard010/JavaScript/0067046_bundle.js b/pool/shard010/JavaScript/0067046_bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..f41d37bc9ec64ddcb3c50b1588adbf941180e8c0 --- /dev/null +++ b/pool/shard010/JavaScript/0067046_bundle.js @@ -0,0 +1,252 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + var Rln = __webpack_require__(1); + + window.Rln = Rln; + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + var index = __webpack_require__(2); + var common = __webpack_require__(3); + + var _ = function() { + return new _.fn.init(); + } + + _.prototype = { + name: 'qqc' + } + + _.fn = _.prototype; + + _.fn.init = function() { + + return this; + } + + _.fn.init.prototype = _.fn; + + _.extend = _.fn.extend = function(dest) { + + var obj = this; + + for (var property in dest) { + if (dest.hasOwnProperty(property)) { + obj[property] = dest[property]; + } + } + }; + + + + _.extend(index) + + module.exports = _; + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + + /** + * created by Nico at 2017/05/26 + * base type + */ + + module.exports = { + isUndefined: function(obj) { + return obj === void 0; + }, + isNull: function(obj) { + return obj === null; + }, + isObject: function(obj) { + return Object.prototype.toString.call(obj) === '[object Object]'; + }, + isBoolean: function(obj) { + return Object.prototype.toString.call(obj) === '[object Boolean]'; + }, + isArray: function(obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }, + isFunction: function(obj) { + return Object.prototype.toString.call(obj) === '[object Function]'; + }, + isNumber: function(obj) { + return Object.prototype.toString.call(obj) === '[object Number]'; + }, + isDate: function(obj) { + return Object.prototype.toString.call(obj) === '[object Date]'; + }, + isString: function(obj) { + return Object.prototype.toString.call(obj) === '[object String]'; + }, + isNaN: function(obj) { + return obj !== obj; + }, + has: function(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + } + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + var indexFn = __webpack_require__(2); + + module.exports = { + //获取url上的参数 + getUrlSearch: function(param) { + var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)"); + var r = window.location.search.substr(1).match(reg); + if (r != null) { + return r[2]; + } else { + return undefined; + } + }, + //数组去重 + uniqArray: function(arr) { + var newArr = []; + var objArr = {}; + + for (var i = 0; i < arr.length; i++) { + var tempVal = arr[i]; + if (objArr[tempVal] !== 1) { + newArr.push(tempVal); + objArr[tempVal] = 1; + } + } + return newArr; + }, + //对象是否为空 + isEmptyObject: function(obj) { + var name; + for (name in obj) { + return false; + } + return true; + }, + //遍历 + each: function(obj, fun) { + if (indexFn.isObject(obj)) { + //对象 + var name; + + for (name in obj) { + fun.call(obj, obj[name], name) + } + + } else if (indexFn.isArray(obj)) { + //数组 + var len = obj.length; + var i = 0; + + for (; i < len; i++) { + fun.call(obj[i], obj[i], i); + } + return obj; + } else { + console.log("error:traversal object is not Object or Array!") + } + }, + //超出长度。。。 + limitstr: function(str, length) { + if (str.length > 0) { + return str.slice(0, length) + '...'; + } else { + return '' + } + + }, + //去前后空格 + trim: function(str) { + return indexFn.isString(str) ? str.replace(/[(^\s*)|(\s*$)]/g, "") : "str is not string"; + }, + //获取当前时间 + getCurrTime: function(type, isComplete) { + var date = new Date(), + pattern; + + var year = date.getFullYear(), + month = date.getMonth() + 1, + day = date.getDate(), + + hour = date.getHours(), + minute = date.getMinutes(), + second = date.getSeconds(); + + if (!indexFn.isUndefined(type)) { + if (type === 'en') { + if (isComplete) { + return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; + } else { + return year + '-' + month + '-' + day; + } + } else if (type === 'cn') { + if (isComplete) { + return year + '年' + month + '月' + day + '日 ' + hour + '时' + minute + '分' + second + '秒'; + } else { + return year + '年' + month + '月' + day + '日 '; + } + } else { + return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; + } + } + } + + + + + + } + +/***/ }) +/******/ ]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067047_app.js b/pool/shard010/JavaScript/0067047_app.js new file mode 100644 index 0000000000000000000000000000000000000000..13b65139e4912ce33b7faeac2c2522176bbd8514 --- /dev/null +++ b/pool/shard010/JavaScript/0067047_app.js @@ -0,0 +1,66 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var routes = require('./routes/index'); +var users = require('./routes/users'); + +var app = express(); + +var cors = require('cors'); +app.use(cors()); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); + +// uncomment after placing your favicon in /public +//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); +// app.use(allowCrossDomain); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ + extended: false +})); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/api/', routes); +app.use('/users', users); + +// catch 404 and forward to error handler +app.use(function (req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067049_default_test.js b/pool/shard010/JavaScript/0067049_default_test.js new file mode 100644 index 0000000000000000000000000000000000000000..919f5965a978b41e74bca14e14d001a6849d5e4a --- /dev/null +++ b/pool/shard010/JavaScript/0067049_default_test.js @@ -0,0 +1,17 @@ +describe("", function() { + var rootEl; + beforeEach(function() { + rootEl = browser.rootEl; + browser.get("examples/example-example48/index.html"); + }); + + it('should check ng-options', function() { + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); + element.all(by.model('myColor')).first().click(); + element.all(by.css('select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); + element(by.css('.nullable select[ng-model="myColor"]')).click(); + element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); + }); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067052_ontologiesActions.js b/pool/shard010/JavaScript/0067052_ontologiesActions.js new file mode 100644 index 0000000000000000000000000000000000000000..ea6f1e4564c32b6e09df195a15cbcf207536fee4 --- /dev/null +++ b/pool/shard010/JavaScript/0067052_ontologiesActions.js @@ -0,0 +1,60 @@ +import { apiURLs, jsonRequest } from '../config/apiURLs' +import { dataParser, arrDataParser } from '../util/dataParser' + +const ontologiesURL = `${apiURLs.kataLOD}/ontologies` + +const requestOntListPending = response => ({ + type: 'REQUEST_ONT_LIST_PENDING' +}) +const requestOntListFulfilled = response => ({ + type: 'REQUEST_ONT_LIST_FULFILLED', + payload: response +}) +const requestOntListRejected = error => ({ + type: 'REQUEST_ONT_LIST_REJECTED', + payload: error +}) + +const requestOntDetailPending = response => ({ + type: 'REQUEST_ONT_DETAIL_PENDING' +}) +const requestOntDetailFulfilled = response => ({ + type: 'REQUEST_ONT_DETAIL_FULFILLED', + payload: response +}) +const requestOntDetailRejected = error => ({ + type: 'REQUEST_ONT_DETAIL_REJECTED', + payload: error +}) + +export const requestOntList = () => dispatch => + new Promise(() => dispatch(requestOntListPending())).then( + fetch(ontologiesURL, jsonRequest) + .then( + response => + response.ok + ? response + .json() + .then(data => + dispatch(requestOntListFulfilled(arrDataParser(data, 'it'))) + ) + : dispatch(requestOntListRejected(response.statusText)) + ) + .catch(error => dispatch(requestOntListRejected(error))) + ) + +export const requestOntDetail = ontID => dispatch => + new Promise(() => dispatch(requestOntDetailPending())).then( + fetch(`${ontologiesURL}/${ontID}`, jsonRequest) + .then( + response => + response.ok + ? response + .json() + .then(data => + dispatch(requestOntDetailFulfilled(dataParser(data, 'it'))) + ) + : dispatch(requestOntDetailRejected(response.statusText)) + ) + .catch(error => dispatch(requestOntDetailRejected(error))) + ) diff --git a/pool/shard010/JavaScript/0067053_decks.controller.js b/pool/shard010/JavaScript/0067053_decks.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..92f8679fd1d724c98d11408b8803ecc4e3d69d0b --- /dev/null +++ b/pool/shard010/JavaScript/0067053_decks.controller.js @@ -0,0 +1,61 @@ +'use strict'; + +angular.module('hciPrototypeApp') + .controller('DecksCtrl', function ($scope, $http, $filter, ngTableParams) { + var allCards = []; + var data = []; + + $http.get('/api/cards').success(function(cardList) { + data = cardList; + allCards = cardList; + $scope.deckParams = new ngTableParams({ + page: 1, // show first page + count: 10, // count per page + //Can set initial filter, but drastically slows the rendering of the table + //filter: { + // name: '' // initial filter + //}, + sorting: { + name: 'asc' // initial sorting (ascending) + } + }, { + total: data.length, // length of data + getData: function($defer, params) { + // use build-in angular filter + var filteredData = params.filter() ? $filter('filter')(data, params.filter()) : data; + var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : data; //ordered array of objects based on filter + + params.total(orderedData.length); // set total for recalc pagination + $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); + } + }); + }).error(function(data, status) { + console.log(status + ': ' + data); + }); + + $scope.removeFromDeck = function(card) { + card.deck = ''; + $http.put('/api/cards/' + card._id, card).success(function(){ + getCards(); + }); + }; + + $scope.filterDecks = function() { + data = $filter('filter')(allCards, $scope.deckName); + $scope.deckParams.reload(); + }; + + function getCards() { + $http.get('/api/cards').success(function(cardList) { + allCards = cardList; + data = cardList; + $scope.deckParams.reload(); + }).error(function(data, status) { + console.log(status + ': ' + data); + }); + } + + $scope.reloadCards = function() { + getCards(); + }; + }); diff --git a/pool/shard010/JavaScript/0067059_deployment-test.js b/pool/shard010/JavaScript/0067059_deployment-test.js new file mode 100644 index 0000000000000000000000000000000000000000..a26a48f91dc8d3479b263ce0a0c267462e239dc8 --- /dev/null +++ b/pool/shard010/JavaScript/0067059_deployment-test.js @@ -0,0 +1,82 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'ember-qunit'; +import { startMirage } from 'nomad-ui/initializers/ember-cli-mirage'; + +module('Unit | Adapter | Deployment', function(hooks) { + setupTest(hooks); + + hooks.beforeEach(async function() { + this.store = this.owner.lookup('service:store'); + this.system = this.owner.lookup('service:system'); + this.subject = () => this.store.adapterFor('deployment'); + + window.localStorage.clear(); + + this.server = startMirage(); + + this.initialize = async ({ region } = {}) => { + if (region) window.localStorage.nomadActiveRegion = region; + + this.server.create('region', { id: 'region-1' }); + this.server.create('region', { id: 'region-2' }); + + this.server.create('node'); + const job = this.server.create('job', { createAllocations: false }); + const deploymentRecord = server.schema.deployments.where({ jobId: job.id }).models[0]; + + this.system.get('shouldIncludeRegion'); + await this.system.get('defaultRegion'); + + const deployment = await this.store.findRecord('deployment', deploymentRecord.id); + this.server.pretender.handledRequests.length = 0; + + return deployment; + }; + }); + + hooks.afterEach(function() { + this.server.shutdown(); + }); + + const testCases = [ + { + variation: '', + region: null, + fail: id => `POST /v1/deployment/fail/${id}`, + promote: id => `POST /v1/deployment/promote/${id}`, + }, + { + variation: 'with non-default region', + region: 'region-2', + fail: id => `POST /v1/deployment/fail/${id}?region=region-2`, + promote: id => `POST /v1/deployment/promote/${id}?region=region-2`, + }, + ]; + + testCases.forEach(testCase => { + test(`promote makes the correct API call ${testCase.variation}`, async function(assert) { + const deployment = await this.initialize({ region: testCase.region }); + await this.subject().promote(deployment); + + const request = this.server.pretender.handledRequests[0]; + + assert.equal(`${request.method} ${request.url}`, testCase.promote(deployment.id)); + assert.deepEqual(JSON.parse(request.requestBody), { + DeploymentId: deployment.id, + All: true, + }); + }); + + test(`fail makes the correct API call ${testCase.variation}`, async function(assert) { + const deployment = await this.initialize({ region: testCase.region }); + await this.subject().fail(deployment); + + const request = this.server.pretender.handledRequests[0]; + + assert.equal(`${request.method} ${request.url}`, testCase.fail(deployment.id)); + assert.deepEqual(JSON.parse(request.requestBody), { + DeploymentId: deployment.id, + }); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067060_my-messages.spec.js b/pool/shard010/JavaScript/0067060_my-messages.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8ee5851e897d4b383c2c3b08d958e3c6cd4460d7 --- /dev/null +++ b/pool/shard010/JavaScript/0067060_my-messages.spec.js @@ -0,0 +1,53 @@ +import MyMessagesModule from './my-messages' +import MyMessagesController from './my-messages.controller'; +import MyMessagesComponent from './my-messages.component'; +import MyMessagesTemplate from './my-messages.html'; + +describe('MyMessages', () => { + let $rootScope, makeController; + + beforeEach(window.module(MyMessagesModule.name)); + beforeEach(inject((_$rootScope_) => { + $rootScope = _$rootScope_; + makeController = () => { + return new MyMessagesController(); + }; + })); + + describe('Module', () => { + // top-level specs: i.e., routes, injection, naming + }); + + describe('Controller', () => { + // controller specs + it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller + let controller = makeController(); + expect(controller).to.have.property('name'); + }); + }); + + describe('Template', () => { + // template specs + // tip: use regex to ensure correct bindings are used e.g., {{ }} + it('has name in template [REMOVE]', () => { + expect(MyMessagesTemplate).to.match(/{{\s?vm\.name\s?}}/g); + }); + }); + + describe('Component', () => { + // component/directive specs + let component = MyMessagesComponent(); + + it('includes the intended template',() => { + expect(component.template).to.equal(MyMessagesTemplate); + }); + + it('uses `controllerAs` syntax', () => { + expect(component).to.have.property('controllerAs'); + }); + + it('invokes the right controller', () => { + expect(component.controller).to.equal(MyMessagesController); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067064_intersection.spec.js b/pool/shard010/JavaScript/0067064_intersection.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..24e0d016180aa3c02ffa4ebf269a810699c7c14c --- /dev/null +++ b/pool/shard010/JavaScript/0067064_intersection.spec.js @@ -0,0 +1,54 @@ +var clipper = require('../'); + +Promise.promisifyAll(clipper); + +var types = clipper.PolyFillType; +var poly1 = [0, 0, 10, 0, 10, 10, 0, 10]; +var poly2 = [5, 5, 15, 5, 15, 15, 5, 15]; + +describe('#intersection', function() { + it('should return the intersection of two polygons', function() { + var clip = clipper.begin(); + clip.setFillTypes(types.POSITIVE, types.POSITIVE); + clip.addSubjectPath(poly1, true); + clip.addClipPath(poly2); + expect(clip.intersection()).to.eql([ + [ + [10, 10, 5, 10, 5, 5, 10, 5] + ], + [] + ]); + }); + + it('should return the difference of two polygons using callbacks', function(done) { + var clip = clipper.begin(); + clip.setFillTypes(types.POSITIVE, types.POSITIVE); + clip.addSubjectPath(poly1, true); + clip.addClipPath(poly2); + clip.intersection(function(err, result) { + expect(result).to.eql([ + [ + [10, 10, 5, 10, 5, 5, 10, 5] + ], + [] + ]); + done(); + }); + }); + + it('should return the difference of two polygons with promises', function() { + return clipper.beginAsync().then(Promise.promisifyAll).then(function(clip) { + return Promise.all([ + clip.setFillTypesAsync(types.POSITIVE, types.POSITIVE), + clip.addSubjectPathAsync(poly1, true), + clip.addClipPathAsync(poly2) + ]).then(function() { + return clip.intersectionAsync(); + }).spread(function(closed, open) { + expect(closed).to.eql([ + [10, 10, 5, 10, 5, 5, 10, 5] + ]); + }); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067069_component.js b/pool/shard010/JavaScript/0067069_component.js new file mode 100644 index 0000000000000000000000000000000000000000..3eb2a12a988695adc09c4891426e9d8b0365291a --- /dev/null +++ b/pool/shard010/JavaScript/0067069_component.js @@ -0,0 +1,142 @@ +import { get, set, observer, computed } from '@ember/object' +import Component from '@ember/component'; +import layout from './template'; +import { inject as service } from '@ember/service'; + +export default Component.extend({ + intl: service(), + + layout, + ingress: null, + rule: null, + isDefault: null, + editing: true, + + pathArray: null, + + init() { + this._super(...arguments); + this.initPathArray(); + }, + + didInsertElement() { + if (get(this, 'editing') && get(this, 'pathArray.length') === 0) { + this.send('addPath', 'workload'); + } + }, + + actions: { + addPath(backendType) { + get(this, 'pathArray').pushObject({ + backendType, + targetPort: '', + serviceId: '', + path: '', + }); + }, + + removePath(path) { + get(this, 'pathArray').removeObject(path); + }, + }, + + pathsChanged: observer('pathArray.@each.{path,backendType,targetPort,serviceId}', 'isDefault', function() { + if (get(this, 'isDefault')) { + this.setDefaultBackend(); + } else { + this.setPaths(); + } + }), + + servicesDidChange: observer('pathArray.@each.{service}', function() { + const pathArray = get(this, 'pathArray'); + + pathArray.forEach((path) => { + const backendType = get(path, 'backendType'); + const targetPort = get(path, 'targetPort'); + const availablePorts = get(path, 'service.availablePorts') || []; + const hasPorts = get(path, 'service.availablePorts.length') > 0; + + if (backendType === 'service' && hasPorts && !availablePorts.find((p) => p.port === targetPort)) { + set(path, 'targetPort', get(path, 'service.availablePorts.firstObject.port')); + } + }); + }), + + hasServiceTargets: computed('pathArray.@each.backendType', function() { + return !!get(this, 'pathArray').findBy('backendType', 'service'); + }), + + initPathArray() { + const pathArray = []; + const paths = get(this, 'rule.paths') || []; + + paths.forEach((path) => { + if (get(path, 'serviceId')) { + pathArray.pushObject(get(this, 'store').createRecord({ + type: 'httpingresspath', + backendType: 'service', + targetPort: `${ get(path, 'targetPort') || '' }`, + serviceId: get(path, 'serviceId').replace('/', ':'), + path: get(path, 'path'), + })); + } else if (get(path, 'workloadIds')) { + get(path, 'workloadIds').forEach((workload) => { + pathArray.pushObject({ + backendType: 'workload', + targetPort: get(path, 'targetPort'), + serviceId: workload, + path: get(path, 'path'), + }); + }); + } + }); + set(this, 'pathArray', pathArray); + }, + + setDefaultBackend() { + const pathArray = get(this, 'pathArray'); + let defaultBackend = { workloadIds: [], }; + + pathArray.forEach((path) => { + const backendType = get(path, 'backendType'); + const serviceId = get(path, 'serviceId'); + const targetPort = get(path, 'targetPort'); + + if (backendType === 'service') { + defaultBackend.serviceId = serviceId; + } else if (backendType === 'workload') { + defaultBackend.workloadIds.pushObject(serviceId); + } + defaultBackend.targetPort = targetPort; + }); + set(this, 'ingress.defaultBackend', defaultBackend); + }, + + setPaths() { + const pathArray = get(this, 'pathArray'); + const paths = []; + + pathArray.forEach((item) => { + const backendType = get(item, 'backendType'); + const path = get(item, 'path'); + const serviceId = get(item, 'serviceId'); + const targetPort = get(item, 'targetPort'); + + if (backendType === 'service') { + paths.pushObject({ + path, + serviceId, + targetPort, + }); + } else if (backendType === 'workload') { + paths.pushObject({ + path, + workloadIds: [serviceId], + targetPort, + }); + } + }) + set(this, 'rule.paths', paths); + } +}); diff --git a/pool/shard010/JavaScript/0067070_login.js b/pool/shard010/JavaScript/0067070_login.js new file mode 100644 index 0000000000000000000000000000000000000000..473860f521eafd627c9db8f5acf0e19d2ecd4a30 --- /dev/null +++ b/pool/shard010/JavaScript/0067070_login.js @@ -0,0 +1,78 @@ +import React, { Component } from 'react'; +import actions from '../modules/user-management/actions'; +import Paper from '../../node_modules/material-ui/lib/paper'; +import TextField from '../../node_modules/material-ui/lib/text-field'; +import RaisedButton from '../../node_modules/material-ui/lib/raised-button'; +import CircularProgress from '../../node_modules/material-ui/lib/circular-progress'; +import ErrorText from './error-text'; +import { connect } from 'nuclear-js-react-addons'; +import * as getters from '../modules/user-management/getters'; + +const ENTER_KEY = 13; + +const style = { + paper: { + height: 380, + width: 314, + margin: '0 auto', + textAlign: 'center', + position: 'relative', + top: '20%' + }, + button: { + margin: 12, + display: 'block' + }, + logo: { + display: 'block', + margin: '0 auto' + } +}; + +class Login extends Component { + constructor(props) { + super(props); + } + + login() { + actions.authenticate(this.usernameInput.getValue(), this.passInput.getValue()); + } + + handleKeyPress(e) { + if (e.charCode === ENTER_KEY) { + this.login(); + } + } + + render() { + const { isLoading, authFailedReason } = this.props; + return ( + + + this.usernameInput = i} hintText="Username" /> + this.passInput = i} type="password" hintText="Password" /> + { + isLoading ? : + + } + { + authFailedReason ? : '' + } + + ); + } +} + +function mapStateToProps(props) { + return { + isLoading: getters.isTalkingToServer, + authFailedReason: getters.authFailedReason + } +} + +const ConnectedLogin = connect(mapStateToProps)(Login); + +export default ConnectedLogin; diff --git a/pool/shard010/JavaScript/0067076_index.js b/pool/shard010/JavaScript/0067076_index.js new file mode 100644 index 0000000000000000000000000000000000000000..04137ba2e11010d8ae5d81436939439d788f679b --- /dev/null +++ b/pool/shard010/JavaScript/0067076_index.js @@ -0,0 +1,189 @@ +'use strict'; + +var yeoman = require('yeoman-generator'); +var optionOrPrompt = require('yeoman-option-or-prompt'); +var fs = require("fs"); +var listModules, listModulesArray; + +var typesDocument = { + + action:{ + folder: '/actions/', + template: '_action.js', + nameFile: '/index.js', + nameType: 'action' + }, + api:{ + folder: '/api/', + template: '_api.js', + nameFile: '/index.js', + nameType: 'api' + }, + component:{ + folder: '/components/', + template: '_component.js', + nameFile: '/index.jsx', + nameType: 'component' + }, + container:{ + folder: '/', + template: '_container.js', + nameFile: '/index.jsx', + nameType: 'container' + }, + models:{ + folder: '/models/', + template: '_models.js', + nameFile: '/index.js', + nameType: 'models' + }, + reducer:{ + folder: '/reducers/', + template: '_reducer.js', + nameFile: '/index.js', + nameType: 'reducer' + }, + styles:{ + folder: '/', + template: '_styles.css', + nameFile: '/styles.css', + nameType: 'styles' + }, + types:{ + folder: '/actionTypes/', + template: '_actionTypes.js', + nameFile: '/index.js', + nameType: 'actionTypes' + } +} + +var baseRoute = 'src/app'; +var sectionCopy; + +function section (route, name, config) { + this.fs.copyTpl( + this.templatePath(config.template), + this.destinationPath(route + name + config.folder + config.nameFile), { + name: name, + nameUpper: name.toUpperCase(), + nameLower: name.toLowerCase(), + namePascal: name.charAt(0).toUpperCase() + name.slice(1), + nameGenerator: '_' + name.charAt(0).toUpperCase() + name.slice(1), + nameState: '_' + name + } + ); +} + +function sectionSpec(route, name, config){ + this.fs.copyTpl( + this.templatePath(config.template), + this.destinationPath(route + name + config.folder + name + config.nameFile), { + name: name, + nameUpper: name.toUpperCase(), + nameLower: name.toLowerCase(), + namePascal: name.charAt(0).toUpperCase() + name.slice(1), + nameGenerator: '_' + name.charAt(0).toUpperCase() + name.slice(1), + nameState: '_' + name + } + ); +} + + +function createComponent(name){ + let routeComponentName = baseRoute +'/components/' + name + '/' ; + let namePascal = name.charAt(0).toUpperCase() + name.slice(1); + + /*COMPONENT*/ + this.fs.copyTpl( + this.templatePath(typesDocument.component.template), + this.destinationPath(routeComponentName + typesDocument.component.nameFile , '/'), { + name: namePascal, + nameUpper: name.toUpperCase(), + nameLower: name.toLowerCase() + } + ); + + /*STYLES*/ + this.fs.copyTpl( + this.templatePath(typesDocument.styles.template), + this.destinationPath(routeComponentName + typesDocument.styles.nameFile, '/'), { + name: namePascal, + nameUpper: name.toUpperCase(), + nameLower: name.toLowerCase() + } + ); +/* + this.fs.copyTpl( + this.templatePath(typesDocument.component_spec.template), + this.destinationPath(routeComponentName + '/spec/' + name + typesDocument.component_spec.nameFile), { + name: namePascal, + nameUpper: name.toUpperCase(), + nameLower: name.toLowerCase() + } + );*/ + +} + +function createContainer(name){ + let route = baseRoute + '/containers/' + let namePascal = name.charAt(0).toUpperCase() + name.slice(1) + sectionCopy(route, namePascal, typesDocument.action); + sectionCopy(route, namePascal, typesDocument.api); + sectionCopy(route, namePascal, typesDocument.component); + sectionCopy(route, namePascal, typesDocument.container); + sectionCopy(route, namePascal, typesDocument.models); + sectionCopy(route, namePascal, typesDocument.reducer); + sectionCopy(route, namePascal, typesDocument.styles); + sectionCopy(route, namePascal, typesDocument.types); + +} + +module.exports = yeoman.Base.extend({ + _optionOrPrompt: optionOrPrompt, + + prompting: function () { + + var done = this.async(); + + var promptsAll = [{ + message: 'React-Base generator, choose your option: \n 1- New Container \n 2- New Component\n write you option: ', + name: 'option', + type: 'input' + }, + { + message: 'Input Name', + name: 'name', + type: 'input' + }]; + + this._optionOrPrompt(promptsAll, function (answers) { + + this.props = answers; + this.props.option = parseInt(answers.option); + this.props.name = answers.name; + done(); + }.bind(this)); + }, + + writing: { + config: function () { + sectionCopy = section.bind(this); + + createComponent = createComponent.bind(this); + switch(this.props.option){ + case 1: + createContainer(this.props.name); + break; + case 2: + createComponent(this.props.name); + break; + default: + return; + } + } + }, + end: function () { + var done = this.async(); + this.spawnCommand('npm', ['run', 'postYeomanGenerator']).on('close', done); + } +}); diff --git a/pool/shard010/JavaScript/0067077_getSoftphoneReducer.test.js b/pool/shard010/JavaScript/0067077_getSoftphoneReducer.test.js new file mode 100644 index 0000000000000000000000000000000000000000..73cb0d1502e06c0da23169cae6b6ccdd53637c43 --- /dev/null +++ b/pool/shard010/JavaScript/0067077_getSoftphoneReducer.test.js @@ -0,0 +1,84 @@ +import { expect } from 'chai'; +import getSoftphoneReducer, { + getSoftphoneStatusReducer, + getConnectingPhoneNumberReducer, +} from './getSoftphoneReducer'; +import softphoneStatus from './softphoneStatus'; +import softphoneActionTypes from './actionTypes'; + +describe('Softphone', () => { + describe('getSoftphoneStatusReducer', () => { + const reducer = getSoftphoneStatusReducer(softphoneActionTypes); + it('should be a function', () => { + expect(getSoftphoneStatusReducer).to.be.a('function'); + }); + it('should have initial state of idle', () => { + expect(reducer(undefined, {})).to.equal(softphoneStatus.idle); + }); + it('should return original state if actionType is not recognized', () => { + const originalState = {}; + expect(reducer(originalState, { type: 'foo' })).to.equal(originalState); + }); + it('should return idle status if actionType is connectComplete', () => { + expect( + reducer('foo', { + type: softphoneActionTypes.connectComplete, + }), + ).to.equal(softphoneStatus.idle); + }); + it('should return connecting status if actionType is startToConnect', () => { + expect( + reducer('foo', { + type: softphoneActionTypes.startToConnect, + }), + ).to.equal(softphoneStatus.connecting); + }); + }); + describe('getConnectingPhoneNumberReducer', () => { + const reducer = getConnectingPhoneNumberReducer(softphoneActionTypes); + it('should be a function', () => { + expect(getConnectingPhoneNumberReducer).to.be.a('function'); + }); + it('should have initial state of null', () => { + expect(reducer(undefined, {})).to.equal(null); + }); + it('should return original state if actionType is not recognized', () => { + const originalState = {}; + expect(reducer(originalState, { type: 'foo' })).to.equal(originalState); + }); + it('should return null if actionType is connectComplete', () => { + expect( + reducer('foo', { + type: softphoneActionTypes.connectComplete, + }), + ).to.equal(null); + }); + it('should return connecting phone number if actionType is startToConnect', () => { + const phoneNumber = '123'; + expect( + reducer('foo', { + type: softphoneActionTypes.startToConnect, + phoneNumber, + }), + ).to.equal(phoneNumber); + }); + }); + describe('getSoftphoneReducer', () => { + it('should be a function', () => { + expect(getSoftphoneReducer).to.be.a('function'); + }); + const reducer = getSoftphoneReducer(softphoneActionTypes); + const softphoneStatusReducer = getSoftphoneStatusReducer( + softphoneActionTypes, + ); + const connectingPhoneNumberReducer = getConnectingPhoneNumberReducer( + softphoneActionTypes, + ); + it('should return combined state', () => { + expect(reducer(undefined, {})).to.deep.equal({ + softphoneStatus: softphoneStatusReducer(undefined, {}), + connectingPhoneNumber: connectingPhoneNumberReducer(undefined, {}), + }); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067078_testDeploy.js b/pool/shard010/JavaScript/0067078_testDeploy.js new file mode 100644 index 0000000000000000000000000000000000000000..86d9a529fab6f2a71492dfd13f7fbae09621ae71 --- /dev/null +++ b/pool/shard010/JavaScript/0067078_testDeploy.js @@ -0,0 +1,56 @@ +var Web3 = require('web3'); +var util = require('ethereumjs-util'); +var tx = require('ethereumjs-tx'); +var lightwallet = require('eth-lightwallet'); +var txutils = lightwallet.txutils; + +var web3 = new Web3( + new Web3.providers.HttpProvider('https://rinkeby.infura.io/RN5ouaGxbPB4wrYNgM2Q') +); + + +var user = require('../../../user2') +var contract = require('./contract') + +/* +web3.eth.getGasPrice(function(err, result) { + if(err) { + console.log(err); + } else { + // Display the transaction number. + console.log("Gas Price: " + result); + } +}); +*/ + + +function sendRaw(rawTx) { + var privateKey = new Buffer(user.key, 'hex'); + var transaction = new tx(rawTx); + transaction.sign(privateKey); + var serializedTx = transaction.serialize().toString('hex'); + web3.eth.sendRawTransaction( + '0x' + serializedTx, function(err, result) { + if(err) { + console.log(err); + } else { + // Display the transaction number. + console.log(result); + } + }); +} + + +var rawTx = { + nonce: web3.toHex(web3.eth.getTransactionCount(user.address)), + gasLimit: web3.toHex(800000), +// gasPrice: web3.toHex(20000000000), + gasPrice: web3.toHex(50000000000), + data: '0x' + contract.bytecode + '0000000000000000000000000000000000000000000000000000000000000005' + +}; + + +sendRaw(rawTx); + + diff --git a/pool/shard010/JavaScript/0067079_index.js b/pool/shard010/JavaScript/0067079_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2461f2634e528e7951f34096a99b2a0c086ca1ac --- /dev/null +++ b/pool/shard010/JavaScript/0067079_index.js @@ -0,0 +1,136 @@ +/** + * @fileOverview Expose a programmatic interface for using Lambda Complex. + */ + +// Core. +var util = require('util'); + +// NPM. +var async = require('async'); +var Janitor = require('cloudwatch-logs-janitor'); +var fs = require('fs-extra'); + +// Local. +var common = require('./lib/build/common'); +var configValidator = require('./lib/build/configValidator'); +var installUtilities = require('./lib/build/installUtilities'); +var packageUtilities = require('./lib/build/packageUtilities'); +var cloudFormationTemplateUtilities = require('./lib/build/cloudFormationTemplateUtilities'); +var cloudFormationUtilities = require('./lib/deploy/cloudFormationUtilities'); +var s3Utilities = require('./lib/deploy/s3Utilities'); + +/** + * Build a Lambda Complex application. + * + * @param {Object} config The application configuration. + * @param {Function} callback Of the form function (error). + */ +exports.build = function (config, callback) { + // Validate the configuration first of all. + var results = configValidator.validate(config); + if (results.length) { + return callback(new Error(util.format( + 'Invalid configuration: %s', + JSON.stringify(results, null, ' ') + ))); + } + + async.series({ + // Clear out the build directory for this application. + clean: function (asyncCallback) { + fs.remove(common.getApplicationBuildDirectory(config), asyncCallback); + }, + + // Download or copy the NPM packages containing Lambda function handlers. + install: function (asyncCallback) { + installUtilities.installLambdaFunctions(config, asyncCallback); + }, + + // Zip up the NPM packages. + package: function (asyncCallback) { + packageUtilities.packageLambdaFunctions(config, asyncCallback); + }, + + // Create the CloudFormation template for this application deployment. + generateCloudFormationTemplate: function (asyncCallback) { + cloudFormationTemplateUtilities.generateTemplate(config, asyncCallback); + } + }, callback); +}; + +/** + * Build and deploy a Lambda Complex application. + * + * @param {Object} config The application configuration. + * @param {Function} callback Of the form function (error, results). + */ +exports.deploy = function (config, callback) { + var startTime = new Date(); + var results; + + async.series({ + // Run the build task. + build: function (asyncCallback) { + exports.build(config, asyncCallback); + }, + + // Take the packaged Lambda functions and upload them to S3. + uploadLambdaFunctions: function (asyncCallback) { + s3Utilities.uploadLambdaFunctions(config, asyncCallback); + }, + + // Upload the configuration to S3. + // + // The application doesn't use this config file instance, rather loading + // config files from the packages, but keeping a record of it in S3 + // alongside the other files for each deployment seems like a smart idea. + uploadConfig: function (asyncCallback) { + s3Utilities.uploadConfig(config, asyncCallback); + }, + + // Now on to the actual CloudFormation deployment, including the activities + // needed to switch over resources to use the new application, and deletion + // of old stacks. + deployCloudFormationStack: function (asyncCallback) { + cloudFormationUtilities.deployStack(config, function (error, _results) { + results = _results; + asyncCallback(error); + }); + }, + + // Every Lambda function generates a CloudWatch log group, and this can + // build up clutter pretty quickly during development. Some people may + // prefer to keep the old groups around for production deployments. + deletePriorCloudwatchLogGroups: function (asyncCallback) { + if (config.deployment.skipPriorCloudWatchLogGroupsDeletion) { + return asyncCallback(); + } + + // This will use AWS config from the environment, like the rest of Lambda + // Complex. + var janitor = new Janitor(); + + janitor.deleteMatchingLogGroups({ + // Using this should be sufficient to avoid deleting log groups for + // the just-deployed Lambda functions. + createdBefore: startTime, + // Lambda function log groups for this application will have names that + // begin with this prefix. + prefix: '/aws/lambda/' + config.name + '-' + }, function (error) { + // Cleaning up old log groups may require a bunch of API requests, and + // these have in the past proven to be somewhat flaky and/or subject to + // very low throttling levels. Failure here isn't critical, as anything + // that is missed will be addressed by the next deployment. So just add + // the error to the results. + if (error) { + results.cloudWatchLogDeletionError = error; + } + + asyncCallback(); + }); + } + }, function (error) { + callback(error, results); + }); +}; diff --git a/pool/shard010/JavaScript/0067080_CCAtlasNodeWebGLRenderCmd.js b/pool/shard010/JavaScript/0067080_CCAtlasNodeWebGLRenderCmd.js new file mode 100644 index 0000000000000000000000000000000000000000..8fce00f8daf299e0e5a12e83229acfb2c818603d --- /dev/null +++ b/pool/shard010/JavaScript/0067080_CCAtlasNodeWebGLRenderCmd.js @@ -0,0 +1,160 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.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. + ****************************************************************************/ + +/** + * cc.AtlasNode's rendering objects of WebGL + */ +(function () { + cc.AtlasNode.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); + this._needDraw = true; + this._textureAtlas = null; + this._colorUnmodified = cc.color.WHITE; + this._colorF32Array = null; + this._uniformColor = null; + + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + + //shader stuff + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); + this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color"); + }; + + var proto = cc.AtlasNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); + proto.constructor = cc.AtlasNode.WebGLRenderCmd; + + proto._updateBlendFunc = function () { + var node = this._node; + if (!this._textureAtlas.texture.hasPremultipliedAlpha()) { + node._blendFunc.src = cc.SRC_ALPHA; + node._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; + } + }; + + proto._updateOpacityModifyRGB = function () { + this._node._opacityModifyRGB = this._textureAtlas.texture.hasPremultipliedAlpha(); + }; + + proto.rendering = function (ctx) { + var context = ctx || cc._renderContext, node = this._node; + + var wt = this._worldTransform; + this._matrix.mat[0] = wt.a; + this._matrix.mat[4] = wt.c; + this._matrix.mat[12] = wt.tx; + this._matrix.mat[1] = wt.b; + this._matrix.mat[5] = wt.d; + this._matrix.mat[13] = wt.ty; + + this._shaderProgram.use(); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + + cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); + if (this._uniformColor && this._colorF32Array) { + context.uniform4fv(this._uniformColor, this._colorF32Array); + this._textureAtlas.drawNumberOfQuads(node.quadsToDraw, 0); + } + }; + + proto.initWithTexture = function (texture, tileWidth, tileHeight, itemsToRender) { + var node = this._node; + node._itemWidth = tileWidth; + node._itemHeight = tileHeight; + this._colorUnmodified = cc.color.WHITE; + node._opacityModifyRGB = true; + + node._blendFunc.src = cc.BLEND_SRC; + node._blendFunc.dst = cc.BLEND_DST; + + var locRealColor = node._realColor; + this._colorF32Array = new Float32Array([locRealColor.r / 255.0, locRealColor.g / 255.0, locRealColor.b / 255.0, node._realOpacity / 255.0]); + this._textureAtlas = new cc.TextureAtlas(); + this._textureAtlas.initWithTexture(texture, itemsToRender); + + if (!this._textureAtlas) { + cc.log(cc._LogInfos.AtlasNode__initWithTexture); + return false; + } + + this._updateBlendFunc(); + this._updateOpacityModifyRGB(); + this._calculateMaxItems(); + node.quadsToDraw = itemsToRender; + + return true; + }; + + proto.setColor = function (color3) { + var temp = cc.color(color3.r, color3.g, color3.b), node = this._node; + this._colorUnmodified = color3; + var locDisplayedOpacity = this._displayedOpacity; + if (node._opacityModifyRGB) { + temp.r = temp.r * locDisplayedOpacity / 255; + temp.g = temp.g * locDisplayedOpacity / 255; + temp.b = temp.b * locDisplayedOpacity / 255; + } + cc.Node.prototype.setColor.call(node, temp); + }; + + proto.setOpacity = function (opacity) { + var node = this._node; + cc.Node.prototype.setOpacity.call(node, opacity); + // special opacity for premultiplied textures + if (node._opacityModifyRGB) { + node.color = this._colorUnmodified; + } + }; + + proto._updateColor = function () { + if (this._colorF32Array) { + var locDisplayedColor = this._displayedColor; + this._colorF32Array[0] = locDisplayedColor.r / 255.0; + this._colorF32Array[1] = locDisplayedColor.g / 255.0; + this._colorF32Array[2] = locDisplayedColor.b / 255.0; + this._colorF32Array[3] = this._displayedOpacity / 255.0; + } + }; + + proto.getTexture = function () { + return this._textureAtlas.texture; + }; + + proto.setTexture = function (texture) { + this._textureAtlas.texture = texture; + this._updateBlendFunc(); + this._updateOpacityModifyRGB(); + }; + + proto._calculateMaxItems = function () { + var node = this._node; + var selTexture = this._textureAtlas.texture; + var size = selTexture.getContentSize(); + if (node._ignoreContentScaleFactor) + size = selTexture.getContentSizeInPixels(); + + node._itemsPerColumn = 0 | (size.height / node._itemHeight); + node._itemsPerRow = 0 | (size.width / node._itemWidth); + }; +})(); diff --git a/pool/shard010/JavaScript/0067081_server.js b/pool/shard010/JavaScript/0067081_server.js new file mode 100644 index 0000000000000000000000000000000000000000..ecc2049d7daf9baead6184c76f3aeb9a064e0539 --- /dev/null +++ b/pool/shard010/JavaScript/0067081_server.js @@ -0,0 +1,82 @@ + +/*! + * nodejs-express-mongoose-demo + * Copyright(c) 2013 Madhusudhan Srinivasa + * MIT Licensed + */ +/** + * Module dependencies + */ +var express = require('express'); + +var app = express(); + +process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; //self-signed SSL fix YOLO.. TODO: look more into/fix + +// Add headers +app.use(function (req, res, next) { + + // Website you wish to allow to connect + res.setHeader('Access-Control-Allow-Origin', '*'); +// res.setHeader('Access-Control-Allow-Origin', 'http://hitcher.us'); + + // Request methods you wish to allow + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); + + // Request headers you wish to allow + res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); + + // Set to true if you need the website to include cookies in the requests sent + // to the API (e.g. in case you use sessions) + res.setHeader('Access-Control-Allow-Credentials', true); + + // Pass to next layer of middleware + next(); +}); +app.options("*", function(req,res,next){res.send(200)}); + + +var fs = require('fs'); +var mongoose = require('mongoose'); +var passport = require('passport'); +var config = require('./config/config'); + +var port = process.env.PORT || 9000; + +// Connect to mongodb +var connect = function () { + var options = { server: { socketOptions: { keepAlive: 1 } } }; + mongoose.connect(config.db, options); +}; +connect(); + +mongoose.connection.on('error', console.log); +mongoose.connection.on('disconnected', connect); + +// Bootstrap models +fs.readdirSync(__dirname + '/server/models').forEach(function (file) { + if (~file.indexOf('.js')) require(__dirname + '/server/models/' + file); +}); + +// Bootstrap passport config +require('./config/passport')(passport, config); + +// Bootstrap application settings +require('./config/express')(app, passport); + +// Bootstrap routes +require('./config/routes')(app, passport); + +//push notifications +require('./pushNotifications'); + + + +app.listen(port); +console.log('Express app started on port ' + port); + +/** + * Expose + */ + +module.exports = app; diff --git a/pool/shard010/JavaScript/0067083_notificationsController.js b/pool/shard010/JavaScript/0067083_notificationsController.js new file mode 100644 index 0000000000000000000000000000000000000000..be9d54c160cb050f106023e209f4a818db69bf77 --- /dev/null +++ b/pool/shard010/JavaScript/0067083_notificationsController.js @@ -0,0 +1,66 @@ +angular + .module('theme.core.notifications_controller', []) + .controller('NotificationsController', ['$scope', '$filter', function($scope, $filter) { + 'use strict'; + $scope.notifications = [{ + text: 'Update 1.0.4 successfully pushed', + time: '8 mins ago', + class: 'notification-success', + iconClasses: 'ti ti-check', + seen: true + }, { + text: 'Update 1.0.3 successfully pushed', + time: '24 mins ago', + class: 'notification-info', + iconClasses: 'ti ti-check', + seen: false + }, { + text: 'Update 1.0.2 successfully pushed', + time: '16 hours ago', + class: 'notification-teal', + iconClasses: 'ti ti-check', + seen: false + }, { + text: 'Update 1.0.1 successfully pushed', + time: '2 days ago', + class: 'notification-indigo', + iconClasses: 'ti ti-check', + seen: false + }, { + text: 'Initial Release 1.0', + time: '4 days ago', + class: 'notification-danger', + iconClasses: 'ti ti-arrow-up', + seen: false + }, ]; + + $scope.setSeen = function(item, $event) { + $event.preventDefault(); + $event.stopPropagation(); + item.seen = true; + }; + + $scope.setUnseen = function(item, $event) { + $event.preventDefault(); + $event.stopPropagation(); + item.seen = false; + }; + + $scope.setSeenAll = function($event) { + $event.preventDefault(); + $event.stopPropagation(); + angular.forEach($scope.notifications, function(item) { + item.seen = true; + }); + }; + + $scope.unseenCount = $filter('filter')($scope.notifications, { + seen: false + }).length; + + $scope.$watch('notifications', function(notifications) { + $scope.unseenCount = $filter('filter')(notifications, { + seen: false + }).length; + }, true); + }]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067088_utils-spec.js b/pool/shard010/JavaScript/0067088_utils-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6a4bf9f619b1de88019e312adcab58f01b5e5e79 --- /dev/null +++ b/pool/shard010/JavaScript/0067088_utils-spec.js @@ -0,0 +1,40 @@ +const utils = require('../lib/utils'); +const expect = require('chai').expect; +const services = { + weather: { GET: { uri: 'test' } } +}; + +describe('utils', function(){ + describe('#loadStack', function(){ + it('should map middleware function from config objects', function() { + const stack = utils.loadStack([ + {type: 'middleware', path: 'test/fixtures/middleware.js#headerTest'}, + {type: 'fixture', data: {foo: 'bar'}} + ], services); + + // expect length to be 3 because we add a response middleware to every route + expect(stack).to.have.length(3); + }); + }); + + describe('#replaceStringTokens', function(){ + it('can parse a tokenized string', function(){ + var conf = { foo: 'bar', baz: 'boo' }; + var str = 'Hello, {foo}. My name is {baz}.'; + var result = utils.replaceStringTokens(conf, str); + expect(result).to.equal('Hello, bar. My name is boo.'); + }); + }); + + describe('#lookupFn', function(){ + it('can lookup a custom module', function(){ + expect(utils.lookupFn('../test/fixtures/middleware.js#headerTest')).to.be.a('function'); + }); + it('can lookup a node_module', function(){ + expect(utils.lookupFn('body-parser')).to.be.a('function'); + }); + it('will throw an error if no module found', function(){ + expect(utils.lookupFn.bind({},'foo')).to.throw('Module not found at foo.'); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067091_jquery.displayinfo.js b/pool/shard010/JavaScript/0067091_jquery.displayinfo.js new file mode 100644 index 0000000000000000000000000000000000000000..6ba837a1d1cfecf636a1baeb34bea4ff1beb5790 --- /dev/null +++ b/pool/shard010/JavaScript/0067091_jquery.displayinfo.js @@ -0,0 +1,110 @@ +(function($) { + $.fn.displayinfo = function(options) { + var opts = $.extend({}, $.fn.displayinfo.defaults, options); + + return this.each(function() { + var self = this, + o = $.meta ? $.extend({}, opts, self.data()) : opts, + displayinfo = $(".DisplayInfo", self); + + if (!displayinfo.length && o.hide == false) { + displayinfo = (self.displayinfo = $('
    ')) + .appendTo(self) + .addClass('DisplayInfo'); + } + + if (o.hide == true) { + if (displayinfo.data('validation') == true) { + displayinfo.hide(); + } + return self; + } + + displayinfo.data('validation', o.validation); + displayInfoCreated(displayinfo, o); + + return self; + }); + }; + + function displayInfoCreated(selfParent, options) { + selfParent.removeClass("DisplayInfoAlert DisplayInfoInfo DisplayInfoConfirm DisplayInfoError DisplayInfoSuccess") + .html(options.message) + .stop(true, true) + .show("pulsate"); + + switch (options.type) { + case "alert": + selfParent.addClass("DisplayInfoAlert"); + break; + case "confirm": + selfParent.addClass("DisplayInfoConfirm"); + break; + case "error": + selfParent.addClass("DisplayInfoError"); + break; + case "info": + selfParent.addClass("DisplayInfoInfo"); + break; + case "success": + selfParent.addClass("DisplayInfoSuccess"); + break; + }; + + return selfParent; + }; + + $.fn.displayinfo.defaults = { + message: "", + type: "error", + hide: false, + validation: false + }; +})(jQuery); +function ValidationSummaryOnSubmit(validationGroup) { + var container = $('#aspnetForm').find('span.DisplayInfoContainer'); + if (Page_IsValid) { + container.displayinfo({ hide: true }); + return; + } + var messageInHtml = "", displayinfoheader = container.attr('displayinfoheader'); + if (displayinfoheader) { + messageInHtml += "" + displayinfoheader + ""; + } + messageInHtml += "
      "; + $.each(Page_Validators, function() { + var self = this; + if (!self.isvalid && typeof (self.errormessage) == "string") { + messageInHtml += "
    • " + self.errormessage + "
    • "; + } + }); + messageInHtml += "
    "; + container.displayinfo({ message: messageInHtml, type: "error", validation: true }); +} +function ValidatorOnChange(event) { + if (!event) { + event = window.event + } + Page_InvalidControlToBeFocused = null; + var targetedControl; + if (typeof event.srcElement != "undefined" && event.srcElement != null) { + targetedControl = event.srcElement + } else { + targetedControl = event.target + } + var vals; + if (typeof targetedControl.Validators != "undefined") { + vals = targetedControl.Validators + } else { + if (targetedControl.tagName.toLowerCase() == "label") { + targetedControl = document.getElementById(targetedControl.htmlFor); + vals = targetedControl.Validators + } + } + var i; + for (i = 0; i < vals.length; i++) { + ValidatorValidate(vals[i], null, event) + } + ValidatorUpdateIsValid() + ValidationSummaryOnSubmit(null) +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067093_server.js b/pool/shard010/JavaScript/0067093_server.js new file mode 100644 index 0000000000000000000000000000000000000000..40d35e14b72045fe824e691cbca66fc7a98065de --- /dev/null +++ b/pool/shard010/JavaScript/0067093_server.js @@ -0,0 +1,28 @@ +var fs = require('fs'); +var http = require('http'); +var mime = require('mime'); +var path = require('path'); + +var wwwRoot = path.resolve(__dirname, 'wwwRoot'); + +http.createServer(function(req, res) { + if (req.method !== 'GET') { + res.writeHead(405, {'content-type': 'text/plain'}); + return res.end('method not supported'); + } + + var reqPath = path.resolve('.' + req.url); + if (reqPath.indexOf(wwwRoot) !== 0) { + res.writeHead(403, {'conent-type': 'text/plain'}); + res.end('forbidden'); + } + + var stream = fs.createReadStream('.' + req.url); + stream.on('error', function() { + res.writeHead(500, {'content-type': 'text/plain'}); + res.end('errord'); + }); + var contentType = mime.lookup(req.url); + res.writeHead(200, {'content-type': contentType}); + stream.pipe(res); +}).listen(1337); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067096_reducer.js b/pool/shard010/JavaScript/0067096_reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..e8915b6e91b2a0c587e999de3dd28ddf830374d7 --- /dev/null +++ b/pool/shard010/JavaScript/0067096_reducer.js @@ -0,0 +1,26 @@ +import { combineReducers } from 'berkeleys-redux-utils'; +import { reducer as formReducer } from 'redux-form'; + +import app from './redux'; +import entities from './entities'; +import map from './Map/redux'; +import nav from './Nav/redux'; +import routes from './routes/redux'; +import toasts from './Toasts/redux'; +import files from './files'; +// not ideal but should go away once we move to react-redux-form +import { projectNormalizer } from './routes/Challenges/redux'; + +const _formReducer = formReducer.normalize({ ...projectNormalizer }); +_formReducer.toString = () => 'form'; + +export default combineReducers( + app, + entities, + map, + nav, + routes, + toasts, + files, + _formReducer +); diff --git a/pool/shard010/JavaScript/0067098_initialize-db.js b/pool/shard010/JavaScript/0067098_initialize-db.js new file mode 100644 index 0000000000000000000000000000000000000000..4ebd35b57ea17ad8c85829b65f7b73ceea3911bb --- /dev/null +++ b/pool/shard010/JavaScript/0067098_initialize-db.js @@ -0,0 +1,288 @@ +import { Accounts } from 'meteor/accounts-base'; +import { Roles } from 'meteor/alanning:roles'; +import { Meteor } from 'meteor/meteor'; +import { _ } from 'meteor/erasaur:meteor-lodash'; +import { moment } from 'meteor/momentjs:moment'; +import { SyncedCron } from 'meteor/percolate:synced-cron'; +import { PublicStats } from '../../api/public-stats/PublicStatsCollection'; +import { RadGrad } from '../../api/radgrad/RadGrad'; +import { Interests } from '../../api/interest/InterestCollection'; +import { CareerGoals } from '../../api/career/CareerGoalCollection'; +import { AcademicPlans } from '../../api/degree-plan/AcademicPlanCollection'; +import { UserInteractions } from '../../api/analytic/UserInteractionCollection'; +import { loadCollection } from '../../api/test/test-utilities'; +import { removeAllEntities } from '../../api/base/BaseUtilities'; +import { checkIntegrity } from '../../api/integrity/IntegrityChecker'; +import { ROLE } from '../../api/role/Role'; +import { StudentParticipation } from '../../api/public-stats/StudentParticipationCollection'; +import { AdvisorProfiles } from '../../api/user/AdvisorProfileCollection'; +import { Slugs } from '../../api/slug/SlugCollection'; +import { FavoriteInterests } from '../../api/favorite/FavoriteInterestCollection'; +import { FavoriteCareerGoals } from '../../api/favorite/FavoriteCareerGoalCollection'; +import { FacultyProfiles } from '../../api/user/FacultyProfileCollection'; +import { StudentProfiles } from '../../api/user/StudentProfileCollection'; +import { MentorProfiles } from '../../api/user/MentorProfileCollection'; + +/* global Assets */ +/* eslint no-console: "off" */ + +/** + * Returns an Array of numbers, one per loadable collection, indicating the number of documents in that collection. + * @returns { Array } An array of collection document counts. + * @memberOf startup/server + */ +function documentCounts() { + return _.map(RadGrad.collectionLoadSequence, collection => collection.count()); +} + +/** + * Returns the total number of documents in the loadable collections. + * @returns { Number } The total number of RadGrad documents in the loadable collections. + * @memberOf startup/server + */ +function totalDocuments() { + return _.reduce(documentCounts(), function reducer(sum, count) { + return sum + count; + }, 0); +} + +/** + * The load/fixture file date format. + * Used when dumping and restoring the RadGrad database. + * @type {string} + * @memberOf startup/server + */ +const loadFileDateFormat = 'YYYY-MM-DD-HH-mm-ss'; + +/** + * Returns a string indicating how long ago the load file was created. Parses the file name string. + * @param loadFileName The file name. + * @returns { String } A string indicating how long ago the file was created. + * @memberOf startup/server + */ +function getRestoreFileAge(loadFileName) { + const terms = _.words(loadFileName, /[^/. ]+/g); + const dateString = terms[terms.length - 2]; + return moment(dateString, loadFileDateFormat).fromNow(); +} + +/** + * If the database is empty, this function looks up the name of the load file in the settings file, + * and if it is specified, then it reads it in and calls define() on its contents in order to load the database. + * Console messages are generated when the contents of the load file does not include collections that + * this function assumes are present. Conversely, if the load file contains collections not processed with + * this file, a string is also printed out. + * @memberOf startup/server + */ +function loadDatabase() { + const loadFileName = Meteor.settings.public.databaseRestoreFileName; + if (loadFileName && (totalDocuments() === 0)) { + const loadFileAge = getRestoreFileAge(loadFileName); + console.log(`Loading database from file ${loadFileName}, dumped ${loadFileAge}.`); + const loadJSON = JSON.parse(Assets.getText(loadFileName)); + // The list of collections, ordered so that they can be sequentially restored. + const collectionList = RadGrad.collectionLoadSequence; + + const loadNames = _.map(loadJSON.collections, obj => obj.name); + const collectionNames = _.map(collectionList, collection => collection._collectionName); + const extraRestoreNames = _.difference(loadNames, collectionNames); + const extraCollectionNames = _.difference(collectionNames, loadNames); + + if (extraRestoreNames.length) { + console.log(`Error: Expected collections are missing from collection list: ${extraRestoreNames}`); + } + if (extraCollectionNames.length) { + console.log(`Error: Expected collections are missing from restore JSON file: ${extraCollectionNames}`); + } + + if (!extraRestoreNames.length && !extraCollectionNames.length) { + _.each(collectionList, collection => loadCollection(collection, loadJSON, true)); + } + console.log('Finished loading database.'); + } +} + +/** + * Runs the PublicStats generator to collect stats on the database, then sets up a cron job to update the stats + * once a day. + * @memberOf startup/server + */ +function startupPublicStats() { + PublicStats.generateStats(); + SyncedCron.add({ + name: 'Run the PublicStats.generateStats method', + schedule(parser) { + return parser.text('every 24 hours'); + }, + job() { + PublicStats.generateStats(); + }, + }); +} + +function startupStudentParticipation() { + StudentParticipation.upsertEnrollmentData(); + SyncedCron.add({ + name: 'Run StudentParticipation.upsertEnrollmentData', + schedule(parser) { + return parser.text('every 24 hours'); + }, + job() { + StudentParticipation.upsertEnrollmentData(); + }, + }); +} + +/** + * Check the integrity of the newly loaded collections; print out problems if any occur. + * @memberOf startup/server + */ +function startupCheckIntegrity() { + console.log('Checking DB integrity.'); + const integrity = checkIntegrity(); + if (integrity.count > 0) { + console.log(checkIntegrity().message); + } +} + +function generateAdminCredential() { + if (Meteor.settings.public.admin.development || Meteor.isTest || Meteor.isAppTest) { + return 'foo'; + } + // adapted from: https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript + let credential = ''; + const maxPasswordLength = 30; + const minPasswordLength = 6; + const passwordLength = Math.floor(Math.random() * (maxPasswordLength - (minPasswordLength + 1))) + minPasswordLength; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < passwordLength; i++) { // eslint-disable-line no-plusplus + credential += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return credential; +} + +function defineAdminUser() { + const adminUsername = Meteor.settings && Meteor.settings.public.admin && Meteor.settings.public.admin.username; + if (!adminUsername) { + console.log('\n\nNO ADMIN USERNAME SPECIFIED IN SETTINGS FILE! SHUTDOWN AND FIX!!\n\n'); + return; + } + if (!Meteor.users.findOne({ username: adminUsername })) { + const credential = generateAdminCredential(); + const userID = Accounts.createUser({ username: adminUsername, email: adminUsername, password: credential }); + Roles.addUsersToRoles(userID, ROLE.ADMIN); + console.log(`${adminUsername}/${credential}`); + } +} + +function defineTestAdminUser() { + if (Meteor.isTest || Meteor.isAppTest) { + const admin = 'radgrad@hawaii.edu'; + const userID = Accounts.createUser({ username: admin, email: admin, password: 'foo' }); + Roles.addUsersToRoles(userID, ROLE.ADMIN); + } +} + +/** + * Fixes issues with user interactions, particularly older documents that are not consistent with the + * new schema. + * @memberOf startup/server + */ +function fixUserInteractions() { + if (Meteor.settings.public.fixUserInteractions) { + console.log('Fixing UserInteraction collection.'); + _.each(UserInteractions.find().fetch(), function (interaction) { + /* if (interaction.userID) { + const username = Meteor.users.findOne({ _id: interaction.userID }).username; + console.log('Fixing interaction for user: ', username); + UserInteractions.update(interaction._id, { $set: { username } }); + } */ + if (!Array.isArray(interaction.typeData)) { + const oldTypeData = interaction.typeData.split(','); + const typeData = []; + const { type } = interaction; + if (type === 'interestIDs' && oldTypeData[0] !== 'n/a') { + _.each(oldTypeData, function (entry) { + typeData.push(Interests.findSlugByID(entry)); + }); + } else if (type === 'careerGoalIDs' && oldTypeData[0] !== 'n/a') { + _.each(oldTypeData, function (entry) { + typeData.push(CareerGoals.findSlugByID(entry)); + }); + } else if (type === 'academicPlanID' && oldTypeData[0] !== 'n/a') { + _.each(oldTypeData, function (entry) { + typeData.push(AcademicPlans.findSlugByID(entry)); + }); + } else { + _.each(oldTypeData, function (entry) { + typeData.push(entry); + }); + } + console.log('Fixing interaction for: ', interaction.username); + UserInteractions.update(interaction._id, { $set: { typeData } }); + } else if (interaction.typeData[0] === 'ERROR: No such UserInteraction type found!') { + const typeData = ['Leveled up!']; + UserInteractions.update(interaction._id, { $set: { typeData } }); + } + }); + } +} + +function favoriteInterests(profile) { + const student = profile.username; + _.forEach(profile.interestIDs, (id) => { + const doc = Interests.findDoc(id); + const interest = Slugs.getNameFromID(doc.slugID); + FavoriteInterests.define({ student, interest }); + }); +} + +function favoriteCareerGoals(profile) { + const student = profile.username; + _.forEach(profile.careerGoalIDs, (id) => { + const doc = CareerGoals.findDoc(id); + const careerGoal = Slugs.getNameFromID(doc.slugID); + FavoriteCareerGoals.define({ student, careerGoal }); + }); +} +function ensureFavorites() { + let profiles = AdvisorProfiles.findNonRetired(); + _.forEach(profiles, (profile) => { + favoriteCareerGoals(profile); + favoriteInterests(profile); + }); + profiles = FacultyProfiles.findNonRetired(); + _.forEach(profiles, (profile) => { + favoriteCareerGoals(profile); + favoriteInterests(profile); + }); + profiles = MentorProfiles.findNonRetired(); + _.forEach(profiles, (profile) => { + favoriteCareerGoals(profile); + favoriteInterests(profile); + }); + profiles = StudentProfiles.findNonRetired({ alumni: false }); + _.forEach(profiles, (profile) => { + favoriteCareerGoals(profile); + favoriteInterests(profile); + }); +} + +// Add a startup callback that distinguishes between test and dev/prod mode and does the right thing. +Meteor.startup(() => { + if (Meteor.isTest || Meteor.isAppTest) { + console.log('Test mode. Database initialization disabled, current database cleared, rate limiting disabled.'); + Accounts.removeDefaultRateLimit(); + removeAllEntities(); + defineTestAdminUser(); + } else { + defineAdminUser(); + loadDatabase(); + startupCheckIntegrity(); + startupPublicStats(); + startupStudentParticipation(); + fixUserInteractions(); + ensureFavorites(); + SyncedCron.start(); + } +}); diff --git a/pool/shard010/JavaScript/0067100_braintreeApi.js b/pool/shard010/JavaScript/0067100_braintreeApi.js new file mode 100644 index 0000000000000000000000000000000000000000..43ef5e8ab35c307b9ade7c94a77aa4c6de4f7080 --- /dev/null +++ b/pool/shard010/JavaScript/0067100_braintreeApi.js @@ -0,0 +1,221 @@ +/* eslint camelcase: 0 */ +import Braintree from "braintree"; +import accounting from "accounting-js"; +import Future from "fibers/future"; +import { Meteor } from "meteor/meteor"; +import { Packages } from "/lib/collections"; +import { Reaction, Logger } from "/server/api"; + + +export const BraintreeApi = {}; +BraintreeApi.apiCall = {}; + + +function getPaymentObj() { + return { + amount: "", + options: { submitForSettlement: true } + }; +} + +function parseCardData(data) { + return { + cardholderName: data.name, + number: data.number, + expirationMonth: data.expirationMonth, + expirationYear: data.expirationYear, + cvv: data.cvv + }; +} + + +function getSettings(settings, ref, valueName) { + if (settings !== null) { + return settings[valueName]; + } else if (ref !== null) { + return ref[valueName]; + } + return undefined; +} + +function getAccountOptions() { + let environment; + const settings = Packages.findOne({ + name: "reaction-braintree", + shopId: Reaction.getShopId(), + enabled: true + }).settings; + if (typeof settings !== "undefined" && settings !== null ? settings.mode : undefined === true) { + environment = "production"; + } else { + environment = "sandbox"; + } + + const ref = Meteor.settings.braintree; + const options = { + environment: environment, + merchantId: getSettings(settings, ref, "merchant_id"), + publicKey: getSettings(settings, ref, "public_key"), + privateKey: getSettings(settings, ref, "private_key") + }; + if (!options.merchantId) { + throw new Meteor.Error("invalid-credentials", "Invalid Braintree Credentials"); + } + return options; +} + +function getGateway() { + const accountOptions = getAccountOptions(); + if (accountOptions.environment === "production") { + accountOptions.environment = Braintree.Environment.Production; + } else { + accountOptions.environment = Braintree.Environment.Sandbox; + } + const gateway = Braintree.connect(accountOptions); + return gateway; +} + +function getRefundDetails(refundId) { + check(refundId, String); + const gateway = getGateway(); + const braintreeFind = Meteor.wrapAsync(gateway.transaction.find, gateway.transaction); + const findResults = braintreeFind(refundId); + return findResults; +} + + +BraintreeApi.apiCall.paymentSubmit = function (paymentSubmitDetails) { + const gateway = getGateway(); + const paymentObj = getPaymentObj(); + if (paymentSubmitDetails.transactionType === "authorize") { + paymentObj.options.submitForSettlement = false; + } + paymentObj.creditCard = parseCardData(paymentSubmitDetails.cardData); + paymentObj.amount = paymentSubmitDetails.paymentData.total; + const fut = new Future(); + gateway.transaction.sale(paymentObj, Meteor.bindEnvironment(function (error, result) { + if (error) { + fut.return({ + saved: false, + error: error + }); + } else if (!result.success) { + fut.return({ + saved: false, + response: result + }); + } else { + fut.return({ + saved: true, + response: result + }); + } + }, function (error) { + Reaction.Events.warn(error); + })); + + return fut.wait(); +}; + + +BraintreeApi.apiCall.captureCharge = function (paymentCaptureDetails) { + const transactionId = paymentCaptureDetails.transactionId; + const amount = accounting.toFixed(paymentCaptureDetails.amount, 2); + const gateway = getGateway(); + const fut = new Future(); + + if (amount === accounting.toFixed(0, 2)) { + gateway.transaction.void(transactionId, function (error, result) { + if (error) { + fut.return({ + saved: false, + error: error + }); + } else { + fut.return({ + saved: true, + response: result + }); + } + }, function (e) { + Logger.warn(e); + }); + return fut.wait(); + } + gateway.transaction.submitForSettlement(transactionId, amount, Meteor.bindEnvironment(function (error, result) { + if (error) { + fut.return({ + saved: false, + error: error + }); + } else { + fut.return({ + saved: true, + response: result + }); + } + }, function (e) { + Logger.warn(e); + })); + + return fut.wait(); +}; + + +BraintreeApi.apiCall.createRefund = function (refundDetails) { + const transactionId = refundDetails.transactionId; + const amount = refundDetails.amount; + const gateway = getGateway(); + const fut = new Future(); + gateway.transaction.refund(transactionId, amount, Meteor.bindEnvironment(function (error, result) { + if (error) { + fut.return({ + saved: false, + error: error + }); + } else if (!result.success) { + if (result.errors.errorCollections.transaction.validationErrors.base[0].code === "91506") { + fut.return({ + saved: false, + error: "Braintree does not allow refunds until transactions are settled. This can take up to 24 hours. Please try again later." + }); + } else { + fut.return({ + saved: false, + error: result.message + }); + } + } else { + fut.return({ + saved: true, + response: result + }); + } + }, function (e) { + Logger.fatal(e); + })); + return fut.wait(); +}; + + +BraintreeApi.apiCall.listRefunds = function (refundListDetails) { + const transactionId = refundListDetails.transactionId; + const gateway = getGateway(); + const braintreeFind = Meteor.wrapAsync(gateway.transaction.find, gateway.transaction); + const findResults = braintreeFind(transactionId); + const result = []; + if (findResults.refundIds.length > 0) { + for (const refund of findResults.refundIds) { + const refundDetails = getRefundDetails(refund); + result.push({ + type: "refund", + amount: parseFloat(refundDetails.amount), + created: moment(refundDetails.createdAt).unix() * 1000, + currency: refundDetails.currencyIsoCode, + raw: refundDetails + }); + } + } + + return result; +}; diff --git a/pool/shard010/JavaScript/0067103_index.js b/pool/shard010/JavaScript/0067103_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3a57dd6aeee5c5770327da868059cdc82eea5548 --- /dev/null +++ b/pool/shard010/JavaScript/0067103_index.js @@ -0,0 +1,31 @@ +var Mocha = require('mocha'), + fs = require('fs'); + +var runAcceptanceTests = function(callback){ + console.log("Running acceptance tests..."); + var acceptance = new Mocha({timeout: 60000, reporter: 'list' }); + + fs.readdirSync('./test/acceptance/') + .filter(function(file){ return file.substr(-3) === '.js';}) + .forEach(function(file){ acceptance.addFile('./test/acceptance/' + file); }); + + acceptance.run(callback); +}; + +var runUnitTests = function(callback){ + console.log("Running unit tests..."); + var unit = new Mocha({ reporter: 'list'}); + + fs.readdirSync('./test/unit/') + .filter(function(file){ return file.substr(-3) === '.js';}) + .forEach(function(file){ unit.addFile('./test/unit/' + file); }); + + unit.run(callback); +}; + +runUnitTests(function(failures){ + if(failures) + process.exit(failures); + else + runAcceptanceTests(process.exit); +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067110_buttons.js b/pool/shard010/JavaScript/0067110_buttons.js new file mode 100644 index 0000000000000000000000000000000000000000..c43cb84eb8b71ceaa82409a63f3120fa6c0eea9b --- /dev/null +++ b/pool/shard010/JavaScript/0067110_buttons.js @@ -0,0 +1,242 @@ +/*! + * OS.js - JavaScript Cloud/Web Desktop Platform + * + * Copyright (c) 2011-2016, Anders Evenrud + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Anders Evenrud + * @licence Simplified BSD License + */ +(function(CoreWM, Panel, PanelItem, Utils, API, GUI, VFS) { + 'use strict'; + + ///////////////////////////////////////////////////////////////////////////// + // ITEM + ///////////////////////////////////////////////////////////////////////////// + + /** + * PanelItem: Buttons + */ + function PanelItemButtons(settings) { + PanelItem.apply(this, ['PanelItemButtons', 'Buttons', settings, { + buttons: [ + { + title: API._('LBL_SETTINGS'), + icon: 'categories/applications-system.png', + launch: 'ApplicationSettings' + } + ] + }]); + } + + PanelItemButtons.prototype = Object.create(PanelItem.prototype); + PanelItemButtons.constructor = PanelItem; + + PanelItemButtons.prototype.init = function() { + var self = this; + var root = PanelItem.prototype.init.apply(this, arguments); + + this.renderButtons(); + + var ghost; + var lastTarget; + var removeTimeout; + var lastPadding = null; + + function clearGhost() { + removeTimeout = clearTimeout(removeTimeout); + ghost = Utils.$remove(ghost); + lastTarget = null; + if ( lastPadding !== null ) { + self._$container.style.paddingRight = lastPadding; + } + } + + function createGhost(target) { + if ( !target || !target.parentNode ) { + return; + } + if ( target.tagName !== 'LI' && target.tagName !== 'UL' ) { + return; + } + + if ( lastPadding === null ) { + lastPadding = self._$container.style.paddingRight; + } + + if ( target !== lastTarget ) { + clearGhost(); + + ghost = document.createElement('li'); + ghost.className = 'Ghost'; + + if ( target.tagName === 'LI' ) { + try { + target.parentNode.insertBefore(ghost, target); + } catch ( e ) {} + } else { + target.appendChild(ghost); + } + } + lastTarget = target; + + self._$container.style.paddingRight = '16px'; + } + + GUI.Helpers.createDroppable(this._$container, { + onOver: function(ev, el, args) { + if ( ev.target && !Utils.$hasClass(ev.target, 'Ghost') ) { + createGhost(ev.target); + } + }, + + onLeave : function() { + clearTimeout(removeTimeout); + removeTimeout = setTimeout(function() { + clearGhost(); + }, 1000); + + // clearGhost(); + }, + + onDrop : function() { + clearGhost(); + }, + + onItemDropped: function(ev, el, item, args) { + if ( item && item.data && item.data.mime === 'osjs/application' ) { + var appName = item.data.path.split('applications:///')[1]; + self.createButton(appName); + } + clearGhost(); + }, + + onFilesDropped: function(ev, el, files, args) { + clearGhost(); + } + }); + + return root; + }; + + PanelItemButtons.prototype.clearButtons = function() { + Utils.$empty(this._$container); + }; + + PanelItemButtons.prototype.renderButtons = function() { + var self = this; + var systemButtons = { + applications: function(ev) { + OSjs.Applications.CoreWM.showMenu(ev); + }, + settings: function(ev) { + var wm = OSjs.Core.getWindowManager(); + if ( wm ) { + wm.showSettings(); + } + }, + exit: function(ev) { + OSjs.API.signOut(); + } + }; + + this.clearButtons(); + + (this._settings.get('buttons') || []).forEach(function(btn, idx) { + var menu = [{ + title: 'Remove button', + onClick: function() { + self.removeButton(idx); + } + }]; + var callback = function() { + API.launch(btn.launch); + }; + + if ( btn.system ) { + menu = null; //systemMenu; + callback = function(ev) { + ev.stopPropagation(); + systemButtons[btn.system](ev); + }; + } + + self.addButton(btn.title, btn.icon, menu, callback); + }); + }; + + PanelItemButtons.prototype.removeButton = function(index) { + var buttons = this._settings.get('buttons'); + buttons.splice(index, 1); + this.renderButtons(); + + this._settings.save(); + }; + + PanelItemButtons.prototype.createButton = function(appName) { + var pkg = OSjs.Core.getPackageManager().getPackage(appName); + var buttons = this._settings.get('buttons'); + buttons.push({ + title: appName, + icon: pkg.icon, + launch: appName + }); + + this.renderButtons(); + + this._settings.save(); + }; + + PanelItemButtons.prototype.addButton = function(title, icon, menu, callback) { + var sel = document.createElement('li'); + sel.title = title; + sel.innerHTML = ''; + sel.setAttribute('role', 'button'); + sel.setAttribute('aria-label', title); + + Utils.$bind(sel, 'mousedown', function(ev) { + ev.preventDefault(); + ev.stopPropagation(); + }); + Utils.$bind(sel, 'click', callback, true); + Utils.$bind(sel, 'contextmenu', function(ev) { + ev.preventDefault(); + ev.stopPropagation(); + if ( menu ) { + API.createMenu(menu, ev); + } + }); + + this._$container.appendChild(sel); + }; + + ///////////////////////////////////////////////////////////////////////////// + // EXPORTS + ///////////////////////////////////////////////////////////////////////////// + + OSjs.Applications = OSjs.Applications || {}; + OSjs.Applications.CoreWM = OSjs.Applications.CoreWM || {}; + OSjs.Applications.CoreWM.PanelItems = OSjs.Applications.CoreWM.PanelItems || {}; + OSjs.Applications.CoreWM.PanelItems.Buttons = PanelItemButtons; + +})(OSjs.Applications.CoreWM.Class, OSjs.Applications.CoreWM.Panel, OSjs.Applications.CoreWM.PanelItem, OSjs.Utils, OSjs.API, OSjs.GUI, OSjs.VFS); diff --git a/pool/shard010/JavaScript/0067111_AuthController.js b/pool/shard010/JavaScript/0067111_AuthController.js new file mode 100644 index 0000000000000000000000000000000000000000..745ac74adffbb93a6837c411167e2ea80456a975 --- /dev/null +++ b/pool/shard010/JavaScript/0067111_AuthController.js @@ -0,0 +1,70 @@ +import web from "express-decorators" +import jwt from "jsonwebtoken" + +import Promise from "bluebird"; +import crypto from "crypto"; + +import _ from "lodash" + +import { jwtSecret, jwtExpire } from "../service" + + +@web.controller("/api/auth") +export default class AuthController { + + @web.post("/") + async list(request, response) { + const database = request.app.get("sql-db"); + const accounts = database.table("accounts"); + + request.check("email").notEmpty(); + request.check("password").notEmpty(); + + let errors = request.validationErrors(true); + if (!_.isEmpty(errors || undefined)) { + response.status(400); + return response.send({ errors }); + } + + let email = request.sanitize("email").trim(); + let password = request.sanitize("password").trim(); + + + const columns = ["id", "email", "password"]; + + let records = await accounts + .select(columns) + .where({ email }) + .limit(1); + + if (records.length === 0) { + response.status(401); + return response.send({}); + } + + let account = records[0]; + + const hashParams = account.password.split("$"); + const salt = hashParams[1]; + const dbPasswordHash = hashParams[2]; + + const pcrypto = Promise.promisifyAll(crypto); + const key = await pcrypto.pbkdf2Async(password, salt, 1000, 20, 'sha1'); + const passwordHash = key.toString('hex'); + + if (passwordHash !== dbPasswordHash) { + response.status(401); + return response.send({}); + } + + const payload = { + id: account.id, + } + + const token = jwt.sign(payload, jwtSecret, { + expiresIn: jwtExpire + }); + + response.send({ token }); + } +} diff --git a/pool/shard010/JavaScript/0067112_logger.js b/pool/shard010/JavaScript/0067112_logger.js new file mode 100644 index 0000000000000000000000000000000000000000..3de0694aa4b2fcb54b09b14ab212d21567d18c88 --- /dev/null +++ b/pool/shard010/JavaScript/0067112_logger.js @@ -0,0 +1,38 @@ + + +var ProxyLogger = exports.ProxyLogger = function ProxyLogger(proxyManager) { + + var self = this; + + this.logData = new Object(); + + proxyManager.on('connect', function(proxyServer) { + var ldata = self.logData[proxyServer.srcPort]; + if (ldata == null || ldata == undefined) { + ldata = new Object(); + ldata.log = new Array(); + ldata.startTime = new Date(); + self.logData[proxyServer.srcPort] = ldata; + }; + + ldata.log.push('Connected'); + }); + + proxyManager.on('PROXYCLOSED', function (srcPort) { + var ldata = self.logData[srcPort]; + debugger; + if (ldata != null && ldata != undefined) { + ldata.log.push('Disconnected'); + } + }); + + proxyManager.on('SHOWLOG', function(args, callback) { + try { + callback(JSON.stringify(self.logData)); + } catch (err) { + proxyManager.emit('error', err); + } + }); + + +}; diff --git a/pool/shard010/JavaScript/0067113_DataUtil.js b/pool/shard010/JavaScript/0067113_DataUtil.js new file mode 100644 index 0000000000000000000000000000000000000000..3d2cb1c9f20de6ad3187b5b31d96e9188469d273 --- /dev/null +++ b/pool/shard010/JavaScript/0067113_DataUtil.js @@ -0,0 +1,58 @@ +/* + * 数据转换/数据验证 + */ +let DataUtil = { + //json转string + jsonToString(v) { + return JSON.stringify(v) + }, + //string转json + stringToJson(v) { + return eval('(' + v + ')') + }, + //截取字符串 + sortString(s, len) { + var len = len - (s + '').length; + for (var i = 0; i < len; i++) { s = '0' + s; } + return s + }, + //手机验证 + isMobile(text) { + return /^[1][34578][0-9]{9}$/i.test(text); + }, + //是否为数字 + isNumber(num){ + return isNaN(num); + }, + //四舍五入保留num位小数 + keepDecimal(val,num = 0){ + let result = Number(val).toFixed(num); + if(result == 'NaN'){ + result = ''; + } + return result; + }, + //格式化年月日 format为格式 eg:yyyy-MM-dd + formatTime(dateTime,format = "yyyy-MM-dd"){ + if(!dateTime) return dateTime; + let args = { + "M+": dateTime.getMonth() + 1, + "d+": dateTime.getDate(), + "h+": dateTime.getHours(), + "m+": dateTime.getMinutes(), + "s+": dateTime.getSeconds(), + "q+": Math.floor((dateTime.getMonth() + 3) / 3), //quarter + "S": dateTime.getMilliseconds() + }; + if (/(y+)/.test(format)) + format = format.replace(RegExp.$1, (dateTime.getFullYear() + "").substr(4 - RegExp.$1.length)); + for (var i in args) { + let n = args[i]; + if (new RegExp("(" + i + ")").test(format)) + format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length)); + } + return format; + } +} + +export default DataUtil diff --git a/pool/shard010/JavaScript/0067115_helpers.js b/pool/shard010/JavaScript/0067115_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..4286e7037a231761132b5a3a0222b35dd1c4611e --- /dev/null +++ b/pool/shard010/JavaScript/0067115_helpers.js @@ -0,0 +1,26 @@ +/*jslint node: true */ +var validate; + +validate = function (options, rules, cb) { + 'use strict'; + var key, value, name, expect, err, res = {}; + for (key in options) { + if (rules.hasOwnProperty(key)) { + value = options[key]; + name = rules[key].name; + expect = rules[key].expect; + if (typeof (value) === expect) { + res[name] = value; + } else { + err = new Error("The " + key + " option is incorrectly set, testrail expects a " + expect); + break; + } + } else { + err = new Error("Unknown variable used in options: " + key); + break; + } + } + cb(err, res); +}; + +exports.validate = validate; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067116_ParenthesisNode.test.js b/pool/shard010/JavaScript/0067116_ParenthesisNode.test.js new file mode 100644 index 0000000000000000000000000000000000000000..acd0c79a9c47fbc8d22d316a74dad008bcf495a6 --- /dev/null +++ b/pool/shard010/JavaScript/0067116_ParenthesisNode.test.js @@ -0,0 +1,186 @@ +// test SymbolNode +var assert = require('assert'); +var approx = require('../../../tools/approx'); +var math = require('../../../index'); +var Node = math.expression.node.Node; +var ConstantNode = math.expression.node.ConstantNode; +var OperatorNode = math.expression.node.OperatorNode; +var ParenthesisNode = math.expression.node.ParenthesisNode; + +describe('ParenthesisNode', function() { + + it ('should create a ParenthesisNode', function () { + var a = new ConstantNode(1); + + var n = new ParenthesisNode(a); + assert(n instanceof ParenthesisNode); + assert(n instanceof Node); + assert.equal(n.type, 'ParenthesisNode'); + }); + + it ('should throw an error when calling without new operator', function () { + var a = new ConstantNode(1); + assert.throws(function () {ParenthesisNode(a)}, SyntaxError); + }); + + it ('should throw an error when calling with wrong arguments', function () { + assert.throws(function () {new ParenthesisNode()}, TypeError); + assert.throws(function () {new ParenthesisNode(2)}, TypeError); + }); + + it ('should compile a ParenthesisNode', function () { + var a = new ConstantNode(1); + var n = new ParenthesisNode(a); + + assert.equal(n.compile().eval.toString(), a.compile().eval.toString()); + }); + + it ('should filter a ParenthesisNode', function () { + var a = new ConstantNode(1); + var n = new ParenthesisNode(a); + + assert.deepEqual(n.filter(function (node) {return node instanceof ParenthesisNode;}), [n]); + assert.deepEqual(n.filter(function (node) {return node.content instanceof ConstantNode;}), [n]); + assert.deepEqual(n.filter(function (node) { + return (typeof node.content !== 'undefined') && (node.content.value == '1'); + }), [n]); + assert.deepEqual(n.filter(function (node) { + return (typeof node.content !== 'undefined') && (node.content.type == 'ConstantNode'); + }), [n]); + assert.deepEqual(n.filter(function (node) {return node instanceof ConstantNode;}), [a]); + }); + + it ('should run forEach on a ParenthesisNode', function () { + var count = 0; + var a = new ConstantNode(1); + + var n = new ParenthesisNode(a); + n.forEach(function (node, path, _parent) { + assert.equal(node.type, 'ConstantNode'); + assert.equal(path, 'content'); + assert.deepEqual(_parent, n); + count++; + }); + + assert.equal(count, 1); + }); + + it ('should map a ParenthesisNode', function () { + var a = new ConstantNode(1); + var b = new ParenthesisNode(a); + + var count = 0; + + var c = b.map(function (node, path, _parent) { + count++; + assert.equal(node.type, 'ConstantNode'); + assert.equal(node.value, 1); + return new ConstantNode(2); + }); + + assert.equal(count, 1); + assert.equal(c.content.value, 2); + }); + + it ('should transform a ParenthesisNode', function () { + var c1 = new ConstantNode(1); + var c2 = new ConstantNode(2); + + var a = new ParenthesisNode(c1); + var b = new ParenthesisNode(c2); + + var c = a.transform(function (node) { + return node instanceof ParenthesisNode && node.content.value == 1 ? b : node; + }); + assert.deepEqual(c, b); + + // no match should leave the constant as is + var d = a.transform(function (node) { + return node instanceof ParenthesisNode && node.name == 2 ? b : node; + }); + assert.deepEqual(d, a); + }); + + it ('should clone a ParenthesisNode', function () { + var a = new ConstantNode(1); + var n = new ParenthesisNode(a); + var clone = n.clone(); + + assert(clone instanceof ParenthesisNode); + assert.deepEqual(n, clone); + assert.notStrictEqual(n, clone); + assert.equal(n.content, clone.content); + }); + + it ('should get the content of a ParenthesisNode', function () { + var c = new math.expression.node.ConstantNode(1); + var p1 = new math.expression.node.ParenthesisNode(c); + var p2 = new math.expression.node.ParenthesisNode(p1); + + assert.equal(p1.content, c); + assert.equal(p1.getContent(), c); + assert.deepEqual(p1.getContent(), c); + assert.equal(p2.getContent(), c); + assert.deepEqual(p2.getContent(), c); + }); + + it ('should stringify a ParenthesisNode', function () { + var a = new ConstantNode(1); + var n = new ParenthesisNode(a); + + assert.equal(n.toString(), '(1)'); + assert.equal(n.toString({}), '(1)'); + }); + + it ('should stringify a ParenthesisNode when not in keep mode', function () { + var c = new math.expression.node.ConstantNode(1); + + var p = new math.expression.node.ParenthesisNode(c); + + assert.equal(p.toString({parenthesis: 'all'}), '1'); + assert.equal(p.toString({parenthesis: 'auto'}), '1'); + }); + + it ('should stringify a ParenthesisNode with custom toString', function () { + var customFunction = function (node, options) { + if (node.type === 'ParenthesisNode') { + return '[' + node.content.toString(options) + ']'; + } + }; + + var c = new math.expression.node.ConstantNode(1); + var n = new math.expression.node.ParenthesisNode(c); + + assert.equal(n.toString({handler: customFunction}), '[1]'); + }); + + it ('should LaTeX a ParenthesisNode', function () { + var a = new ConstantNode(1); + var n = new ParenthesisNode(a); + + assert.equal(n.toTex(), '\\left(1\\right)'); + assert.equal(n.toTex({}), '\\left(1\\right)'); + }); + + it ('should LaTeX a ParenthesisNode when not in keep mode', function () { + var c = new math.expression.node.ConstantNode(1); + + var p = new math.expression.node.ParenthesisNode(c); + + assert.equal(p.toTex({parenthesis: 'all'}), '1'); + assert.equal(p.toTex({parenthesis: 'auto'}), '1'); + }); + + it ('should LaTeX a ParenthesisNode with custom toTex', function () { + var customFunction = function (node, options) { + if (node.type === 'ParenthesisNode') { + return '\\left[' + node.content.toTex(options) + '\\right]'; + } + }; + + var c = new math.expression.node.ConstantNode(1); + var n = new math.expression.node.ParenthesisNode(c); + + assert.equal(n.toTex({handler: customFunction}), '\\left[1\\right]'); + }); +}); diff --git a/pool/shard010/JavaScript/0067117_AutoExplorationVO.js b/pool/shard010/JavaScript/0067117_AutoExplorationVO.js new file mode 100644 index 0000000000000000000000000000000000000000..932e707e1720721ffd0873b7c4ee3847a5e0a2a7 --- /dev/null +++ b/pool/shard010/JavaScript/0067117_AutoExplorationVO.js @@ -0,0 +1,46 @@ +define(['ash', 'game/components/common/PositionComponent'], function (Ash, PositionComponent) { + + var AutoExplorationVO = Ash.Class.extend({ + + // settings + limitToCurrentLevel: false, + + // current goal + exploreGoal: null, + exploreSector: null, + explorePath: null, + exploreResource: null, + isExploreGoalComplete: false, + + constructor: function () { + this.limitToCurrentLevel = false; + this.exploreGoal = null; + this.exploreSector = null; + this.explorePath = null; + this.exploreResource = null; + this.isExploreGoalComplete = false; + }, + + isExploreObjectiveSet: function () { + return this.exploreGoal; + }, + + setExploreObjective: function (goal, sector, path, resource) { + this.exploreGoal = goal; + this.exploreSector = sector; + this.explorePath = path; + this.exploreResource = resource; + this.isExploreGoalComplete = false; + }, + + getExploreObjectiveDescription: function () { + return this.exploreGoal + " " + + (this.exploreSector ? this.exploreSector.get(PositionComponent).getPosition() : "-") + " " + + (this.explorePath ? this.explorePath.length : "[-]") + " " + + this.exploreResource; + }, + + }); + + return AutoExplorationVO; +}); diff --git a/pool/shard010/JavaScript/0067119_manage-dashboard-layouts.controller.js b/pool/shard010/JavaScript/0067119_manage-dashboard-layouts.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..1ccf48f74a859fb616cf6a4a0ef41efc33b5e0c3 --- /dev/null +++ b/pool/shard010/JavaScript/0067119_manage-dashboard-layouts.controller.js @@ -0,0 +1,83 @@ +/* + * Copyright © 2016-2017 The Thingsboard 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. + */ + +/* eslint-disable import/no-unresolved, import/default */ + +import dashboardSettingsTemplate from '../dashboard-settings.tpl.html'; + +/* eslint-enable import/no-unresolved, import/default */ + +/*@ngInject*/ +export default function ManageDashboardLayoutsController($scope, $mdDialog, $document, dashboardUtils, layouts) { + + var vm = this; + + vm.openLayoutSettings = openLayoutSettings; + vm.cancel = cancel; + vm.save = save; + + vm.layouts = layouts; + vm.displayLayouts = { + main: angular.isDefined(vm.layouts.main), + right: angular.isDefined(vm.layouts.right) + } + + for (var l in vm.displayLayouts) { + if (!vm.layouts[l]) { + vm.layouts[l] = dashboardUtils.createDefaultLayoutData(); + } + } + + function openLayoutSettings($event, layoutId) { + var gridSettings = angular.copy(vm.layouts[layoutId].gridSettings); + $mdDialog.show({ + controller: 'DashboardSettingsController', + controllerAs: 'vm', + templateUrl: dashboardSettingsTemplate, + locals: { + settings: null, + gridSettings: gridSettings + }, + parent: angular.element($document[0].body), + skipHide: true, + fullscreen: true, + targetEvent: $event + }).then(function (data) { + var gridSettings = data.gridSettings; + if (gridSettings) { + dashboardUtils.updateLayoutSettings(vm.layouts[layoutId], gridSettings); + } + $scope.theForm.$setDirty(); + }, function () { + }); + } + + function cancel() { + $mdDialog.cancel(); + } + + function save() { + $scope.theForm.$setPristine(); + for (var l in vm.displayLayouts) { + if (!vm.displayLayouts[l]) { + if (vm.layouts[l]) { + delete vm.layouts[l]; + } + } + } + $mdDialog.hide(vm.layouts); + } +} diff --git a/pool/shard010/JavaScript/0067121_link.js b/pool/shard010/JavaScript/0067121_link.js new file mode 100644 index 0000000000000000000000000000000000000000..409a350f9917b54475a8e487f798a25a0e6b8e30 --- /dev/null +++ b/pool/shard010/JavaScript/0067121_link.js @@ -0,0 +1,124 @@ +const _ = require('lodash'); +const installedSomeModules = require('./libs/some-module-discoverer'); + +const _links = []; +const _active_links = []; + +var plat; + + +function _findExistingLink(type, param){ + return _links.find((element) => { + if(type == element.type && _.isEqual(param, element.param)){ + return true; + } + return false; + }); +} + +/* + * Create a new link, and once connected, + * construct a new thing with given link. + */ +function _constructThingByCreateLink(type, param){ + try { + var link = new Link(type, param); + var thing = plat.newInitByLinkThing(link); + link._thing = thing; + } + catch(e){ + if(e == 'Duplicated Link'){ + let link = _findExistingLink(type, param); + let thing = link._thing; + return thing; + } + else + throw(e); + } + return link.connect().then(() => { + return link._thing.init(); + }); +} + +/* + * Callback Function called by link modules + * for auto discover things to create link + * and construct things + */ +function callback (type){ + return function (param){ + return _constructThingByCreateLink(type, param); + }; +} + +/* + * Init all modules + */ +function init(base){ + plat = base; + return new Promise((resolve) => { + installedSomeModules.getByType('link') + .reduce((promiseChain, module) => { + return promiseChain.then( + () => module.module.init(callback(module.meta.type)) + ).catch((e) => { + console.error('Failure during driver init: ' + e); + }); + }, Promise.resolve()) + .then(() => { + resolve(); + }).catch((e) => { + console.log(e); + }); + }); +} + + +/* + * Connect to some hardware without auto-detect + */ +class Link { + constructor(type, param, thing){ + this.type = type; + this.param = param; + this.thing = thing; + if(_findExistingLink(type, param)) + throw 'Duplicated Link'; + _links.push(this); + } + + + connect () { + var that = this; + if(this.type in installedSomeModules.getByType('link')){ + return installedSomeModules.getByType('link')[this.type].connect(that).then(() => { + _active_links.push(that); + }); + } + else{ + throw new Error('Unsupported link type:' + this.type); + } + } + + + receive (data){ + if(this.thing) + this.thing.emit(data); + else + console.error('Detached Link.'); + } + + send (_data){ + console.error('Link send not initialized'); + } +} + +function connect (type, param) { + return _constructThingByCreateLink(type, param); +} + +module.exports = { + 'Link': Link, + 'init': init, + 'connect': connect, +}; diff --git a/pool/shard010/JavaScript/0067123_L7RuleList.js b/pool/shard010/JavaScript/0067123_L7RuleList.js new file mode 100644 index 0000000000000000000000000000000000000000..2cd575e9b9f11e228d447da4e51854be6068d785 --- /dev/null +++ b/pool/shard010/JavaScript/0067123_L7RuleList.js @@ -0,0 +1,197 @@ +import { useState, useEffect, useMemo } from "react"; +import { DefeatableLink } from "lib/components/defeatable_link"; +import useCommons from "../../../lib/hooks/useCommons"; +import HelpPopover from "../shared/HelpPopover"; +import useL7Rule from "../../../lib/hooks/useL7Rule"; +import { useGlobalState } from "../StateProvider"; +import { Table } from "react-bootstrap"; +import ErrorPage from "../ErrorPage"; +import L7RuleListItem from "./L7RuleListItem"; +import { Tooltip, OverlayTrigger } from "react-bootstrap"; +import { SearchField } from "lib/components/search_field"; +import { policy } from "policy"; +import { scope } from "ajax_helper"; +import SmartLink from "../shared/SmartLink"; +import Log from "../shared/logger"; +import { regexString } from "lib/tools/regex_string"; + +const L7RulesList = ({ props, loadbalancerID }) => { + const { searchParamsToString } = useCommons(); + const { persistL7Rules, setSearchTerm } = useL7Rule(); + const listenerID = useGlobalState().listeners.selected; + const l7PolicyID = useGlobalState().l7policies.selected; + const state = useGlobalState().l7rules; + + useEffect(() => { + initialLoad(); + }, [l7PolicyID]); + + const initialLoad = () => { + if (l7PolicyID) { + Log.debug("FETCH L7 RULES"); + persistL7Rules(loadbalancerID, listenerID, l7PolicyID, null) + .then((data) => {}) + .catch((error) => {}); + } + }; + + const canCreate = useMemo( + () => + policy.isAllowed("lbaas2:l7rule_create", { + target: { scoped_domain_name: scope.domain }, + }), + [scope.domain] + ); + + const search = (term) => { + setSearchTerm(term); + }; + + const error = state.error; + const searchTerm = state.searchTerm; + const selected = state.selected; + const isLoading = state.isLoading; + const items = state.items; + + const filterItems = (searchTerm, items) => { + if (!searchTerm) return items; + // filter items + if (selected) { + return items.filter((i) => i.id == searchTerm.trim()); + } else { + const regex = new RegExp(regexString(searchTerm.trim()), "i"); + return items.filter( + (i) => `${i.id} ${i.type} ${i.value}`.search(regex) >= 0 + ); + } + }; + + const l7Rules = filterItems(searchTerm, items); + return useMemo(() => { + return ( + + {l7PolicyID && ( + + {error ? ( +
    + +
    + ) : ( +
    +
    +

    L7 Rules

    + +
    + + {!selected && ( + +
    + search(term)} + placeholder="ID, type or value" + text="Searches by ID, type or value." + /> + +
    + + New L7 Rule + +
    +
    +
    + )} + + 0 + ? "table table-hover l7rules" + : "table l7rules" + } + responsive + > + + + + + + + + + + + + + + {l7Rules && l7Rules.length > 0 ? ( + l7Rules.map((l7Rule, index) => ( + + )) + ) : ( + + + + )} + +
    IDStatusTags +
    + Type +
    + + Sorted by Type ASC + + } + > + + +
    + /Compare Type +
    +
    InvertKeyValue
    + {isLoading ? ( + + ) : ( + "No L7 Rules found." + )} +
    +
    + )} +
    + )} +
    + ); + }, [ + l7PolicyID, + JSON.stringify(l7Rules), + error, + selected, + isLoading, + searchTerm, + props, + ]); +}; + +export default L7RulesList; diff --git a/pool/shard010/JavaScript/0067127_angularGetBibleNavigation.directive.js b/pool/shard010/JavaScript/0067127_angularGetBibleNavigation.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..0b705a066bf4478eb7213e249fd89894e73a2427 --- /dev/null +++ b/pool/shard010/JavaScript/0067127_angularGetBibleNavigation.directive.js @@ -0,0 +1,70 @@ +angular.module('angularGetBible.directives').directive('getBibleNavigation', function($templateCache, GetBibleService) { + return { + scope: { + showOptions: '=?shownOptions', + selectedVersion: '=?selectedVersion', + selectedChapter: '=?selectedChapter', + selectedBook: '=?selectedBook', + selectedVerses: '=?selectedVerses', + selection: '=?selection' + }, + link: function(scope, element, attrs) { + scope.selection = {}; + var optArr = ['version', 'book', 'chapter', 'verse']; + scope.selectedVersion = scope.selectedVersion || 'kjv'; + scope.selectedBook = scope.selectedBook || ''; + scope.selectedChapter = scope.selectedChapter || ''; + scope.selectedVerses = scope.selectedVerses || []; + scope.shownOptions = scope.shownOptions || optArr; + + scope.$watch('shownOptions', function(opts) { + scope.options = optArr.filter(function(o) { + return opts.indexOf(o) !== -1; + }); + }); + GetBibleService.getBooks(scope.selectedVersion).success(function(json) { + scope.books = json; + }).error(function(err) { + console.log(err); + }); + scope.selectBook = function(book) { + scope.selectedBook = book; + if (book) { + GetBibleService.getChapters(book['book_nr'], scope.selectedVersion).success(function(json) { + scope.chapters = json; + }).error(function(err) { + console.log(err); + }); + } + }; + scope.selectChapter = function(chapterNr) { + scope.selectedChapter = chapterNr; + if (chapterNr) { + GetBibleService.getVerses(scope.selectedBook['book_name'], chapterNr, scope.selectedVersion) + .success(function(json) { + scope.verseNrs = Object.keys(json.chapter); + scope.verses = json; + }).error(function(err) { + console.log(err); + }); + } + }; + scope.selectVerses = function(verseNr) { + if (scope.selectedVerses.indexOf(verseNr) === -1) { + scope.selectedVerses.push(verseNr); + } else { + scope.selectedVerses = scope.selectedVerses.filter(function(v) { + return (v !== verseNr); + }); + } + scope.selection.verses = scope.selectedVerses.map(function(vNr) { + return scope.verses.chapter[vNr]; + }); + scope.selection['verse_nr'] = scope.selectedVerses; + scope.selection['book_name'] = scope.verses['book_name']; + scope.selection['chapter_nr'] = scope.verses['chapter_nr']; + }; + }, + template: $templateCache.get('angular-get-bible/templates/Navigation.template.html') + }; +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067128_notification.js b/pool/shard010/JavaScript/0067128_notification.js new file mode 100644 index 0000000000000000000000000000000000000000..7199abcd856c0da15a6b2052fe96ae76f6c7ab75 --- /dev/null +++ b/pool/shard010/JavaScript/0067128_notification.js @@ -0,0 +1,37 @@ +(function (HandsomeTrello) { + 'use strict'; + + HandsomeTrello.notification = { + data: { + timeout: 0 + }, + + open: function (_message, type, timeout) { + if (typeof type === 'undefined') { + type = 'warning'; + } + + if (typeof timeout === 'undefined') { + timeout = HandsomeTrello.settings.notification.defaultTimeout; + } + + var _notification = document.getElementById('notification'), + _notificationContent = document.createElement('div'); + + _notificationContent.setAttribute( + 'class', + 'handsome-trello__inheritance-notification js-inheritance-notification app-alert-item mod-' + type + ); + _notificationContent.appendChild(_message); + + _notification.appendChild(_notificationContent); + + _notification.style.display = 'block'; + + this.data.timeout = setTimeout(function () { + HandsomeTrello.helpers.removeElement(_notificationContent); + }, timeout); + } + }; + +})(HandsomeTrello); diff --git a/pool/shard010/JavaScript/0067129_entity.plugin.test.js b/pool/shard010/JavaScript/0067129_entity.plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..986d3a99f297c73b5e19923848ddfb0543cbd6ac --- /dev/null +++ b/pool/shard010/JavaScript/0067129_entity.plugin.test.js @@ -0,0 +1,248 @@ +/* Copyright (c) 2010-2012 Richard Rodger */ + +var common = require('../lib/common'); +var seneca = require('../lib/seneca'); + +var eyes = common.eyes +var assert = common.assert +var gex = common.gex + +var logger = require('./logassert') + + +module.exports = { + +/* + mem: function() { + try { + seneca( + {plugins:['mem-store']}, + function(err,si){ + assert.isNull(err) + + var entity = si.make('ten','base',null) + var ent = entity.make$('ent',{p1:'v1'}) + ent.p2 = 100; + + ;ent.save$( function(err,ent) { + assert.isNull(err) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p2=100}').on(''+ent), ''+ent ) + + + ;ent.load$( {id:ent.id}, function(err,entR) { + assert.isNull(err) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p2=100}').on(''+entR) ) + var ent1 = entR + + + ent = entity.make$('ent',{p1:'v1'}) + ent.p3 = true + ;ent.save$( function(err,ent) { + assert.isNull(err) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p3=true}').on(''+ent) ) + + + ;ent.load$( {id:ent.id}, function(err,entR) { + assert.isNull(err) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p3=true}').on(''+entR) ) + var ent2 = entR + + + ;ent.list$( {p1:'v1'}, function(err,list) { + assert.isNull(err) + assert.equal(2,list.length) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p2=100}').on(''+list[0]) ) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p3=true}').on(''+list[1]) ) + + ;ent.list$( {p2:100}, function(err,list) { + assert.isNull(err) + assert.equal(1,list.length) + assert.ok( gex('ten/base/ent:{id=*;p1=v1;p2=100}').on(''+list[0]) ) + + + ;ent.remove$( {p1:'v1',all$:true}, function(err) { + assert.isNull(err) + + ;ent.list$( {p1:'v1'}, function(err,list) { + assert.isNull(err) + assert.equal(0,list.length) + + console.log('DONE') + + }) // list + }) //remove + + }) // list + }) // list + + }) // load + }) // save + + }) // load + }) // save + } + ) + } + catch(e) { + eyes.inspect(e) + throw e + } + }, +*/ + + multi: function() { + seneca( + {plugins:[ + + {name:'mem-store',opts:{ + tag:'foo', + map:{ + '//foo':'*' + } + }}, + + {name:'mem-store',opts:{ + tag:'bar', + map:{ + '//bar':'*' + } + }}, + + {name:'mem-store',opts:{ + tag:'foo', + map:{ + '//faa':'*' + } + }}, + + ]}, + function(err,si){ + assert.isNull(err) + + + // mem/foo + var foo = si.make('foo') + foo.a = 1 + + // mem/bar + var bar = si.make('bar') + bar.b = 2 + + // also mem/foo instance + var faa = si.make('faa') + faa.c = 3 + + // handled by default mem instance + var zen = si.make('zen') + zen.d = 4 + + + ;foo.save$( function(err,foo) { + assert.isNull(err) + assert.ok( gex('//foo:{a=1;id=*}').on(''+foo), ''+foo ) + + ;foo.load$( {id:foo.id}, function(err,fooR) { + assert.isNull(err) + assert.ok( gex('//foo:{a=1;id=*}').on(''+fooR) ) + + + + ;bar.save$( function(err,bar) { + assert.isNull(err) + assert.ok( gex('//bar:{b=2;id=*}').on(''+bar), ''+bar ) + + ;bar.load$( {id:bar.id}, function(err,barR) { + assert.isNull(err) + assert.ok( gex('//bar:{b=2;id=*}').on(''+barR) ) + + + + ;faa.save$( function(err,faa) { + assert.isNull(err) + assert.ok( gex('//faa:{c=3;id=*}').on(''+faa), ''+faa ) + + ;faa.load$( {id:faa.id}, function(err,faaR) { + assert.isNull(err) + assert.ok( gex('//faa:{c=3;id=*}').on(''+faaR) ) + + + ;zen.save$( function(err,zen) { + assert.isNull(err) + assert.ok( gex('//zen:{d=4;id=*}').on(''+zen), ''+zen ) + + ;zen.load$( {id:zen.id}, function(err,zenR) { + assert.isNull(err) + assert.ok( gex('//zen:{d=4;id=*}').on(''+zenR) ) + + + }) }) }) }) }) }) }) }) + } + ) + }, + +/* + noop: function() { + try { + seneca( + {plugins:['noop-store']}, + function(err,si){ + assert.isNull(err) + + var entity = si.make('zone','base','name') + var ent = entity.make$('ent',{p1:'v1'}) + ent.p2 = 100; + + ;ent.save$( function(err,ent) { + assert.isNull(err) + + + ;ent.load$( {id:ent.id}, function(err,entR) { + assert.isNull(err) + + ent = entity.make$('ent',{p1:'v1'}) + ent.p3 = true + + ;ent.save$( function(err,ent) { + assert.isNull(err) + + ;ent.load$( {id:ent.id}, function(err,entR) { + assert.isNull(err) + + ;ent.list$( {p1:'v1'}, function(err,list) { + assert.isNull(err) + + ;ent.list$( {p2:100}, function(err,list) { + assert.isNull(err) + + ;ent.remove$( {p1:'v1'}, function(err) { + assert.isNull(err) + + ;ent.list$( {p1:'v1'}, function(err,list) { + assert.isNull(err) + + console.log('DONE') + + }) // list + }) //remove + + }) // list + }) // list + + }) // load + }) // save + + }) // load + }) // save + } + ) + } + catch(e) { + eyes.inspect(e) + throw e + } + }, +*/ + + + +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067130_css.js b/pool/shard010/JavaScript/0067130_css.js new file mode 100644 index 0000000000000000000000000000000000000000..fa97bbf6bdd7e975bed39e2c457282dc8551192e --- /dev/null +++ b/pool/shard010/JavaScript/0067130_css.js @@ -0,0 +1,19 @@ +var gulp = require('gulp'); +var gulpif = require('gulp-if'); +var less = require('gulp-less'); +var filter = require('gulp-filter'); +var pleeease = require('gulp-pleeease'); +var concat = require('gulp-concat'); +var plumber = require('gulp-plumber'); +var notify = require('gulp-notify'); +var config = require('../config').css; + +gulp.task('css', function(){ + gulp.src(config.entry) + .pipe(plumber({errorHandler: notify.onError('<%= error.message %>')})) + .pipe(filter([ '*', '!**/_*.less' ])) + .pipe(less({paths: config.paths})) + .pipe(pleeease(config.pleeease)) + .pipe(gulp.dest(config.dest)); +}); + diff --git a/pool/shard010/JavaScript/0067131_crudlab.js b/pool/shard010/JavaScript/0067131_crudlab.js new file mode 100644 index 0000000000000000000000000000000000000000..c828edef6c86d545f992b9caf935cd8c2b4327c9 --- /dev/null +++ b/pool/shard010/JavaScript/0067131_crudlab.js @@ -0,0 +1,63 @@ +/** + * @pakacge system.js.views + */ +$( function() { + Pendientes(0,'Reportes'); + + var dates = $( "#fecha_desde, #fecha_hasta" ).datepicker({ + showOn: "button", + buttonImage: sImg + "calendar.gif", + buttonImageOnly: true, + onSelect: function( selectedDate ) { + var option = this.id == "fecha_desde" ? "minDate" : "maxDate", + instance = $( this ).data( "datepicker" ), + date = $.datepicker.parseDate( + instance.settings.dateFormat || + $.datepicker._defaults.dateFormat, + selectedDate, instance.settings ); + dates.not( this ).datepicker( "option", option, date ); + } + }); + + $.datepicker.regional['es'] = { + closeText : 'Cerrar', + prevText : '<Ant', + nextText : 'Sig>', + currentText : 'Hoy', + monthNames : ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], + monthNamesShort : ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'], + dayNames : ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], + dayNamesShort : ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'], + dayNamesMin : ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'], + weekHeader : 'Sm', + dateFormat : 'dd/mm/yy', + firstDay : 1, + isRTL : false, + showMonthAfterYear : false, + yearSuffix : '' + }; + $.datepicker.setDefaults($.datepicker.regional['es']); + $( "#fecha_desde" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); + $( "#fecha_hasta" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); + +}); + + +function Pendientes(estado, div) { + + strUrl_Proceso = sUrlP + "lstLaboratorio"; + $.ajax({ + url : strUrl_Proceso, + dataType : "json", + success : function(oEsq) { + Grid = new TGrid(oEsq, div, ''); + Grid.SetXls(false); + Grid.SetNumeracion(true); + Grid.SetName(div); + Grid.SetDetalle(); + Grid.Generar(); + } + }); +} + + diff --git a/pool/shard010/JavaScript/0067134_activity.js b/pool/shard010/JavaScript/0067134_activity.js new file mode 100644 index 0000000000000000000000000000000000000000..6f2736284bf96548e8dbdd2f3c2c74331d2d7949 --- /dev/null +++ b/pool/shard010/JavaScript/0067134_activity.js @@ -0,0 +1,282 @@ + + /***************************************************************************/ + /* Augeo.io is a web application that uses Natural Language Processing to */ + /* classify a user's internet activity into different 'skills'. */ + /* Copyright (C) 2016 Brian Redd */ + /* */ + /* 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 . */ + /***************************************************************************/ + + /***************************************************************************/ + /* Description: Logic for ACTIVITY database collection */ + /***************************************************************************/ + + // Required libraries + var Mongoose = require('mongoose'); + + // Required local modules + var AugeoDB = require('../../database'); + var Logger = require('../../../module/logger'); + + // Constants + var COLLECTION = 'activity-collection'; + + // Global variables + var log = new Logger(); + + // Schema declaration + var ACTIVITY = Mongoose.Schema({ + classification: String, + classificationGlyphicon: String, + data: {type: Mongoose.Schema.Types.ObjectId, 'refPath':'kind'}, + experience: Number, + kind: String, + timestamp: Date, + user: {type: Mongoose.Schema.Types.ObjectId, ref:'AUGEO_USER'} + }); + + /***************************************************************************/ + /* Static Methods: Accessible at Model level */ + /***************************************************************************/ + + ACTIVITY.statics.addActivities = function(activities, logData, callback) { + + // Add activities if they don't exist and update when they do exist + upsertActivities(this, activities, logData, callback); + }; + + ACTIVITY.statics.addActivity = function(activity, logData, callback) { + + // Add activity if it doesn't exist and update when it does exist + upsertActivity(this, activity, logData, callback); + }; + + ACTIVITY.statics.getActivities = function(dataId, logData, callback) { + this.find({data:dataId}, function(error, activities) { + if(error) { + log.functionError(COLLECTION, 'getActivities', logData.parentProcess, logData.username, 'Failed to get activities with dataId: ' + dataId + + '. Error: ' + error); + callback(); + } else { + log.functionCall(COLLECTION, 'getActivities', logData.parentProcess, logData.username, {"dataId":dataId}); + callback(activities); + } + }); + }; + + ACTIVITY.statics.getActivity = function(userId, dataId, logData, callback) { + this.findOne({$and:[{user:userId}, {data:dataId}]}, function(error, activity) { + if(error) { + log.functionError(COLLECTION, 'getActivity', logData.parentProcess, logData.username, 'Failed to get activity for user with ID: ' + userId + + '. Error: ' + error); + callback(); + } else { + log.functionCall(COLLECTION, 'getActivity', logData.parentProcess, logData.username, {'userId': userId, 'dataId': dataId}); + callback(activity); + } + }); + }; + + ACTIVITY.statics.getSkillActivity = function(userId, skill, limit, maxTimestamp, logData, callback) { + var model = this; + + if(!maxTimestamp) { + maxTimestamp = new Date(8640000000000000); + } + + var query = { + $and:[ + { + user: userId, + timestamp: {$lt: maxTimestamp} + } + ] + }; + + if(skill && skill != 'Augeo') { + query.classification = skill; + } + + // First grab the activity IDs + model.find(query) + .select('_id') + .sort({'timestamp': -1}) + .limit(limit) + //.populate('data') // Can't use populate & sort due to Mongoose issue: https://github.com/Automattic/mongoose/issues/2202 + .exec(function(error, activityIds) { + if(error) { + log.functionError(COLLECTION, 'getSkillActivity', logData.parentProcess, logData.username, + 'Failed to retrieve ' + userId + ' activity IDs for skill:' + skill + '. Error: ' + error); + } else { + log.functionCall(COLLECTION, 'getSkillActivity', logData.parentProcess, logData.username, + {'userId':userId, 'skill':skill,'maxTimestamp':maxTimestamp}, 'Retrieved activity IDs'); + + // Second, get all populated objects + // Can't use MongoDB's $in function because of issue with mongoose populate + var activities = new Array(); + if(activityIds && activityIds.length > 0) { + + // Asynchronous method calls in loop - Using Recursion + (function myClojure(i) { + model.findOne({'_id':activityIds[i]}) + .populate('data') + .exec(function(error, activity) { + + if(error) { + log.functionError(COLLECTION, 'getSkillActivity', logData.parentProcess, logData.username, + 'Failed to retrieve activity with id: ' + activityIds[i]); + callback(); + } else { + + activities.push(activity); + i++; + if (i < activityIds.length) { + myClojure(i); + } else { + log.functionCall(COLLECTION, 'getSkillActivity', logData.parentProcess, logData.username, {'activityId':activityIds[i]}, + 'Retrieved populated activities'); + + // Sort activities by timestamp in descending order + var sortedActivities = activities.sort(function (a, b) { + return new Date(b.timestamp) - new Date(a.timestamp); + }); + + callback(sortedActivities); + } + } + }); + })(0); // Pass i as 0 and myArray to myClojure + } else { + callback(activities); + } + } + }); + }; + + ACTIVITY.statics.getUserActivities = function(userId, logData, callback) { + this.find({user:userId}, function(error, activities) { + if(error) { + log.functionError(COLLECTION, 'getUserActivities', logData.parentProcess, logData.username, {'userId':userId}); + callback(); + } else { + log.functionCall(COLLECTION, 'getUserActivities', logData.parentProcess, logData.username, {'userId':userId}); + callback(activities); + } + }); + }; + + ACTIVITY.statics.increaseExperience = function(userId, dataId, experience, logData, callback) { + this.findOneAndUpdate({$and:[{user:userId}, {data:dataId}]}, {$inc:{experience:experience}}, {'new':true}, function(error, activity) { + if(error) { + log.functionError(COLLECTION, 'increaseExperience', logData.parentProcess, logData.username, 'Failed to increase activity with data ID:' + + dataId + ' . Error: ' + error); + } else { + log.functionCall(COLLECTION, 'increaseExperience', logData.parentProcess, logData.username, {'userId':userId, 'dataId':dataId, 'experience':experience}); + callback(activity); + } + }); + }; + + ACTIVITY.statics.removeActivities = function(userId, logData, callback) { + this.remove({user:userId}, function(error) { + if(error) { + log.functionError(COLLECTION, 'removeActivities', logData.parentProcess, logData.username, 'Failed to remove activities with userId: ' + userId + + '. Error: ' + error); + callback(); + } else { + log.functionCall(COLLECTION, 'removeActivities', logData.parentProcess, logData.username, {'userId': userId}); + callback(); + } + }); + }; + + ACTIVITY.statics.removeActivity = function(userId, dataId, logData, callback) { + this.remove({$and:[{user:userId},{data:dataId}]}, function(error) { + if(error) { + log.functionError(COLLECTION, 'removeActivity', logData.parentProcess, logData.username, 'Failed to remove activity with userId: ' + userId + + '. Error: ' + error); + callback(); + } else { + log.functionCall(COLLECTION, 'removeActivity', logData.parentProcess, logData.username, {'userId': userId, dataId:dataId}); + callback(); + } + }); + }; + + /***************************************************************************/ + /* Private Methods */ + /***************************************************************************/ + + var upsertActivity = function(activityDocument, activity, logData, callback) { + activityDocument.findOne({$and:[{user:activity.user},{data:activity.data}]}, function(error, foundActivity) { + + if(error) { + log.functionError(COLLECTION, 'upsertActivity (private)', logData.parentProcess, logData.username, + 'Failed to find activity with data ID: ' + (activity) ? activity.data : 'invalid'); + callback(); + } else { + + var duplicateExperience = 0; + if (foundActivity && typeof foundActivity.experience == 'number') { + // Grab current experience so it's not duplicated in user's experience + duplicateExperience = foundActivity.experience; + } + + activityDocument.findOneAndUpdate({$and: [{user: activity.user}, {data: activity.data}]}, activity, { upsert: true, 'new': true}, + function (error, updatedActivity) { + if (error) { + log.functionError(COLLECTION, 'upsertActivity (private)', logData.parentProcess, logData.username, + 'Failed to upsert activity with data ID: ' + (activity) ? activity.data : 'invalid' + '. Error: ' + error); + callback(); + } else { + log.functionCall(COLLECTION, 'upsertActivity (private)', logData.parentProcess, logData.username, { + 'activityDocument': (activityDocument) ? 'defined' : 'invalid', + 'activity.data': (activity) ? activity.data : 'invalid' + }); + + // Add attribute for duplicate experience + updatedActivity.duplicateExperience = duplicateExperience; + + callback(updatedActivity); + } + }); + } + }); + }; + + var upsertActivities = function(activityDocument, activities, logData, callback) { + var updatedActivities = new Array(); + + if(activities.length > 0) { + // Asynchronous method calls in loop - Using Recursion + (function myClojure(i) { + upsertActivity(activityDocument, activities[i], logData, function (updatedActivity) { + if(updatedActivity) { + updatedActivities.push(updatedActivity); + } + i++; + if (i < activities.length) { + myClojure(i); + } else { + callback(updatedActivities); + } + }); + })(0); // Pass i as 0 and myArray to myClojure + } else { + callback(); + } + }; + + // Declare Model + module.exports = AugeoDB.model('ACTIVITY', ACTIVITY); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067138_db-init.js b/pool/shard010/JavaScript/0067138_db-init.js new file mode 100644 index 0000000000000000000000000000000000000000..6180c2afc297e6dcd0cb79908ee17277e3c5b47b --- /dev/null +++ b/pool/shard010/JavaScript/0067138_db-init.js @@ -0,0 +1,259 @@ +require('dotenv-safe').load() + +process.debug = {}; + +process.debug.startTime = Date.now(); + +const chalk = require('chalk'); +const path = require('path'); +const fs = require('./fs.js'); +const db = require('./db.js'); +const _ = db._; + + +const moment = require('moment'); +const fm = require('gray-matter'); + + +const fmOpts = { + excerpt: true // use this to get post descriptions/social media meta data snippets +, excerpt_separator: '' +}; + +const IS_DEV = process.env.NODE_ENV === 'dev'; + + + +// // RESET DB STATE +// // ------------------------------------------------------------ +// db.setState({}); + + +// GET LIST OF CONTENT FILES TO GROK +// ------------------------------------------------------------ + +let configPath = path.resolve(__dirname, 'config.yaml'); +let config = fs.readYAML(configPath); +let posts = db.get('posts').value(); + + + +// GET LIST OF CONTENT FILES TO GROK +// ------------------------------------------------------------ + +const contentDir = path.resolve(__dirname, '../content'); + +const contentPath = [ + path.resolve(contentDir, '**/*.md') +]; + +let files = fs.glob({ filter: 'isFile' }, contentPath); + + + +// RUN INITIAL FILE LOOP TO COMPOSE 'POSTS' COLLECTION +// ------------------------------------------------------------ + +_.each(files, (filepath) => { + + let file = fm(fs.readFileSync(filepath, { encoding: 'utf-8' }), fmOpts); + + file = Object.assign({}, file, file.data); + + file.filepath = filepath; + + + // GET POST/PAGE META DESCRIPTION + if (file.excerpt === '') { + file.excerpt = file.content.substr(0,400); + } + + file.description = file.excerpt; + + if (!file.description && IS_DEV) { + file.description = file.content + .replace(/[\s]+/g, ' ') + .substr(0,60) + '...' + ; + + file.MISSING_DESCRIPTION = true; + } + + + // GET FILE STATS + file.stats = fs.statSync(filepath); + + + // UPDATE TIMESTAMPS TO THEIR EPOCH EQUIVALENT + file.published + ? file.published = new Date(file.published).getTime() + : null + ; + + file.updated + ? file.updated = new Date(file.stats.mtime).getTime() + : null + ; + + + // DEFINE AUTHOR + if (file.author) { + file.author = config.authors[file.author]; + file.author.slug = file.author.name.toLowerCase().replace(/\s+/g, '-'); + } + + // IF THE FILE IS SCHEDULED TO BE PUBLISHED LATER + file.published > Date.now() + ? file.private = true + : null + ; + + + // GET THE POST ROUTE + file.route = file.filepath + .substr(contentDir.length) // remove content base dir + .replace(/\.\S{2,}/, '') // remove file extension + ; + + if (file.route === '/index') { + file.route = '/'; + } + + + // GET POST TYPE FROM POST ROUTE + let posttype = file.route.substr(1).split('/') + + posttype.length > 1 + ? file.posttype = posttype[0] + : file.posttype = 'page' + ; + + + // DETERMINE WHAT THE POST TEMPLATE FILE SHOULD BE IF NOT DEFINED + if (!file.template) { + file.posttype !== 'page' + ? file.template = `pages/${file.posttype}-single` + : file.template = 'pages/default' + ; + } + + + // APPEND CANONICAL ID'S TO DB + if (file.canonical) { + db.get('series').push(file.canonical).write(); // push the tag to the collection + + let series = db.get('series').value(); + + db.set('series', _.uniq(series)).write(); + } + + + // CLEAN UP DATA MODEL + delete(file.data); + + + // ENSURE UNIQUE POSTS + if (db.get('posts').find({ route: file.route }).value()) { + db.get('posts').find({ route: file.route }).assign(file).write(); + + } else { + db.get('posts').push(file).write(); + + } + +}); + + + + +// POSTTYPE LISTINGS +// ----------------------------------------------------------------- + +let postGroups = db.get('posts') + .filter((p) => { return p.posttype !== 'page'; }) // ignore pages + .filter((p) => { return !p.items; }) // ignore listings + .sortBy('published') + .groupBy('posttype') + .value() + ; + + +// TODO: iterate over postGroups and generate listing pages + +_.each(postGroups, (postGroup) => { + + // TODO: allow for custom handlers to come in for parsing posttypes/groups like this + + let groups = _.chunk(postGroup, config.paging.postCount); + + _.each(groups, (group, index) => { + + let post = { + title: group[0].posttype + , items: group + , route: '/' + group[0].posttype + '/' + (index > 0 ? index + 1 : '') + , index: index + 1 + , template: `pages/${group[0].posttype}-list` + }; + + + if (db.get('posts').find({ route: post.route }).value()) { + db.get('posts').find({ route: post.route }).assign(post).write(); + + } else { + db.get('posts').push(post).write(); + + } + + }); + +}); + + + +// SEO ROUND +// ----------------------------------------------------------------- + +posts = db.get('posts').value(); + +_.each(posts, (post) => { + + + // DETERMINE PAGE PRIORITY FOR SITEMAP.XML GENERATION + if (!post.priority) { + post.isHomepage + ? post.priority = 1.0 + : post.priority = 0.5 + ; + + !post.items + ? post.priority = 0.7 + : null + ; + } + + // TODO: setup maths to determine change frequency + // -- requires long term analysis of file changes to determine this + // -- might need to migrate to SQLite to make this happen + // -- https://www.v9seo.com/blog/2011/12/27/sitemap-xml-why-changefreq-priority-are-important/ + + // SET OLD POSTS TO LOWER PRIORITY + let d = moment(Date.now()); + let yearsOld = d.diff(post.published, 'years', true).toFixed(2); + + if (yearsOld > 1) { + post.priority = (0.3 / yearsOld).toFixed(1); + } + + + db.get('posts') + .find({ filepath: post.filepath }) + .assign(post) + .write() + ; + +}); + + +console.log('PROCESS EXECUTION TIME:', Date.now() - process.debug.startTime + 'ms'); + diff --git a/pool/shard010/JavaScript/0067139_pipe.js b/pool/shard010/JavaScript/0067139_pipe.js new file mode 100644 index 0000000000000000000000000000000000000000..99f481816772e51131eb6f65364711b3969c8756 --- /dev/null +++ b/pool/shard010/JavaScript/0067139_pipe.js @@ -0,0 +1,44 @@ +var logger = require('../logger')('micromono:discovery:pipe') +var config = require('../config') + + +exports.prepareDiscovery = function(discoveryOptions) { + if (!discoveryOptions) + discoveryOptions = config(['default', 'discovery']) + + var options = {} + Object.keys(discoveryOptions).forEach(function(key) { + if (/^MICROMONO_DISCOVERY/.test(key)) + options[key] = discoveryOptions[key] + }) + + var discovery = require('./' + options.MICROMONO_DISCOVERY_BACKEND) + + return { + discoveryListen: discovery.listen, + discoveryAnnounce: discovery.announce, + discoveryOptions: options + } +} + +exports.listenProviders = function(services, discoveryListen, discoveryOptions, addProvider) { + var remoteServices = Object.keys(services).filter(function(serviceName) { + return true === services[serviceName].isRemote + }) + + if (0 < remoteServices.length) { + logger.info('start listening remote service providers', { + remoteServices: remoteServices + }) + discoveryListen(discoveryOptions, function(err, ann) { + if (err) { + logger.error('Service discovery error', { + error: err && err.stack || err, + provider: ann + }) + } else if (ann && -1 < remoteServices.indexOf(ann.name)) { + addProvider(services[ann.name].scheduler, ann) + } + }) + } +} diff --git a/pool/shard010/JavaScript/0067145_SettingsPage.js b/pool/shard010/JavaScript/0067145_SettingsPage.js new file mode 100644 index 0000000000000000000000000000000000000000..b849fe80ba18d9c4748204df2c92ca4473feb9b6 --- /dev/null +++ b/pool/shard010/JavaScript/0067145_SettingsPage.js @@ -0,0 +1,75 @@ +import React from 'react' + +import SettingsStore from '../stores/SettingsStore' +import SettingsAPI from '../apis/SettingsAPI' + +import { SETTINGS_SECTIONS } from '../constants/SettingsConstants' + +import SettingsHolder from './settings/SettingsHolder' +import MigrationNotice from './settings/MigrationNotice' + +import SettingsContent from './settings/SettingsContent' + +function getStateFromStores() { + return { + settings: SettingsStore.getSettings() + } +} + +function dismissMigration() { + SettingsAPI.setOption('dismissMigration', true) +} + +const SettingsPage = React.createClass({ + getInitialState() { + return getStateFromStores() + }, + + componentDidMount() { + SettingsAPI.loadSettings() + + SettingsStore.addChangeListener(this._onChange) + }, + + componentWillUnmount() { + SettingsStore.removeChangeListener(this._onChange) + }, + + _onChange() { + this.setState(getStateFromStores()) + }, + + componentDidUpdate() { + // When changing the sync option, the user + // must be remembered about migrating the + // old data if not already migrated + }, + + getSettingsValue(key) { + return this.state.settings[key] + }, + + render() { + let settings = this.state.settings + + if (Object.keys(settings).length === 0) { + // This should return a loader view + return ( + +

    Loading settings...

    +
    + ) + } + + let shouldShowMigrationNotice = settings.syncData && !settings.dismissMigration + + return ( + + { shouldShowMigrationNotice && } + + + ) + } +}) + +export default SettingsPage diff --git a/pool/shard010/JavaScript/0067146_callHierarchy.proposed.js b/pool/shard010/JavaScript/0067146_callHierarchy.proposed.js new file mode 100644 index 0000000000000000000000000000000000000000..2a9fb26a62019cef4abbd1fe10af4b39d4a7e1f5 --- /dev/null +++ b/pool/shard010/JavaScript/0067146_callHierarchy.proposed.js @@ -0,0 +1,161 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const vscode_1 = require("vscode"); +const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol"); +const client_1 = require("./client"); +function ensure(target, key) { + if (target[key] === void 0) { + target[key] = {}; + } + return target[key]; +} +var protocol2code; +(function (protocol2code) { + function asCallHierarchyItem(converter, item) { + if (item === null) { + return undefined; + } + let result = new vscode_1.CallHierarchyItem(converter.asSymbolKind(item.kind), item.name, item.detail || '', converter.asUri(item.uri), converter.asRange(item.range), converter.asRange(item.selectionRange)); + if (item.tags !== undefined) { + result.tags = converter.asSymbolTags(item.tags); + } + return result; + } + protocol2code.asCallHierarchyItem = asCallHierarchyItem; + function asCallHierarchyItems(converter, items) { + if (items === null) { + return undefined; + } + let result = items.map(item => asCallHierarchyItem(converter, item)); + return result[0]; + } + protocol2code.asCallHierarchyItems = asCallHierarchyItems; + function asCallHierarchyIncomingCall(converter, item) { + return new vscode_1.CallHierarchyIncomingCall(asCallHierarchyItem(converter, item.from), converter.asRanges(item.fromRanges)); + } + protocol2code.asCallHierarchyIncomingCall = asCallHierarchyIncomingCall; + function asCallHierarchyIncomingCalls(converter, items) { + if (items === null) { + return undefined; + } + return items.map(item => asCallHierarchyIncomingCall(converter, item)); + } + protocol2code.asCallHierarchyIncomingCalls = asCallHierarchyIncomingCalls; + function asCallHierarchyOutgoingCall(converter, item) { + return new vscode_1.CallHierarchyOutgoingCall(asCallHierarchyItem(converter, item.to), converter.asRanges(item.fromRanges)); + } + protocol2code.asCallHierarchyOutgoingCall = asCallHierarchyOutgoingCall; + function asCallHierarchyOutgoingCalls(converter, items) { + if (items === null) { + return undefined; + } + return items.map(item => asCallHierarchyOutgoingCall(converter, item)); + } + protocol2code.asCallHierarchyOutgoingCalls = asCallHierarchyOutgoingCalls; +})(protocol2code || (protocol2code = {})); +var code2protocol; +(function (code2protocol) { + function asCallHierarchyItem(converter, value) { + const result = { + name: value.name, + kind: converter.asSymbolKind(value.kind), + uri: converter.asUri(value.uri), + range: converter.asRange(value.range), + selectionRange: converter.asRange(value.selectionRange) + }; + if (value.detail !== undefined && value.detail.length > 0) { + result.detail = value.detail; + } + if (value.tags !== undefined) { + result.tags = converter.asSymbolTags(value.tags); + } + return result; + } + code2protocol.asCallHierarchyItem = asCallHierarchyItem; +})(code2protocol || (code2protocol = {})); +class CallHierarchyProvider { + constructor(client) { + this.client = client; + this.middleware = client.clientOptions.middleware; + } + prepareCallHierarchy(document, position, token) { + const client = this.client; + const middleware = this.middleware; + const prepareCallHierarchy = (document, position, token) => { + const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position); + return client.sendRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyPrepareRequest.type, params, token).then((result) => { + return protocol2code.asCallHierarchyItems(this.client.protocol2CodeConverter, result); + }, (error) => { + client.logFailedRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyPrepareRequest.type, error); + return Promise.resolve(null); + }); + }; + return middleware.prepareCallHierarchy + ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy) + : prepareCallHierarchy(document, position, token); + } + provideCallHierarchyIncomingCalls(item, token) { + const client = this.client; + const middleware = this.middleware; + const provideCallHierarchyIncomingCalls = (item, token) => { + const params = { + item: code2protocol.asCallHierarchyItem(client.code2ProtocolConverter, item) + }; + return client.sendRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyIncomingCallsRequest.type, params, token).then((result) => { + return protocol2code.asCallHierarchyIncomingCalls(client.protocol2CodeConverter, result); + }, (error) => { + client.logFailedRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyIncomingCallsRequest.type, error); + return Promise.resolve(null); + }); + }; + return middleware.provideCallHierarchyIncomingCalls + ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) + : provideCallHierarchyIncomingCalls(item, token); + } + provideCallHierarchyOutgoingCalls(item, token) { + const client = this.client; + const middleware = this.middleware; + const provideCallHierarchyOutgoingCalls = (item, token) => { + const params = { + item: code2protocol.asCallHierarchyItem(client.code2ProtocolConverter, item) + }; + return client.sendRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyOutgoingCallsRequest.type, params, token).then((result) => { + return protocol2code.asCallHierarchyOutgoingCalls(client.protocol2CodeConverter, result); + }, (error) => { + client.logFailedRequest(vscode_languageserver_protocol_1.Proposed.CallHierarchyOutgoingCallsRequest.type, error); + return Promise.resolve(null); + }); + }; + return middleware.provideCallHierarchyOutgingCalls + ? middleware.provideCallHierarchyOutgingCalls(item, token, provideCallHierarchyOutgoingCalls) + : provideCallHierarchyOutgoingCalls(item, token); + } +} +class CallHierarchyFeature extends client_1.TextDocumentFeature { + constructor(client) { + super(client, vscode_languageserver_protocol_1.Proposed.CallHierarchyPrepareRequest.type); + } + fillClientCapabilities(cap) { + const capabilites = cap; + const capability = ensure(ensure(capabilites, 'textDocument'), 'callHierarchy'); + capability.dynamicRegistration = true; + } + initialize(cap, documentSelector) { + const capabilities = cap; + const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider); + if (!id || !options) { + return; + } + this.register(this.messages, { id: id, registerOptions: options }); + } + registerLanguageProvider(options) { + const client = this._client; + const provider = new CallHierarchyProvider(client); + return [vscode_1.languages.registerCallHierarchyProvider(options.documentSelector, provider), provider]; + } +} +exports.CallHierarchyFeature = CallHierarchyFeature; diff --git a/pool/shard010/JavaScript/0067149_Menu.js b/pool/shard010/JavaScript/0067149_Menu.js new file mode 100644 index 0000000000000000000000000000000000000000..87792954214b2d5f47925eebe3c81ad6616decfa --- /dev/null +++ b/pool/shard010/JavaScript/0067149_Menu.js @@ -0,0 +1,256 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends2 = require('babel-runtime/helpers/extends'); + +var _extends3 = _interopRequireDefault(_extends2); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _createReactClass = require('create-react-class'); + +var _createReactClass2 = _interopRequireDefault(_createReactClass); + +var _MenuMixin = require('./MenuMixin'); + +var _MenuMixin2 = _interopRequireDefault(_MenuMixin); + +var _util = require('./util'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// import React from 'react'; +var Menu = (0, _createReactClass2["default"])({ + displayName: 'Menu', + + propTypes: { + openSubMenuOnMouseEnter: _propTypes2["default"].bool, + closeSubMenuOnMouseLeave: _propTypes2["default"].bool, + selectedKeys: _propTypes2["default"].arrayOf(_propTypes2["default"].string), + defaultSelectedKeys: _propTypes2["default"].arrayOf(_propTypes2["default"].string), + defaultOpenKeys: _propTypes2["default"].arrayOf(_propTypes2["default"].string), + openKeys: _propTypes2["default"].arrayOf(_propTypes2["default"].string), + mode: _propTypes2["default"].string, + onClick: _propTypes2["default"].func, + onSelect: _propTypes2["default"].func, + onDeselect: _propTypes2["default"].func, + onDestroy: _propTypes2["default"].func, + openTransitionName: _propTypes2["default"].string, + openAnimation: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].object]), + level: _propTypes2["default"].number, + eventKey: _propTypes2["default"].string, + selectable: _propTypes2["default"].bool, + children: _propTypes2["default"].any + }, + + mixins: [_MenuMixin2["default"]], + + getDefaultProps: function getDefaultProps() { + return { + openSubMenuOnMouseEnter: true, + closeSubMenuOnMouseLeave: true, + selectable: true, + onClick: _util.noop, + onSelect: _util.noop, + onOpenChange: _util.noop, + onDeselect: _util.noop, + defaultSelectedKeys: [], + defaultOpenKeys: [] + }; + }, + getInitialState: function getInitialState() { + var props = this.props; + var selectedKeys = props.defaultSelectedKeys; + var openKeys = props.defaultOpenKeys; + if ('selectedKeys' in props) { + selectedKeys = props.selectedKeys || []; + } + if ('openKeys' in props) { + openKeys = props.openKeys || []; + } + return { + selectedKeys: selectedKeys, + openKeys: openKeys + }; + }, + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + var props = {}; + if ('selectedKeys' in nextProps) { + props.selectedKeys = nextProps.selectedKeys || []; + } + if ('openKeys' in nextProps) { + props.openKeys = nextProps.openKeys || []; + } + this.setState(props); + }, + onDestroy: function onDestroy(key) { + var state = this.state; + var props = this.props; + var selectedKeys = state.selectedKeys; + var openKeys = state.openKeys; + var index = selectedKeys.indexOf(key); + if (!('selectedKeys' in props) && index !== -1) { + selectedKeys.splice(index, 1); + } + index = openKeys.indexOf(key); + if (!('openKeys' in props) && index !== -1) { + openKeys.splice(index, 1); + } + }, + onItemHover: function onItemHover(e) { + var _this = this; + + var item = e.item; + var _props = this.props, + mode = _props.mode, + closeSubMenuOnMouseLeave = _props.closeSubMenuOnMouseLeave; + var _e$openChanges = e.openChanges, + openChanges = _e$openChanges === undefined ? [] : _e$openChanges; + // special for top sub menu + + if (mode !== 'inline' && !closeSubMenuOnMouseLeave && item.isSubMenu) { + (function () { + var activeKey = _this.state.activeKey; + var activeItem = _this.getFlatInstanceArray().filter(function (c) { + return c && c.props.eventKey === activeKey; + })[0]; + if (activeItem && activeItem.props.open) { + openChanges = openChanges.concat({ + key: item.props.eventKey, + item: item, + originalEvent: e, + open: true + }); + } + })(); + } + openChanges = openChanges.concat(this.getOpenChangesOnItemHover(e)); + if (openChanges.length) { + this.onOpenChange(openChanges); + } + }, + onSelect: function onSelect(selectInfo) { + var props = this.props; + if (props.selectable) { + // root menu + var selectedKeys = this.state.selectedKeys; + var selectedKey = selectInfo.key; + if (props.multiple) { + selectedKeys = selectedKeys.concat([selectedKey]); + } else { + selectedKeys = [selectedKey]; + } + if (!('selectedKeys' in props)) { + this.setState({ + selectedKeys: selectedKeys + }); + } + props.onSelect((0, _extends3["default"])({}, selectInfo, { + selectedKeys: selectedKeys + })); + } + }, + onClick: function onClick(e) { + this.props.onClick(e); + }, + onOpenChange: function onOpenChange(e_) { + var props = this.props; + var openKeys = this.state.openKeys.concat(); + var changed = false; + var processSingle = function processSingle(e) { + var oneChanged = false; + if (e.open) { + oneChanged = openKeys.indexOf(e.key) === -1; + if (oneChanged) { + openKeys.push(e.key); + } + } else { + var index = openKeys.indexOf(e.key); + oneChanged = index !== -1; + if (oneChanged) { + openKeys.splice(index, 1); + } + } + changed = changed || oneChanged; + }; + if (Array.isArray(e_)) { + // batch change call + e_.forEach(processSingle); + } else { + processSingle(e_); + } + if (changed) { + if (!('openKeys' in this.props)) { + this.setState({ openKeys: openKeys }); + } + props.onOpenChange(openKeys); + } + }, + onDeselect: function onDeselect(selectInfo) { + var props = this.props; + if (props.selectable) { + var selectedKeys = this.state.selectedKeys.concat(); + var selectedKey = selectInfo.key; + var index = selectedKeys.indexOf(selectedKey); + if (index !== -1) { + selectedKeys.splice(index, 1); + } + if (!('selectedKeys' in props)) { + this.setState({ + selectedKeys: selectedKeys + }); + } + props.onDeselect((0, _extends3["default"])({}, selectInfo, { + selectedKeys: selectedKeys + })); + } + }, + getOpenTransitionName: function getOpenTransitionName() { + var props = this.props; + var transitionName = props.openTransitionName; + var animationName = props.openAnimation; + if (!transitionName && typeof animationName === 'string') { + transitionName = props.prefixCls + '-open-' + animationName; + } + return transitionName; + }, + isInlineMode: function isInlineMode() { + return this.props.mode === 'inline'; + }, + lastOpenSubMenu: function lastOpenSubMenu() { + var lastOpen = []; + var openKeys = this.state.openKeys; + + if (openKeys.length) { + lastOpen = this.getFlatInstanceArray().filter(function (c) { + return c && openKeys.indexOf(c.props.eventKey) !== -1; + }); + } + return lastOpen[0]; + }, + renderMenuItem: function renderMenuItem(c, i, subIndex) { + if (!c) { + return null; + } + var state = this.state; + var extraProps = { + openKeys: state.openKeys, + selectedKeys: state.selectedKeys, + openSubMenuOnMouseEnter: this.props.openSubMenuOnMouseEnter + }; + return this.renderCommonMenuItem(c, i, subIndex, extraProps); + }, + render: function render() { + var props = (0, _extends3["default"])({}, this.props); + props.className += ' ' + props.prefixCls + '-root'; + return this.renderRoot(props); + } +}); + +exports["default"] = Menu; +module.exports = exports['default']; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067151_CallbackListSpec.js b/pool/shard010/JavaScript/0067151_CallbackListSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..37f6ff637a03ce62f97188425540a6bdf6224f76 --- /dev/null +++ b/pool/shard010/JavaScript/0067151_CallbackListSpec.js @@ -0,0 +1,177 @@ +describe("CallbackList",function(){ + + var subject; + + var match = function(){}; + + var bare_callback_factory = function(){ + return {completed: function(){}, is_match: match}; + }; + + var callback_factory = function(){ + return new Frabjous.Callback(bare_callback_factory()); + }; + + beforeEach(function(){ + subject = new Frabjous.CallbackList(); + }); + + describe("add", function(){ + + it("should allow adding of one bare callback", function(){ + var bare_callback = bare_callback_factory(); + + var result = subject.add(bare_callback); + + expect(result).toIncludeCallback(bare_callback); + }); + + it("should allow adding of an array of bare callbacks", function(){ + var bare_callbacks = [bare_callback_factory(),bare_callback_factory()]; + + var result = subject.add(bare_callbacks); + + expect(result).toIncludeCallback(bare_callbacks); + }); + + it("should allow adding of one callback", function(){ + var callback = callback_factory(); + + var result = subject.add(callback); + + expect(result).toIncludeCallback(callback); + }); + + it("should allow adding of an array of callbacks", function(){ + var callback1 = callback_factory(); + var callback2 = callback_factory(); + var callbacks = [callback1,callback2]; + + var result = subject.add(callbacks); + + expect(result).toIncludeCallback(callbacks); + }); + + }); + + describe("clear", function(){ + it("should clear all callbacks", function(){ + var callback1 = bare_callback_factory(); + var callback2 = bare_callback_factory(); + subject.add(callback1); + subject.add(callback2); + + expect(subject.size()).toEqual(2); + + subject.clear(); + + expect(subject.size()).toEqual(0); + }); + }); + + describe("handle", function(){ + + it("should not run any callbacks if none match", function(){ + var ran = false; + subject.add({completed: function(){ ran = true; }, is_match: function(){return false;}}); + + subject.handle(); + + expect(ran).toBeFalse(); + }); + + it("should run callbacks", function(){ + var ran1 = false; + var ran2 = false; + subject.add({completed: function(){ ran1 = true; }, is_match: function(){return true;}}); + subject.add({completed: function(){ ran2 = true; }, is_match: function(){return true;}}); + + subject.handle(); + + expect(ran1).toBeTrue(); + expect(ran2).toBeTrue(); + }); + + it("should pass correct arguments to callback", function(){ + var callback = callback_factory(); + var first, second, third, fourth = false; + + // Override the callbacks handle function with our mock + callback.handle = function(success,extra1,extra2,extra3){ + first = success; + second = extra1; + third = extra2; + fourth = extra3; + }; + + subject.add(callback); + + subject.handle(true,"one","two","three"); + + expect( first ).toBeTrue(); + expect( second ).toEqual("one"); + expect( third ).toEqual("two"); + expect( fourth ).toEqual("three"); + }); + + it("should remove callback if must_keep returns false", function(){ + var alive = null; + + var callback = {completed: function(){alive = true;}, must_keep: false, is_match: function(){return true;}}; + + // Register callback + subject.add(callback); + + // Size increase, alive not affected + expect(subject.size()).toEqual(1); + expect(alive).toBeNull(); + + // Callback run + subject.handle(); + + // Size decrease and alive set + expect(subject.size()).toEqual(0); + expect(alive).toBeTrue(); + + // Reset alive + alive = false; + + // Callback run + subject.handle(); + + // alive not touched + expect(alive).toBeFalse(); + }); + + it("should not remove callback if must_keep returns true", function(){ + var alive = null; + + var callback = {completed: function(){alive = true;}, must_keep: true, is_match: function(){return true;}}; + + // Register callback + subject.add(callback); + + // Size increase, alive not affected + expect(subject.size()).toEqual(1); + expect(alive).toBeNull(); + + // Callback run + subject.handle(); + + // Size remains constant and alive set + expect(subject.size()).toEqual(1); + expect(alive).toBeTrue(); + + // Reset alive + alive = false; + + // Callback run + subject.handle(); + + // alive not touched + expect(alive).toBeTrue(); + }); + + }); + +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067152_quick-clear.js b/pool/shard010/JavaScript/0067152_quick-clear.js new file mode 100644 index 0000000000000000000000000000000000000000..5f1974e31197d891414298b7c7e10c681edf1e38 --- /dev/null +++ b/pool/shard010/JavaScript/0067152_quick-clear.js @@ -0,0 +1,48 @@ +(function( $ ) { + $.fn.quickClear = function() { + return this.filter("[data-clear-btn='true']").each(function() { + var $input = $(this); + $input.addClass("clearable"); + $input.wrap("
    "); + var $wrapper = $input.parent(); + $wrapper.append(""); + var $btn = $wrapper.find(".btn-clear"); + // clear input when press x button + $wrapper.delegate(".btn-clear", "click", function(){ + $input.val('').focus(); + $btn.addClass("hide"); + return false; + }); + $input.focus(function() { + $wrapper.addClass("input-focus").removeClass("input-hover"); + }); + $input.hover(function() { + $wrapper.toggleClass("input-hover"); + toggleClear(); + }); + $input.blur(function() { + $wrapper.removeClass("input-focus").removeClass("input-hover"); + }); + $input.keyup(function(e) { + // clear input if escape key pressed + var code = e.charCode || e.keyCode; + if (code === 27) { + $input.val('').focus(); + } + }); + function toggleClear() { + setTimeout( function() { + if ($input.val()) { + $btn.removeClass("hide"); + } else { + $btn.addClass("hide"); + } + }, 0 ); + } + $input.bind( "paste cut keyup input focus change blur", toggleClear ); + }); + }; +}( jQuery )); +(function() { + $("input").quickClear(); +})(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067154_Icon.js b/pool/shard010/JavaScript/0067154_Icon.js new file mode 100644 index 0000000000000000000000000000000000000000..425618a3a85456b1ce0075577edd3a87555fe9cf --- /dev/null +++ b/pool/shard010/JavaScript/0067154_Icon.js @@ -0,0 +1,36 @@ +/** + * @file + * @copyright 2020 Aleksej Komarov + * @license MIT + */ + +import { classes, pureComponentHooks } from 'common/react'; +import { Box } from './Box'; + +const FA_OUTLINE_REGEX = /-o$/; + +export const Icon = props => { + const { name, size, spin, className, style = {}, rotation, ...rest } = props; + if (size) { + style['font-size'] = (size * 100) + '%'; + } + if (typeof rotation === 'number') { + style['transform'] = `rotate(${rotation}deg)`; + } + const faRegular = FA_OUTLINE_REGEX.test(name); + const faName = name.replace(FA_OUTLINE_REGEX, ''); + return ( + + ); +}; + +Icon.defaultHooks = pureComponentHooks; diff --git a/pool/shard010/JavaScript/0067155_slideshow.js b/pool/shard010/JavaScript/0067155_slideshow.js new file mode 100644 index 0000000000000000000000000000000000000000..696f74fe240c4a92bb96900f3eeb1588ff9cd977 --- /dev/null +++ b/pool/shard010/JavaScript/0067155_slideshow.js @@ -0,0 +1,17 @@ +$(document).ready(function() { + var myIndex = 0; + carousel(); + + function carousel() { + var i; + var x = document.getElementsByClassName("mySlides"); + for (i = 0; i < x.length; i++) { + x[i].style.display = "none"; + } + myIndex++; + if (myIndex > x.length) {myIndex = 1} + x[myIndex-1].style.display = "block"; + setTimeout(carousel, 6000); + } +}); + diff --git a/pool/shard010/JavaScript/0067157_local.js b/pool/shard010/JavaScript/0067157_local.js new file mode 100644 index 0000000000000000000000000000000000000000..3d787a40fb9b9cdd2995625c515c60502be31824 --- /dev/null +++ b/pool/shard010/JavaScript/0067157_local.js @@ -0,0 +1,21 @@ +(function () { + "use strict"; + + WinJS.UI.Pages.define("/pages/advanced/local/local.html", { + // This function is called whenever a user navigates to this page. + // It populates the page with data and initializes the media player control. + ready: function (element, options) { + var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0); + element.querySelector(".titlearea .pagetitle").textContent = item.title; + if (WinJS.Utilities.isPhone) { + document.getElementById("header").style.display = "none"; + } + }, + + // This function is called whenever a user navigates away from this page. + // It resets the page and disposes of the media player control. + unload: function () { + } + }); + +})(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067164_index.js b/pool/shard010/JavaScript/0067164_index.js new file mode 100644 index 0000000000000000000000000000000000000000..003b0a094c7352b4850a5350b741137c003cefbf --- /dev/null +++ b/pool/shard010/JavaScript/0067164_index.js @@ -0,0 +1,55 @@ +// --- Directions +// Write a function that accepts a positive number N. +// The function should console log a pyramid shape +// with N levels using the # character. Make sure the +// pyramid has spaces on both the left *and* right hand sides +// --- Examples +// pyramid(1) +// '#' +// pyramid(2) +// ' # ' +// '###' +// pyramid(3) +// ' # ' +// ' ### ' +// '#####' + +function pyramid(n, row = 0, level = '') { + if (row === n) { + return; + } + + if (level.length === 2 * n - 1) { + console.log(level); + return pyramid(n, row + 1); + } + + const midpoint = Math.floor((2 * n - 1) / 2); + let add; + if (midpoint - row <= level.length && midpoint + row >= level.length) { + add = '#'; + } else { + add = ' '; + } + pyramid(n, row, level + add); +} + +module.exports = pyramid; +// +// function pyramid(n) { +// const midpoint = Math.floor((2 * n - 1) / 2); +// +// for (let row = 0; row < n; row++) { +// let level = ''; +// +// for (let column = 0; column < 2 * n - 1; column++) { +// if (midpoint - row <= column && midpoint + row >= column) { +// level += '#'; +// } else { +// level += ' '; +// } +// } +// +// console.log(level); +// } +// } diff --git a/pool/shard010/JavaScript/0067166_district_gps.js b/pool/shard010/JavaScript/0067166_district_gps.js new file mode 100644 index 0000000000000000000000000000000000000000..6cee7c1b777616c2f5b034fcd0eec596fb618b58 --- /dev/null +++ b/pool/shard010/JavaScript/0067166_district_gps.js @@ -0,0 +1,144 @@ +var map = require("../../../iRobots/baidu.js") +var loader = require('../../../iRobots/loader.js'); +var helper = require('../../../iRobots/helper.js'); +var db = require('../../../iRobots/db.js')("10.82.0.1", "house"); + +export var loadDistrictPoint = function(table, geoURL) { + db.close(); + db.open(table).then(function() { + return db.collection.find({ + point: null + }, { + area: 1, + district: 1 + }).toArray() + }).then(function(arr) { + return helper.iteratorArr(arr, function(it) { + var search = it.area; + if (search == "全部") { + search = it.district; + } + return loadSpace(geoURL, search).then(function(data) { + if (data.lat) { + it.point = { + lat: parseFloat(data.lat), + lng: parseFloat(data.lng) + } + } + return it; + }).then(function(data) { + return db.collection.update({ + _id: db.ObjectId(data._id) + }, { + $set: { + point: data.point + } + }).then(function() { + console.log(search, "point success") + return data; + }).catch(function(e) { + db.close(); + console.log(e); + return + }) + }) + }) + }).then(function() { + db.close(); + console.log("success"); + }) + +} + +export var loadDistrictBDPoint = function(table, city) { + db.close(); + db.open(table).then(function() { + return db.collection.find({ + point: null + }, { + area: 1, + district: 1 + }).toArray() + }).then(function(arr) { + return helper.iteratorArr(arr, function(it) { + var search = it.area; + if (search == "全部") { + search = it.district; + } + return map.loadPlaceAPI(search, city).then(function(data) { + //console.log(data) + it.point = data.results[0].location; + return it; + }).then(function(data) { + return db.collection.update({ + _id: db.ObjectId(data._id) + }, { + $set: { + point: data.point + } + }).then(function() { + console.log(search, "point success") + return data; + }) + }) + + }) + }).then(function(arr) { + //console.log(arr); + db.close(); + console.log("Address Point finish"); + }).catch(function(e) { + db.close(); + console.log(e); + }) +} + + +// district: '园区', +// point: { +// lng: 120.71463459445, +// lat: 31.328803977968 +// } +// loadSpace("姑苏区") + +export var loadSpace = function(geoURL, name) { + + return loader.postJSON(geoURL, { + kw: name + }).then(function(json) { + console.log(json); + return (json) + }).catch(function(e) { + console.log(e, "error"); + }) +} + + +function _old() { + //通过地图方式获取 + var url = "http://suzhou.anjuke.com/map/sale/"; + loader.getDOM(url).then(function($) { + var json = []; + $("#area_link_list a").each((i, a) => { + var a = $(a); + var district = a.text(); + if (district != "不限") { + + var point = { + lng: parseFloat(a.attr("lng")), + lat: parseFloat(a.attr("lat")) + } + if (a.attr("lng") == "") { + point = null; + } + json.push({ + district, + point + }); + } + }); + return json; + }).then(function(arr) { + console.log(arr); + }) +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067167_authentication.client.controller.js b/pool/shard010/JavaScript/0067167_authentication.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..fed9225718ba3faad6ef6d21c319ed8fe084054b --- /dev/null +++ b/pool/shard010/JavaScript/0067167_authentication.client.controller.js @@ -0,0 +1,37 @@ +'use strict'; + +angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', + function($scope, $http, $location, Authentication) { + $scope.authentication = Authentication; + + // Get an eventual error defined in the URL query string: + $scope.error = $location.search().err; + + // If user is signed in then redirect back home + if ($scope.authentication.user) $location.path('/'); + + $scope.signup = function() { + $http.post('/api/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('/api/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; + }); + }; + } +]); diff --git a/pool/shard010/JavaScript/0067170_Pool.js b/pool/shard010/JavaScript/0067170_Pool.js new file mode 100644 index 0000000000000000000000000000000000000000..b5bd56fab52c468fa124575965525c0a26371292 --- /dev/null +++ b/pool/shard010/JavaScript/0067170_Pool.js @@ -0,0 +1,263 @@ +/** +@license +The MIT License (MIT) + +Copyright (c) 2016 John Pittman + +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. +*/ + +'use strict'; + +/** +@example +// Here are a couple of example classes for better visualization. + +// Create a test parent class. +class Person { + constructor(name) { + this._name = name; + } + + init(name) { + this._name = name; + } + + dispose() {} +} + +// Create a test child class. +class Gunner extends Person { + constructor(name) { + super(name); + + this._gunType = 'Machine Gun'; + // This is replaced by a bullet pool in production. + this._bullets = [50]; + } + + // Don't forget to call parent's init if there is one. + init(name) { + super.init(name); + } + + dispose() { + // Dispose parent. + super.dispose(); + + // Reuse the array. + const bullets = this._bullets; + + // Note: In reality we would use a bullet pool for all bullets which means there would be no need + // to store bullets here in the first place. Each time a bullet is needed we would + // do a BulletPool.create() and BulletPool.destroy(bullet) so there's nothing to clean up here + // unless there's never going to be anymore bullets used again which would mean we would + // do a BulletPool.drain() to get the memory back. + while (bullets.length > 0) { + bullets.pop(); + } + } +} + +// Stand-alone pool creation. +// Create a GunnerPool.js file. +// Create and export a new pool of Gunners. + +import Pool from '@chickendinosaur/pool/Pool.js'; +import Gunner from './Gunner.js'; + +export default new Pool( + function(name) { + return new Gunner(name); + // Or set up defaults for generating up front objects when setting the size or just calling create() with no arguments. (not implemented yet) + // return new Gunner( name || 'Billy Bob'); + }, + function(name) { + return this.pull().init(name); + }, + // The dispose callback parameter also accepts null which will only + // use the init callback when calling create(); + function(obj) { + obj.dispose(); + } +); + +// Use the pool anywhere. + +import GunnerPool from './GunnerPool.js'; + +let gunner = GunnerPool.create('Crazy Gunner Guy'); + +GunnerPool.destroy(gunner); + +gunner = GunnerPool.create('Another Gunner Guy'); + +@class Pool +@param {function} allocatorCallback +@param {function} renewObjectCallback +@param {function|null} disposeObjectCallback +*/ +export default function Pool( + allocatorCallback, + renewObjectCallback, + disposeObjectCallback +) { + /** + Hotswap reference for the allocation and renew callbacks. + Single point of entry for user friendly api and avoids using .apply(this, arguments). + + @method create + @param {*} * - Mimics the constructor. + @return {*} - Newly created object or one from the pool. + */ + this.create = null + + /** + Container for all reusable objects. + + @private + @property _pool + @type {array} + */ + this._pool = []; + + /** + @private + @method _renewObjectCallback + @param {*} * - Mimics the constructor. + @return {*} - Object from the pool. + */ + this._renewObjectCallback = null; + + /** + @private + @method _disposeObjectCallback + @param {*} obj - Object being added to the pool. + */ + this._disposeObjectCallback = null; + + /** + @private + @method _allocatorCallback + @param {*} * - Mimics the constructor. + @return {*} - A new object. + */ + this._allocatorCallback = null; + + // Use the init method to encapsulate argument type checking. + this.init( + allocatorCallback, + renewObjectCallback, + disposeObjectCallback + ); +} + +Pool.prototype.constructor = Pool; + +/** +Used for pooling. + +@method init +*/ +Pool.prototype.init = function( + allocatorCallback, + renewObjectCallback, + disposeObjectCallback +) { + if (typeof allocatorCallback !== 'function') + throw new TypeError(); + else if (typeof renewObjectCallback !== 'function') + throw new TypeError(); + else if (typeof disposeObjectCallback !== 'function' && + disposeObjectCallback) + throw new TypeError(); + + this.create = allocatorCallback; + this._allocatorCallback = allocatorCallback; + this._renewObjectCallback = renewObjectCallback; + this._disposeObjectCallback = disposeObjectCallback; +}; + +/** +Used for pooling. + +@method dispose +*/ +Pool.prototype.dispose = function() { + // Need to replace with an array pool eventually. + const pool = this._pool; + while (pool.length > 0) { + pool.pop(); + } +}; + +/** +Does not create any new objects. +Hot swaps the create ref to the allocation callback for an easy api. + +@method pull +@return {*} - object from the pool or null if empty. +*/ +Pool.prototype.pull = function() { + const pool = this._pool; + + // Hot-swap + if (pool.length === 1) { + this.create = this._allocatorCallback; + } + + return pool.pop(); +}; + +/** +Adds an object to the object pool for reuse. +Hot swaps the create ref to the object reuse callback for an easy api. +Disposes the object. + +@method destroy +@param {*} obj +*/ +Pool.prototype.destroy = function(obj) { + const pool = this._pool; + + // Put in the pool + pool[pool.length] = obj; + + // Trigger hot-swap. + if (pool.length === 1) { + this.create = this._renewObjectCallback; + } + + // Dispose the object + if (this._disposeObjectCallback) { + this._disposeObjectCallback(obj); + } +}; + +/** +Dereferences/Clears all objects in the pool. + +@method drain +*/ +Pool.prototype.drain = function() { + const pool = this._pool; + while (pool.length > 0) { + this.pull(); + } +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067175_paginationItem.js b/pool/shard010/JavaScript/0067175_paginationItem.js new file mode 100644 index 0000000000000000000000000000000000000000..4e967814cc1628511586057f98c5b705a470fe6a --- /dev/null +++ b/pool/shard010/JavaScript/0067175_paginationItem.js @@ -0,0 +1,33 @@ +lucid.html.bootstrap.tags.paginationItem = function(factory){ + this.factory = factory; + lucid.html.base.tags.listItem.apply(this, arguments); + this.tag = 'li'; + this.parameters = ['href']; + this.href = ''; + this.addClass('page-item'); + this.addTrait(lucid.html.bootstrap.traits.Activable); + +}; +lucid.html.bootstrap.tags.paginationItem.prototype = Object.create(lucid.html.base.tags.listItem.prototype); +lucid.html.factory.tags.paginationItem = lucid.html.bootstrap.tags.paginationItem; + +lucid.html.bootstrap.tags.paginationItem.prototype.setDisabled=function(val){ + if (val === true) { + this.addClass('disabled'); + } else { + this.removeClass('disabled'); + } + return this; +}; + +lucid.html.bootstrap.tags.paginationItem.prototype.getDisabled=function(){ + return this.hasClass('disabled'); +}; + +lucid.html.bootstrap.tags.paginationItem.prototype.preRender=function(){ + if (String(this.href).trim() != '') { + this.preChildrenHtml += ''; + this.postChildrenHtml = '' + this.postChildrenHtml; + } + return lucid.html.base.tags.listItem.prototype.preRender.call(this); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067178_skills-display.client.directive.js b/pool/shard010/JavaScript/0067178_skills-display.client.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..8ef5f8eb4c49a2d0976d1b4ff6fa32621de34545 --- /dev/null +++ b/pool/shard010/JavaScript/0067178_skills-display.client.directive.js @@ -0,0 +1,78 @@ +(function () { + 'use strict'; + + angular + .module('characters') + .directive('skillsDisplay', skillsDisplay); + + skillsDisplay.$inject = ['CharacterSourceService']; + + function skillsDisplay(sourceService) { + var controller = function($scope) { + var vm = this; + vm.canSelect = $scope.canSelect; + vm.character = $scope.character; + vm.skills = sourceService.getSkills(); + + vm.toggleProficiency = toggleProficiency; + vm.numberProficiencies = numberProficiencies; + vm.getSkillMod = getSkillMod; + vm.getSaveMod = getSaveMod; + vm.getMod = getMod; + + function getMod(attribute) { + return toMod(vm.character.attributes[attribute]); + } + + function getSaveMod(attribute) { + if(!vm.character.playableClass[0].profession) { return 0; } + + var mod = toMod(vm.character.attributes[attribute]); + if(vm.character.playableClass[0].profession.saveProficiencies.indexOf(attribute) > -1) { + return getProficiency() + mod; + } + return mod; + } + + function getSkillMod(skill, attribute) { + var mod = toMod(vm.character.attributes[attribute]); + if(vm.character.skills.indexOf(skill) > -1 || vm.character.background.generalization.skillProficiencies.indexOf(skill) > -1) { + return getProficiency() + mod; + } + return mod; + } + + function numberProficiencies() { + return parseInt(vm.character.playableClass[0].profession.numSkillProficiencies) + parseInt(vm.character.race.numSkillProficiencies); + } + + function toggleProficiency(skill) { + var skillIndex = vm.character.skills.indexOf(skill); + if(skillIndex > -1) { + vm.character.skills.splice(skillIndex, 1); + return; + } + vm.character.skills.push(skill); + } + + // Statics + function getProficiency() { + return 2; + } + + function toMod(attVal) { + return Math.floor((attVal-10) / 2); + } + }; + + return { + templateUrl: 'modules/characters/client/views/directives/skills-display.view.html', + controller: controller, + controllerAs: 'vm', + scope: { + character: '=', + canSelect: '=' + } + }; + } +})(); diff --git a/pool/shard010/JavaScript/0067188_onRequestTest.client.js b/pool/shard010/JavaScript/0067188_onRequestTest.client.js new file mode 100644 index 0000000000000000000000000000000000000000..3d5c8ee5ba5d2a1124bd0fb0cda94426b2bbf214 --- /dev/null +++ b/pool/shard010/JavaScript/0067188_onRequestTest.client.js @@ -0,0 +1,32 @@ +feather.ns("api_tester"); +(function() { + api_tester.onRequestTest = feather.Widget.create({ + name: "api_tester.onRequestTest", + path: "widgets/onRequestTest/", + prototype: { + onInit: function() { + + }, + addTests: function() { + var me = this; + + var suite = new Y.Test.Suite("onRequest"); + + suite.add(new Y.Test.Case({ + name: "onRequest - is foo here?", + setUp: feather.emptyFn, + tearDown : feather.emptyFn, + + testFooHere: function () { + Y.Assert.areEqual("bar", me.foo); + } + })); + + Y.Test.Runner.add(suite); + }, + onRequest: function(foo) { + this.foo = foo; + } + } + }); +})(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067189_BoxHelper.tests.js b/pool/shard010/JavaScript/0067189_BoxHelper.tests.js new file mode 100644 index 0000000000000000000000000000000000000000..3c1b01256795ba83c26f72280ef7b76f2b3d810b --- /dev/null +++ b/pool/shard010/JavaScript/0067189_BoxHelper.tests.js @@ -0,0 +1,81 @@ +/** + * @author TristanVALCKE / https://github.com/Itee + * @author Anonymous + */ +/* global QUnit */ + +import { runStdGeometryTests } from '../../qunit-utils'; +import { BoxHelper } from '../../../../src/helpers/BoxHelper'; +import { BoxGeometry } from '../../../../src/geometries/BoxGeometry'; +import { SphereGeometry } from '../../../../src/geometries/SphereGeometry'; +import { Mesh } from '../../../../src/objects/Mesh'; + +export default QUnit.module( 'Helpers', () => { + + QUnit.module( 'BoxHelper', ( hooks ) => { + + var geometries = undefined; + hooks.beforeEach( function () { + + const parameters = { + radius: 10, + widthSegments: 20, + heightSegments: 30, + phiStart: 0.5, + phiLength: 1.0, + thetaStart: 0.4, + thetaLength: 2.0, + }; + + // Test with a normal cube and a box helper + var boxGeometry = new BoxGeometry( parameters.diameter ); + var box = new Mesh( boxGeometry ); + var boxHelper = new BoxHelper( box ); + + // The same should happen with a comparable sphere + var sphereGeometry = new SphereGeometry( parameters.diameter / 2 ); + var sphere = new Mesh( sphereGeometry ); + var sphereBoxHelper = new BoxHelper( sphere ); + + // Note that unlike what I'd like to, these doesn't check the equivalency of the two generated geometries + geometries = [ boxHelper.geometry, sphereBoxHelper.geometry ]; + + } ); + + // INHERITANCE + QUnit.todo( "Extending", ( assert ) => { + + assert.ok( false, "everything's gonna be alright" ); + + } ); + + // INSTANCING + QUnit.todo( "Instancing", ( assert ) => { + + assert.ok( false, "everything's gonna be alright" ); + + } ); + + // PUBLIC STUFF + QUnit.todo( "update", ( assert ) => { + + assert.ok( false, "everything's gonna be alright" ); + + } ); + + QUnit.todo( "setFromObject", ( assert ) => { + + assert.ok( false, "everything's gonna be alright" ); + + } ); + + // OTHERS + QUnit.test( 'Standard geometry tests', ( assert ) => { + + runStdGeometryTests( assert, geometries ); + + } ); + + } ); + +} ); diff --git a/pool/shard010/JavaScript/0067191_app.js b/pool/shard010/JavaScript/0067191_app.js new file mode 100644 index 0000000000000000000000000000000000000000..f5c06933be5af1d46d9e2b414bb49edabafb4060 --- /dev/null +++ b/pool/shard010/JavaScript/0067191_app.js @@ -0,0 +1,138 @@ +//app.js +App({ + globalData: { + apiBaseUrl: 'https://awuhan.com/', + + openid: null, + userInfo: {}, + dbUserInfo: {} + }, + onLaunch: function () { + //调用API从本地缓存中获取数据 + var logs = wx.getStorageSync('logs') || [] + logs.unshift(Date.now()) + wx.setStorageSync('logs', logs) + }, + getLoginStatus: function (cb) { + //获取登录状态,返回登录状态 + var that = this + wx.login({ + success: function (res) { + if (res.code) { + //获取到code,向后端请求openid + wx.request({ + url: that.globalData.apiBaseUrl + 'getopenid', + data: { js_code: res.code }, + method: 'POST', + success: function (json) { + //openid写入公共数据 + that.globalData.openid = json.data.openid + typeof cb == "function" && cb(true) + } + }) + } else { + typeof cb == "function" && cb(false) + } + }, fail: function () { + typeof cb == "function" && cb(false) + } + }) + }, + getUserInfo: function (cb) { + //获取用户授权,返回授权状态 + var that = this + wx.getUserInfo({ + withCredentials: false, + success: function (res) { + if (res) { + //userInfo写入公共数据 + that.globalData.userInfo = res.userInfo + typeof cb == "function" && cb(true) + } else { + typeof cb == "function" && cb(true) + } + }, fail: function () { + typeof cb == "function" && cb(false) + } + }) + }, + creatUser: function (cb) { + //尝试创建用户,返回用户全部信息 + var that = this + var userInfo = that.globalData.userInfo + wx.request({ + url: that.globalData.apiBaseUrl + 'creatuser', + data: { openid: that.globalData.openid, username: userInfo.nickName, avatar: userInfo.avatarUrl, gender: userInfo.gender, country: userInfo.country, province: userInfo.province, city: userInfo.city }, + method: 'POST', + success: function (res) { + if (res.data.status) { + that.globalData.dbUserInfo = res.data.dbUserInfo[0] + typeof cb == "function" && cb(true) + } else { + typeof cb == "function" && cb(false) + } + }, fail: function (res) { + typeof cb == "function" && cb(false) + } + }) + }, + reAuth: function (cb) { + //调起重新授权的设置 + wx.openSetting({ + success: function (res) { + if (!res.authSetting['scope.userInfo']) { + typeof cb == "function" && cb(false) + } else { + typeof cb == "function" && cb(true) + } + } + }) + }, + checkModal: function (cb) { + //提醒授权 + wx.showModal({ + title: '重要提醒', + content: '您必须登录后才可以发布和管理拼车信息', + confirmText: '登录', + cancelText: '不登录', + success: function (ms) { + if (ms.confirm) { + typeof cb == "function" && cb(true) + } else { + typeof cb == "function" && cb(false) + } + } + }) + }, + changeOrderCount: function (did, pid) { + var that = this + //console.log(did+','+pid) + wx.request({ + url: that.globalData.apiBaseUrl + 'updateuser', + data: { tp: 'driver_order', opid: did }, + method: 'POST', + success: function (res) { + //console.log(res.data.msg) + } + }) + wx.request({ + url: that.globalData.apiBaseUrl + 'updateuser', + data: { tp: 'user_order', opid: pid }, + method: 'POST', + success: function (res) { + //console.log(res.data.msg) + } + }) + }, + creatOrder: function (tp, did, pid, dusername, pusername, start_local, end_local, go_date, go_time, highway) { + //console.log(tp + ',' + did + ',' + pid + ',' + dusername + ',' + pusername + ',' + start_local + ',' + end_local + ',' + go_date + ',' + go_time + ',' +highway) + wx.request({ + url: this.globalData.apiBaseUrl + 'creatorder', + data: {tp: tp, driver: dusername, passenger: pusername, driver_id: did, passenger_id: pid, start_local: start_local, end_local: end_local, go_date: go_date, go_time: go_time, highway: highway}, + method: 'POST', + success: function(res) { + //console.log(res.data) + } + }) + } +}) diff --git a/pool/shard010/JavaScript/0067193_Repos.js b/pool/shard010/JavaScript/0067193_Repos.js new file mode 100644 index 0000000000000000000000000000000000000000..96d2a17d3b826c131f7aebb0f06075c448fb2283 --- /dev/null +++ b/pool/shard010/JavaScript/0067193_Repos.js @@ -0,0 +1,51 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router'; +import 'whatwg-fetch'; + +class Repos extends Component { + constructor(){ + super(...arguments); + this.state = { + repositories: [] + }; + } + + componentDidMount(){ + fetch('https://api.github.com/users/pro-react/repos') + .then((response) => { + if(response.ok){ + return response.json(); + } else { + throw new Error("Server response wasn't OK"); + } + }) + .then((responseData) => { + this.setState({repositories:responseData}); + }) + .catch((error) => { + this.props.history.pushState(null,'/error'); + }); + } + + render() { + let repos = this.state.repositories.map((repo) => ( +
  • {repo.name}
  • + )); + + let child = this.props.children && React.cloneElement(this.props.children, + { repositories: this.state.repositories } + ); + + return ( +
    +

    Github Repos

    +
      + {repos} +
    + {child} +
    + ); + } +} + +export default Repos; diff --git a/pool/shard010/JavaScript/0067195_unix-read.test.js b/pool/shard010/JavaScript/0067195_unix-read.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6b289dba6bf07a61402fb46630fc5a2d44bcd26e --- /dev/null +++ b/pool/shard010/JavaScript/0067195_unix-read.test.js @@ -0,0 +1,104 @@ +const unixRead = require('./unix-read') + +const makeFsRead = (bytesRead, fill) => (fd, buffer, offset, length) => { + buffer.fill(fill, offset, Math.min(length, bytesRead)) + return { + buffer, + bytesRead, + } +} + +const makeFsReadError = code => { + const err = new Error(`Error: ${code}`) + err.code = code + return () => { + throw err + } +} + +const sequenceCalls = (...functions) => { + const funcs = [...functions] + return (...args) => { + const func = funcs.shift() + if (func) { + return func(...args) + } else { + throw new Error('"sequenceCalls" has no more functions') + } + } +} + +const makeMockBinding = () => { + return { + isOpen: true, + fd: 1, + poller: { + once(event, func) { + setImmediate(func) + }, + }, + } +} + +describe('unixRead', () => { + let mock + beforeEach(() => { + mock = makeMockBinding() + }) + it('rejects when not open', async () => { + mock.isOpen = false + const readBuffer = Buffer.alloc(8, 0) + await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync: makeFsRead(8, 255) })) + }) + it('handles reading the requested number of bytes', async () => { + const readBuffer = Buffer.alloc(8, 0) + const { bytesRead, buffer } = await unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync: makeFsRead(8, 255) }) + assert.strictEqual(bytesRead, 8) + assert.strictEqual(buffer, readBuffer) + assert.deepStrictEqual(buffer, Buffer.alloc(8, 255)) + }) + it('handles reading less than requested number of bytes', async () => { + const readBuffer = Buffer.alloc(8, 0) + const { bytesRead, buffer } = await unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync: makeFsRead(4, 255) }) + assert.strictEqual(bytesRead, 4) + assert.strictEqual(buffer, readBuffer) + assert.deepStrictEqual(buffer, Buffer.from([255, 255, 255, 255, 0, 0, 0, 0])) + }) + it('handles reading 0 bytes then requested number of bytes', async () => { + const readBuffer = Buffer.alloc(8, 0) + + const fsReadAsync = sequenceCalls(makeFsRead(0, 0), makeFsRead(8, 255)) + const { bytesRead, buffer } = await unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync }) + assert.strictEqual(bytesRead, 8) + assert.strictEqual(buffer, readBuffer) + assert.deepStrictEqual(buffer, Buffer.alloc(8, 255)) + }) + it('handles retryable errors', async () => { + const readBuffer = Buffer.alloc(8, 0) + + const fsReadAsync = sequenceCalls(makeFsReadError('EAGAIN'), makeFsReadError('EWOULDBLOCK'), makeFsReadError('EINTR'), makeFsRead(8, 255)) + const { bytesRead, buffer } = await unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync }) + assert.strictEqual(bytesRead, 8) + assert.strictEqual(buffer, readBuffer) + assert.deepStrictEqual(buffer, Buffer.alloc(8, 255)) + }) + it('rejects read errors', async () => { + const readBuffer = Buffer.alloc(8, 0) + await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync: makeFsReadError('Error') })) + }) + it('rejects a canceled error if port closes after read a retryable error', async () => { + const readBuffer = Buffer.alloc(8, 0) + const fsReadAsync = () => { + mock.isOpen = false + makeFsReadError('EAGAIN')() + } + const err = await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync })) + assert.isTrue(err.canceled) + }) + it('rejects a disconnected error when fsread errors a disconnect error', async () => { + const readBuffer = Buffer.alloc(8, 0) + const fsReadAsync = makeFsReadError('EBADF') + const err = await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync })) + assert.isTrue(err.disconnect) + }) +}) diff --git a/pool/shard010/JavaScript/0067198_eol-last.js b/pool/shard010/JavaScript/0067198_eol-last.js new file mode 100644 index 0000000000000000000000000000000000000000..24b0c9279c71ca74d56c58e0b70954a65fa72a58 --- /dev/null +++ b/pool/shard010/JavaScript/0067198_eol-last.js @@ -0,0 +1,107 @@ +/** + * @fileoverview Require or disallow newline at the end of files + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + type: "layout", + + docs: { + description: "require or disallow newline at the end of files", + category: "Stylistic Issues", + recommended: false, + url: "https://eslint.org/docs/rules/eol-last" + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "unix", "windows"] + } + ], + + messages: { + missing: "Newline required at end of file but not found.", + unexpected: "Newline not allowed at end of file." + } + }, + create(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkBadEOF(node) { + const sourceCode = context.getSourceCode(), + src = sourceCode.getText(), + lastLine = sourceCode.lines[sourceCode.lines.length - 1], + location = { + column: lastLine.length, + line: sourceCode.lines.length + }, + LF = "\n", + CRLF = `\r${LF}`, + endsWithNewline = src.endsWith(LF); + + /* + * Empty source is always valid: No content in file so we don't + * need to lint for a newline on the last line of content. + */ + if (!src.length) { + return; + } + + let mode = context.options[0] || "always", + appendCRLF = false; + + if (mode === "unix") { + + // `"unix"` should behave exactly as `"always"` + mode = "always"; + } + if (mode === "windows") { + + // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility + mode = "always"; + appendCRLF = true; + } + if (mode === "always" && !endsWithNewline) { + + // File is not newline-terminated, but should be + context.report({ + node, + loc: location, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfterRange([0, src.length], appendCRLF ? CRLF : LF); + } + }); + } else if (mode === "never" && endsWithNewline) { + + // File is newline-terminated, but shouldn't be + context.report({ + node, + loc: location, + messageId: "unexpected", + fix(fixer) { + const finalEOLs = /(?:\r?\n)+$/u, + match = finalEOLs.exec(sourceCode.text), + start = match.index, + end = sourceCode.text.length; + + return fixer.replaceTextRange([start, end], ""); + } + }); + } + } + }; + } +}; diff --git a/pool/shard010/JavaScript/0067200_multislider.js b/pool/shard010/JavaScript/0067200_multislider.js new file mode 100644 index 0000000000000000000000000000000000000000..d0c68c3c90f22c2c91e2a647493b8d979b3d598a --- /dev/null +++ b/pool/shard010/JavaScript/0067200_multislider.js @@ -0,0 +1,64 @@ +// $('#carouselExample').on('slide.bs.carousel', function (e) { +// +// +// var $e = $(e.relatedTarget); +// var idx = $e.index(); +// var itemsPerSlide = 4; +// var totalItems = $('.carousel-item').length; +// +// if (idx >= totalItems-(itemsPerSlide-1)) { +// var it = itemsPerSlide - (totalItems - idx); +// for (var i=0; i events. + +var MessagingNatives = requireNative('messaging_natives'); +var WebViewConstants = require('webViewConstants').WebViewConstants; +var WebViewInternal = require('webViewInternal').WebViewInternal; + +var PERMISSION_TYPES = ['media', + 'geolocation', + 'pointerLock', + 'download', + 'loadplugin', + 'filesystem']; + +// ----------------------------------------------------------------------------- +// WebViewActionRequest object. + +// Default partial implementation of a webview action request. +function WebViewActionRequest(webViewImpl, event, webViewEvent, interfaceName) { + this.webViewImpl = webViewImpl; + this.event = event; + this.webViewEvent = webViewEvent; + this.interfaceName = interfaceName; + this.guestInstanceId = this.webViewImpl.guest.getId(); + this.requestId = event.requestId; + this.actionTaken = false; +} + +// Performs the default action for the request. +WebViewActionRequest.prototype.defaultAction = function() { + // Do nothing if the action has already been taken or the requester is + // already gone (in which case its guestInstanceId will be stale). + if (this.actionTaken || + this.guestInstanceId != this.webViewImpl.guest.getId()) { + return; + } + + this.actionTaken = true; + WebViewInternal.setPermission(this.guestInstanceId, this.requestId, + 'default', '', function(allowed) { + if (allowed) { + return; + } + this.showWarningMessage(); + }.bind(this)); +}; + +// Called to handle the action request's event. +WebViewActionRequest.prototype.handleActionRequestEvent = function() { + // Construct the interface object and attach it to |webViewEvent|. + var request = this.getInterfaceObject(); + this.webViewEvent[this.interfaceName] = request; + + var defaultPrevented = !this.webViewImpl.dispatchEvent(this.webViewEvent); + // Set |webViewEvent| to null to break the circular reference to |request| so + // that the garbage collector can eventually collect it. + this.webViewEvent = null; + if (this.actionTaken) { + return; + } + + if (defaultPrevented) { + // Track the lifetime of |request| with the garbage collector. + MessagingNatives.BindToGC(request, this.defaultAction.bind(this)); + } else { + this.defaultAction(); + } +}; + +// Displays a warning message when an action request is blocked by default. +WebViewActionRequest.prototype.showWarningMessage = function() { + window.console.warn(this.WARNING_MSG_REQUEST_BLOCKED); +}; + +// This function ensures that each action is taken at most once. +WebViewActionRequest.prototype.validateCall = function() { + if (this.actionTaken) { + throw new Error(this.ERROR_MSG_ACTION_ALREADY_TAKEN); + } + this.actionTaken = true; +}; + +// The following are implemented by the specific action request. + +// Returns the interface object for this action request. +WebViewActionRequest.prototype.getInterfaceObject = undefined; + +// Error/warning messages. +WebViewActionRequest.prototype.ERROR_MSG_ACTION_ALREADY_TAKEN = undefined; +WebViewActionRequest.prototype.WARNING_MSG_REQUEST_BLOCKED = undefined; + +// ----------------------------------------------------------------------------- +// Dialog object. + +// Represents a dialog box request (e.g. alert()). +function Dialog(webViewImpl, event, webViewEvent) { + WebViewActionRequest.call(this, webViewImpl, event, webViewEvent, 'dialog'); + + this.handleActionRequestEvent(); +} + +Dialog.prototype.__proto__ = WebViewActionRequest.prototype; + +Dialog.prototype.getInterfaceObject = function() { + return { + ok: function(user_input) { + this.validateCall(); + user_input = user_input || ''; + WebViewInternal.setPermission( + this.guestInstanceId, this.requestId, 'allow', user_input); + }.bind(this), + cancel: function() { + this.validateCall(); + WebViewInternal.setPermission( + this.guestInstanceId, this.requestId, 'deny'); + }.bind(this) + }; +}; + +Dialog.prototype.showWarningMessage = function() { + var VOWELS = ['a', 'e', 'i', 'o', 'u']; + var dialogType = this.event.messageType; + var article = (VOWELS.indexOf(dialogType.charAt(0)) >= 0) ? 'An' : 'A'; + this.WARNING_MSG_REQUEST_BLOCKED = this.WARNING_MSG_REQUEST_BLOCKED. + replace('%1', article).replace('%2', dialogType); + window.console.warn(this.WARNING_MSG_REQUEST_BLOCKED); +}; + +Dialog.prototype.ERROR_MSG_ACTION_ALREADY_TAKEN = + WebViewConstants.ERROR_MSG_DIALOG_ACTION_ALREADY_TAKEN; +Dialog.prototype.WARNING_MSG_REQUEST_BLOCKED = + WebViewConstants.WARNING_MSG_DIALOG_REQUEST_BLOCKED; + +// ----------------------------------------------------------------------------- +// NewWindow object. + +// Represents a new window request. +function NewWindow(webViewImpl, event, webViewEvent) { + WebViewActionRequest.call(this, webViewImpl, event, webViewEvent, 'window'); + + this.handleActionRequestEvent(); +} + +NewWindow.prototype.__proto__ = WebViewActionRequest.prototype; + +NewWindow.prototype.getInterfaceObject = function() { + return { + attach: function(webview) { + this.validateCall(); + if (!webview || !webview.tagName || webview.tagName != 'WEBVIEW') { + throw new Error(ERROR_MSG_WEBVIEW_EXPECTED); + } + + var webViewImpl = privates(webview).internal; + // Update the partition. + if (this.event.partition) { + webViewImpl.onAttach(this.event.partition); + } + + var attached = webViewImpl.attachWindow(this.event.windowId); + if (!attached) { + window.console.error(ERROR_MSG_NEWWINDOW_UNABLE_TO_ATTACH); + } + + if (this.guestInstanceId != this.webViewImpl.guest.getId()) { + // If the opener is already gone, then its guestInstanceId will be + // stale. + return; + } + + // If the object being passed into attach is not a valid + // then we will fail and it will be treated as if the new window + // was rejected. The permission API plumbing is used here to clean + // up the state created for the new window if attaching fails. + WebViewInternal.setPermission(this.guestInstanceId, this.requestId, + attached ? 'allow' : 'deny'); + }.bind(this), + discard: function() { + this.validateCall(); + if (!this.guestInstanceId) { + // If the opener is already gone, then we won't have its + // guestInstanceId. + return; + } + WebViewInternal.setPermission( + this.guestInstanceId, this.requestId, 'deny'); + }.bind(this) + }; +}; + +NewWindow.prototype.ERROR_MSG_ACTION_ALREADY_TAKEN = + WebViewConstants.ERROR_MSG_NEWWINDOW_ACTION_ALREADY_TAKEN; +NewWindow.prototype.WARNING_MSG_REQUEST_BLOCKED = + WebViewConstants.WARNING_MSG_NEWWINDOW_REQUEST_BLOCKED; + +// ----------------------------------------------------------------------------- +// PermissionRequest object. + +// Represents a permission request (e.g. to access the filesystem). +function PermissionRequest(webViewImpl, event, webViewEvent) { + WebViewActionRequest.call(this, webViewImpl, event, webViewEvent, 'request'); + + if (!this.validPermissionCheck()) { + return; + } + + this.handleActionRequestEvent(); +} + +PermissionRequest.prototype.__proto__ = WebViewActionRequest.prototype; + +PermissionRequest.prototype.getInterfaceObject = function() { + return { + allow: function() { + this.validateCall(); + WebViewInternal.setPermission( + this.guestInstanceId, this.requestId, 'allow'); + }.bind(this), + deny: function() { + this.validateCall(); + WebViewInternal.setPermission( + this.guestInstanceId, this.requestId, 'deny'); + }.bind(this) + }; +}; + +PermissionRequest.prototype.showWarningMessage = function() { + window.console.warn( + this.WARNING_MSG_REQUEST_BLOCKED.replace('%1', this.event.permission)); +}; + +// Checks that the requested permission is valid. Returns true if valid. +PermissionRequest.prototype.validPermissionCheck = function() { + if (PERMISSION_TYPES.indexOf(this.event.permission) < 0) { + // The permission type is not allowed. Trigger the default response. + this.defaultAction(); + return false; + } + return true; +}; + +PermissionRequest.prototype.ERROR_MSG_ACTION_ALREADY_TAKEN = + WebViewConstants.ERROR_MSG_PERMISSION_ACTION_ALREADY_TAKEN; +PermissionRequest.prototype.WARNING_MSG_REQUEST_BLOCKED = + WebViewConstants.WARNING_MSG_PERMISSION_REQUEST_BLOCKED; + +// ----------------------------------------------------------------------------- + +var WebViewActionRequests = { + WebViewActionRequest: WebViewActionRequest, + Dialog: Dialog, + NewWindow: NewWindow, + PermissionRequest: PermissionRequest +}; + +exports.WebViewActionRequests = WebViewActionRequests; diff --git a/pool/shard010/JavaScript/0067203_managementLockListResult.js b/pool/shard010/JavaScript/0067203_managementLockListResult.js new file mode 100644 index 0000000000000000000000000000000000000000..27b7ebecb8439c9328898c16556554d9c0fb3298 --- /dev/null +++ b/pool/shard010/JavaScript/0067203_managementLockListResult.js @@ -0,0 +1,59 @@ +'use strict'; + +var util = require('util'); + +var models = require('./index'); + +/** + * @class + * Initializes a new instance of the ManagementLockListResult class. + * @constructor + */ +function ManagementLockListResult() { } + +/** + * Validate the payload against the ManagementLockListResult schema + * + * @param {JSON} payload + * + */ +ManagementLockListResult.prototype.validate = function (payload) { + if (!payload) { + throw new Error('ManagementLockListResult cannot be null.'); + } + if (util.isArray(payload['value'])) { + for (var i = 0; i < payload['value'].length; i++) { + if (payload['value'][i]) { + models['ManagementLock'].validate(payload['value'][i]); + } + } + } + + if (payload['nextLink'] !== null && payload['nextLink'] !== undefined && typeof payload['nextLink'].valueOf() !== 'string') { + throw new Error('payload[\'nextLink\'] must be of type string.'); + } +}; + +/** + * Deserialize the instance to ManagementLockListResult schema + * + * @param {JSON} instance + * + */ +ManagementLockListResult.prototype.deserialize = function (instance) { + if (instance) { + if (instance.value !== null && instance.value !== undefined) { + var deserializedArray = []; + instance.value.forEach(function(element) { + if (element !== null && element !== undefined) { + element = models['ManagementLock'].deserialize(element); + } + deserializedArray.push(element); + }); + instance.value = deserializedArray; + } + } + return instance; +}; + +module.exports = new ManagementLockListResult(); diff --git a/pool/shard010/JavaScript/0067212_codes.services.spec.js b/pool/shard010/JavaScript/0067212_codes.services.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..78530fe9c389d839300547c90cbb58680d54d806 --- /dev/null +++ b/pool/shard010/JavaScript/0067212_codes.services.spec.js @@ -0,0 +1,44 @@ +'use strict'; + +describe("Code Unit Tests", function() { + + beforeEach(module('myApp')); + + var $httpBackend; + var Code; + var email = 'sm@polkaspots.com'; + + beforeEach(inject(function($injector, _Code_) { + + Code = _Code_; + $httpBackend = $injector.get('$httpBackend'); + + $httpBackend.when('GET', 'http://mywifi.dev:8080/api/v1/locations/123/vouchers/456/codes') + .respond(200, {}); + + $httpBackend.when('POST', 'http://mywifi.dev:8080/api/v1/codes/generate_password') + .respond(200, {name: name, email: email, success: true}); + + $httpBackend.whenGET('/translations/en_GB.json').respond(""); + + })); + + afterEach(function() { + $httpBackend.verifyNoOutstandingExpectation(); + $httpBackend.verifyNoOutstandingRequest(); + }); + + it('should have sent a GET request to location codes', function() { + var result = Code.get({location_id: 123, voucher_id: 456, vouchers: 'vouchers'}); + $httpBackend.expectGET('http://mywifi.dev:8080/api/v1/locations/123/vouchers/456/codes'); + $httpBackend.flush(); + }); + + it('should have sent a GET request to the location users API', function() { + var result = Code.generate_password() + $httpBackend.expectPOST('http://mywifi.dev:8080/api/v1/codes/generate_password') + $httpBackend.flush(); + }); + +}) + diff --git a/pool/shard010/JavaScript/0067227_index.js b/pool/shard010/JavaScript/0067227_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3bc11f26a5c5de9c05839e09a4f3e892dce49026 --- /dev/null +++ b/pool/shard010/JavaScript/0067227_index.js @@ -0,0 +1,34 @@ + +var gitlogger = require('./gitlogger.js') +var gitparser = require('./gitparser.js') +var gitprocessor = require('./gitprocessor.js') +var defaultParserplugins = [ + require('./gitparser-plugin-refnames.js'), + require('./gitparser-plugin-parents.js') ] + +var defaultProcessorplugins = [ + require('./gitprocessor-plugin-relations.js'), + require('./gitprocessor-plugin-heads.js'), + require('./gitprocessor-plugin-index.js') ] + +module.exports = { + logger : gitlogger, + parser : gitparser, + processor : gitprocessor, + parserplugins : defaultParserplugins, + processorplugins : defaultProcessorplugins, + + run : function(callback, maxCommits) { + var parserplugins = this.parserplugins; + var processorplugins = this.processorplugins; + var loggerCallback = function(text) { + var commits = gitparser(text, parserplugins) + gitprocessor(commits, processorplugins); + + callback(commits); + } + + gitlogger.retrieve(maxCommits || 300, loggerCallback) + } +} + diff --git a/pool/shard010/JavaScript/0067228_zone.js b/pool/shard010/JavaScript/0067228_zone.js new file mode 100644 index 0000000000000000000000000000000000000000..822ced4a8dc6884743f38df2919afef37fd2dcda --- /dev/null +++ b/pool/shard010/JavaScript/0067228_zone.js @@ -0,0 +1,32 @@ +var util = require('util'); +var EventEmitter = require('events').EventEmitter; + +var id = 0; + +/** + * The origint zone object + */ +var Zone = function(opts) { + this.zoneId = id++; + this.width = opts.width; + this.height = opts.height; + this.x = opts.x; + this.y = opts.y; + this.area = opts.area; +}; + +util.inherits(Zone, EventEmitter); + +/** + * Update the zone, the funciton is time driven + */ +Zone.prototype.update = function() { +}; + +/** + * Remove an entity from the zone, default function will do nothing + */ +Zone.prototype.remove = function() { +}; + +module.exports = Zone; diff --git a/pool/shard010/JavaScript/0067229_websockets.js b/pool/shard010/JavaScript/0067229_websockets.js new file mode 100644 index 0000000000000000000000000000000000000000..94b9c22765a76e1f188fadbb91451a161c9f5333 --- /dev/null +++ b/pool/shard010/JavaScript/0067229_websockets.js @@ -0,0 +1,170 @@ +import { Meteor } from 'meteor/meteor'; +import { AppStatus, AppStatusUtils } from '@rocket.chat/apps-engine/definition/AppStatus'; + +export const AppEvents = Object.freeze({ + APP_ADDED: 'app/added', + APP_REMOVED: 'app/removed', + APP_UPDATED: 'app/updated', + APP_STATUS_CHANGE: 'app/statusUpdate', + APP_SETTING_UPDATED: 'app/settingUpdated', + COMMAND_ADDED: 'command/added', + COMMAND_DISABLED: 'command/disabled', + COMMAND_UPDATED: 'command/updated', + COMMAND_REMOVED: 'command/removed', +}); + +export class AppServerListener { + constructor(orch, engineStreamer, clientStreamer, received) { + this.orch = orch; + this.engineStreamer = engineStreamer; + this.clientStreamer = clientStreamer; + this.received = received; + + this.engineStreamer.on(AppEvents.APP_ADDED, this.onAppAdded.bind(this)); + this.engineStreamer.on(AppEvents.APP_STATUS_CHANGE, this.onAppStatusUpdated.bind(this)); + this.engineStreamer.on(AppEvents.APP_SETTING_UPDATED, this.onAppSettingUpdated.bind(this)); + this.engineStreamer.on(AppEvents.APP_REMOVED, this.onAppRemoved.bind(this)); + this.engineStreamer.on(AppEvents.APP_UPDATED, this.onAppUpdated.bind(this)); + this.engineStreamer.on(AppEvents.COMMAND_ADDED, this.onCommandAdded.bind(this)); + this.engineStreamer.on(AppEvents.COMMAND_DISABLED, this.onCommandDisabled.bind(this)); + this.engineStreamer.on(AppEvents.COMMAND_UPDATED, this.onCommandUpdated.bind(this)); + this.engineStreamer.on(AppEvents.COMMAND_REMOVED, this.onCommandRemoved.bind(this)); + } + + async onAppAdded(appId) { + await this.orch.getManager().loadOne(appId); + this.clientStreamer.emit(AppEvents.APP_ADDED, appId); + } + + async onAppStatusUpdated({ appId, status }) { + this.received.set(`${ AppEvents.APP_STATUS_CHANGE }_${ appId }`, { appId, status, when: new Date() }); + + if (AppStatusUtils.isEnabled(status)) { + await this.orch.getManager().enable(appId); + this.clientStreamer.emit(AppEvents.APP_STATUS_CHANGE, { appId, status }); + } else if (AppStatusUtils.isDisabled(status)) { + await this.orch.getManager().disable(appId, AppStatus.MANUALLY_DISABLED === status); + this.clientStreamer.emit(AppEvents.APP_STATUS_CHANGE, { appId, status }); + } + } + + async onAppSettingUpdated({ appId, setting }) { + this.received.set(`${ AppEvents.APP_SETTING_UPDATED }_${ appId }_${ setting.id }`, { appId, setting, when: new Date() }); + + await this.orch.getManager().getSettingsManager().updateAppSetting(appId, setting); + this.clientStreamer.emit(AppEvents.APP_SETTING_UPDATED, { appId }); + } + + async onAppUpdated(appId) { + this.received.set(`${ AppEvents.APP_UPDATED }_${ appId }`, { appId, when: new Date() }); + + const storageItem = await this.orch.getStorage().retrieveOne(appId); + + await this.orch.getManager().update(storageItem.zip); + this.clientStreamer.emit(AppEvents.APP_UPDATED, appId); + } + + async onAppRemoved(appId) { + await this.orch.getManager().remove(appId); + this.clientStreamer.emit(AppEvents.APP_REMOVED, appId); + } + + async onCommandAdded(command) { + this.clientStreamer.emit(AppEvents.COMMAND_ADDED, command); + } + + async onCommandDisabled(command) { + this.clientStreamer.emit(AppEvents.COMMAND_DISABLED, command); + } + + async onCommandUpdated(command) { + this.clientStreamer.emit(AppEvents.COMMAND_UPDATED, command); + } + + async onCommandRemoved(command) { + this.clientStreamer.emit(AppEvents.COMMAND_REMOVED, command); + } +} + +export class AppServerNotifier { + constructor(orch) { + this.engineStreamer = new Meteor.Streamer('apps-engine', { retransmit: false }); + this.engineStreamer.serverOnly = true; + this.engineStreamer.allowRead('none'); + this.engineStreamer.allowEmit('all'); + this.engineStreamer.allowWrite('none'); + + // This is used to broadcast to the web clients + this.clientStreamer = new Meteor.Streamer('apps', { retransmit: false }); + this.clientStreamer.serverOnly = true; + this.clientStreamer.allowRead('all'); + this.clientStreamer.allowEmit('all'); + this.clientStreamer.allowWrite('none'); + + this.received = new Map(); + this.listener = new AppServerListener(orch, this.engineStreamer, this.clientStreamer, this.received); + } + + async appAdded(appId) { + this.engineStreamer.emit(AppEvents.APP_ADDED, appId); + this.clientStreamer.emit(AppEvents.APP_ADDED, appId); + } + + async appRemoved(appId) { + this.engineStreamer.emit(AppEvents.APP_REMOVED, appId); + this.clientStreamer.emit(AppEvents.APP_REMOVED, appId); + } + + async appUpdated(appId) { + if (this.received.has(`${ AppEvents.APP_UPDATED }_${ appId }`)) { + this.received.delete(`${ AppEvents.APP_UPDATED }_${ appId }`); + return; + } + + this.engineStreamer.emit(AppEvents.APP_UPDATED, appId); + this.clientStreamer.emit(AppEvents.APP_UPDATED, appId); + } + + async appStatusUpdated(appId, status) { + if (this.received.has(`${ AppEvents.APP_STATUS_CHANGE }_${ appId }`)) { + const details = this.received.get(`${ AppEvents.APP_STATUS_CHANGE }_${ appId }`); + if (details.status === status) { + this.received.delete(`${ AppEvents.APP_STATUS_CHANGE }_${ appId }`); + return; + } + } + + this.engineStreamer.emit(AppEvents.APP_STATUS_CHANGE, { appId, status }); + this.clientStreamer.emit(AppEvents.APP_STATUS_CHANGE, { appId, status }); + } + + async appSettingsChange(appId, setting) { + if (this.received.has(`${ AppEvents.APP_SETTING_UPDATED }_${ appId }_${ setting.id }`)) { + this.received.delete(`${ AppEvents.APP_SETTING_UPDATED }_${ appId }_${ setting.id }`); + return; + } + + this.engineStreamer.emit(AppEvents.APP_SETTING_UPDATED, { appId, setting }); + this.clientStreamer.emit(AppEvents.APP_SETTING_UPDATED, { appId }); + } + + async commandAdded(command) { + this.engineStreamer.emit(AppEvents.COMMAND_ADDED, command); + this.clientStreamer.emit(AppEvents.COMMAND_ADDED, command); + } + + async commandDisabled(command) { + this.engineStreamer.emit(AppEvents.COMMAND_DISABLED, command); + this.clientStreamer.emit(AppEvents.COMMAND_DISABLED, command); + } + + async commandUpdated(command) { + this.engineStreamer.emit(AppEvents.COMMAND_UPDATED, command); + this.clientStreamer.emit(AppEvents.COMMAND_UPDATED, command); + } + + async commandRemoved(command) { + this.engineStreamer.emit(AppEvents.COMMAND_REMOVED, command); + this.clientStreamer.emit(AppEvents.COMMAND_REMOVED, command); + } +} diff --git a/pool/shard010/JavaScript/0067232_LoginFactory.js b/pool/shard010/JavaScript/0067232_LoginFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..64708fdf86a8118ce49c14b56a38fb4e6fcc863a --- /dev/null +++ b/pool/shard010/JavaScript/0067232_LoginFactory.js @@ -0,0 +1,27 @@ +indexApp.factory('loginFactory', function($http){ + var factory = {}; + + factory.userlogin = function(login){ + var code_arr = { + username : login.username, + password : login.password + }; + + var promise = $http({ + url:'./Functions/Auth/Login.php', + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + transformRequest: function(obj) { + var str = []; + for(var p in obj) + str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); + return str.join("&"); + }, + data : code_arr + }) + + return promise; + }; + + return factory; +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067234_widget-base-ie.js b/pool/shard010/JavaScript/0067234_widget-base-ie.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb65162e2b5f7b67fb24e7a0e82be20462c6079 --- /dev/null +++ b/pool/shard010/JavaScript/0067234_widget-base-ie.js @@ -0,0 +1,55 @@ +/* +YUI 3.5.0 (build 5089) +Copyright 2012 Yahoo! Inc. All rights reserved. +Licensed under the BSD License. +http://yuilibrary.com/license/ +*/ +YUI.add('widget-base-ie', function(Y) { + +/** + * IE specific support for the widget-base module. + * + * @module widget-base-ie + */ +var BOUNDING_BOX = "boundingBox", + CONTENT_BOX = "contentBox", + HEIGHT = "height", + OFFSET_HEIGHT = "offsetHeight", + EMPTY_STR = "", + IE = Y.UA.ie, + heightReallyMinHeight = IE < 7, + bbTempExpanding = Y.Widget.getClassName("tmp", "forcesize"), + contentExpanded = Y.Widget.getClassName("content", "expanded"); + +// TODO: Ideally we want to re-use the base _uiSizeCB impl +Y.Widget.prototype._uiSizeCB = function(expand) { + + var bb = this.get(BOUNDING_BOX), + cb = this.get(CONTENT_BOX), + borderBoxSupported = this._bbs; + + if (borderBoxSupported === undefined) { + this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get("ownerDocument").get("compatMode") != "BackCompat"); + } + + if (borderBoxSupported) { + cb.toggleClass(contentExpanded, expand); + } else { + if (expand) { + if (heightReallyMinHeight) { + bb.addClass(bbTempExpanding); + } + + cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT)); + + if (heightReallyMinHeight) { + bb.removeClass(bbTempExpanding); + } + } else { + cb.setStyle(HEIGHT, EMPTY_STR); + } + } +}; + + +}, '3.5.0' ,{requires:['widget-base']}); diff --git a/pool/shard010/JavaScript/0067236_application-v10.js b/pool/shard010/JavaScript/0067236_application-v10.js new file mode 100644 index 0000000000000000000000000000000000000000..abac787e13ff2d833809e8c6d86ef534a6a653e9 --- /dev/null +++ b/pool/shard010/JavaScript/0067236_application-v10.js @@ -0,0 +1,148 @@ +'use strict'; + +angular.module( 'dv1' ) + +// common data service +.factory( 'application', [function() { + // gender handling for natural language + const PRONOUN = { + G: { + they: 'they', + their: 'their', + them: 'them', + your: 'their' + }, + F: { + they: 'she', + their: 'her', + them: 'her', + your: 'her' + }, + M: { + they: 'he', + their: 'his', + them: 'him', + your: 'his' + } + }; + const GENDER = { + F: 'Female', + G: 'Unknown', + M: 'Male', + // keys + FEMALE: 'F', + GENERIC: 'G', + MALE: 'M', + // regexes + FEMININE: /Woman|Female|mother|daughter|sister|neice|aunt|wife|girl/i, + MASCULINE: /Man|Male|father|son|brother|nephew|uncle|husband|boy/i, + }; + + + let data = {}; + data.respondent = { + name: { + short: 'the respondent', + shortCap: 'The respondent' + }, + pronoun: angular.copy( PRONOUN.G ) + }; + data.aggrieved = { + name: { + short: 'the aggrieved', + shortCap: 'The aggrieved' + }, + confidential: { + address: true, + contact: true + }, + pronoun: angular.copy( PRONOUN.G ), + relationship: { + type: {} + }, + children: [{ + confidential: { + address: true + } + }], + associates: [{ + confidential: { + address: true + } + }] + }; + data.aggrieved.pronoun.you = data.aggrieved.name.short; + data.aggrieved.pronoun.your = data.aggrieved.pronoun.my = data.aggrieved.name.short + '’s'; + data.applicant = { + name: { + short: 'the applicant', + shortCap: 'The applicant' + }, + confidential: { + address: true + }, + pronoun: angular.copy( PRONOUN.G ), + relationship: {} + }; + + + // set gender based on "idenfied as" + // example: setGender( vm.aggrieved, 'their wife' ); + // wife is in GENDER.FEMININE so will set them as female. + this.setGender = function( party, relationship ) { + relationship = relationship || party.gender; + var gender = GENDER.GENERIC; + if ( GENDER.FEMININE.test( relationship )) { + gender = GENDER.FEMALE; + } else if ( GENDER.MASCULINE.test( relationship )) { + gender = GENDER.MALE; + } + + party.gender = angular.copy( GENDER[ gender ]); + party.pronoun = angular.copy( PRONOUN[ gender ]); + }; + + + this.saveAggrieved = function( aggrievedData, isApplicant ) { + data.aggrieved = aggrievedData; + data.aggrievedIsApplicant = isApplicant === true; + data.aggrieved.name.short = data.aggrieved.name.given || 'the aggrieved'; + data.aggrieved.name.shortCap = data.aggrieved.name.given || 'The aggrieved'; + if ( isApplicant ) { + this.saveApplicant( aggrievedData ); + data.aggrieved.pronoun.you = 'you (the aggrieved)'; + data.aggrieved.pronoun.they = 'you'; + data.aggrieved.pronoun.your = 'your'; + data.aggrieved.pronoun.my = 'my'; + data.aggrieved.pronoun.me = 'me'; + } else { + data.aggrieved.pronoun.you = data.aggrieved.name.short + ' (the aggrieved)'; + data.aggrieved.pronoun.your = angular.copy( PRONOUN[ GENDER[ data.aggrieved.gender.toUpperCase() ] || GENDER.GENERIC ].your ); + data.aggrieved.pronoun.my = data.aggrieved.pronoun.your; + data.aggrieved.pronoun.me = data.aggrieved.name.short; + if ( data.aggrieved.name.given ) { + data.aggrieved.pronoun.your = data.aggrieved.name.given + '’s'; + } + } + }; + this.saveApplicant = function( applicantData ) { + data.applicant = applicantData; + data.applicant.name.short = data.applicant.name.given || 'the applicant'; + data.applicant.name.shortCap = data.applicant.name.given || 'The applicant'; + }; + this.saveRespondent = function( respondentData ) { + data.respondent = respondentData; + data.respondent.name.short = data.respondent.name.given || 'the respondent'; + data.respondent.name.shortCap = data.respondent.name.given || 'The respondent'; + }; + + this.saveTemporaryProtection = function( tpoData ) { + data.temporaryProtection = tpoData; + }; + + this.getData = function() { + return data; + }; + + return this; +}]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067244_actions.spec.js b/pool/shard010/JavaScript/0067244_actions.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4b4dc6fb63255653a4c29a1c6904c573d374803a --- /dev/null +++ b/pool/shard010/JavaScript/0067244_actions.spec.js @@ -0,0 +1,72 @@ +import configureMockStore from 'redux-mock-store'; +import thunk from 'redux-thunk'; +import ReduxPromise from 'redux-promise'; +import expect from 'expect'; + +import * as actions from '../../actions/index'; + +const middlewares = [thunk, ReduxPromise]; +const mockStore = configureMockStore(middlewares); + +const store = mockStore({ + channels: { + list: [], + selected: null, + }, + tone: {}, +}); + +describe('action creators', () => { + + afterEach(() => { + store.clearActions(); + }); + + it('creates GET_CHANNELS action when getChannels is called', () => { + return store.dispatch(actions.getChannels()) + .then(() => { + const createdActions = store.getActions(); + expect(createdActions[0].type).toEqual(actions.GET_CHANNELS); + }); + }); + + it('creates SET_CHANNEL action when setChannel is called', () => { + return store.dispatch(actions.setChannel('someChannel')) + .then(() => { + const createdActions = store.getActions(); + expect(createdActions[0].type).toEqual(actions.SET_CHANNEL); + }); + }); + + it('creates UNSET_CHANNEL action when unsetChannel is called', () => { + const expectedAction = { + type: actions.UNSET_CHANNEL, + payload: null, + }; + expect(actions.unsetChannel()).toEqual(expectedAction); + }); + + it('creates GET_TONE action when getTone is called', () => { + return store.dispatch(actions.getTone()) + .then(() => { + const createdActions = store.getActions(); + expect(createdActions[0].type).toEqual(actions.GET_TONE); + }); + }); + + it('creates UNSET_TONE action when unsetTone is called', () => { + const expectedAction = { + type: actions.UNSET_TONE, + payload: null, + }; + expect(actions.unsetTone()).toEqual(expectedAction); + }); + + it('creates GET_LONGTERMTONE action when getLongTermTone is called', () => { + return store.dispatch(actions.getLongTermTone()) + .then(() => { + const createdActions = store.getActions(); + expect(createdActions[0].type).toEqual(actions.GET_LONGTERMTONE); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067245_CardContent.js b/pool/shard010/JavaScript/0067245_CardContent.js new file mode 100644 index 0000000000000000000000000000000000000000..d29394829394ba94fa01309a02e6616f95ddb0a3 --- /dev/null +++ b/pool/shard010/JavaScript/0067245_CardContent.js @@ -0,0 +1,85 @@ +import cx from 'clsx' +import _ from 'lodash' +import PropTypes from 'prop-types' +import React from 'react' + +import { + childrenUtils, + createShorthand, + customPropTypes, + getElementType, + getUnhandledProps, + SUI, + useKeyOnly, + useTextAlignProp, +} from '../../lib' +import CardDescription from './CardDescription' +import CardHeader from './CardHeader' +import CardMeta from './CardMeta' + +/** + * A card can contain blocks of content or extra content meant to be formatted separately from the main content. + */ +function CardContent(props) { + const { children, className, content, description, extra, header, meta, textAlign } = props + + const classes = cx(useKeyOnly(extra, 'extra'), useTextAlignProp(textAlign), 'content', className) + const rest = getUnhandledProps(CardContent, props) + const ElementType = getElementType(CardContent, props) + + if (!childrenUtils.isNil(children)) { + return ( + + {children} + + ) + } + if (!childrenUtils.isNil(content)) { + return ( + + {content} + + ) + } + + return ( + + {createShorthand(CardHeader, (val) => ({ content: val }), header, { autoGenerateKey: false })} + {createShorthand(CardMeta, (val) => ({ content: val }), meta, { autoGenerateKey: false })} + {createShorthand(CardDescription, (val) => ({ content: val }), description, { + autoGenerateKey: false, + })} + + ) +} + +CardContent.propTypes = { + /** An element type to render as (string or function). */ + as: PropTypes.elementType, + + /** Primary content. */ + children: PropTypes.node, + + /** Additional classes. */ + className: PropTypes.string, + + /** Shorthand for primary content. */ + content: customPropTypes.contentShorthand, + + /** Shorthand for CardDescription. */ + description: customPropTypes.itemShorthand, + + /** A card can contain extra content meant to be formatted separately from the main content. */ + extra: PropTypes.bool, + + /** Shorthand for CardHeader. */ + header: customPropTypes.itemShorthand, + + /** Shorthand for CardMeta. */ + meta: customPropTypes.itemShorthand, + + /** A card content can adjust its text alignment. */ + textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')), +} + +export default CardContent diff --git a/pool/shard010/JavaScript/0067249_hits.js b/pool/shard010/JavaScript/0067249_hits.js new file mode 100644 index 0000000000000000000000000000000000000000..852ace8ecdd4b5273e5d5bcbe5224ba6921aee51 --- /dev/null +++ b/pool/shard010/JavaScript/0067249_hits.js @@ -0,0 +1,159 @@ +// JavaScript for hits.php. Requires jQuery + +jQuery(document).ready(function($) { + var tablename="{$_GET['table']}"; + // create a div for name popup + $("body").append(""); + + $("h2.table").each(function() { + $(this).append(" Show Table"); + }); + + $("table").not("#hitCountertbl").addClass('tablesorter'); // attach class tablesorter to all except our counter + $("#memberHits, #otherMemberHits, #memberNot").tablesorter(); + $("#lamphost table").tablesorter({ sortList: [[2,1]], headers: { 1: {sorter: "currency"} } } ); + $("#OScnt table").tablesorter({ sortList:[[1,1]] , headers: { 1: {sorter: "currency"}, 2: {sorter: "currency"}}}); + $("#browserCnt table").tablesorter({ sortList:[[1,1]], headers: { 1: {sorter: "currency"}, 2: {sorter: "currency"}} }); + + $("div.table").hide(); + + if(tablename != "") { + $("div[name='"+tablename+"']").show(); + $("div[name='"+tablename+"']").prev().children().first().text("Hide Table"); + } + $(".showhide").css("cursor", "pointer"); + + var flip = 0; + //$(".showhide").toggle(function() { + + $(".showhide").click(function() { + if(flip++ % 2 == 0) { + tablename = $(this).parent().next().attr("name"); + var tbl = $("#"+tablename); // The
    "+ + "You can toggle the display of the ID "+ + "
    "+ + "Your can taggle the display of the Webmaster "+ + " "+ + "

    "; + + $("#ipAgentHits").before(mlinetext); + + // Ip Agent Hits. + // Hide all ids of zero + $(".noId").hide(); + + // Button to toggle between all and members only in Ip Agent Hits + // table + $("#hideShowNonMembers").toggle(function() { + $(".noId").not("[name='blp']").show(); + $(".botmsg").css("visibility", "visible"); + }, function() { + $(".noId").hide(); + $(".botmsg").css("visibility", "hidden"); + }); + + // Hide the ID field in Ip Agent Hits table + $("#ipAgentHits td:nth-child(3)").hide(); + $("#ipAgentHits thead th:nth-child(3)").hide(); + + // Button to toggle between no ID and showing ID in Ip Agent Hits + // table + $("#hideShowIdField").toggle(function() { + $("#ipAgentHits td:nth-child(3)").show(); + $("#ipAgentHits thead th:nth-child(3)").show(); + }, function() { + $("#ipAgentHits td:nth-child(3)").hide(); + $("#ipAgentHits thead th:nth-child(3)").hide(); + }); + + // Hide the webmaster (me) in the Ip Agent Hits table + $(".blp").hide(); + + // Button to toggle between hide and show of Webmaster in Ip Agents + // Hits Table + $("#hideShowWebmaster").toggle(function() { + $(".blp").show(); + }, function() { + $(".blp").hide(); + }); + break; + + case "ipHits": + $("#ipHits").tablesorter(); // {sortList:[[2,1]] } + // Set up Ip Hits + $("#ipHits").before("

    Move the mouse over ID to see the member's name.
    \ + Click to toggle all or members-only \ +

    "); + + $("#ipHits tbody tr td:nth-child(2)").hover(function(e) { + var name = "Non Member"; + if($(this).text() != '0') { + name = $("#Id_"+$(this).text()).text(); + } + $("#popup").text(name).css({ top: e.pageY+20, left: e.pageX }).show(); + }, function() { + $("#popup").hide(); + }); + + // Hide and mark all IDs that are zero in the Ip Hits table + $("#ipHits tbody tr td:nth-child(2)").each(function() { + var \$this = $(this); + if(\$this.text() == '0') \$this.parent().addClass('ipHitsNoId').hide(); + }); + + // Members only button toggles members and all in Ip Hits table + $("#membersonly").toggle(function() { + $(".ipHitsNoId").show(); + }, function() { + $(".ipHitsNoId").hide(); + }); + break; + } // end of switch + $("body").css("cursor", "default"); + t.css("cursor", "pointer"); + }); + } + } else { + $(this).parent().next().hide(); + $(this).text("Show Table"); + }); +}); + diff --git a/pool/shard010/JavaScript/0067251_memory.js b/pool/shard010/JavaScript/0067251_memory.js new file mode 100644 index 0000000000000000000000000000000000000000..91145d65eef007cbdf5b9b109bfb4d805e4033c9 --- /dev/null +++ b/pool/shard010/JavaScript/0067251_memory.js @@ -0,0 +1,196 @@ +function getRandomInt(min, max) { + return Math.floor(Math.random() * (max - min)) + min; +} + + +function MemoryGame(mainDivId, imagesArray, rows, repetitions) { + console.log("MemoryGame.constructor()") + + this.mainDivId = mainDivId; + this.imagesArray = imagesArray; + if (!repetitions) { + this.repetitions = 2 + } else { + this.repetitions = repetitions; + } + + if (!rows) { + //var totalCards = this.repetitions * imageArray.length; + // var tryRows = 2; + this.rows = 2; + } else { + this.rows = rows; + } + + this.firstCardOpenned = undefined; + this.secondCardOpenned = undefined; + +}; + +MemoryGame.prototype.start = function() { + this.mountTable(); + this.bindEvents(); +}; + +MemoryGame.prototype.mountTable = function() { + console.log("MemoryGame.createTable()"); + + var totalCards = this.repetitions * this.imagesArray.length; + var elementsByRow = totalCards / this.rows; + this.positions = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + this.positions[i] = Array(elementsByRow); + for (var j = 0; j < elementsByRow; j++) { + var position = new CardPosition(this.mainDivId, i, j); + this.positions[i][j] = position; + } + } + console.log(this.positions); + + for (var i = 0; i < totalCards; i++) { + var inserted = false; + + while (!inserted) { + var indexI = getRandomInt(0, this.rows); + var indexJ = getRandomInt(0, elementsByRow); + var position = this.positions[indexI][indexJ]; + var cardKey = Math.floor(i/this.repetitions); + + if (position.card == undefined) { + position.card = new Card(position, + this.imagesArray[cardKey], + cardKey); + inserted = true; + } + } + } +}; + +MemoryGame.prototype.bindEvents = function() { + $(document).on('click','.card_container', $.proxy( + function(event) { + this.openCard($(event.currentTarget).data("cardObject")); + + }, this)); +}; + +MemoryGame.prototype.openCard = function(card) { + console.log("MemoryGame.openCard()") + + if (this.firstCardOpenned == card) { + return; //Double click on the same card + } + + if (this.firstCardOpenned == undefined) { + this.firstCardOpenned = card; + card.open(); + } else if (this.secondCardOpenned == undefined) { + this.secondCardOpenned = card; + card.open(); + + if (this.firstCardOpenned.key == this.secondCardOpenned.key) { + this.rightMove(); + } else { + this.wrongMove(); + } + } +}; + +MemoryGame.prototype.rightMove = function() { + console.log("MemoryGame.rightMove()"); + + setTimeout($.proxy ( + function() { + this.firstCardOpenned.hide(); + this.secondCardOpenned.hide(); + }, this), + 1000); + + setTimeout($.proxy ( + function() { + this.firstCardOpenned.close(); + this.secondCardOpenned.close(); + this.firstCardOpenned = undefined; + this.secondCardOpenned = undefined; + }, this), + 1100); + +}; + +MemoryGame.prototype.wrongMove = function() { + console.log("MemoryGame.wrongMove()"); + + setTimeout($.proxy ( + function() { + this.firstCardOpenned.close(); + this.secondCardOpenned.close(); + this.firstCardOpenned = undefined; + this.secondCardOpenned = undefined; + }, this), + 1000); +}; + +function CardPosition(mainDivId, i,j, angle) { + console.log("CardPosition.constructor()") + + this.mainDivId = mainDivId; + this.i = i; + this.j = j; + this.card = undefined; + + this.create(); +}; + +CardPosition.prototype.create = function() { + console.log("CardPosition.create()") + this.divId = "pos_" + this.i + "x" + this.j; + var innerHTML = "
    " + this.divId = "#" + this.divId; + + $(this.mainDivId).append(innerHTML); +}; + +function Card(position, image, key) { + console.log("Card.constructor()") + + this.position = position; + this.image = image; + this.key = key; + + this.create(); +}; + +Card.prototype.create = function() { + console.log("Card.create()") + + var innerHTML = "
    \ +
    \ +
    \ + \ +
    \ +
    "; + + $(this.position.divId).append(innerHTML); + $(this.position.divId).data("cardObject", this); +}; + +Card.prototype.open = function() { + console.log("Card.open()") + + $(this.position.divId).children('.card').addClass('active'); +}; + +Card.prototype.hide = function() { + console.log("Card.open()") + + $(this.position.divId).children('.card').css({ + 'opacity':'0', + 'cursor':'default' + }); +}; + +Card.prototype.close = function() { + console.log("Card.open()") + + $(this.position.divId).children('.card').removeClass('active'); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067253_ColumnListItemRenderer-dbg.js b/pool/shard010/JavaScript/0067253_ColumnListItemRenderer-dbg.js new file mode 100644 index 0000000000000000000000000000000000000000..8bce71aca1b6cc5cfc81be0d0a3634007477605c --- /dev/null +++ b/pool/shard010/JavaScript/0067253_ColumnListItemRenderer-dbg.js @@ -0,0 +1,307 @@ +/*! + * 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. + */ + +sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', './ListRenderer', 'sap/ui/core/Renderer'], + function(jQuery, ListItemBaseRenderer, ListRenderer, Renderer) { + "use strict"; + + /** + * ColumnListItem renderer. + * @namespace + */ + var ColumnListItemRenderer = Renderer.extend(ListItemBaseRenderer); + + ColumnListItemRenderer.render = function(rm, oLI) { + var oTable = oLI.getTable(); + if (!oTable) { + return; + } + + ListItemBaseRenderer.render.apply(this, arguments); + + if (oLI.getVisible() && oTable.hasPopin()) { + this.renderPopin(rm, oLI, oTable); + } + }; + + // render type highlight always within a cell + ColumnListItemRenderer.renderHighlight = function(rm, oLI) { + rm.write(''); + }; + + // render type content always within a cell + ColumnListItemRenderer.renderType = function(rm, oLI) { + rm.write(''); + }; + + // wrap mode content with a cell + ColumnListItemRenderer.renderModeContent = function(rm, oLI) { + rm.write(''); + }; + + // ColumnListItem does not respect counter property of the LIB + ColumnListItemRenderer.renderCounter = function(rm, oLI) { + }; + + // Returns aria accessibility role + ColumnListItemRenderer.getAriaRole = function(oLI) { + return ""; + }; + + /** + * Renders the HTML for the given control, using the provided + * {@link sap.ui.core.RenderManager}. + * + * @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 + */ + ColumnListItemRenderer.renderLIAttributes = function(rm, oLI) { + rm.addClass("sapMListTblRow"); + var vAlign = oLI.getVAlign(); + if (vAlign != sap.ui.core.VerticalAlign.Inherit) { + rm.addClass("sapMListTblRow" + vAlign); + } + }; + + + /** + * Overwriting hook method of ListItemBase + * + * @public + * + * @param {sap.ui.core.RenderManager} rm RenderManager + * @param {sap.m.ListItemBase} oLI List item + */ + ColumnListItemRenderer.renderLIContentWrapper = function(rm, oLI) { + var oTable = oLI.getTable(); + if (!oTable) { + return; + } + + var aColumns = oTable.getColumns(true), + aCells = oLI.getCells(); + + // remove cloned headers + oLI._destroyClonedHeaders(); + + aColumns.forEach(function(oColumn, i) { + var cls, + oHeader, + bRenderCell = true, + oCell = aCells[oColumn.getInitialOrder()]; + + if (!oCell || !oColumn.getVisible() || oColumn.isPopin()) { + // update the visible index of the column + oColumn.setIndex(-1); + return; + } + + rm.write(""); + + if (bRenderCell) { + this.applyAriaLabelledBy(oHeader, oCell); + rm.renderControl(oColumn.applyAlignTo(oCell)); + } + + rm.write(""); + }, this); + }; + + ColumnListItemRenderer.applyAriaLabelledBy = function(oHeader, oCell) { + if (oCell) { + oCell.removeAssociation("ariaLabelledBy", oCell.data("ariaLabelledBy") || undefined, true); + } + + /* add the header as an aria-labelled by association for the cells */ + /* only set the header text to the aria-labelled association if the header is a textual control and is visible */ + if (oHeader && + oHeader.getText && + oCell.getAriaLabelledBy && + oHeader.getVisible()) { + + // suppress the invalidation during the rendering + oCell.addAssociation("ariaLabelledBy", oHeader, true); + oCell.data("ariaLabelledBy", oHeader.getId()); + } + }; + + /** + * Renders pop-ins for Table Rows + * + * @private + * + * @param {sap.ui.core.RenderManager} rm RenderManager + * @param {sap.m.ListItemBase} oLI List item + * @param {sap.m.Table} oTable Table control + */ + ColumnListItemRenderer.renderPopin = function(rm, oLI, oTable) { + // remove existing popin first + oLI.removePopin(); + + // popin row + rm.write(""); + + this.renderHighlight(rm, oLI); + + // cell + rm.write("
    "); + + var aCells = oLI.getCells(), + aColumns = oTable.getColumns(true); + + aColumns.forEach(function(oColumn) { + if (!oColumn.getVisible() || !oColumn.isPopin()) { + return; + } + + var oCell = aCells[oColumn.getInitialOrder()], + oHeader = oColumn.getHeader(); + + if (!oHeader && !oCell) { + return; + } + + var sStyleClass = oColumn.getStyleClass(), + sPopinDisplay = oColumn.getPopinDisplay(); + + /* row start */ + rm.write(""); + + /* header cell */ + if (oHeader && sPopinDisplay != sap.m.PopinDisplay.WithoutHeader) { + rm.write(""); + oHeader = oHeader.clone(); + oColumn.addDependent(oHeader); + oLI._addClonedHeader(oHeader); + oColumn.applyAlignTo(oHeader, "Begin"); + rm.renderControl(oHeader); + rm.write("
    "); + + /* separator cell */ + rm.write("
    :
    "); + } + + /* value cell */ + if (oCell) { + rm.write(""); + oColumn.applyAlignTo(oCell, "Begin"); + this.applyAriaLabelledBy(oHeader, oCell); + rm.renderControl(oCell); + rm.write(""); + } + + /* row end */ + rm.write(""); + }, this); + + rm.write("
    "); + }; + + /** + * Overwriting hook method of ListItemBase. + * + * @param {sap.ui.core.RenderManager} rm RenderManager + * @param {sap.m.ListItemBase} [oLI] List item + */ + ColumnListItemRenderer.addLegacyOutlineClass = function(rm, oLI) { + }; + + return ColumnListItemRenderer; + +}, /* bExport= */ true); diff --git a/pool/shard010/JavaScript/0067254_socketio.test.js b/pool/shard010/JavaScript/0067254_socketio.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9357da1c565b27a8706262ba579d574381914264 --- /dev/null +++ b/pool/shard010/JavaScript/0067254_socketio.test.js @@ -0,0 +1,28 @@ +import socketio from 'feathers-socketio'; +import io from 'socket.io-client'; +import baseTests from 'feathers-commons/lib/test/client'; + +import app from '../fixture'; +import feathers from '../../src/client'; + +describe('Socket.io connector', function () { + const socket = io('http://localhost:9988'); + const client = feathers() + .configure(feathers.socketio(socket)); + + before(function (done) { + this.server = app(function () { + this.configure(socketio()); + }).listen(9988, done); + }); + + after(function (done) { + socket.once('disconnect', () => { + this.server.close(); + done(); + }); + socket.disconnect(); + }); + + baseTests(client, 'todos'); +}); diff --git a/pool/shard010/JavaScript/0067255_api.js b/pool/shard010/JavaScript/0067255_api.js new file mode 100644 index 0000000000000000000000000000000000000000..9b4825466fd3eb87cae0f91c5829f983bd3f48c5 --- /dev/null +++ b/pool/shard010/JavaScript/0067255_api.js @@ -0,0 +1,168 @@ +const Api = new Restivus({ + useDefaultAuth: true, + apiPath: 'api/lg/', + prettyJson: true, + enableCors: false, +}) + +function errorResponse(error, statusCode = 500) { + return { + statusCode, + body: { + status: 'fail', + message: `${error.name}::${error.message}` + }, + } +} + +function successResponse(data, statusCode = 200) { + return { + statusCode, + body: Object.assign({}, { + status: 'success', + }, data) + } +} + +const validRoomName = new RegExp('^[0-9a-zA-Z-_.]+$', 'i') + +Api.addRoute('rooms', {authRequired: true}, { + post() { + try { + const { + userId, + bodyParams: { + name, + topic, + members, + }, + } = this + if (!RocketChat.authz.hasPermission(userId, 'create-c')) { + throw new Meteor.Error('insufficient-permissions', 'you do not have permission to do this') + } + if (!validRoomName.test(name)) { + throw new Meteor.Error('invalid-room-name', `${name} is not a valid room name`) + } + /* eslint-disable prefer-arrow-callback */ + const result = Meteor.runAsUser(userId, function () { + const {rid} = Meteor.call('createChannel', name, members) + const user = RocketChat.models.Users.findOneById(userId) + RocketChat.saveRoomTopic(rid, topic, user) + return { + status: 'success', + room: { + rid, + name, + topic, + members, + }, + } + }) + return successResponse({result}) + } catch (err) { + console.error(err.stack) + RavenLogger.log(err) + return errorResponse(err) + } + }, +}) + +Api.addRoute('rooms/:name/join', {authRequired: true}, { + post() { + try { + const { + userId, + bodyParams: { + members, + }, + urlParams: {name}, + } = this + + if (!RocketChat.authz.hasPermission(userId, 'add-user-to-room')) { + throw new Meteor.Error('insufficient-permissions', 'you do not have permission to do this') + } + /* eslint-disable prefer-arrow-callback */ + const room = Meteor.runAsUser(this.userId, () => { + return RocketChat.models.Rooms.findOneByName(name) + }) + if (!room) { + throw new Meteor.Error('error-invalid-room', `there is no room named ${name}`) + } + const usersJoined = [] + const alreadyInRoom = [] + members.forEach(username => { + const rcUser = RocketChat.models.Users.findOneByUsername(username) + if (!rcUser) { + throw new Meteor.Error('error-invalid-username', `there is no user named ${username}`) + } + Meteor.runAsUser(rcUser._id, () => { + Meteor.call('joinRoom', room._id, (err, joined) => { + if (err) { + throw err + } + if (joined) { + usersJoined.push(username) + } else { + alreadyInRoom.push(username) + } + }) + }) + }) + return successResponse({result: {room: name, usersJoined, alreadyInRoom}}) + } catch (err) { + console.error(err.stack) + RavenLogger.log(err) + return errorResponse(err) + } + } +}) + +Api.addRoute('rooms/:name/send', {authRequired: true}, { + post() { + try { + const { + userId, + bodyParams: {msg}, + urlParams: {name}, + } = this + + /* eslint-disable prefer-arrow-callback */ + const result = Meteor.runAsUser(userId, function () { + const room = RocketChat.models.Rooms.findOneByName(name) + if (!room) { + throw new Meteor.Error('error-invalid-room', `there is no room named ${name}`) + } + return Meteor.call('sendMessage', {msg, rid: room._id}) + }) + return successResponse({result}) + } catch (err) { + console.error(err.stack) + RavenLogger.log(err) + return errorResponse(err) + } + } +}) + +Api.addRoute('rooms/:name', {authRequired: true}, { + delete() { + try { + const { + userId, + urlParams: {name}, + } = this + + const result = Meteor.runAsUser(userId, function () { + const room = RocketChat.models.Rooms.findOneByName(name) + if (!room) { + throw new Meteor.Error('error-invalid-room', `there is no room named ${name}`) + } + return Meteor.call('eraseRoom', room._id) + }) + return successResponse({result}) + } catch (err) { + console.error(err.stack) + RavenLogger.log(err) + return errorResponse(err) + } + } +}) diff --git a/pool/shard010/JavaScript/0067256_githubContributor.service.js b/pool/shard010/JavaScript/0067256_githubContributor.service.js new file mode 100644 index 0000000000000000000000000000000000000000..e774dbfe2c86537e32ea2eced7766bae3a0c9e2b --- /dev/null +++ b/pool/shard010/JavaScript/0067256_githubContributor.service.js @@ -0,0 +1,37 @@ +(function() { + 'use strict'; + + angular + .module('rapCypher') + .factory('githubContributor', githubContributor); + + /** @ngInject */ + function githubContributor($log, $http) { + var apiHost = 'https://api.github.com/repos/Swiip/generator-gulp-angular'; + + var service = { + apiHost: apiHost, + getContributors: getContributors + }; + + return service; + + function getContributors(limit) { + if (!limit) { + limit = 30; + } + + return $http.get(apiHost + '/contributors?per_page=' + limit) + .then(getContributorsComplete) + .catch(getContributorsFailed); + + function getContributorsComplete(response) { + return response.data; + } + + function getContributorsFailed(error) { + $log.error('XHR Failed for getContributors.\n' + angular.toJson(error.data, true)); + } + } + } +})(); diff --git a/pool/shard010/JavaScript/0067257_static-template.js b/pool/shard010/JavaScript/0067257_static-template.js new file mode 100644 index 0000000000000000000000000000000000000000..ee1a89fd546d977a15801b26a8bc303795857aa6 --- /dev/null +++ b/pool/shard010/JavaScript/0067257_static-template.js @@ -0,0 +1,130 @@ +/** + * Copyright 2018 The AMP HTML 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. + */ + +import {devAssert} from './log'; +import {map} from './core/types/object'; + +let htmlContainer; +let svgContainer; + +/** + * Creates the html helper for the doc. + * + * @param {!Element|!Document} nodeOrDoc + * @return {function(!Array):!Element} + */ +export function htmlFor(nodeOrDoc) { + const doc = nodeOrDoc.ownerDocument || nodeOrDoc; + if (!htmlContainer || htmlContainer.ownerDocument !== doc) { + htmlContainer = doc.createElement('div'); + } + + return html; +} + +/** + * Creates the svg helper for the doc. + * + * @param {!Element|!Document} nodeOrDoc + * @return {function(!Array):!Element} + */ +export function svgFor(nodeOrDoc) { + const doc = nodeOrDoc.ownerDocument || nodeOrDoc; + if (!svgContainer || svgContainer.ownerDocument !== svgContainer) { + svgContainer = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); + } + + return svg; +} + +/** + * A tagged template literal helper to generate static SVG trees. + * This must be used as a tagged template, ie + * + * ``` + * const circle = svg``; + * ``` + * + * Only the root element and its subtree will be returned. DO NOT use this to + * render subtree's with dynamic content, it WILL result in an error! + * + * @param {!Array} strings + * @return {!Element} + */ +function svg(strings) { + return createNode(svgContainer, strings); +} + +/** + * A tagged template literal helper to generate static DOM trees. + * This must be used as a tagged template, ie + * + * ``` + * const div = html`
    `; + * ``` + * + * Only the root element and its subtree will be returned. DO NOT use this to + * render subtree's with dynamic content, it WILL result in an error! + * + * @param {!Array} strings + * @return {!Element} + */ +function html(strings) { + return createNode(htmlContainer, strings); +} + +/** + * Helper used by html and svg string literal functions. + * @param {!Element} container + * @param {!Array} strings + * @return {!Element} + */ +function createNode(container, strings) { + devAssert(strings.length === 1, 'Improper html template tag usage.'); + container./*OK*/ innerHTML = strings[0]; + + const el = container.firstElementChild; + devAssert(el, 'No elements in template'); + devAssert(!el.nextElementSibling, 'Too many root elements in template'); + + // Clear to free memory. + container.removeChild(el); + + return el; +} + +/** + * Queries an element for all elements with a "ref" attribute, removing + * the attribute afterwards. + * Returns a named map of all ref elements. + * + * @param {!Element} root + * @return {!Object} + */ +export function htmlRefs(root) { + const elements = root.querySelectorAll('[ref]'); + const refs = map(); + + for (let i = 0; i < elements.length; i++) { + const element = elements[i]; + const ref = devAssert(element.getAttribute('ref'), 'Empty ref attr'); + element.removeAttribute('ref'); + devAssert(refs[ref] === undefined, 'Duplicate ref'); + refs[ref] = element; + } + + return refs; +} diff --git a/pool/shard010/JavaScript/0067264_util.js b/pool/shard010/JavaScript/0067264_util.js new file mode 100644 index 0000000000000000000000000000000000000000..a70315ddde1c497d878f8bbe549de3f9758bcde1 --- /dev/null +++ b/pool/shard010/JavaScript/0067264_util.js @@ -0,0 +1,58 @@ +/** + * Created by freedmand on 10/20/15. + */ + +Util = {}; + +// We need to store the dep, ready flag, and data for each call +Util.d_waitOns = {}; + +// This function returns a handle with a reactive ready function, which +// is what waitOn expects. waitOn will complete when the reactive function +// returns true. +Util.waitOnServer = function(name) { + // This prevents the waitOnServer call from being called multiple times + // and the resulting infinite loop. + if (this.d_waitOns[name] !== undefined && + this.d_waitOns[name].ready === true) { + return; + } + else { + this.d_waitOns[name] = {}; + } + var self = this; + // We need to store the dependency and the ready flag. + this.d_waitOns[name].dep = new Deps.Dependency(); + this.d_waitOns[name].ready = false; + + var callback = function(err, or) { + // The call has complete, so set the ready flag, notify the reactive + // function that we are ready, and store the data. + self.d_waitOns[name].ready = true; + self.d_waitOns[name].dep.changed(); + self.d_waitOns[name].data = (err || or); + }; + + var args = Array.prototype.slice.call(arguments) + args.push(callback); + + Meteor.call.apply(this, args); + + // The reactive handle that we are returning. + var handle = { + ready: function() { + self.d_waitOns[name].dep.depend(); + return self.d_waitOns[name].ready; + } + }; + return handle; +} + +// Retrieve the data that we stored in the async callback. +Util.getResponse = function(name) { + var data = this.d_waitOns[name].data; + // Clear out the data so a second call with the same name wont return + // the same data. + this.d_waitOns[name] = {}; + return data; +} \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067266_mustache.js b/pool/shard010/JavaScript/0067266_mustache.js new file mode 100644 index 0000000000000000000000000000000000000000..4d1e53beb79891a8af8c663eb109a78ce4a01ec2 --- /dev/null +++ b/pool/shard010/JavaScript/0067266_mustache.js @@ -0,0 +1,45 @@ +var engine; + +function render(path, str, data, callback) { + var mustache = engine || (engine = require('mustache')); + callback(null, mustache.render(str, data)); +} + +/** + * + * This function returns the rendertype as string. + * The rendertype is the type of input the renderer needs to render the template, + * + * These are the possible rendertypes + * - string + * - file + * + * @returns {String} + */ +function renderType() { + return 'string'; +} + +/** + * + * This function returns the possible extensions the template engine has to look for. + * + * @returns {Array} + */ +function extensions() { + return ['html']; +} + +/** + * + * This function returns if the rederer has caching support + * + * @returns {Boolean} + */ +function caches() { + return false; +} + +exports.extensions = extensions; +exports.render = render; +exports.renderType = renderType; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067267_Lines.js b/pool/shard010/JavaScript/0067267_Lines.js new file mode 100644 index 0000000000000000000000000000000000000000..3ec783ee7f8b0a16a028c3ef609b003e013ff729 --- /dev/null +++ b/pool/shard010/JavaScript/0067267_Lines.js @@ -0,0 +1,24 @@ +/* + Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. + Available via Academic Free License >= 2.1 OR the modified BSD license. + see: http://dojotoolkit.org/license for details +*/ + + +if(!dojo._hasResource["dojox.charting.plot2d.Lines"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. +dojo._hasResource["dojox.charting.plot2d.Lines"] = true; +dojo.provide("dojox.charting.plot2d.Lines"); + +dojo.require("dojox.charting.plot2d.Default"); + +dojo.declare("dojox.charting.plot2d.Lines", dojox.charting.plot2d.Default, { + // summary: + // A convenience constructor to create a typical line chart. + constructor: function(){ + // summary: + // Preset our default plot to be line-based. + this.opt.lines = true; + } +}); + +} diff --git a/pool/shard010/JavaScript/0067270_ma-tours-entry.js b/pool/shard010/JavaScript/0067270_ma-tours-entry.js new file mode 100644 index 0000000000000000000000000000000000000000..90179c5450bd97b5a5c6fd00054ba5af4b12d3be --- /dev/null +++ b/pool/shard010/JavaScript/0067270_ma-tours-entry.js @@ -0,0 +1,224 @@ +// MAToursEntryCtrl +ctrls.controller('MAToursEntryCtrl', ['$scope', '$state', '$stateParams', '$window', function ($scope, $state, $stateParams, $window) { + /* Định nghĩa biến toàn cục */ + $scope.data = {}; + $scope.variable = {}; + $scope.objEntry = {}; + $scope.objLocale = {}; + $scope.edtNotes = {}; + // Gán giá trị init + $scope.data.HasAuth = false; + $scope.variable.ShowLinkBack = $state.is('master-tours-list-entry'); + $scope.variable.BasicInfo = $dataHelper.toBasicInfo($stateParams); + $scope.objEntry.tblResultOptions = $optionHelper.gridBase({ width: 700 }); + $scope.edtNotes.options = $optionHelper.editorBase(); + /* Định nghĩa phương thức xử lý */ + // Xử lý init + $scope.init = function () { + $pc({ + action: 'InitLayout', + url: '/adm/hdl/ma/tours/entry.ashx', + data: { + Status: $scope.variable.BasicInfo.Status, + CallType: $scope.variable.BasicInfo.CallType, + TourCd: $stateParams.TourCd + }, + success: function (data) { + // Ẩn/Hiện cửa sổ chính + $scope.$parent.showViewMain(true); + // Gán dữ liệu xử lý + $scope.data = data; + $scope.objEntry.DataInfo = data.LocaleModel.DataInfo; + $scope.objEntry.ListLocale = data.LocaleModel.ListLocale; + $scope.objLocale.LocaleCd = $scope.data.CboLocalesSeleted; + // Trường hợp kết quả trả về không phải mảng + if (!$.isArray($scope.objEntry.ListLocale)) { + $scope.objEntry.ListLocale = []; + } + // Xử lý select thông tin dòng đầu tiên + $scope.selectRow($scope.objLocale.LocaleCd); + // Xử lý focus + $ti('txtTourName'); + } + }); + }; + // Xử lý save + $scope.save = function () { + $pc({ + action: 'Save', + url: '/adm/hdl/ma/tours/entry.ashx', + data: { + Status: $scope.variable.BasicInfo.Status, + CallType: $scope.variable.BasicInfo.CallType, + LocaleModel: { + DataInfo: $scope.objEntry.DataInfo, + ListLocale: $scope.objEntry.ListLocale + } + }, + success: function (data) { + if ($scope.variable.BasicInfo.IsEdit) { + $scope.back(); + } else { + var fnYes = function () { + $scope.init(); + }; + var fnNo = function () { + $scope.back(); + }; + $dialogHelper.showDialogConfirm($ms('I.MSG.00003'), fnYes, fnNo); + } + } + }); + }; + // Xử lý back + $scope.back = function () { + $pc(function () { + $state.go('master-tours-list'); + }); + }; + // Tạo mới mã + $scope.genCd = function () { + $pc({ + action: 'GenCd', + url: '/adm/hdl/ma/tours/entry.ashx', + data: { + Status: $scope.variable.BasicInfo.Status, + CallType: $scope.variable.BasicInfo.CallType + }, + success: function (data) { + if ($scope.variable.BasicInfo.IsAdd && data.TourCd) { + $scope.objEntry.DataInfo.TourCd = data.TourCd; + } + } + }); + }; + // Xử lý tải lên hình ảnh + $scope.uploadImage = function (obj) { + $pc(function () { + var modalInstance = $dialogHelper.showDialogUpload({ + LocaleCd: obj.LocaleCd, + FileCd: obj.FileCd, + HasGen: obj.HasGen, + FileGroupCd: 'stg.ma.tours.file-cd' + }); + // Lấy kết quả xử lý + modalInstance.result.then(function (result) { + obj.FileCd = result.data; + obj.HasGen = result.hasGen; + }); + }); + }; + // Xử lý cố định dòng + $scope.fixRow = function () { + $pc(function () { + // Khởi tạo biến cục bộ + var obj = $scope.objLocale; + // Trường hợp là ngôn ngữ chuẩn + if ($scope.data.BasicLocale === obj.LocaleCd) { + $dialogHelper.showDialogError($resourceHelper.getMessage('E.MSG.00004', 'ADM.MA.TOURS.ENTRY.LocaleCd')); + return; + } + // Lấy số dòng hợp lệ + obj.RowNo = $gridHelper.genRowNo(obj.RowNo, $scope.objEntry.ListLocale); + // Lấy chỉ số dòng trong mảng + var rowIdx = $dataHelper.getRowIndex(obj.LocaleCd, $scope.objEntry.ListLocale, 'LocaleCd'); + if (rowIdx === -1) { + // Thêm dữ liệu vào danh sách + $scope.objEntry.ListLocale.push(obj); + } else { + // Cập nhật dữ liệu vào danh sách + $scope.objEntry.ListLocale[rowIdx] = obj; + } + // Xử lý select thông tin dòng + $scope.selectRow(obj.LocaleCd); + }); + }; + // Xử lý clear thông tin dòng + $scope.clearRow = function () { + $pc(function () { + $scope.objLocale.RowNo = ''; + $scope.objLocale.TourName = ''; + $scope.objLocale.SearchName = ''; + $scope.objLocale.Summary = ''; + $scope.objLocale.Notes = ''; + $scope.objLocale.MetaTitle = ''; + $scope.objLocale.MetaDesc = ''; + $scope.objLocale.MetaKeys = ''; + }); + }; + // Xử lý select thông tin dòng + $scope.selectRow = function (localeCd) { + $pc(function () { + // Lấy chỉ số dòng trong mảng + var rowIdx = $dataHelper.getRowIndex(localeCd, $scope.objEntry.ListLocale, 'LocaleCd'); + // Trường hợp không tồn tại dòng + if (rowIdx === -1) { + // Xử lý clear thông tin dòng + $scope.clearRow(); + } else { + // Khởi tạo biến cục bộ + var tmp = {}; + var obj = $scope.objEntry.ListLocale[rowIdx]; + // Gán dữ liệu vào đối tượng + angular.copy(obj, tmp); + $scope.objLocale = tmp; + } + }); + }; + // Xử lý copy thông tin chính + $scope.copyInfo = function () { + var fnYes = function () { + $pc(function () { + $scope.objLocale.TourName = $scope.objEntry.DataInfo.TourName; + $scope.objLocale.SearchName = $scope.genSearchName($scope.objLocale); + $scope.objLocale.Summary = $scope.objEntry.DataInfo.Summary; + $scope.objLocale.Notes = $scope.objEntry.DataInfo.Notes; + $scope.objLocale.MetaTitle = $scope.objEntry.DataInfo.MetaTitle; + $scope.objLocale.MetaDesc = $scope.objEntry.DataInfo.MetaDesc; + $scope.objLocale.MetaKeys = $scope.objEntry.DataInfo.MetaKeys; + }); + }; + $dialogHelper.showDialogConfirm($ms('I.MSG.00002'), fnYes); + }; + // Xử lý thay đổi tên + $scope.blurTourName = function (data, obj, genSlug) { + $pc(function () { + if (genSlug) { + $scope.genSlug(obj); + } + $scope.genSearchName(obj); + }); + }; + // Xử lý thay đổi ngôn ngữ + $scope.changedLocaleCd = function (data) { + $pc(function () { + // Lấy thông tin dữ liệu + var rowData = $dataHelper.getRowData(data, $scope.data.CboLocales, 'Code'); + $scope.objLocale.LocaleName = rowData.Name; + // Xử lý select thông tin dòng + $scope.selectRow(rowData.Code); + }); + }; + // Tạo tự động tên liên kết + $scope.genSlug = function (obj) { + if ($checkHelper.isNull(obj.Slug)) { + obj.Slug = $dataHelper.toSlug(obj.TourName); + } + }; + // Tạo tự động tên tìm kiếm + $scope.genSearchName = function (obj) { + obj.SearchName = $dataHelper.toSearchName(obj.TourName); + }; + /* Định nghĩa các events */ + // Ẩn/Hiện cửa sổ chính + $scope.$parent.showViewMain(false); + // Tiến hành xử lý init + $scope.init(); + /* Đăng ký các events */ + // $watch('objLocale.LocaleCd') + $scope.$watch('objLocale.LocaleCd', function (newValue, oldValue) { + if (newValue) { + $scope.changedLocaleCd(newValue); + } + }); +} ]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067271_gameserver.js b/pool/shard010/JavaScript/0067271_gameserver.js new file mode 100644 index 0000000000000000000000000000000000000000..c06326c03ab66eb632330179f7a66e285abbfce7 --- /dev/null +++ b/pool/shard010/JavaScript/0067271_gameserver.js @@ -0,0 +1,78 @@ +/* ./server/gameserver.js + + + To Do list +-------------------------------------------------------- +[X] MongoDB on same server (localhost) +[] Use React (Flux) with Node JS +[] Spin up DarkAge droplet +[] Implement Flightplan +[] buy https: certificate +[] Spin up DarkAgedroplet https: certificate + +*/ + +'use strict'; + +/* Dependencies */ + + const express = require('express'); + const app = express(); + const http = require('http').Server(app); + const io = require('socket.io')(http); + + const port = process.env.PORT || 8080; + const host = process.env.IP; + + const cookieParser= require('cookie-parser'); + const bodyParser = require('body-parser'); + const session = require('express-session'); + const mongoose = require('mongoose'); + const passport = require('passport'); + +/* Configuration */ + const configDb = require('./config/database.js'); + +/* Database */ + +const db = require('./config/mongodb'); + + // Make our db accessible to our router + app.use(function(req,res,next){ + req.db = db; + next(); + }); + +/* View Engine */ + app.set('views', './views'); + app.set('view engine', 'ejs'); + +/* Middleware */ + app.use(cookieParser()); + app.use(bodyParser.json()); + app.use(bodyParser.urlencoded({ extended: false })); + app.use(session({ secret: 'any string', saveUninitialized: true, resave: true, cookie: { maxAge: 120000 }})); + app.use(express.static('./public_html')); + +http.listen(port,function() { + console.log(Date.now() + ' | server is running...'); +}); + +/* Socket.io server */ +app.get('/', function(req, res){ + res.render('test/game',{ + title: "Game", + description: "", + breadcrumb: ["home","game"], + }); +}) + +/* Routes */ +app.use('/test', require('./routes/test_routes')(io)); +app.use('/auth', require('./routes/auth_routes')); +app.use('/game', require('./routes/game_routes')(io)); +app.use('/admin', require('./routes/admin_routes')(io)); + + + + diff --git a/pool/shard010/JavaScript/0067272_app.js b/pool/shard010/JavaScript/0067272_app.js new file mode 100644 index 0000000000000000000000000000000000000000..cb879a178745863b4a26589509b5b4ad20a193cd --- /dev/null +++ b/pool/shard010/JavaScript/0067272_app.js @@ -0,0 +1,155 @@ +/** + * KJSencha Example Application + * + * @see http://docs.sencha.com/ext-js/4-1/#!/guide/application_architecture + */ +Ext.application({ + name: 'Banking', + // this variable is inherited from the output of view helper `kjSenchaVariables` + appFolder: App.basePath + '/js/app', + + launch: function() { + + var store1 = Ext.create('Ext.data.JsonStore', { + fields: [ + 'turnover', 'entryDate', 'monthSum' + ], + proxy: { + type: 'ajax', + url: '/application/extjs/turnover.json', + reader: { + type: 'json', + root: 'data', + idProperty: 'entryDate' + } + }, + autoLoad: true + }); + + var chart = Ext.create('Ext.chart.Chart', { + style: 'background:#fff', + animate: true, + store: store1, + shadow: true, + theme: 'Category1', + legend: { + position: 'right' + }, + axes: [{ + type: 'Numeric', + minimum: -1100, + maximum: 9000, + position: 'left', + fields: ['turnover', 'monthSum'], + title: 'Ausgabe', + //minorTickSteps: 1, + grid: { + odd: { + opacity: 1, + fill: '#ddd', + stroke: '#bbb', + 'stroke-width': 0.5 + } + } + }, { + type: 'Category', + position: 'bottom', + fields: ['entryDate'], + title: 'Datum', + label: { + renderer: function(v){ + var date = v.substring(0, v.indexOf(' ')); + date = Ext.Date.format(new Date(date), "Y-m-d"); + + return date; + } + } + }], + series: [ + { + type: 'line', + highlight: { + size: 7, + radius: 7 + }, + tips: { + trackMouse: true, + width: 130, + renderer: function(storeItem, item) { + var v = storeItem.get('entryDate'); + var date = v.substring(0, v.indexOf(' ')); + + this.setTitle(storeItem.get('turnover') + '-' + date); + } + }, + axis: 'left', + xField: 'entryDate', + yField: 'turnover', + markerConfig: { + type: 'cross', + size: 4, + radius: 4, + 'stroke-width': 0 + } + }, + { + type: 'line', + highlight: { + size: 7, + radius: 7 + }, + tips: { + trackMouse: true, + width: 130, + renderer: function(storeItem, item) { + var v = storeItem.get('entryDate'); + var date = v.substring(0, v.indexOf(' ')); + + this.setTitle(storeItem.get('monthSum') + '-' + date); + } + }, + axis: 'left', + xField: 'entryDate', + yField: 'monthSum', + markerConfig: { + type: 'cross', + size: 4, + radius: 4, + 'stroke-width': 0 + } + } + ] + }); + + + var win = Ext.create('Ext.Window', { + width: 800, + height: 600, + minHeight: 400, + minWidth: 550, + hidden: false, + closable: false, + maximized: true, + renderTo: Ext.getBody(), + layout: 'fit', + tbar: [{ + text: 'Save Chart', + handler: function() { + Ext.MessageBox.confirm('Confirm Download', 'Would you like to download the chart as an image?', function(choice){ + if(choice == 'yes'){ + chart.save({ + type: 'image/png' + }); + } + }); + } + }, { + text: 'Reload Data', + handler: function() { + store1.loadData(); + } + }], + items: chart + }); + } +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067275_websocket.js b/pool/shard010/JavaScript/0067275_websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..e228daf6f0560d52a08ac4ac46c94ac3aea0053f --- /dev/null +++ b/pool/shard010/JavaScript/0067275_websocket.js @@ -0,0 +1,101 @@ +if ("WebSocket" in window) { + // Let us open a web socket + var ws = new WebSocket("ws://" + window.location.hostname + ":8082"); + //var ws = new WebSocket("ws://ubuntuWorkstation:8082"); + + ws.onopen = function() { + // Web Socket is connected, send data using send() + $("#playPause").click(function() { + ws.send("{\"command\":\"playPause\"}"); + }); + + $("#prev").click(function() { + ws.send("{\"command\":\"prev\"}"); + }); + + $("#next").click(function() { + ws.send("{\"command\":\"next\"}"); + }); + + $("#volume").on('change', function() { + ws.send("{\"command\":\"setVolume\", \"volume\":" + $('input[name=volume]').val() + "}"); + }); + + $("#addStream").click(function() { + $("#newStationUploader").css("visibility", "unset"); + $("#uploadFormContainer").css("visibility", "unset"); + }); + + $("#closeAddForm").click(function() { + $("#newStationUploader").css("visibility", "hidden"); + $("#uploadFormContainer").css("visibility", "hidden"); + }); + }; + + ws.onmessage = function(evt) { + console.log(evt.data); + jObject = JSON.parse(evt.data) + console.log(jObject); + + if(jObject.command == "setPaused"){ + $("#playPause").css("background-image", "url(/img/start.png)"); + } + + if(jObject.command == "setPlay"){ + $("#playPause").css("background-image", "url(/img/pause.png)"); + } + + if(jObject.command == "setCurrent"){ + $("#marquee").text(jObject.current) + } + + if(jObject.command == "setVolume"){ + $('input[name=volume]').val(jObject.volume); + } + + if (jObject.command == "addStation") { + jQuery('
    ', { + class: 'tile', + stationID: jObject.stationID, + name: jObject.stationID, + css: { + "background-image": "url(/img/" + jObject.cover + ")" + }, + click: function(e) { + if (!e) var e = window.event; + e.cancelBubble = true; + if (e.stopPropagation) e.stopPropagation(); + ws.send("{\"command\":\"changeStation\", \"stationID\":\"" + $(this).attr("stationID") + "\"}"); + } + }).appendTo('#streams'); + + jQuery('
    ', { + class: 'cross', + stationID: jObject.stationID, + click: function(e) { + if (!e) var e = window.event; + e.cancelBubble = true; + if (e.stopPropagation) e.stopPropagation(); + ws.send("{\"command\":\"deleteStation\", \"stationID\":\"" + $(this).attr("stationID") + "\"}"); + } + }).appendTo('[stationID=' + jObject.stationID + ']'); + } + + if(jObject.command == "deleteStation"){ + $('[stationID=' + jObject.stationID + ']').remove(); + } + + if(jObject.command == "updateCover"){ + $('[name=' + jObject.stationID + ']').css("background-image", "url(/img/" + jObject.cover + ")"); + } + }; + + ws.onclose = function() {}; +} else { + // The browser doesn't support WebSocket + alert("WebSocket NOT supported by your Browser!"); +} + +window.onload = function() { + +} diff --git a/pool/shard010/JavaScript/0067279_jquery.maxlength.js b/pool/shard010/JavaScript/0067279_jquery.maxlength.js new file mode 100644 index 0000000000000000000000000000000000000000..2d9d1d3fb32172ffcdd9c390f3f72854ea819ebc --- /dev/null +++ b/pool/shard010/JavaScript/0067279_jquery.maxlength.js @@ -0,0 +1,139 @@ +/** +* jQuery Maxlength plugin +* @version $Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $ +* @package jQuery maxlength 1.0.5 +* @copyright Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se +* @license GNU/GPL, see LICENSE.txt +*/ + +(function ($) { + + $.fn.maxlength = function (options) { + var settings = jQuery.extend( + { + events: [], // Array of events to be triggerd + maxCharacters: 10, // Characters limit + status: true, // True to show status indicator bewlow the element + statusClass: "status", // The class on the status div + statusText: "character left", // The status text + notificationClass: "notification", // Will be added to the emement when maxlength is reached + showAlert: false, // True to show a regular alert message + alertText: "You have typed too many characters.", // Text in the alert message + slider: false // Use counter slider + }, options); + + // Add the default event + $.merge(settings.events, ['keyup']); + + return this.each(function () { + var item = $(this); + var charactersLength = $(this).val().length; + + // Update the status text + function updateStatus() { + var charactersLeft = settings.maxCharacters - charactersLength; + + if (charactersLeft < 0) { + charactersLeft = 0; + } + + //item.next("div").html(charactersLeft + " " + settings.statusText); + if(settings.statusText.indexOf("**")>0) + item.next("div").html(settings.statusText.replace("**", charactersLeft)); + else + item.next("div").html(charactersLeft + " " + settings.statusText); + } + + function checkChars() { + var valid = true; + + // Too many chars? + if (charactersLength >= settings.maxCharacters) { + // Too may chars, set the valid boolean to false + valid = false; + // Add the notifycation class when we have too many chars + item.addClass(settings.notificationClass); + // Cut down the string + item.val(item.val().substr(0, settings.maxCharacters)); + // Show the alert dialog box, if its set to true + showAlert(); + } + else { + // Remove the notification class + if (item.hasClass(settings.notificationClass)) { + item.removeClass(settings.notificationClass); + } + } + + if (settings.status) { + updateStatus(); + } + } + + // Shows an alert msg + function showAlert() { + if (settings.showAlert) { + alert(settings.alertText); + } + } + + // Check if the element is valid. + function validateElement() { + var ret = false; + + if (item.is('textarea')) { + ret = true; + } else if (item.filter("input[type=text]")) { + ret = true; + } else if (item.filter("input[type=password]")) { + ret = true; + } + + return ret; + } + + // Validate + if (!validateElement()) { + return false; + } + + // Loop through the events and bind them to the element + $.each(settings.events, function (i, n) { + item.bind(n, function (e) { + charactersLength = item.val().length; + checkChars(); + }); + }); + + // Insert the status div + if (settings.status) { + item.after($("
    ").addClass(settings.statusClass).html('-')); + updateStatus(); + } + + // Remove the status div + if (!settings.status) { + var removeThisDiv = item.next("div." + settings.statusClass); + + if (removeThisDiv) { + removeThisDiv.remove(); + } + + } + + // Slide counter + if (settings.slider) { + item.next().hide(); + + item.focus(function () { + item.next().slideDown('fast'); + }); + + item.blur(function () { + item.next().slideUp('fast'); + }); + } + + }); + }; +})(jQuery); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067280_drag-and-drop-utils.js b/pool/shard010/JavaScript/0067280_drag-and-drop-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..bbfd37f4591e2ba5c9af7adaab7ea0e151615463 --- /dev/null +++ b/pool/shard010/JavaScript/0067280_drag-and-drop-utils.js @@ -0,0 +1,265 @@ +import { + DragDropContext as dragDropContext, + DragSource as dragSource, + DropTarget as dropTarget, +} from 'react-dnd'; +import HTML5Backend from 'react-dnd-html5-backend'; +import React from 'react'; +import PropTypes from 'prop-types'; +import { findDOMNode } from 'react-dom'; +import { getDepth } from './tree-data-utils'; +import { memoizedInsertNode } from './memoized-tree-data-utils'; + +const nodeDragSource = { + beginDrag(props) { + props.startDrag(props); + + return { + node: props.node, + parentNode: props.parentNode, + path: props.path, + treeIndex: props.treeIndex, + }; + }, + + endDrag(props, monitor) { + props.endDrag(monitor.getDropResult()); + }, + + isDragging(props, monitor) { + const dropTargetNode = monitor.getItem().node; + const draggedNode = props.node; + + return draggedNode === dropTargetNode; + }, +}; + +const externalSource = { + beginDrag(props) { + return { + node: { + ...props.node, + }, + path: [], + type: 'rst__NewItem', + parentNode: null, + treeIndex: -1, // Use -1 to indicate external node + }; + }, + + endDrag(props, monitor) { + if (!monitor.didDrop()) { + props.dropCancelled(); + } else { + props.addNewItem(monitor.getDropResult()); + } + }, +}; + +function getTargetDepth(dropTargetProps, monitor, component) { + let dropTargetDepth = 0; + const draggedItem = monitor.getItem(); + + const rowAbove = dropTargetProps.getPrevRow(); + if (rowAbove) { + // Limit the length of the path to the deepest possible + dropTargetDepth = Math.min( + rowAbove.path.length, + dropTargetProps.path.length + ); + } + + let blocksOffset; + if (monitor.getItem().type === 'rst__NewItem') { + // Add new node from external source + if (component) { + const relativePosition = findDOMNode(component).getBoundingClientRect(); // eslint-disable-line react/no-find-dom-node + const leftShift = + monitor.getSourceClientOffset().x - relativePosition.left; + blocksOffset = Math.round( + leftShift / dropTargetProps.scaffoldBlockPxWidth + ); + } else { + blocksOffset = dropTargetProps.path.length; + } + } else { + blocksOffset = Math.round( + monitor.getDifferenceFromInitialOffset().x / + dropTargetProps.scaffoldBlockPxWidth + ); + } + + let targetDepth = Math.min( + dropTargetDepth, + Math.max(0, draggedItem.path.length + blocksOffset - 1) + ); + + // If a maxDepth is defined, constrain the target depth + if ( + typeof dropTargetProps.maxDepth !== 'undefined' && + dropTargetProps.maxDepth !== null + ) { + const draggedNode = monitor.getItem().node; + const draggedChildDepth = getDepth(draggedNode); + + targetDepth = Math.min( + targetDepth, + dropTargetProps.maxDepth - draggedChildDepth - 1 + ); + } + + return targetDepth; +} + +function canDrop(dropTargetProps, monitor, component) { + if (!monitor.isOver()) { + return false; + } + + const rowAbove = dropTargetProps.getPrevRow(); + const abovePath = rowAbove ? rowAbove.path : []; + const aboveNode = rowAbove ? rowAbove.node : {}; + const targetDepth = getTargetDepth(dropTargetProps, monitor, component); + + // Cannot drop if we're adding to the children of the row above and + // the row above is a function + if ( + targetDepth >= abovePath.length && + typeof aboveNode.children === 'function' + ) { + return false; + } + + if (typeof dropTargetProps.customCanDrop === 'function') { + const node = monitor.getItem().node; + const addedResult = memoizedInsertNode({ + treeData: dropTargetProps.treeData, + newNode: node, + depth: targetDepth, + getNodeKey: dropTargetProps.getNodeKey, + minimumTreeIndex: dropTargetProps.listIndex, + expandParent: true, + }); + + return dropTargetProps.customCanDrop({ + node, + prevPath: monitor.getItem().path, + prevParent: monitor.getItem().parentNode, + prevTreeIndex: monitor.getItem().treeIndex, // Equals -1 when dragged from external tree + nextPath: addedResult.path, + nextParent: addedResult.parentNode, + nextTreeIndex: addedResult.treeIndex, + }); + } + + return true; +} + +const nodeDropTarget = { + drop(dropTargetProps, monitor, component) { + return { + node: monitor.getItem().node, + path: monitor.getItem().path, + minimumTreeIndex: dropTargetProps.treeIndex, + depth: getTargetDepth(dropTargetProps, monitor, component), + }; + }, + + hover(dropTargetProps, monitor, component) { + const targetDepth = getTargetDepth(dropTargetProps, monitor, component); + const draggedNode = monitor.getItem().node; + const needsRedraw = + // Redraw if hovered above different nodes + dropTargetProps.node !== draggedNode || + // Or hovered above the same node but at a different depth + targetDepth !== dropTargetProps.path.length - 1; + + if (!needsRedraw) { + return; + } + + dropTargetProps.dragHover({ + node: draggedNode, + path: monitor.getItem().path, + minimumTreeIndex: dropTargetProps.listIndex, + depth: targetDepth, + }); + }, + + canDrop, +}; + +function externalSourcePropInjection(connect, monitor) { + return { + connectDragSource: connect.dragSource(), + isDragging: monitor.isDragging(), + }; +} + +function nodeDragSourcePropInjection(connect, monitor) { + return { + connectDragSource: connect.dragSource(), + connectDragPreview: connect.dragPreview(), + isDragging: monitor.isDragging(), + didDrop: monitor.didDrop(), + }; +} + +function nodeDropTargetPropInjection(connect, monitor) { + const dragged = monitor.getItem(); + return { + connectDropTarget: connect.dropTarget(), + isOver: monitor.isOver(), + canDrop: monitor.canDrop(), + draggedNode: dragged ? dragged.node : null, + }; +} + +export function dndWrapExternalSource(UserComponent, type) { + class DndWrapExternalSource extends React.Component { + render() { + return this.props.connectDragSource( +
    + +
    , + { dropEffect: 'copy' } + ); + } + } + + // these defaultProps must be passed to the custom external node component as props + DndWrapExternalSource.defaultProps = { + dropCancelled() { + throw new Error('External Nodes must define dropCancelled prop function'); + }, + addNewItem() { + throw new Error('External Nodes must define addNewItem prop function'); + }, + }; + + DndWrapExternalSource.propTypes = { + connectDragSource: PropTypes.func.isRequired, + /* eslint-disable react/no-unused-prop-types */ + // The following are used within the react-dnd lifecycle hooks + node: PropTypes.shape({}).isRequired, + dropCancelled: PropTypes.func.isRequired, + addNewItem: PropTypes.func.isRequired, + /* eslint-enable react/no-unused-prop-types */ + }; + + return dragSource(type, externalSource, externalSourcePropInjection)( + DndWrapExternalSource + ); +} + +export function dndWrapSource(el, type) { + return dragSource(type, nodeDragSource, nodeDragSourcePropInjection)(el); +} + +export function dndWrapTarget(el, type) { + return dropTarget(type, nodeDropTarget, nodeDropTargetPropInjection)(el); +} + +export function dndWrapRoot(el) { + return dragDropContext(HTML5Backend)(el); +} diff --git a/pool/shard010/JavaScript/0067283_draw.js b/pool/shard010/JavaScript/0067283_draw.js new file mode 100644 index 0000000000000000000000000000000000000000..f386276f3a32f3f3895deb547eb1de6166c3c3b1 --- /dev/null +++ b/pool/shard010/JavaScript/0067283_draw.js @@ -0,0 +1,61 @@ +var chalk = require('chalk'); +var inquirer = require('inquirer'); +var winners = require('../lib/winners'); + +var drawBalls = function ($this) { + var balls = []; + + while (balls.length < 3) { + var randNumber = Math.floor((Math.random() * $this.people.length) + 0); + if (balls.indexOf(randNumber) < 0) { + balls.push(randNumber); + } + } + + return balls; +}; + +var start = function ($this, callback) { + if ($this.people.length < 4) { + console.log(chalk.red('\n Unable to draw. Atleast three tickets need to get sold before drawing\n')); + return callback(); + } + else { + console.log(chalk.yellow('\n Tickets sold since last draw: ' + $this.people.length)); + console.log(chalk.yellow(' Total money in the pot: ' + $this.pot + '$\n')); + var promptArray = [{ + name: 'drawConfirm', + type: 'confirm', + message: 'Would you like to draw? ', + default: true + }]; + + inquirer.prompt(promptArray, function (answers) { + if (answers.drawConfirm) { + var totalPrize = $this.pot / 2, + firstPrize = Math.round(totalPrize * 0.75), + secondPrize = Math.round(totalPrize * 0.15), + thirdPrize = Math.round(totalPrize * 0.1); + $this.winners = []; + + var ballsDrawn = drawBalls($this); + + $this.winners.push(chalk.green($this.people[ballsDrawn[0]] + ':' + firstPrize + '$')); + $this.winners.push(chalk.green($this.people[ballsDrawn[1]] + ':' + secondPrize + '$')); + $this.winners.push(chalk.green($this.people[ballsDrawn[2]] + ':' + thirdPrize + '$')); + $this.pot -= (firstPrize + secondPrize + thirdPrize); + $this.drawDate = new Date(); + $this.people = []; + winners.display($this); + } + else { + console.log(chalk.yellow('\n Draw cancelled!\n')); + } + callback(); + }); + } +}; + +module.exports = { + start: start +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067284_gulpfile.js b/pool/shard010/JavaScript/0067284_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..60127a1531801cc50cd4d82d622b248ddcaa12d4 --- /dev/null +++ b/pool/shard010/JavaScript/0067284_gulpfile.js @@ -0,0 +1,32 @@ + 'use strict'; + var gulp = require('gulp'), + concat = require('gulp-concat'), + uglify = require('gulp-uglify'), + ts = require('gulp-typescript'), + ngAnnotate = require('gulp-ng-annotate'); + + var tsOrder = [ + 'app/modules/**/module.ts', + 'app/modules/**/*.ts', + 'app/*.ts' + ]; + + gulp.task('ts', function() { + gulp.src(tsOrder) + .pipe(ts({ + noImplicitAny: true, + out: 'app.js', + target: 'ES5', + removeComments:false + })) + .js + .pipe(ngAnnotate()) + .pipe(uglify()) + .pipe(gulp.dest('app/dist')); + }); + + gulp.task('default', function() { + gulp.watch(tsOrder , ['ts']); + }); + + diff --git a/pool/shard010/JavaScript/0067285_toggle-attribute_spec.js b/pool/shard010/JavaScript/0067285_toggle-attribute_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b594a256c3c4ffe371a24146ac9237c256b36106 --- /dev/null +++ b/pool/shard010/JavaScript/0067285_toggle-attribute_spec.js @@ -0,0 +1,35 @@ +describe('A toggle attribute module', function () { + 'use strict' + + var element + + beforeEach(function () { + element = document.createElement('div') + element.innerHTML = + '
    ' + + '
    ' + + '' + + '
    ' + var toggle = new GOVUK.Modules.ToggleAttribute(element) + toggle.init() + }) + + it('sets the state to open when clicked and back again', function () { + var unnested = element.querySelector('#unnested-click') + + expect(unnested).toHaveAttr('data-state', 'closed') + unnested.click() + expect(unnested).toHaveAttr('data-state', 'open') + unnested.click() + expect(unnested).toHaveAttr('data-state', 'closed') + }) + + it('can handle a click on a nested element', function () { + var nested = element.querySelector('#nested-click') + var span = nested.querySelector('span') + + expect(nested).toHaveAttr('data-state', 'closed') + span.click() + expect(nested).toHaveAttr('data-state', 'open') + }) +}) diff --git a/pool/shard010/JavaScript/0067288_plugins.js b/pool/shard010/JavaScript/0067288_plugins.js new file mode 100644 index 0000000000000000000000000000000000000000..8a7732f7f4f514d915f4c74c4cc638b7835995a3 --- /dev/null +++ b/pool/shard010/JavaScript/0067288_plugins.js @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Amadeus s.a.s. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var Q = require('q'); + +var attester = require("../attester"); +var logger = attester.logger; +var merge = require("../util/merge"); + +/** + * This module describe the interface of plugins. + * + * A plugin has two interfaces: + * - the user, she needs to load a plugin and configure it + * - the plugin developer, she needs to get the user configuration and modify attester behavior + */ + +var pluginsConfig = {}; +var requiredPlugins = {}; +var pendingRequire = []; + +/** + * Set the plugin configuration. + * It returns a copy of the configuration set or the previous one if no config was specified. + * The configuration is not merged but it simply replaces any old configuration. + */ +exports.config = function (name, config) { + if (config) { + var newConfig = {}; + merge(newConfig, config); + pluginsConfig[name] = newConfig; + } + + var returnValue = {}; + merge(returnValue, pluginsConfig[name] || {}); + return returnValue; +}; + +/** + * Require a plugin. + * It tells attester to load and execute the corresponding plugin. + * + * The second parameter, config, is optional, if specified it's the plugin configuration + */ +exports.require = function (name, config) { + // Do it here so that it's available for the plugin even before it gets called + var pluginConfig = exports.config(name, config); + + var pending = function () { + // Try to resolve the plugin name using node require, it'll work with npm as well + logger.logDebug("Requiring plugin " + name); + + if (requiredPlugins[name]) { + return logger.logDebug("already required"); + } + + var plugin; + try { + plugin = require(name); + } catch (ex) { + logger.logError("Unable to load plugin " + name); + } + + if (plugin) { + try { + plugin(attester, pluginConfig); + requiredPlugins[name] = true; + } catch (ex) { + logger.logError("Exception while executing plugin: " + name + "\nMessage: " + ex.message); + } + } + }; + pendingRequire.push(pending); + attester.event.on("attester.server.started", pending); +}; + +exports.__reset__ = function () { + pluginsConfig = {}; + requiredPlugins = {}; + for (var i = 0; i < pendingRequire.length; i += 1) { + attester.event.off("attester.server.started", pendingRequire[i]); + } + pendingRequire = []; + + attester.logger.logDebug("__reset__ plugins done"); + return Q(); +}; diff --git a/pool/shard010/JavaScript/0067289_GameTimerManager.js b/pool/shard010/JavaScript/0067289_GameTimerManager.js new file mode 100644 index 0000000000000000000000000000000000000000..d5504ed5decb7c1b448bfac4ed88089874d6bf8b --- /dev/null +++ b/pool/shard010/JavaScript/0067289_GameTimerManager.js @@ -0,0 +1,30 @@ +game.GameTimerManager = Object.extend({ + init: function(x, y, settings) { + this.now = new Date().getTime(); + //keeps track of the last time we made a creep happen + this.lastCreep = new Date().getTime(); + this.paused = false; + this.alwaysUpdate = true; + }, + update: function() { + //keeps track of the timer + this.now = new Date().getTime(); + this.goldTimerCheck(); + this.creepTimerCheck(); + + return true; + }, + goldTimerCheck: function() { + if (Math.round(this.now / 1000) % 20 === 0 && (this.now - this.lastCreep >= 1000)) { + game.data.gold += (game.data.exp1 + 1); + console.log("current gold:" + game.data.gold); + } + }, + creepTimerCheck: function() { + if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1800)) { + this.lastCreep = this.now; + var creepe = me.pool.pull("EnemyCreep", 4800, 0, {}); + me.game.world.addChild(creepe, 5); + } + } +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067291_ui_add_gauge.js b/pool/shard010/JavaScript/0067291_ui_add_gauge.js new file mode 100644 index 0000000000000000000000000000000000000000..74e7fb4da71cadb14049f8e023b7dc64c9a606a9 --- /dev/null +++ b/pool/shard010/JavaScript/0067291_ui_add_gauge.js @@ -0,0 +1,23 @@ + +function main( argv ) { + + p = hz.util.append(); + + var c = hz.ui.create.gauge( 'Gauge Text', 0.6 ); + p.appendChild( c ); + + c = hz.ui.create.pulse( 'Pulse Text' ); + p.appendChild( c ); + + c = hz.ui.create.progress( 'Progress Text', 0.0, 1 ); + p.appendChild( c ); + var pcent = 0.0; + window.setInterval( + function( event ) { + pcent = pcent > 1.0 ? 0.0 : pcent + 0.05; + c.hz.set_value( pcent ); + }, + 1000 + ); + +} diff --git a/pool/shard010/JavaScript/0067292_kraken-api-promise.js b/pool/shard010/JavaScript/0067292_kraken-api-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..168c24c59fba1b8fcf1a2f70bdf4d11094643afe --- /dev/null +++ b/pool/shard010/JavaScript/0067292_kraken-api-promise.js @@ -0,0 +1,224 @@ +var Promise = require("bluebird"); +var request = require('requestretry'); +var crypto = require('crypto'); +var querystring = require('querystring'); +var Queue = require('promise-queue-rate-limited'); + +/** + * KrakenClient connects to the Kraken.com API + * + * @param {String} key API Key + * @param {String} secret API Secret + * @param {Number} [timeoutMillis] Server response timeout in milliseconds (optional, default: 5000 ms) + * @param {Number} [retryAttepms] Retries after server connction errors + * @param {Number} [retryDelayMillis] Delay between retry attempts + * @param {Number} [requestsPerSecond] Requests per seconds. If specified and > 0 then a rate-limited queue will be used internally to execute the requests. Of <= 0 then no queue will be used. + * @param logger - An optional logger which has an info method to log the kraken-api requests + */ +function KrakenClient(key, secret, timeoutMillis, retryAttepms, retryDelayMillis, requestsPerSecond, logger) { + var self = this; + var nonce = new Date() * 1000; // spoof microsecond + + var config = { + url: 'https://api.kraken.com', + userAgent: 'Kraken Javascript API Client', + version: '0', + key: key, + secret: secret, + timeoutMS: timeoutMillis || 5000, + maxRetryAttempts: retryAttepms || 5, + retryDelayMillis: retryDelayMillis || 5000, + requestsPerSecond: requestsPerSecond && requestsPerSecond > 0 ? requestsPerSecond : null + }; + + const queue = config.requestsPerSecond && config.requestsPerSecond > 0 + ? new Queue(config.requestsPerSecond, logger) + : null; + + if (queue) { + queue.start(); + } + + /** + * This method makes a public or private API request. + * @param {String} method The API method (public or private) + * @param {Object} params Arguments to pass to the api call + * @return {Promise} A promise which will resolve to the servers reponse + */ + function api(method, params) { + if (logger && logger.info) { + logger.info("kraken-api queueing", {method: method, params: params}); + } + + var methods = { + public: ['Time', 'Assets', 'AssetPairs', 'Ticker', 'Depth', 'Trades', 'Spread', 'OHLC'], + private: ['Balance', 'TradeBalance', 'OpenOrders', 'ClosedOrders', 'QueryOrders', 'TradesHistory', + 'QueryTrades', 'OpenPositions', 'Ledgers', 'QueryLedgers', 'TradeVolume', 'AddOrder', 'CancelOrder', + 'DepositMethods', 'DepositAddresses', 'DepositStatus', 'WithdrawInfo', 'Withdraw', 'WithdrawStatus', + 'WithdrawCancel'], + withoutRetry: ['AddOrder', 'CancelOrder', 'Withdraw', 'WithdrawCancel'] + }; + + if (methods.public.indexOf(method) !== -1) { + return publicMethod(method, params, true); + } else if (methods.private.indexOf(method) !== -1) { + return privateMethod(method, params, methods.withoutRetry.indexOf(method) == -1); + } + + return Promise.reject(new Error(method + ' is not a valid API method.')); + } + + /** + * This method makes a public API request. + * @param {String} method The API method (public or private) + * @param {Object} params Arguments to pass to the api call + * @param {boolean} allowRetry - True if a retry of the command on network errors is allowed + * @return {Promise} A promise which will resolve to the servers reponse + */ + function publicMethod(method, params, allowRetry) { + params = params || {}; + + var url = config.url + '/' + config.version + '/public/' + method; + return rawRequest(url, {}, params, retryStrategy(allowRetry)); + } + + /** + * This method makes a private API request. + * @param {String} method The API method (public or private) + * @param {Object} params Arguments to pass to the api call + * @param {boolean} allowRetry - True if a retry of the command on network errors is allowed + * @return {Promise} A promise which will resolve to the servers reponse + */ + function privateMethod(method, params, allowRetry) { + params = params || {}; + + var path = '/' + config.version + '/private/' + method; + var url = config.url + path; + + params.nonce = nonce++; + + var headers = { + 'API-Key': config.key, + 'API-Sign': getMessageSignature(path, params, params.nonce) + }; + + return rawRequest(url, headers, params, retryStrategy(allowRetry)); + } + + /** + * This method returns a signature for a request as a Base64-encoded string + * @param {String} path The relative URL path for the request + * @param {Object} request The POST body + * @param {Number} nonce A unique, incrementing integer + * @return {String} The request signature + */ + function getMessageSignature(path, request, nonce) { + var message = querystring.stringify(request); + var secret = new Buffer(config.secret, 'base64'); + var hash = new crypto.createHash('sha256'); + var hmac = new crypto.createHmac('sha512', secret); + + var hash_digest = hash.update(nonce + message).digest('binary'); + return hmac.update(path + hash_digest, 'binary').digest('base64'); + } + + function retryStrategy(allowRetry) { + return allowRetry ? null : function () { + return false; + } + } + + function bluebirdPromiseFactory(resolver) { + if (logger && logger.debug) { + logger.debug("creating new promise for request"); + } + return new Promise(resolver); + } + + /** + * This method sends the actual HTTP request + * @param {String} url The URL to make the request + * @param {Object} headers Request headers + * @param {Object} params POST body + * @param {Function} retryStrategy - The optional retry strategy. Fallback is to retry on network errors. + * @return {Promise} A promise which will resolve to the servers response. + */ + function rawRequest(url, headers, params, retryStrategy) { + function doRawRequest() { + if (logger && logger.debug) { + logger.debug("doRawRequest"); + } + + headers['User-Agent'] = config.userAgent; + var options = { + promiseFactory: bluebirdPromiseFactory, + fullResponse: false, // to resolve with just the response body + forever: true, //http keep-alive + strictSSL: true, + url: url, + method: 'POST', + headers: headers, + form: params, + timeout: config.timeoutMS, + // The parameters below are specific to request-retry + maxAttempts: config.maxRetryAttempts, + retryDelay: config.retryDelayMillis, + retryStrategy: retryStrategy || request.RetryStrategies.NetworkError // retry only on network erros, avoid possibly duplicate requests on http errors + }; + + return request(options).then(function (body) { + var jsonBody; + try { + jsonBody = JSON.parse(body); + } catch (e) { + throw new Error('Could not parse response from server. Exception: ' + e); + } + + //If any errors occured, Kraken will give back an array with error strings under + //the key "error". We should then propagate back the error message as a proper error. + if (jsonBody && jsonBody.error && jsonBody.error.length) { + var krakenError = null; + jsonBody.error.forEach(function (element) { + if (element.charAt(0) === "E") { + krakenError = element.substr(1); + return false; + } + }); + + if (krakenError) { + throw new Error('Kraken API returned error: ' + krakenError); + } + } + + if (logger && logger.silly) { + logger.silly("kraken-api", {url: url, result: jsonBody.result}); + } + return jsonBody.result; + }); + } + + if (queue) { + if (logger && logger.debug) { + logger.debug("kraken-api: queuing new request"); + } + return queue.append(() => { + if (logger && logger.debug) { + logger.debug("in queue append"); + } + + return doRawRequest(); + }); + } + + if (logger && logger.debug) { + logger.debug("kraken-api: new request, no queue"); + } + return doRawRequest(); + } + + self.api = api; + self.publicMethod = publicMethod; + self.privateMethod = privateMethod; +} + +module.exports = KrakenClient; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067293_dashboard.js b/pool/shard010/JavaScript/0067293_dashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..266cd91156b5c49c67f415ccc091f60faa5c695a --- /dev/null +++ b/pool/shard010/JavaScript/0067293_dashboard.js @@ -0,0 +1,174 @@ +var URLHelper = require('./url-helper'); +var _ = require('underscore'); + +function Dashboard (dashboard) { + this._dashboard = dashboard; + + this.onDataviewsFetched(function () { + dashboard.widgets._widgetsCollection.initialState(); + dashboard.widgets._widgetsCollection.each(function (m) { + m && m.applyInitialState && m.applyInitialState(); + }); + }); +} + +Dashboard.prototype = { + + /** + * @return {View} used in the dashboard + */ + getView: function () { + return this._dashboard.dashboardView; + }, + + /** + * @return {Map} the map used in the dashboard + */ + getMap: function () { + return this._dashboard.vis; + }, + + reloadMap: function () { + this.getMap().reload(); + }, + + forceResize: function () { + this._dashboard.widgets.getCollection() + .each(function (widget) { + widget.forceResize(); + }); + }, + + /** + * @return {Array} of widgets in the dashboard + */ + getWidgets: function () { + return this._dashboard.widgets.getList(); + }, + + getDashboardURL: function () { + return URLHelper.getURLFromState(this.getState()); + }, + + getState: function () { + var state = {}; + var mapState = this.getMapState(); + if (!_.isEmpty(mapState)) state.map = mapState; + + var widgetsCollection = this._dashboard.widgets.getCollection(); + var widgetsState = widgetsCollection.getStates(); + if (!_.isEmpty(widgetsState)) state.widgets = widgetsState; + return state; + }, + + getMapState: function () { + var map = this._dashboard.vis.map; + var currentBoundingBox = map.getViewBounds(); + var center = map.get('center'); + var zoom = map.get('zoom'); + + return { + ne: currentBoundingBox[0], + sw: currentBoundingBox[1], + center: center, + zoom: zoom + }; + }, + + setState: function (state) { + // todo: set map state + this._dashboard.widgets.setWidgetsState(state.widgets); + this._dashboard.vis.mapvis.map.setBounds([state.map.ne, state.map.sw]); + }, + + onDataviewsFetched: function (callback) { + var areWidgetsInitialized = this._dashboard.areWidgetsInitialised(); + if (areWidgetsInitialized) { + callback && callback(); + } else { + this._dashboard.vis.once('dataviewsFetched', function () { + callback && callback(); + }); + } + }, + + onStateChanged: function (callback) { + this.onDataviewsFetched(function () { + callback && this._bindChange(callback); + }.bind(this)); + }, + + _bindChange: function (callback) { + var widgetsCollection = this._dashboard.widgets.getCollection(); + widgetsCollection.bind('change', function () { + callback(this.getState(), this.getDashboardURL()); + }, this); + + this._dashboard.vis.map.bind('change', function () { + callback(this.getState(), this.getDashboardURL()); + }, this); + }, + + /** + * @param {Integer} id - widget id + * @return a widget object + */ + getWidget: function (id) { + return this._dashboard.widgets.get(id); + }, + + /** + * Create a category widget. + * @param {Object} widgetAttrs - attributes for the new widget + * @param {string} widgetAttrs.id - id (required) + * @param {string} widgetAttrs.title - title (required) + * @param {number} widgetAttrs.order - index of the widget (optional) + * @param ... + * @return {CategoryWidget} The new widget + */ + createCategoryWidget: function (widgetAttrs, layer) { + return this._dashboard.widgets.createCategoryModel(widgetAttrs, layer, null); + }, + + /** + * Create a histogram widget + * @param {Object} widgetAttrs - attributes for the new widget + * @param {string} widgetAttrs.id - id (required) + * @param {string} widgetAttrs.title - title (required) + * @param {number} widgetAttrs.order - index of the widget (optional) + * @param ... + * @return {HistogramWidget} The new widget + */ + createHistogramWidget: function (widgetAttrs, layer) { + return this._dashboard.widgets.createHistogramModel(widgetAttrs, layer, null); + }, + + /** + * Create a formula widget + * @param {Object} widgetAttrs - attributes for the new widget + * @param {string} widgetAttrs.id - id (required) + * @param {string} widgetAttrs.title - title (required) + * @param {number} widgetAttrs.order - index of the widget (optional) + * @param ... + * @return {FormulaWidget} The new widget + */ + createFormulaWidget: function (widgetAttrs, layer) { + return this._dashboard.widgets.createFormulaModel(widgetAttrs, layer, null); + }, + + /** + * Create a timesier es widget + * @param {Object} widgetAttrs - attributes for the new widget + * @param {string} widgetAttrs.id - id (required) + * @param {string} widgetAttrs.title - title (required) + * @param {number} widgetAttrs.order - index of the widget (optional) + * @param ... + * @return {TimeSeriesWidget} The new widget + */ + createTimeSeriesWidget: function (widgetAttrs, layer) { + return this._dashboard.widgets.createTimeSeriesModel(widgetAttrs, layer, null); + } + +}; + +module.exports = Dashboard; diff --git a/pool/shard010/JavaScript/0067294_AssemblyFor.js b/pool/shard010/JavaScript/0067294_AssemblyFor.js new file mode 100644 index 0000000000000000000000000000000000000000..2e7c28578c51a1dd6132483a130497b68e3ffd6f --- /dev/null +++ b/pool/shard010/JavaScript/0067294_AssemblyFor.js @@ -0,0 +1,18 @@ +const { + doc: { + builders: { join } + } +} = require('prettier/standalone'); + +const AssemblyFor = { + print: ({ path, print }) => + join(' ', [ + 'for', + path.call(print, 'pre'), + path.call(print, 'condition'), + path.call(print, 'post'), + path.call(print, 'body') + ]) +}; + +module.exports = AssemblyFor; diff --git a/pool/shard010/JavaScript/0067298_transitions.js b/pool/shard010/JavaScript/0067298_transitions.js new file mode 100644 index 0000000000000000000000000000000000000000..67a6f9c44180bbc3b4e902766a38ebae08b6ca65 --- /dev/null +++ b/pool/shard010/JavaScript/0067298_transitions.js @@ -0,0 +1,66 @@ +/** + * @fileOverview 特效渐变方式。 + * @author xuld + */ + +Fx.Transitions = { + + linear: function(p){ + return p; + }, + + power: function(p, x){ + return Math.pow(p, x || 3); + }, + + exponential: function(p){ + return Math.pow(2, 8 * (p - 1)); + }, + + circular: function(p){ + return 1 - Math.sin(Math.acos(p)); + }, + + sinusoidal: function(p){ + return 1 - Math.sin((1 - p) * Math.PI / 2); + }, + + back: function(p, x){ + x = x || 1.618; + return Math.pow(p, 2) * ((x + 1) * p - x); + }, + + bounce: function(p){ + var value; + for (var a = 0, b = 1; 1; a += b, b /= 2){ + if (p >= (7 - 4 * a) / 11){ + value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); + break; + } + } + return value; + }, + + elastic: function(p, x){ + return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x || 1) / 3); + } + +}; + +Fx.easeIn = function(transition, x){ + return function(p){ + return transition(p, x); + }; +}; + +Fx.easeOut = function(transition, x){ + return function(p){ + return 1 - transition(1 - p, x); + }; +}; + +Fx.easeInOut = function(transition, x){ + return function(p){ + return (p <= 0.5) ? transition(2 * p, x) / 2 : (2 - transition(2 * (1 - p), x)) / 2; + }; +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067302_home.js b/pool/shard010/JavaScript/0067302_home.js new file mode 100644 index 0000000000000000000000000000000000000000..be4af4bfc5bf1192431debb53ea8f91786f8510c --- /dev/null +++ b/pool/shard010/JavaScript/0067302_home.js @@ -0,0 +1,61 @@ +$('#J-go-attention').on('click',function () { + var userID=$('input[name="userID"]').val(); + $.ajax({ + url: '/album/ajax-follow', + type: 'GET', + data: {id: userID}, + }) + .done(function(data) { + if(data) + { + $('#J-go-attention').css('display','none'); + $('#J-go-unfollow').css('display','inline-block'); + } + }) + .fail(function() { + console.log("error"); + }) + .always(function() { + console.log("complete"); + }); +}); +$('#J-go-unfollow').on('click',function () { + var userID=$('input[name="userID"]').val(); + $.ajax({ + url: '/album/ajax-unfollow', + type: 'GET', + data: {id: userID}, + }) + .done(function(data) { + //console.log(data); + if(data) + { + $('#J-go-attention').css('display','inline-block'); + $('#J-go-unfollow').css('display','none'); + } + }) + .fail(function() { + console.log("error"); + }) + .always(function() { + //console.log("complete"); + }); +}); +/**********AJAX取消展示***********/ +$('.editarea .del').on('click',function () { + var del=$(this); + var id=$(this).attr('data-id'); + $.ajax({ + url: '/home/ajax-remove-album', + type: 'GET', + data: {id: id}, + dataType:'json', + }) + .done(function() { + del.parent().parent().remove(); + }) + .fail(function() { + alert('删除失败!'); + }) + +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067304_kingsisland.js b/pool/shard010/JavaScript/0067304_kingsisland.js new file mode 100644 index 0000000000000000000000000000000000000000..4fb99de6c2d75eb00a89f3404f047ff1e5f70f30 --- /dev/null +++ b/pool/shard010/JavaScript/0067304_kingsisland.js @@ -0,0 +1,30 @@ +const CedarFairPark = require('./cedarfairparkbase'); + +/** + * KingsIsland + * @class + * @extends CedarFairPark + */ +class KingsIsland extends CedarFairPark { + /** + * Create new KingsIsland Object. + */ + constructor(options = {}) { + options.name = options.name || 'Kings Island'; + + // park ID + options.park_id = options.park_id || 'CF_KI'; + + // entrance location + options.latitude = 39.3447; + options.longitude = -84.2686; + + // timezone + options.timezone = 'America/New_York'; + + // inherit from base class + super(options); + } +} + +module.exports = KingsIsland; diff --git a/pool/shard010/JavaScript/0067305_ex1.js b/pool/shard010/JavaScript/0067305_ex1.js new file mode 100644 index 0000000000000000000000000000000000000000..cda048496428ba70f68adc2ae3357ea16ac72e9f --- /dev/null +++ b/pool/shard010/JavaScript/0067305_ex1.js @@ -0,0 +1,18 @@ +var obj = { + a: 1, + b: "2", + c: [3], + d: { val: 4 }, + e: function() { return "5"; }, + f: false +}; + +if (Boolean(obj.c)) { + obj.f = Boolean(obj.d.val / Number(obj.b)); +} + +obj.a = (Number(obj.b) * obj.c[0]) + Number(obj.e()); + +console.log(JSON.stringify(obj)); +// should be: +// {"a":11,"b":"2","c":[3],"d":{"val":4},"f":true} diff --git a/pool/shard010/JavaScript/0067311_logging.js b/pool/shard010/JavaScript/0067311_logging.js new file mode 100644 index 0000000000000000000000000000000000000000..b47fe6bc17fc4cd2a0fc94e1b01633e78a1eb3ac --- /dev/null +++ b/pool/shard010/JavaScript/0067311_logging.js @@ -0,0 +1,59 @@ +/*global module:true, require:true */ + +'use strict'; + +var fs = require('fs') + , path = require('path') + , config = require('yaml-config') + , bunyan = require('bunyan'); + + +exports.createLogger = createLogger; + + +/* + * configure and start logging + * @param {Object} config The configuration object for defining dir: log directory, level: loglevel + * @return the created logger instance + */ +function createLogger (config) { + + var pkg = require(path.join(__dirname, 'package')) + , appName = pkg.name + , appVersion = pkg.version + , logDir = config.dir || path.join(__dirname, 'logs') + , logFile = path.join(logDir, appName + '-log.json') + , logErrorFile = path.join(logDir, appName + '-errors.json') + , logLevel = config.level || 'debug'; + + // Create log directory if it doesnt exist + if (! fs.existsSync(logDir)) fs.mkdirSync(logDir); + + // Log to console and log file + var log = bunyan.createLogger({ + name: appName + , streams: [ + { + stream: process.stdout + , level: 'warn' + } + , { + path: logFile + , level: logLevel + , type: 'rotating-file' + , period: '1d' + } + , { + path: logErrorFile + , level: 'error' + } + ] + , serializers: bunyan.stdSerializers + }); + + log.info('Starting ' + appName + ', version ' + appVersion); + log.info('Environment set to ' + process.env.NODE_ENV); + log.debug('Logging setup completed.'); + + return log; +} diff --git a/pool/shard010/JavaScript/0067312_TrackerTask.js b/pool/shard010/JavaScript/0067312_TrackerTask.js new file mode 100644 index 0000000000000000000000000000000000000000..24dffc0ecc5562789bd908524fd4e17803d1fdee --- /dev/null +++ b/pool/shard010/JavaScript/0067312_TrackerTask.js @@ -0,0 +1,103 @@ +(function() { + /** + * TrackerTask utility. + * @constructor + * @extends {tracking.EventEmitter} + */ + tracking.TrackerTask = function(tracker) { + tracking.TrackerTask.base(this, 'constructor'); + + if (!tracker) { + throw new Error('Tracker instance not specified.'); + } + + this.setTracker(tracker); + }; + + tracking.inherits(tracking.TrackerTask, tracking.EventEmitter); + + /** + * Holds the tracker instance managed by this task. + * @type {tracking.Tracker} + * @private + */ + tracking.TrackerTask.prototype.tracker_ = null; + + /** + * Holds if the tracker task is in running. + * @type {boolean} + * @private + */ + tracking.TrackerTask.prototype.running_ = false; + + /** + * Gets the tracker instance managed by this task. + * @return {tracking.Tracker} + */ + tracking.TrackerTask.prototype.getTracker = function() { + return this.tracker_; + }; + + /** + * Returns true if the tracker task is in running, false otherwise. + * @return {boolean} + * @private + */ + tracking.TrackerTask.prototype.inRunning = function() { + return this.running_; + }; + + /** + * Sets if the tracker task is in running. + * @param {boolean} running + * @private + */ + tracking.TrackerTask.prototype.setRunning = function(running) { + this.running_ = running; + }; + + /** + * Sets the tracker instance managed by this task. + * @return {tracking.Tracker} + */ + tracking.TrackerTask.prototype.setTracker = function(tracker) { + this.tracker_ = tracker; + }; + + /** + * Emits a `run` event on the tracker task for the implementers to run any + * child action, e.g. `requestAnimationFrame`. + * @return {object} Returns itself, so calls can be chained. + */ + tracking.TrackerTask.prototype.run = function() { + var self = this; + + if (this.inRunning()) { + return; + } + + this.setRunning(true); + this.reemitTrackEvent_ = function(event) { + self.emit('track', event); + }; + this.tracker_.on('track', this.reemitTrackEvent_); + this.emit('run'); + return this; + }; + + /** + * Emits a `stop` event on the tracker task for the implementers to stop any + * child action being done, e.g. `requestAnimationFrame`. + * @return {object} Returns itself, so calls can be chained. + */ + tracking.TrackerTask.prototype.stop = function() { + if (!this.inRunning()) { + return; + } + + this.setRunning(false); + this.emit('stop'); + this.tracker_.removeListener('track', this.reemitTrackEvent_); + return this; + }; +}()); diff --git a/pool/shard010/JavaScript/0067319_actions.js b/pool/shard010/JavaScript/0067319_actions.js new file mode 100644 index 0000000000000000000000000000000000000000..3fa1c560fae46fd494c048da320df472e8e14f2f --- /dev/null +++ b/pool/shard010/JavaScript/0067319_actions.js @@ -0,0 +1,240 @@ +import store from './store'; +import { getValidWaypoints } from './reducers/waypoints'; +import { getSource } from './reducers/profiles'; +import geocoder from './geocoder'; +import routing from './routing'; +import map from './map'; +import config from '../config'; +import MapUtils from './utils/MapUtils'; +import profiles from './profiles'; +import util from './util'; +import { findById } from './immulib'; +import {messages} from './constants'; + + +const dispatch = store.dispatch; +const getState = store.getState; + + +function canCalculateRoute(force=false) { + const state = getState(); + + const waypoints = getValidWaypoints(state.waypoints); + if (waypoints.length < 2) + return messages.MISSING_WAYPOINTS; + + const profile = state.profiles::findById(state.options.profileId); + if (!profile.source) + return messages.EMPTY_PROFILE_SOURCE; + + const distance = MapUtils.calculateDistance(waypoints); + if (distance > config.maxBrouterCalculationDistance) { + return messages.DISTANCE_TOO_LONG; + } + else if (distance > config.maxBrouterAutoCalculationDistance && !force) { + return messages.DISTANCE_TOO_LONG_FOR_AUTOCALCULATION; + } + return true; +} + + +export function calculateRoute(options = {}) { + const {fit=true, force=false} = options; + + const canCalculate = canCalculateRoute(force); + if (canCalculate === true) { + const state = getState(); + const waypoints = getValidWaypoints(state.waypoints); + if (fit) { + fitWaypoints(waypoints); + } + const latLngs = MapUtils.getLatLngsFromWaypoints(waypoints); + const profile = state.profiles::findById(state.options.profileId); + const routeIndex = state.options.routeIndex; + const profileOptions = state.options.profileOptions; + + dispatch({type: 'CALCULATE_ROUTE'}); + MapUtils.showTrailer(latLngs); + MapUtils.cleanRouteLayers(getState().routes); + + routing.route(latLngs, getSource(profile, profileOptions), routeIndex, (error, geojson) => { + if (geojson) { + const id = util.id(); + const name = `${waypoints[0].address} - ${waypoints[waypoints.length - 1].address}`; + const route = {id, name, geojson, waypoints, profile, profileOptions, routeIndex, color: MapUtils.getRouteFreeColor(getState().routes)}; + dispatch({type: 'CALCULATE_ROUTE_SUCCESS', ...route}); + MapUtils.createRouteLayer(id, geojson, route.color); + if (fit) { + fitRoute(id); + } + } else { + dispatch({type: 'CALCULATE_ROUTE_FAIL', message: error}); + } + MapUtils.hideTrailer(); + }); + } else { + dispatch({type: 'CALCULATE_ROUTE_ABORT', message: canCalculate}); + } +} + +export function clearErrorMessage() { + dispatch({type: 'CLEAR_ERROR_MESSAGE'}); +} + + +/* + * Waypoints + */ +export function putWaypointAtLatLng(type, latLng) { + let id; + if (type !== 'via') { + const waypoints = getState().waypoints; + if (type === 'start') + id = waypoints[0].id; + else if (type === 'end') + id = waypoints[waypoints.length - 1].id; + updateWaypoint(id, {latLng, address: MapUtils.latLngToString(latLng)}); + } else { + id = util.id(); + addViaWaypoint(id, {latLng, address: MapUtils.latLngToString(latLng)}); + } + reverseGeocodeWaypoint(id, latLng); + calculateRoute(); + updateMarkers(); +} + +export function addViaWaypoint(id, props) { + dispatch({type: 'ADD_VIA_WAYPOINT', id, ...props}); +} + +export function geocodeWaypoint(id, address) { + dispatch({type: 'GEOCODE_START', id, address}); + geocoder.query(address, (results) => { + if (results && results[0]) { + const result = results[0]; + const latLng = MapUtils.latLngToArray(result.latLng); + dispatch({type: 'GEOCODE_SUCCESS', id, latLng, address}); + updateMarkers(); + + const validWaypoints = getValidWaypoints(getState().waypoints); + if (validWaypoints.length === 1) { + zoomWaypoint(latLng); + } else { + fitWaypoints(validWaypoints); + calculateRoute(); + } + } else { + dispatch({type: 'GEOCODE_FAIL', id, address}); + updateMarkers(); + } + }); +} + +export function reverseGeocodeWaypoint(id, latLng) { + dispatch({type: 'REVERSE_GEOCODE_START', id, latLng, address: MapUtils.latLngToString(latLng)}); + geocoder.reverse(latLng, (result) => { + if (result) { + dispatch({type: 'REVERSE_GEOCODE_SUCCESS', id, latLng, address: result.formatted}); + updateMarkers(); + } else { + dispatch({type: 'REVERSE_GEOCODE_FAIL', id, latLng}); + updateMarkers(); + } + }); +} + +export function zoomWaypoint(latLng) { + map.setView(latLng, 14); +} + +export function fitWaypoints(waypoints) { + map.fitBounds(MapUtils.getWaypointBounds(waypoints), MapUtils.FIT_OPTIONS); +} + +export function moveWaypoint(id, latLng) { + reverseGeocodeWaypoint(id, latLng); + calculateRoute({fit: false}); +} + +export function deleteWaypointOnClick(id) { + deleteWaypoint(id); + calculateRoute(); +} + +export function swapWaypoints() { + dispatch({type: 'SWAP_WAYPOINTS'}); + calculateRoute(); +} + +export function reorderWaypoints(idA, idB) { + dispatch({type: 'REORDER_WAYPOINTS', idA, idB}); +} + +export function updateWaypoint(id, updates) { + dispatch({type: 'UPDATE_WAYPOINT', id, ...updates}); + updateMarkers(); +} + +export function clearWaypoint(id) { + updateWaypoint(id, {address: '', latLng: null}); +} + +export function deleteWaypoint(id) { + dispatch({type: 'DELETE_WAYPOINT', id}); + updateMarkers(); +} + + +/* + * Routes + */ +export function fitRoute(id) { + map.fitBounds(MapUtils.getRouteLayer(id).getBounds(), MapUtils.FIT_OPTIONS); +} + +export function updateRoute(id, updates) { + dispatch({type: 'UPDATE_ROUTE', id, ...updates}); +} + +export function toggleRouteLock(id) { + const route = getState().routes::findById(id); + updateRoute(id, {locked: !route.locked}); +} + +export function deleteRoute(id) { + dispatch({type: 'DELETE_ROUTE', id}); + MapUtils.cleanRouteLayers(getState().routes); +} + + +/* + * Profile + */ +export function setProfile(id) { + dispatch({type: 'SET_PROFILE', id}); + if (id !== 'custom') { + calculateRoute(); + } +} + +export function setRouteIndex(routeIndex) { + dispatch({type: 'SET_ROUTE_INDEX', routeIndex}); + calculateRoute(); +} + +export function setProfileOption(optionId, value) { + dispatch({type: 'SET_PROFILE_OPTION', optionId, value}); + calculateRoute(); +} + +export function setCustomProfileSource(source) { + dispatch({type: 'SET_CUSTOM_PROFILE_SOURCE', source}); +} + + +/* + * Helper functions + */ +function updateMarkers() { + MapUtils.updateMarkers(getState().waypoints); +} diff --git a/pool/shard010/JavaScript/0067321_server.js b/pool/shard010/JavaScript/0067321_server.js new file mode 100644 index 0000000000000000000000000000000000000000..100b141039b2d826370968a9fa64ddd918fb1088 --- /dev/null +++ b/pool/shard010/JavaScript/0067321_server.js @@ -0,0 +1,32 @@ +/** + * @author Kris Doromal + */ + +//required modules +var io = require("socket.io"), + connect("connect"); + +//use connect to start a server use function is used to connect to the public folder +var app = connect().use(connect.static("public"))listen(3000, "0.0.0.0"); + +//create websocket listen to the app made with connect +var server = io.listen(app); + +//client connects +server.sockets.on("connection", function(socket){ + + //broadcast to users when dot is drawn + socket.on("drawDot", function(data){ + socket.broadcast.emit("drawDot", data); + }) + + //braodcast to users when line is drawn + socket.on("drawLine", function(data){ + socket.broadcast.emit("drawLine", data); + }) + + //broadcast to users when clear is called + socket.on("clearDrawing", function(){ + socket.broadcast.emit("clearDrawing"); + }) +}); diff --git a/pool/shard010/JavaScript/0067323_CreateClassifierHandlerFunction.js b/pool/shard010/JavaScript/0067323_CreateClassifierHandlerFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..0c4c56ec19879d81baac183441024065c1772acd --- /dev/null +++ b/pool/shard010/JavaScript/0067323_CreateClassifierHandlerFunction.js @@ -0,0 +1,274 @@ +'use strict'; + +/* eslint-disable no-console */ +const fs = require('fs'); +const config = require('config'); +const request = require('request'); +const utils = require('../utils/Utils'); +const logger = require('../modules/logger'); +//const WatsonVisualRecognitionRestClient = require('./WatsonVisualRecognitionRestClientConfigureFunction'); +const WatsonVisualRecognitionUtil = require('../utils/WatsonVisualRecognitionUtil'); + + +//グローバル設定パラメター (config設定ファイルから値を取得) +const keepUploadedImageFiles = config.app.global.keep_uploaded_image_files; +const keepGeneratedTrainingZipFiles = config.app.global.keep_generated_training_zip_files; + +const NEGATIVE_EXAMPLES = 'negativeExamples'; +const POSITIVE_EXAMPLES = 'positiveExamples'; + +/** + * Routeハンドラー:POST /api/classifiers用 + */ +const handlerFunc = (req, res) => { + logger.app.debug("Called CreateClassifierHandlerFunction."); + + //HTML側でのname属性と整合性を併せてミドルウェア設定しているため、ここでは req.files に情報が入っている + //console.log('req.files = ' + JSON.stringify(req.files)); + + //requestモジュールによるファイルアップロードでformDataキーにセットする送信データの入れ物 + const formData = {}; + + //multerのany()でうけったreq.filesオブジェクトそのままでは送信に使えない。 + //そのため、加工処理して + // { + // "positiveExamples" : { //値はオブジェクト型 + // "className1" : [] //ファイル情報オブジェクトの配列 + // "className2" : [] // + // }, + // "negativeExamples" : [ ファイル情報オブジェクトの配列] //値は配列型, + // "classNames" : [] //PositiceExampleのクラス名配列 + // } + // + //となるようなオブジェクトを生成する + const fileInfoContainer = createUploadedFileInfoContainer(req.files); + + // // + // const negativeExampleFileInfo = req.files['negativeExamples']; + // + // for (var j = 0, m = negativeExampleFileInfo.length; j < m; j++) { + // console.log('negativeExamples[' + j + ']=' + JSON.stringify(negativeExampleFileInfo[j])); + // } + + const classifierName = req.body.classifierName; + logger.app.debug('new classifierName = ' + classifierName); + + const promiseArray = createAllZip(fileInfoContainer, []); + + //すべてのZIP化が完了後に実際の送信処理を行う + Promise.all(promiseArray).then((array) => { + + logger.app.debug('after createAllZip result array = ' + JSON.stringify(array)); + + formData['name'] = classifierName; + + const hasNegativeExamples = (fileInfoContainer['negativeExamples'].length > 0); + + for (let i = 0; i < array.length; i++) { + //fileInfoContainerの生成ロジック仕様に基づいて、 + //Promise配列の先頭は、ネガティブ画像イメージデータである可能性がある + //(ネガティブ画像イメージデータはオプションのため、必ずしも先頭の要素だからといってネガティブ画像だとは限らない) + //fileInfoContainerに、キーnegativeExamplesにセットされている配列の要素数が1以上であれば、ネガティブ画像データが + //ブラウザ側からアップロードされてきていることになる。 + if (i === 0 && hasNegativeExamples) { + formData['negative_examples'] = { + value: fs.createReadStream(array[i][0]), + options: { + filename: 'negativeExamples.zip', + contentType: 'application/zip' + } + }; + } else { + // 先頭データであってもfileInfoContainer['negativeExamples'].length === 0 の場合や、 + //そもそも2番目以降の場合は、それは常にポジティブ画像データである。 + + // クラス名の取得 + let classname = (hasNegativeExamples ? fileInfoContainer.classNames[i - 1] : fileInfoContainer.classNames[i]); + + //送信フォームデータのパラメータ名は、ポジティブ画像データについては<クラス名>_positive_examplesとしなければならない仕様 + formData[classname + '_positive_examples'] = { + // value: positiveExampleZipBuffer, //Bufferデータはrequestモジュールによってサポートされる + value: fs.createReadStream(array[i][0]), + options: { + filename: 'positiveExamples' + '_' + (hasNegativeExamples ? i - 1 : i) + '.zip', + contentType: 'application/zip' + } + } + } + } + // logger.app.debug('positive_examples zip file path = ' + positiveExamplesZipFilePath); + // logger.app.debug('negative_examples zip file path = ' + negativeExamplesZipFilePath); + + var hrstart = process.hrtime(); + + logger.app.debug('Create Classifier Request start to send...'); + + logger.app.debug('formData = ' + JSON.stringify(formData)); + + //node-rest-clientではファイルアップロードに対応していないので、requestを使ってデータを送る + request({ + method: 'POST', + preambleCRLF: true, + postambleCRLF: true, + //url: config.watson.visual_recognition.baseUrl + '/v2/classifiers?version=2015-12-02', + url: WatsonVisualRecognitionUtil.createApiUrl('/v3/classifiers'), + headers: { + 'X-Watson-Learning-Opt-Out': config.bluemix_service.watson_visualrecognition_v3.opt_out + }, + formData: formData + }, (error, response, body) => { + //処理時間計測 + const hrend = process.hrtime(hrstart); //引数にhrstartを指定することで、そことの差分時間を返す + + if (error) { + logger.app.error("ERROR " + JSON.stringify(error)); + res.status(500).json(error); + } else if (response.statusCode >= 300) { + + logger.app.error("ERROR HTTP Response Status = " + response.statusCode + ', body = ' + response.body + 'headers = ' + JSON.stringify(response.headers)); + + try { + const parsedBody = JSON.parse(response.body); + //Watson VR API仕様上、エラーJSONは code と error の2つのキーを持つ + if (parsedBody) { + res.status(response.statusCode).json(parsedBody); + } else { + res.status(response.statusCode).send("Server Error"); + } + } catch (ex) { + // JSON.parseに失敗した場合など。500番台で、レスポンスボディがJSONテキストではなく、文字列テキストであるような場合(502など) + res.status(response.statusCode).send("Server Error : " + response.body); + } + } else { + logger.app.debug('Upload success! Server response:', body); + //文字列テキストであるbodyを、再度JavaScriptオブジェクト化し、処理時間の配列を保持するプロパティを生やす。 + var respdata = JSON.parse(body); + //console.log('elapsedTime = ' + JSON.stringify(hrend)); + respdata['elapsedTime'] = hrend; + // console.log('update respdata:', JSON.stringify(respdata)); + //res.status(response.statusCode).send(respdata); + res.status(response.statusCode).json(respdata); + + } + + //delete files + //後処理:ファイルの削除 + if (!keepUploadedImageFiles) { + //fileInfoContinerを元に、そこに指定されているすべてのファイルを削除 + utils.deleteUplodedFiles(req.files); + } + + if (!keepGeneratedTrainingZipFiles && array.length > 0) { + array.forEach((arr) => { + + fs.unlink(arr[0], (err) => { + if (err) { + //throw err; + } + logger.app.debug('zip file deleted = ' + arr[0]); + }); + }); + } + + } + + ); + + + }).catch((err) => { + res.status(500).json(err); + }); + +} + +// { +// "positiveExamples" : { //値はオブジェクト型 +// "className1" : [] //ファイル情報オブジェクトの配列 +// "className2" : [] // +// }, +// "negativeExamples" : [ ファイル情報オブジェクトの配列] //値は配列型 +// } +const createUploadedFileInfoContainer = (files) => { + + //戻り値 + const fileInfoContainer = {}; + + const _POSITIVEEXAMPLES = "_positiveExamples"; + + fileInfoContainer['classNames'] = []; + + //v3APIの仕様上、negativeExamplesは1つしかないので、クラス名ではなくそのまま配列を値としてセット + fileInfoContainer['negativeExamples'] = []; ///空の配列 + fileInfoContainer['positiveExamples'] = {}; ///空のオブジェクト + + const positiveExamples = fileInfoContainer['positiveExamples']; + + if (files) { + + let previousclassName = null; + + files.forEach((value) => { + const fieldName = value.fieldname; + if (fieldName === 'negativeExamples' && value) { + //フィールド名が negativeExamples の場合は、各ファイル情報オブジェクトを単純に追加していく + fileInfoContainer['negativeExamples'].push(value); + } else if (fieldName.indexOf(_POSITIVEEXAMPLES) !== -1) { + //フィールド名が_positiveExamplesを含んでいる場合、クラス名を切り出してそれをキー名に配列をセット(なければセット)して追加 + const regexp = new RegExp(_POSITIVEEXAMPLES, "g"); + const className = fieldName.replace(regexp, ''); //空文字に置換つまり該当部分の文字を削除 + if (!positiveExamples[className]) { + positiveExamples[className] = []; //空の配列をセット + } + + positiveExamples[className].push(value); + //classNames配列は、同じクラス名は二度と入れない。そのため、前と同じでない場合にのみセットする + if (previousclassName !== className) { + fileInfoContainer['classNames'].push(className); + } + //1つ前のものとしてセット + previousclassName = className; + + } + }); + } + + logger.app.debug('fileInfoContainer = ' + JSON.stringify(fileInfoContainer)); + + return fileInfoContainer; +}; + +/** + * 関数 全部のZIPファイルを作成する + */ +const createAllZip = (fileInfoContainer) => { + + const promiseArray = []; + + let negativeExampleFileInfo = fileInfoContainer['negativeExamples']; + + //ネガティブ画像ファイル(単発またはZIPのどちらにしても)はオプションであり、何もファイルが送信されてこない場合がある。 + //その場合は fileInfoContainer['negativeExamples'] の値は初期値としての「空の配列」がセットされている。 + //この場合は、そもそもZIPファイルのセットを行わない(Promise配列にセットしない) + if (negativeExampleFileInfo.length > 0) { + //negativeExampleのアップロード用ZIPファイルを生成 + const firstPromise = utils.createZip(negativeExampleFileInfo, []); + promiseArray.push(firstPromise); + } + + //以降、数が不定のpositiveExamples用の処理を行う + // 値はオブジェクト型 + const positiveExamples = fileInfoContainer.positiveExamples; + + //logger.app.debug('positiveExamples' + JSON.stringify(positiveExamples)); + + Object.keys(positiveExamples).forEach((key) => { + //logger.app.debug('key=' + key); + const positiveClassExampleFileInfo = positiveExamples[key]; + const promise = utils.createZip(positiveClassExampleFileInfo, []); + promiseArray.push(promise); + }); + + return promiseArray; +}; + +module.exports = handlerFunc; diff --git a/pool/shard010/JavaScript/0067324_modal.spec.js b/pool/shard010/JavaScript/0067324_modal.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a64acd955033af599a7fa8c82864fa00b6043061 --- /dev/null +++ b/pool/shard010/JavaScript/0067324_modal.spec.js @@ -0,0 +1,163 @@ +/* + * (c) Copyright 2015 Hewlett-Packard Development Company, L.P. + * + * 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. + */ +(function() { + "use strict"; + + describe('horizon.framework.widgets.modal module', function() { + + beforeEach(module('horizon.framework.widgets.modal')); + + describe('SimpleModalController', function() { + var modalInstance, context, ctrl; + + beforeEach(inject(function($controller) { + modalInstance = { + close: function() {}, + dismiss: function() {} + }; + context = { what: 'is it' }; + ctrl = $controller('SimpleModalController', + {$modalInstance: modalInstance, + context: context}); + })); + + it('establishes a controller', function() { + expect(ctrl).toBeDefined(); + }); + + it('sets context on the modalCtrl variable', function() { + expect(ctrl.context).toBeDefined(); + expect(ctrl.context).toEqual({ what: 'is it' }); + }); + + it('sets action functions', function() { + expect(ctrl.submit).toBeDefined(); + expect(ctrl.cancel).toBeDefined(); + }); + + it('makes submit close the modal instance', function() { + expect(ctrl.submit).toBeDefined(); + spyOn(modalInstance, 'close'); + ctrl.submit(); + expect(modalInstance.close.calls.count()).toBe(1); + }); + + it('makes cancel close the modal instance', function() { + expect(ctrl.cancel).toBeDefined(); + spyOn(modalInstance, 'dismiss'); + ctrl.cancel(); + expect(modalInstance.dismiss).toHaveBeenCalledWith('cancel'); + }); + + }); + + describe('horizon.framework.widgets.modal.service', function() { + var service, modal; + + beforeEach(module(function($provide) { + modal = { open: function() {return 'val';} }; + $provide.value('horizon.framework.widgets.basePath', '/this/path/'); + $provide.value('$modal', modal); + })); + + beforeEach(inject(function($injector) { + service = $injector.get('horizon.framework.widgets.modal.service'); + })); + + it('defines the service', function() { + expect(service).toBeDefined(); + }); + + it('returns undefined if called with no parameters', function() { + expect(service.modal()).toBeUndefined(); + }); + + it('returns undefined if called without required parameters', function() { + expect(service.modal({title: {}})).toBeUndefined(); + expect(service.modal({body: {}})).toBeUndefined(); + }); + + describe('Maximal Values Passed to the Modal', function() { + + var returned, passed, passedContext; + + beforeEach(function() { + var opts = { title: 'my title', body: 'my body', submit: 'Yes', + cancel: 'No' }; + spyOn(modal, 'open'); + returned = service.modal(opts); + passed = modal.open.calls.argsFor(0)[0]; + passedContext = passed.resolve.context(); + }); + + it('sets the controller', function() { + expect(passed.controller).toBe('SimpleModalController'); + }); + + it('sets the template URL', function() { + expect(passed.templateUrl).toBe('/this/path/modal/simple-modal.html'); + }); + + it('sets the title', function() { + expect(passedContext.title).toBe('my title'); + }); + + it('sets the body', function() { + expect(passedContext.body).toBe('my body'); + }); + + it('sets the submit', function() { + expect(passedContext.submit).toBe('Yes'); + }); + + it('sets the cancel', function() { + expect(passedContext.cancel).toBe('No'); + }); + + }); + + describe('Minimal Values Passed to the Modal', function() { + + var returned, passed, passedContext; + + beforeEach(function() { + var opts = { title: 'my title', body: 'my body' }; + spyOn(modal, 'open'); + returned = service.modal(opts); + passed = modal.open.calls.argsFor(0)[0]; + passedContext = passed.resolve.context(); + }); + + it('sets the title', function() { + expect(passedContext.title).toBe('my title'); + }); + + it('sets the body', function() { + expect(passedContext.body).toBe('my body'); + }); + + it('defaults the submit', function() { + expect(passedContext.submit).toBe('Submit'); + }); + + it('defaults the cancel', function() { + expect(passedContext.cancel).toBe('Cancel'); + }); + }); + }); + }); + +})(); diff --git a/pool/shard010/JavaScript/0067329_spawn_chain_daemon.js b/pool/shard010/JavaScript/0067329_spawn_chain_daemon.js new file mode 100644 index 0000000000000000000000000000000000000000..f1e965599de51a1d9057331c774ab74e499f35e0 --- /dev/null +++ b/pool/shard010/JavaScript/0067329_spawn_chain_daemon.js @@ -0,0 +1,88 @@ +const {join} = require('path'); +const {tmpdir} = require('os'); + +const removeDir = require('rimraf'); +const {v4} = require('uuid'); + +const btcsuiteTypeDaemon = require('./btcsuite_type_daemon'); + +/** Spawn a chain daemon for testing on regtest + + This method will also listen for uncaught exceptions and stop the daemon + before the process dies. + + { + daemon: + [is_tls]: // only supported for btcsuite type + mining_public_key: + } + + @returns via cbk + { + daemon: + dir: + listen_port: + [rpc_cert]: + rpc_port: + } +*/ +module.exports = (args, cbk) => { + if (!args.daemon) { + return cbk([400, 'ExpectedDaemonTypeToSpawn']); + } + + let daemon; + + const dir = join(tmpdir(), v4()); + + switch (args.daemon) { + case 'btcd': + daemon = btcsuiteTypeDaemon({ + dir, + daemon: args.daemon, + is_tls: args.is_tls, + mining_public_key: args.mining_public_key, + }, + (err, res) => { + if (!!err) { + return cbk(err); + } + + res.daemon.stderr.on('data', data => { + if (/mandatory.script.verify.flag/gim.test(data+'')) { + return; + } + + if (/txn.already.in.mempool/gim.test(data+'')) { + return; + } + + return; + }); + + res.daemon.on('close', code => removeDir(dir, () => {})); + + process.setMaxListeners(20); + + process.on('uncaughtException', err => { + res.daemon.kill(); + process.exit(1) + }); + + return cbk(null, { + dir, + daemon: res.daemon, + listen_port: res.listen_port, + rpc_cert: join(dir, 'rpc.cert'), + rpc_port: res.rpc_port, + }); + }); + break; + + default: + return cbk([400, 'UnknownDaemonType', args.daemon]); + } + + return; +}; + diff --git a/pool/shard010/JavaScript/0067333_next-url.js b/pool/shard010/JavaScript/0067333_next-url.js new file mode 100644 index 0000000000000000000000000000000000000000..700732e0f2630f416ba07abea7c33cced5f84de8 --- /dev/null +++ b/pool/shard010/JavaScript/0067333_next-url.js @@ -0,0 +1,70 @@ +/** + * next-url.js | https://theme-next.org/api/helpers/next-url/ + */ + +/* global hexo */ + +'use strict'; + +hexo.extend.helper.register('next_url', function(path, text, options) { + var htmlTag = require('hexo-util').htmlTag; + var config = this.config; + var url = require('url'); + var data = url.parse(path); + var siteHost = url.parse(config.url).hostname || config.url; + + var theme = hexo.theme.config; + var exturl = ''; + var tag = 'a'; + var attrs = { href: this.url_for(path) }; + + // If `exturl` enabled, set spanned links only on external links. + if (theme.exturl && data.protocol && data.hostname !== siteHost) { + tag = 'span'; + exturl = 'exturl'; + var encoded = Buffer.from(path).toString('base64'); + attrs = { + class : exturl, + 'data-url': encoded + }; + } + + options = options || {}; + + var keys = Object.keys(options); + var key = ''; + + for (var i = 0, len = keys.length; i < len; i++) { + key = keys[i]; + + /** + * If option have `class` attribute, add it to + * 'exturl' class if `exturl` option enabled. + */ + if (exturl !== '' && key === 'class') { + attrs[key] += ' ' + options[key]; + } else { + attrs[key] = options[key]; + } + } + + if (attrs.class && Array.isArray(attrs.class)) { + attrs.class = attrs.class.join(' '); + } + + // If it's external link, rewrite attributes. + if (data.protocol && data.hostname !== siteHost) { + attrs.external = null; + + if (!theme.exturl) { + // Only for simple link need to rewrite/add attributes. + attrs.rel = 'noopener'; + attrs.target = '_blank'; + } else { + // Remove rel attributes for `exturl` in main menu. + attrs.rel = null; + } + } + + return htmlTag(tag, attrs, text); +}); diff --git a/pool/shard010/JavaScript/0067341_modulesAndPatterns.js b/pool/shard010/JavaScript/0067341_modulesAndPatterns.js new file mode 100644 index 0000000000000000000000000000000000000000..379b8c7fbe022aa580627cdad7092b3c3cf42902 --- /dev/null +++ b/pool/shard010/JavaScript/0067341_modulesAndPatterns.js @@ -0,0 +1,156 @@ +function solve() { + var Course = { + init: function (title, presentations) { + //title-js oop, presentation-[lec1,lec2,lec3] + validateTitle(title); + validatePresentations(presentations); + + this.title = title; + this.presentations = presentations; + this.students = []; +// + return this; + }, + addStudent: function (name) {//console.log(arguments[1]); + if (!name) { + throw 'addStudent can not name be empty' + } + if(name.split(' ').length>2){ + throw 'name length can not be >2' + } + let firstName = name.split(' ')[0]; + let lastName = name.split(' ')[1]; + validateName(firstName); + validateName(lastName); + let id = this.students.length + 1; + let student = { + firstName: firstName, + lastName: lastName, + id: id, + homeworks: [], + examScore: 0,//if studentsIDs not listed get 0 points + finalScore: 0 + }; + this.students.push(student); + + return id; + }, + getAllStudents: function () {//console.log(arguments); + return this.students.map(s => { + return { + firstname: s.firstName, + lastname: s.lastName, + id: s.id + }; + }); + }, + submitHomework: function (studentID, homeworkID) {//console.log(arguments); + if (+studentID < 1 || +studentID > this.students.length) { + throw 'Invalid student ID!'; + } + + if (+homeworkID < 1 || +homeworkID > this.presentations.length) { + throw 'Invalid homework ID!'; + } + let currStudent = this.students[studentID - 1]; + + if (currStudent.homeworks.indexOf(homeworkID) === -1) { + currStudent.homeworks.push(homeworkID);//push in orig students bec is ref + } + return this; + }, + pushExamResults: function (results) {//console.log(arguments); + if (!results || !Array.isArray(results)) { + throw 'Exam results must be passed as an array!'; + } + + for (let i = 0, len = results.length; i < len; i += 1) { + let currStudentID = results[i].StudentID, + currStudentScore = results[i].score; + if (!Number(currStudentScore) && !isFinite(currStudentScore)) { + throw 'Student score must be a valid number!'; + } + currStudentID = +currStudentID; + currStudentScore = +currStudentScore; + + if (currStudentID < 1 || currStudentID > this.students.length) { + throw 'Invalid student ID!'; + } + if (this.students[currStudentID - 1].examScore !== 0) { + throw 'This student already has a score!'; + } + this.students[currStudentID - 1].examScore = currStudentScore;//add prop examScore for topStudents + } + return this + }, + getTopStudents: function () {//console.log(arguments); + this.students.forEach(student => { + let hwScore = student.homeworks.length / this.presentations.length; + student.finalScore = (0.75 * student.examScore) + (0.25 * hwScore); + }); + + this.students.sort((st1, st2) => { + return st2.finalScore - st1.finalScore; + }); + let topStudentsCount = 10, + topTenStudents = []; + + if (this.students.length < 10) { + topStudentsCount = this.students.length; + } + + for (let i = 0; i < topStudentsCount; i += 1) { + let topStudent = { + firstName: this.students[i].firstName, + lastName: this.students[i].lastName, + id: this.students[i].id + }; + + topTenStudents.push(topStudent); + } + + return topTenStudents; + } + }; + + function validateTitle(t) { + //if(t[0]===' '||t[t.length-1]===' '||t.includes(' ')){ + //check whitespace at both ends: ^(?!\s|.*\s$) + if (!(/^(?!\s|.*\s$)/.test(t))) {//||t.includes(' ')||t.length===0){ + throw 'Name title can not start nad end with whitespace' + } + if (t.includes(' ')) { + throw 'Name title can not consucutive whiteSpace' + } + if (!t || typeof t !== 'string') { + throw 'Title must be a non-empty string!'; + } + } + + function validatePresentations(p) { + if (!p || p.length === 0 || !Array.isArray(p)) { + //console.log(p.length,Array.isArray(p)); + throw 'invalid presentaion parameters' + } + for (let i = 0; i < p.length; i += 1) { + validateTitle(p[i]); + } + } + function validateName(n) { + if (typeof n !== 'string') { + throw 'Name must be a string' + } + if(n.length>1){ + if (!(/^[A-Z]/.test(n[0]))) { + throw 'Name must begin capital letters' + } + } + if(n.length>1) { + if (!(/^[a-z]/.test(n.slice(1)))) { + throw 'other symbols in the name (if any) are lowercase letters' + } + } + } + + return Course; +} diff --git a/pool/shard010/JavaScript/0067344_people.js b/pool/shard010/JavaScript/0067344_people.js new file mode 100644 index 0000000000000000000000000000000000000000..b7b39f7cedd8634dc279680e2c582947e77caa1d --- /dev/null +++ b/pool/shard010/JavaScript/0067344_people.js @@ -0,0 +1,36 @@ +//Generate a random set of user data +//based on example from: https://egghead.io/lessons/nodejs-creating-demo-apis-with-json-server +// +module.exports = function(){ + var _ = require("lodash"); + var faker = require("faker"); + + return { + people: _.times(10, function (n) { + // Constants for creating a uniform user + var fn = faker.name.firstName(); + var ln = faker.name.lastName(); + var dn = faker.internet.domainName(); + var tld = faker.internet.domainSuffix(); + var phTyp = ["cell","work","home"]; + return{ + //Define the schema + //TODO: other generators, validation, + //specify ports + //id: n, + uuid: faker.random.uuid(), + userName: fn + '.' + ln, + firstName: fn, + lastName: ln, + email: fn + '.' + ln + '@' + dn, + phone: _.times(_.random(0,3), function (i) { + return { + type: faker.random.arrayElement(phTyp), + value: faker.helpers.replaceSymbolWithNumber('###-###-####'), + } + }), + avatar: faker.internet.avatar() + } + }) + } +} diff --git a/pool/shard010/JavaScript/0067345_examplesLoader.js b/pool/shard010/JavaScript/0067345_examplesLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..39cd3d201b872f1109ed64614f4368e3a4181386 --- /dev/null +++ b/pool/shard010/JavaScript/0067345_examplesLoader.js @@ -0,0 +1,43 @@ +var fs = require('fs'); +var path = require('path'); + +function scanDir(dir) { + var files = fs.readdirSync(dir); + var filepath; + var subFiles; + var returnValue = []; + for (var i = 0, len = files.length; i < len; ++i) { + if (files[i].charAt(0) !== '.') { + filepath = path.resolve(path.join(dir, files[i])); + if (fs.lstatSync(filepath).isDirectory()) { + subFiles = scanDir(path.join(dir, files[i])); + returnValue.push.apply(returnValue, subFiles); + } else { + returnValue.push({ + file: path.join(dir, files[i]), + filepath: filepath + }); + } + } + } + return returnValue; +} + +module.exports = function(source) { + var dirname = path.join(__dirname, '..'); + var files = scanDir(path.join(dirname, 'examples')); + var file; + + source = 'let data = {};\n'; + for (var i = 0, len = files.length; i < len; ++i) { + file = files[i]; + var filename = file.file.replace(dirname, '').replace(/\.js$/, ''); + var key = filename.replace(/[\/\-]/g, '_'); + source += 'import ' + key + ' from \'.' + filename + '\';\n'; + source += 'data[\'' + filename + '\'] = ' + key + ';\n'; + } + + source += 'export default data;'; + + return source; +}; diff --git a/pool/shard010/JavaScript/0067346_chartsCtrl.js b/pool/shard010/JavaScript/0067346_chartsCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..1c97176019c404d27871f2f472c25043870edcda --- /dev/null +++ b/pool/shard010/JavaScript/0067346_chartsCtrl.js @@ -0,0 +1,49 @@ +angular.module('app') + +.controller('chartsCtrl', ['$scope', '$rootScope', '$filter', '$state', 'api', 'Assets', 'Charts', 'Translate', + function($scope, $rootScope, $filter, $state, api, Assets, Charts, Translate) { + + $scope.tabs = [{ + active: false, + name: 'charts.prices' + }, { + active: true, + name: 'charts.transactions' + }, { + active: false, + name: 'charts.accounts' + }, { + active: false, + name: 'charts.supply' + }, { + active: false, + name: 'charts.feeds' + }]; + + $scope.goTo = function(route) { + $state.go(route); + }; + + $scope.$watch('$state.current.name', function(newValue, oldValue) { + if (newValue !== oldValue) { + checkTabs(); + } + }); + + function checkTabs() { + if ($state.current.name.split('.').length === 2) { + $scope.tabs.forEach(function(tab) { + if (tab.name === $state.current.name) { + tab.active = true; + } else { + tab.active = false; + } + }); + } + } + + checkTabs(); + + + } +]); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067347_compass.js b/pool/shard010/JavaScript/0067347_compass.js new file mode 100644 index 0000000000000000000000000000000000000000..27e02625b3b2d16bb64d81da18cc6ca907f967f4 --- /dev/null +++ b/pool/shard010/JavaScript/0067347_compass.js @@ -0,0 +1,143 @@ +'use strict'; + +var PLUGIN_NAME = 'gulp-compass', + path = require('path'), + spawn = require('child_process').spawn, + gutil = require('gulp-util'), + path = require('path'), + helpers = require('./helpers'), + defaults = { + style: false, + comments: false, + relative: true, + css: 'css', + sass: 'sass', + image: false, + generated_images_path: false, + http_path: false, + javascript: false, + font: false, + import_path: false, + config_file: false, + require: false, + logging: true, + load_all: false, + project: process.cwd(), + bundle_exec: false, + debug: false, + time: false, + sourcemap: false, + boring: false, + force: false, + task: 'compile' + }; + +module.exports = function(file, opts, callback) { + opts = opts || {}; + + for (var key in defaults) { + if (opts[key] === undefined) { + opts[key] = defaults[key]; + } + } + + var compassExecutable = 'compass', + file_path = file.replace(/\\/g, '/'), + relPathToSass = path.relative(path.resolve(opts.project, opts.sass), file), + pathToCss = path.resolve(opts.project, opts.css, gutil.replaceExtension(relPathToSass, '.css')); + + // check command exist + if (opts.bundle_exec) { + compassExecutable = helpers.command('bundle', callback); + } else { + compassExecutable = helpers.command(compassExecutable, callback); + } + + if (!compassExecutable) { + return false; + } + + var options = []; + if (opts.bundle_exec) { + options.push('exec', 'compass'); + } + options.push(opts.task); + if (process.platform === 'win32') { + options.push(opts.project.replace(/\\/g, '/')); + } else { + options.push(opts.project); + } + + if (opts.task !== 'watch') { + options.push(file_path); + } + + // set compass setting + if (opts.environment) { options.push('--environment', opts.environment); } + if (opts.config_file) { options.push('-c', opts.config_file); } + if (!opts.comments) { options.push('--no-line-comments'); } + if (opts.relative) { options.push('--relative-assets'); } + if (opts.debug) { options.push('--debug-info'); } + if (opts.time) { options.push('--time'); } + if (opts.boring) { options.push('--boring'); } + if (opts.sourcemap) { options.push('--sourcemap'); } + if (opts.font) { options.push('--fonts-dir', opts.font); } + if (opts.style) { options.push('--output-style', opts.style); } + if (opts.image) { options.push('--images-dir', opts.image); } + if (opts.generated_images_path) { options.push('--generated-images-path', opts.generated_images_path); } + if (opts.http_path) { options.push('--http-path', opts.http_path); } + if (opts.javascript) { options.push('--javascripts-dir', opts.javascript); } + if (opts.force) { options.push('--force'); } + options.push('--css-dir', path.normalize(opts.css)); + options.push('--sass-dir', path.normalize(opts.sass)); + + if (opts.import_path) { + if(helpers.isArray(opts.import_path)) { + opts.import_path.forEach(function(i) { + options.push('-I', i); + }); + } else { + options.push('-I', opts.import_path); + } + } + if (opts.load_all) { options.push('--load-all', opts.load_all); } + if (opts.require) { + if (helpers.isArray(opts.require)) { + for (var i = 0, len = opts.require.length; i < len; i++) { + options.push('--require', opts.require[i]); + } + } else { + options.push('--require', opts.require); + } + } + + if (opts.debug) { + gutil.log(PLUGIN_NAME + ':', 'Running command:', compassExecutable, options.join(' ')); + } + + var child = spawn(compassExecutable, options, {cwd: opts.project || process.cwd()}), + stdout = '', + stderr = ''; + if (opts.logging) { + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function (data) { + stdout += data; + console.log(data); + }); + + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function (data) { + stderr += data; + if (!data.match(/^\u001b\[\d+m$/)) { + gutil.log(data); + } + }); + } + + // support callback + child.on('close', function(code) { + if(callback){ + callback(code, stdout, stderr, pathToCss, opts); + } + }); +}; diff --git a/pool/shard010/JavaScript/0067359_leave.js b/pool/shard010/JavaScript/0067359_leave.js new file mode 100644 index 0000000000000000000000000000000000000000..69c35403469ab638cf5332379ec10bc80dc9d0a2 --- /dev/null +++ b/pool/shard010/JavaScript/0067359_leave.js @@ -0,0 +1,32 @@ +/* jshint node: true */ +'use strict'; + +/** + #### leave + + ``` + /leave|{"id":"..."} + ``` + + When a leave message is received from a peer, we check to see if that is + a peer that we are managing state information for and if we are then the + peer state is removed. + +**/ +module.exports = function(signaller, opts) { + return function(args) { + var data = args[0]; + var peer = signaller.peers.get(data && data.id); + + if (peer) { + // start the inactivity timer + peer.leaveTimer = setTimeout(function() { + peer.inactive = true; + signaller('peer:leave', data.id, peer); + }, opts.leaveTimeout); + } + + // emit the event + signaller('peer:disconnected', data.id, peer); + }; +}; diff --git a/pool/shard010/JavaScript/0067364_paper-thumbnail-sidebar.v2.directives.js b/pool/shard010/JavaScript/0067364_paper-thumbnail-sidebar.v2.directives.js new file mode 100644 index 0000000000000000000000000000000000000000..2267cddd0403dd2b3853ed790c8bd84662390f2d --- /dev/null +++ b/pool/shard010/JavaScript/0067364_paper-thumbnail-sidebar.v2.directives.js @@ -0,0 +1,190 @@ +angular.module('focus.v2.controllers') + .directive('paperThumbnailSidebarDirective', ['User', function(User) { + + var charWidth = 1; + var charHeight = 1; + var citationWidth = 20; + var previewWidth = 35; + var citationGroups = null; + var tip = null; + + function computeParagraphPreviewHeight(i) { + var paragraphs = User.activeParagraphs(); + var height = Math.floor(paragraphs[i].timestamps.length * charWidth / previewWidth) * (charHeight+1); + return Math.max(height, 50); + } + + function drawParagraphSelector(group) { + group.append('rect') + .attr('id', 'bound') + .attr('width', previewWidth) + .attr('height', function(d, i) { + return computeParagraphPreviewHeight(i); + }) + .attr('fill', 'white') + .attr('fill-opacity', 0) + .attr('stroke', 'white') + .attr('stroke-width', 3) + .attr('rx', 3) + .on('mouseenter', function(d, i) { + if (i === User.selectedParagraph()) return; + d3.select(this).attr('stroke', '#ccc'); + }) + .on('mouseleave', function(d, i) { + if (i === User.selectedParagraph()) return; + d3.select(this).attr('stroke', 'white'); + }) + .on('click', function(d, i) { + var myElement = document.getElementById('paragraph-' + i); + var topPos = myElement.offsetTop; + document.getElementById('selected-thumbnail').scrollTop = topPos; + if (i === User.selectedParagraph()) { + User.selectedParagraph(-1); + } + else { + User.selectedParagraph(i); + } + }); + } + + function updateCitationMarkers(scope) { + if (citationGroups === null) return; + var paragraphs = User.activeParagraphs(); + var citations = User.paragraphCitation(); + var markers = citationGroups.selectAll('.citationMarker') + .data(function(d, i) { + return d.map(function(c) { + return { + citation: c, + groupIndex: i + } + }); + }) + markers.exit().remove(); + markers.enter() + .append('rect') + .attr('class', 'citationMarker') + .attr('width', 10) + .attr('height', 5) + .attr('stroke-width', 0) + .attr('fill', '#feb24c'); + + markers + .attr('transform', function(d, i) { + var left = 1; + var top = computeParagraphPreviewHeight(d.groupIndex) - (i+1) * 7; + return 'translate(' + left + ',' + top + ')'; + }) + .on('mouseover', function(d, i) { + var top = Math.floor(paragraphs[d.groupIndex].timestamps.length * charWidth / previewWidth) * (charHeight+1) - d.citation.index * 7; + console.log(d) + tip.show(d); + }) + .on('mouseout', tip.hide) + .on('click', function(d) { + scope.searchTitle = d.citation.evidence.title; + scope.searchEvidenceByTitle(); + }); + } + + function visualize(container, totalWidth, height, scope) { + var paragraphs = User.activeParagraphs(); + var citations = User.paragraphCitation(); + + if (paragraphs === null || paragraphs === undefined || paragraphs.length === 0) return; + var minTime = paragraphs[0].timestamps[0].getTime(); + var maxTime = 0; + paragraphs.forEach(function(p) { + p.timestamps.forEach(function(ts) { + var tsm = ts.getTime(); + minTime = tsm < minTime ? tsm : minTime; + maxTime = tsm > maxTime ? tsm : maxTime; + }) + }) + + var timeColorScale = d3.scale.linear() + .domain([minTime, maxTime]) + .range(['#e9f5ef', '#2ca25f']); + + container.selectAll('g').remove(); + var freshness = container.selectAll('.freshness') + .data(paragraphs) + .enter() + .append('g') + .attr('class', 'freshness') + .attr('transform', function(d, i) { + var top = 20; + for (var j = 0; j < i; ++j) { + top += computeParagraphPreviewHeight(j) + 5; +// top += Math.floor(paragraphs[j].timestamps.length * charWidth / previewWidth) * (charHeight+1) + 5; + } + return 'translate(20, ' + top + ')'; + }); + + freshness.selectAll('rect') + .data(function(d) { + return d.timestamps; + }) + .enter() + .append('rect') + .attr('width', charWidth) + .attr('height', charHeight) + .attr('transform', function(d, i) { + var left = (i * charWidth) % previewWidth; + var top = Math.floor(i / (previewWidth / charWidth)) * (charHeight+1); + return 'translate(' + left + ', ' + top + ')'; + }) + .attr('fill', function(d, i) { + return timeColorScale(d.getTime()); + }); + + drawParagraphSelector(freshness); + + citationGroups = container.selectAll('.citation') + .data(citations) + .enter() + .append('g') + .attr('class', 'citation') + .attr('transform', function(d, i) { + var top = 20; + for (var j = 0; j < i; ++j) { + top += computeParagraphPreviewHeight(j) + 5; +// top += Math.floor(paragraphs[j].timestamps.length * charWidth / previewWidth) * (charHeight+1) + 5; + } + return 'translate(0, ' + top + ')'; + }); + + citationGroups.append('rect') + .attr('rx', 2) + .attr('width', 12) + .attr('height', function(d, i) { return computeParagraphPreviewHeight(i); }) + .attr('stroke', '#ccc') + .attr('stroke-width', 1) + .attr('fill', 'white'); + + tip = d3.tip() + .attr('class', 'd3-tip') + .direction('n') + .offset([-10, 0]) + .html(function(d) { + return d.citation.evidence.title; + }) + citationGroups.call(tip); + + updateCitationMarkers(scope); + } + + return function(scope, element, attrs) { + visualize(d3.select(element[0]), 60, 600, scope); + scope.$watch(function () { + return User.paragraphCitation(); + }, + function (newVal) { + if (typeof newVal !== 'undefined') { + updateCitationMarkers(scope); + } + }, true); + }; + + }]); + diff --git a/pool/shard010/JavaScript/0067370_user.js b/pool/shard010/JavaScript/0067370_user.js new file mode 100644 index 0000000000000000000000000000000000000000..4e04ed4cc83133164c0dee69c6879c4fc49e4342 --- /dev/null +++ b/pool/shard010/JavaScript/0067370_user.js @@ -0,0 +1,15 @@ +const mongoose = require('./connection'); + +const userSchema = mongoose.Schema({ + username: String, + password: String, + 'first-name': String, + 'last-name': String, +}); + +userSchema.virtual('full-name').get(function () { + return `${this['first-name']} ${this['last-name']}`; +}); + +module.exports.userSchema = userSchema; +module.exports.User = mongoose.model('User', userSchema); diff --git a/pool/shard010/JavaScript/0067374_privateuse.js b/pool/shard010/JavaScript/0067374_privateuse.js new file mode 100644 index 0000000000000000000000000000000000000000..0df28cffa317cb92237945e402af6b4c20a242a1 --- /dev/null +++ b/pool/shard010/JavaScript/0067374_privateuse.js @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2013 Google Inc. 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 Private Use packets. + */ + +goog.provide('e2e.openpgp.packet.PrivateUse'); +goog.provide('e2e.openpgp.packet.PrivateUse60'); +goog.provide('e2e.openpgp.packet.PrivateUse61'); +goog.provide('e2e.openpgp.packet.PrivateUse62'); +goog.provide('e2e.openpgp.packet.PrivateUse63'); + +goog.require('e2e.openpgp.packet.Packet'); +goog.require('e2e.openpgp.packet.factory'); + + + +/** + * Base class for private-use packets. + * @param {!e2e.ByteArray} data uninterpreted contents of packet. + * @constructor + * @extends {e2e.openpgp.packet.Packet} + */ +e2e.openpgp.packet.PrivateUse = function(data) { + goog.base(this); + /** + * Uninterpreted contents of packet + * @type {!e2e.ByteArray} + */ + this.data = data; +}; +goog.inherits(e2e.openpgp.packet.PrivateUse, + e2e.openpgp.packet.Packet); + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse.prototype.serializePacketBody = function() { + return this.data; +}; + + + +/** + * Private Use Packet (Tag 60) defined in RFC 4880 section 13.10. + * @param {!e2e.ByteArray} data uninterpreted content of packet. + * @constructor + * @extends {e2e.openpgp.packet.PrivateUse} + */ +e2e.openpgp.packet.PrivateUse60 = function(data) { + goog.base(this, data); +}; +goog.inherits(e2e.openpgp.packet.PrivateUse60, + e2e.openpgp.packet.PrivateUse); + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse60.parse = function(data) { + return new e2e.openpgp.packet.PrivateUse60(data); +}; + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse60.prototype.tag = 60; + + + +/** + * Private Use Packet (Tag 61) defined in RFC 4880 section 13.10. + * @param {!e2e.ByteArray} data uninterpreted content of packet. + * @constructor + * @extends {e2e.openpgp.packet.PrivateUse} + */ +e2e.openpgp.packet.PrivateUse61 = function(data) { + goog.base(this, data); +}; +goog.inherits(e2e.openpgp.packet.PrivateUse61, + e2e.openpgp.packet.PrivateUse); + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse61.parse = function(data) { + return new e2e.openpgp.packet.PrivateUse61(data); +}; + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse61.prototype.tag = 61; + + + +/** + * Private Use Packet (Tag 62) defined in RFC 4880 section 13.10. + * @param {!e2e.ByteArray} data uninterpreted content of packet. + * @constructor + * @extends {e2e.openpgp.packet.PrivateUse} + */ +e2e.openpgp.packet.PrivateUse62 = function(data) { + goog.base(this, data); +}; +goog.inherits(e2e.openpgp.packet.PrivateUse62, + e2e.openpgp.packet.PrivateUse); + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse62.parse = function(data) { + return new e2e.openpgp.packet.PrivateUse62(data); +}; + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse62.prototype.tag = 62; + + + +/** + * Private Use Packet (Tag 63) defined in RFC 4880 section 13.10. + * @param {!e2e.ByteArray} data uninterpreted content of packet. + * @constructor + * @extends {e2e.openpgp.packet.PrivateUse} + */ +e2e.openpgp.packet.PrivateUse63 = function(data) { + goog.base(this, data); +}; +goog.inherits(e2e.openpgp.packet.PrivateUse63, + e2e.openpgp.packet.PrivateUse); + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse63.parse = function(data) { + return new e2e.openpgp.packet.PrivateUse63(data); +}; + + +/** @inheritDoc */ +e2e.openpgp.packet.PrivateUse63.prototype.tag = 63; + + +e2e.openpgp.packet.factory.add(e2e.openpgp.packet.PrivateUse60); +e2e.openpgp.packet.factory.add(e2e.openpgp.packet.PrivateUse61); +e2e.openpgp.packet.factory.add(e2e.openpgp.packet.PrivateUse62); +e2e.openpgp.packet.factory.add(e2e.openpgp.packet.PrivateUse63); diff --git a/pool/shard010/JavaScript/0067377_grammar-registry.js b/pool/shard010/JavaScript/0067377_grammar-registry.js new file mode 100644 index 0000000000000000000000000000000000000000..f2994acf1812658640c324d708a7c29abb73a523 --- /dev/null +++ b/pool/shard010/JavaScript/0067377_grammar-registry.js @@ -0,0 +1,171 @@ +const _ = require('underscore-plus') +const FirstMate = require('first-mate') +const Token = require('./token') +const fs = require('fs-plus') +const Grim = require('grim') + +const PathSplitRegex = new RegExp('[/.]') + +// Extended: Syntax class holding the grammars used for tokenizing. +// +// An instance of this class is always available as the `atom.grammars` global. +// +// The Syntax class also contains properties for things such as the +// language-specific comment regexes. See {::getProperty} for more details. +module.exports = +class GrammarRegistry extends FirstMate.GrammarRegistry { + constructor ({config} = {}) { + super({maxTokensPerLine: 100, maxLineLength: 1000}) + this.config = config + } + + createToken (value, scopes) { + return new Token({value, scopes}) + } + + // Extended: Select a grammar for the given file path and file contents. + // + // This picks the best match by checking the file path and contents against + // each grammar. + // + // * `filePath` A {String} file path. + // * `fileContents` A {String} of text for the file path. + // + // Returns a {Grammar}, never null. + selectGrammar (filePath, fileContents) { + return this.selectGrammarWithScore(filePath, fileContents).grammar + } + + selectGrammarWithScore (filePath, fileContents) { + let bestMatch = null + let highestScore = -Infinity + for (let grammar of this.grammars) { + const score = this.getGrammarScore(grammar, filePath, fileContents) + if ((score > highestScore) || (bestMatch == null)) { + bestMatch = grammar + highestScore = score + } + } + return {grammar: bestMatch, score: highestScore} + } + + // Extended: Returns a {Number} representing how well the grammar matches the + // `filePath` and `contents`. + getGrammarScore (grammar, filePath, contents) { + if ((contents == null) && fs.isFileSync(filePath)) { + contents = fs.readFileSync(filePath, 'utf8') + } + + let score = this.getGrammarPathScore(grammar, filePath) + if ((score > 0) && !grammar.bundledPackage) { + score += 0.125 + } + if (this.grammarMatchesContents(grammar, contents)) { + score += 0.25 + } + return score + } + + getGrammarPathScore (grammar, filePath) { + if (!filePath) { return -1 } + if (process.platform === 'win32') { filePath = filePath.replace(/\\/g, '/') } + + const pathComponents = filePath.toLowerCase().split(PathSplitRegex) + let pathScore = -1 + + let customFileTypes + if (this.config.get('core.customFileTypes')) { + customFileTypes = this.config.get('core.customFileTypes')[grammar.scopeName] + } + + let { fileTypes } = grammar + if (customFileTypes) { + fileTypes = fileTypes.concat(customFileTypes) + } + + for (let i = 0; i < fileTypes.length; i++) { + const fileType = fileTypes[i] + const fileTypeComponents = fileType.toLowerCase().split(PathSplitRegex) + const pathSuffix = pathComponents.slice(-fileTypeComponents.length) + if (_.isEqual(pathSuffix, fileTypeComponents)) { + pathScore = Math.max(pathScore, fileType.length) + if (i >= grammar.fileTypes.length) { + pathScore += 0.5 + } + } + } + + return pathScore + } + + grammarMatchesContents (grammar, contents) { + if ((contents == null) || (grammar.firstLineRegex == null)) { return false } + + let escaped = false + let numberOfNewlinesInRegex = 0 + for (let character of grammar.firstLineRegex.source) { + switch (character) { + case '\\': + escaped = !escaped + break + case 'n': + if (escaped) { numberOfNewlinesInRegex++ } + escaped = false + break + default: + escaped = false + } + } + const lines = contents.split('\n') + return grammar.firstLineRegex.testSync(lines.slice(0, numberOfNewlinesInRegex + 1).join('\n')) + } + + // Deprecated: Get the grammar override for the given file path. + // + // * `filePath` A {String} file path. + // + // Returns a {String} such as `"source.js"`. + grammarOverrideForPath (filePath) { + Grim.deprecate('Use atom.textEditors.getGrammarOverride(editor) instead') + + const editor = getEditorForPath(filePath) + if (editor) { + return atom.textEditors.getGrammarOverride(editor) + } + } + + // Deprecated: Set the grammar override for the given file path. + // + // * `filePath` A non-empty {String} file path. + // * `scopeName` A {String} such as `"source.js"`. + // + // Returns undefined. + setGrammarOverrideForPath (filePath, scopeName) { + Grim.deprecate('Use atom.textEditors.setGrammarOverride(editor, scopeName) instead') + + const editor = getEditorForPath(filePath) + if (editor) { + atom.textEditors.setGrammarOverride(editor, scopeName) + } + } + + // Deprecated: Remove the grammar override for the given file path. + // + // * `filePath` A {String} file path. + // + // Returns undefined. + clearGrammarOverrideForPath (filePath) { + Grim.deprecate('Use atom.textEditors.clearGrammarOverride(editor) instead') + + const editor = getEditorForPath(filePath) + if (editor) { + atom.textEditors.clearGrammarOverride(editor) + } + } +} + +function getEditorForPath (filePath) { + if (filePath != null) { + return atom.workspace.getTextEditors().find(editor => editor.getPath() === filePath) + } +} diff --git a/pool/shard010/JavaScript/0067378_deploy-client.js b/pool/shard010/JavaScript/0067378_deploy-client.js new file mode 100644 index 0000000000000000000000000000000000000000..672996734f372ab5b262307ef2d931c07fa8b5d5 --- /dev/null +++ b/pool/shard010/JavaScript/0067378_deploy-client.js @@ -0,0 +1,19 @@ +// ./index.js +const express = require('express'); +const path = require('path'); + +const port = process.env.PORT || 3001; +const app = express(); + +// serve static static normally +// asset files +app.use(express.static(path.join(__dirname, 'public'))); + +// Handles all routes so you do not get a not found error +app.get('/*', (request, response) => { + response.sendFile(path.resolve(__dirname, 'public', 'index.html')); +}); + +app.listen(port); + +console.log(`server started on port ${port}`); diff --git a/pool/shard010/JavaScript/0067380_dstr-gen-meth-static-dflt-ary-ptrn-elem-id-init-hole.js b/pool/shard010/JavaScript/0067380_dstr-gen-meth-static-dflt-ary-ptrn-elem-id-init-hole.js new file mode 100644 index 0000000000000000000000000000000000000000..0a08074c6c2ba668b643a1203520d3e7dd8d387b --- /dev/null +++ b/pool/shard010/JavaScript/0067380_dstr-gen-meth-static-dflt-ary-ptrn-elem-id-init-hole.js @@ -0,0 +1,83 @@ +// This file was procedurally generated from the following sources: +// - src/dstr-binding/ary-ptrn-elem-id-init-hole.case +// - src/dstr-binding/default/cls-expr-gen-meth-static-dflt.template +/*--- +description: Destructuring initializer with a "hole" (static class expression generator method (default parameter)) +esid: sec-class-definitions-runtime-semantics-evaluation +es6id: 14.5.16 +features: [generators, destructuring-binding, default-parameters] +flags: [generated] +info: | + ClassExpression : class BindingIdentifieropt ClassTail + + 1. If BindingIdentifieropt is not present, let className be undefined. + 2. Else, let className be StringValue of BindingIdentifier. + 3. Let value be the result of ClassDefinitionEvaluation of ClassTail + with argument className. + [...] + + 14.5.14 Runtime Semantics: ClassDefinitionEvaluation + + 21. For each ClassElement m in order from methods + a. If IsStatic of m is false, then + b. Else, + Let status be the result of performing PropertyDefinitionEvaluation + for m with arguments F and false. + [...] + + 14.4.13 Runtime Semantics: PropertyDefinitionEvaluation + + GeneratorMethod : + * PropertyName ( StrictFormalParameters ) { GeneratorBody } + + 1. Let propKey be the result of evaluating PropertyName. + 2. ReturnIfAbrupt(propKey). + 3. If the function code for this GeneratorMethod is strict mode code, + let strict be true. Otherwise let strict be false. + 4. Let scope be the running execution context's LexicalEnvironment. + 5. Let closure be GeneratorFunctionCreate(Method, + StrictFormalParameters, GeneratorBody, scope, strict). + + 9.2.1 [[Call]] ( thisArgument, argumentsList) + + [...] + 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). + [...] + + 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) + + 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). + [...] + + 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) + + [...] + 23. Let iteratorRecord be Record {[[iterator]]: + CreateListIterator(argumentsList), [[done]]: false}. + 24. If hasDuplicates is true, then + [...] + 25. Else, + b. Let formalStatus be IteratorBindingInitialization for formals with + iteratorRecord and env as arguments. + [...] + + 13.3.3.6 Runtime Semantics: IteratorBindingInitialization + SingleNameBinding : BindingIdentifier Initializeropt + [...] 6. If Initializer is present and v is undefined, then + a. Let defaultValue be the result of evaluating Initializer. + b. Let v be GetValue(defaultValue). + [...] + 7. If environment is undefined, return PutValue(lhs, v). 8. Return InitializeReferencedBinding(lhs, v). +---*/ + +var callCount = 0; +var C = class { + static *method([x = 23] = [,]) { + assert.sameValue(x, 23); + // another statement + callCount = callCount + 1; + } +}; + +C.method().next(); +assert.sameValue(callCount, 1, 'method invoked exactly once'); diff --git a/pool/shard010/JavaScript/0067382_regress-465366.js b/pool/shard010/JavaScript/0067382_regress-465366.js new file mode 100644 index 0000000000000000000000000000000000000000..aab502daf661b83a768ff96fa217e62ac712c920 --- /dev/null +++ b/pool/shard010/JavaScript/0067382_regress-465366.js @@ -0,0 +1,74 @@ +/* -*- 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 JavaScript Engine testing utilities. + * + * The Initial Developer of the Original Code is + * Mozilla Foundation. + * Portions created by the Initial Developer are Copyright (C) 2008 + * 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 ***** */ + +var gTestfile = 'regress-465366.js'; +//----------------------------------------------------------------------------- +var BUGNUMBER = 465366; +var summary = 'TM: JIT: error with multiplicative loop'; +var actual = ''; +var expect = ''; + + +//----------------------------------------------------------------------------- +test(); +//----------------------------------------------------------------------------- + +function test() +{ + enterFunc ('test'); + printBugNumber(BUGNUMBER); + printStatus (summary); + + jit(true); + + function f() + { + var k = 1; + for (var n = 0; n < 2; n++) { + k = (k * 10); + } + return k; + } + f(); + print(f()); + + jit(false); + + reportCompare(expect, actual, summary); + + exitFunc ('test'); +} diff --git a/pool/shard010/JavaScript/0067384_account-settings-test.js b/pool/shard010/JavaScript/0067384_account-settings-test.js new file mode 100644 index 0000000000000000000000000000000000000000..e224d260c716bc5afef2c99096ed9faec0971124 --- /dev/null +++ b/pool/shard010/JavaScript/0067384_account-settings-test.js @@ -0,0 +1,108 @@ +var webdriver = require('browserstack-webdriver'), + assert = require('assert'), + testUtils = require('./testUtils.js'), + config = require('../config.js'), + q = require('q'), + timeOut = 25000; +module.exports = function(capabilities, options) { + describe('Account settings test: ' + options.id, function() { + this.timeout(4 * timeOut); + var driver, server = options.server, + random = Math.random() + ""; + before(function(done) { + this.timeout(4 * timeOut); + driver = testUtils.openUrl(capabilities, server, "testroom1"); + testUtils.loginFacebook(driver, config.facebookUser.email, config.facebookUser.password, function() { + console.log("logging in through facebook..."); + done(); + }); + }); + + it("account settings test(profile)", function(done) { + this.timeout(4 * timeOut); + console.log("testing for user area"); + driver.findElement(webdriver.By.css('.main-area .user-area.js-has-user-menu')).click(). + then(function() { + console.log("this is profile testing..."); + return driver.findElement(webdriver.By.css('.userpref')).click(); + }).then(function() { + return q.delay(3000); + }).then(function() { + return driver.findElement(webdriver.By.css('.list-item-profile-settings')).click(); + }).then(function() { + return driver.findElement(webdriver.By.id('pref-about-me')).sendKeys(random); + }).then(function() { + return driver.findElement(webdriver.By.css('.conf-save')).click(); + }).then(function() { + return q.delay(1000); + }).then(function() { + return driver.findElement(webdriver.By.css('.main-area .user-area.js-has-user-menu')).click(); + }).then(function() { + return driver.findElement(webdriver.By.css('.userpref')).click(); + }).then(function() { + return q.delay(3000); + }).then(function() { + return driver.findElement(webdriver.By.id('pref-about-me')).getAttribute("value"); + }).then(function(text) { + console.log("text", text); + var b = text.indexOf(random) !== -1; + assert.equal(b, true, "saving not successful"); + driver.findElement(webdriver.By.css('.conf-save')).click(); + done(); + }); + }); + + it("account settings test(Email)", function(done) { + this.timeout(4 * timeOut); + console.log("testing for user area"); + driver.findElement(webdriver.By.css('.main-area .user-area.js-has-user-menu')).click(). + then(function() { + console.log("this is Email testing..."); + return driver.findElement(webdriver.By.css('.userpref')).click(); + }).then(function() { + return driver.findElement(webdriver.By.css('.list-item-email-settings')).click(); + }).then(function() { + return driver.findElement(webdriver.By.css('.radio-item')).click(); + }).then(function() { + return driver.findElement(webdriver.By.css('.conf-save')).click(); + }).then(function() { + return q.delay(3000); + }).then(function() { + return driver.findElement(webdriver.By.css(".main-area .user-area.js-has-user-menu")) + .isDisplayed(); + }).then(function(t) { + assert.equal(t, true, "saving unsuccessful"); + done(); + }); + }); + + /*it("account settings test(notifications)", function(done){ + this.timeout(4 * timeOut); + console.log("testing for user area"); + driver.findElement(webdriver.By.css('.user-area')).click(). + then(function() { + console.log("this is account settings"); + return driver.findElement(webdriver.By.css('.userpref')).click(); + }).then(function(){ + return driver.findElement(webdriver.By.css('.list-item-notification-settings')).click(); + }).then(function(){ + return driver.findElement(webdriver.By.id('sound-notification')).click(); + }).then(function(){ + return driver.findElement(webdriver.By.id('desktop-notification')).click(); + }).then(function(){ + return driver.findElement(webdriver.By.css('.conf-save')).click(); + }).then(function(){ + return driver.findElement(webdriver.By.css(".sb-user")).isDisplayed(); + }).then(function(t){ + assert.equal(t, true, "saving unsuccessful"); + done(); + }); + });*/ + + after(function(done) { + this.timeout(timeOut); + driver.quit(); + done(); + }); + }); +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067385_Dealers.js b/pool/shard010/JavaScript/0067385_Dealers.js new file mode 100644 index 0000000000000000000000000000000000000000..f8db3a28b0fefb6e5e9fcd376ef880fd350f0035 --- /dev/null +++ b/pool/shard010/JavaScript/0067385_Dealers.js @@ -0,0 +1,28 @@ +var mongoose = require('mongoose') +var Schema = mongoose.Schema +var ObjectId = Schema.ObjectId; + +var dealersSchema = new Schema({ + id: ObjectId, + dname: { type: String, required: true }, + daddress_first: { type: String, required: false }, + daddress_second: { type: String, required: false }, + daddress_city: { type: String, required: false }, + daddress_state: { type: String, required: false }, + daddress_country: { type: String, required: false }, + dadmin_id: { type: String, required: true }, + created_at: Date, + updated_at: Date +}) + +dealersSchema.pre('save', function(next) { + var currentDate = new Date() + this.updated_at = currentDate + if (!this.created_at) + this.created_at = currentDate + next() +}) + +// Register Dealers and its schema with mongoose +// This is the name of the created collection +mongoose.model('Dealer', dealersSchema) diff --git a/pool/shard010/JavaScript/0067387_stratux.js b/pool/shard010/JavaScript/0067387_stratux.js new file mode 100644 index 0000000000000000000000000000000000000000..932c0a0414f0e65e61fa659398f83bc54b921080 --- /dev/null +++ b/pool/shard010/JavaScript/0067387_stratux.js @@ -0,0 +1,98 @@ +var socket; + +function setLEDstatus (ledElement, status) { + if(status) { + ledElement.removeClass('led-red'); + ledElement.addClass('led-green'); + } + else { + ledElement.removeClass('led-green'); + ledElement.addClass('led-red'); + } +} + +function setConnectedClass (cssClass) { + $('#connectedLabel').removeClass('label-success'); + $('#connectedLabel').removeClass('label-warning'); + $('#connectedLabel').removeClass('label-danger'); + $('#connectedLabel').addClass( cssClass ); + + if(cssClass == 'label-success') + $('#connectedLabel').text('Connected'); + else + $('#connectedLabel').text('Disconnected'); +} + +function connect() { + socket = new WebSocket('ws://' + window.location.hostname + '/control'); + + socket.onopen = function(msg) { + setConnectedClass('label-success'); + }; + + socket.onclose = function(msg) { + setConnectedClass('label-danger'); + setTimeout(connect,1000); + }; + + socket.onerror = function(msg) { + setConnectedClass('label-danger'); + }; + + socket.onmessage = function(msg) { + console.log('Received status update.') + + var status = JSON.parse(msg.data) + + // Update Status + $('#Version').text(status.Version); + $('#Devices').text(status.Devices); + $('#Connected_Users').text(status.Connected_Users); + $('#UAT_messages_last_minute').text(status.UAT_messages_last_minute); + $('#UAT_messages_max').text(status.UAT_messages_max); + $('#ES_messages_last_minute').text(status.ES_messages_last_minute); + $('#ES_messages_max').text(status.ES_messages_max); + $('#GPS_satellites_locked').text(status.GPS_satellites_locked); + setLEDstatus($('#RY835AI_connected'), status.RY835AI_connected); + $('#Uptime').text(status.Uptime); + + // Update Settings + $('input[name=UAT_Enabled]').prop('checked', status.UAT_Enabled); + $('input[name=ES_Enabled]').prop('checked', status.ES_Enabled); + $('input[name=GPS_Enabled]').prop('checked', status.GPS_Enabled); + $('input[name=AHRS_Enabled]').prop('checked', status.AHRS_Enabled); + }; +} + +$(document).ready(function() { + connect(); + + $('input[name=UAT_Enabled]').click(function () { + console.log('UAT_Enabled clicked'); + + msg = {setting: 'UAT_Enabled', state: $('input[name=UAT_Enabled]').prop('checked') }; + socket.send(JSON.stringify(msg)); + }); + + $('input[name=ES_Enabled]').click(function () { + console.log('ES_Enabled clicked'); + + msg = {setting: 'ES_Enabled', state: $('input[name=ES_Enabled]').prop('checked') }; + socket.send(JSON.stringify(msg)); + }); + + $('input[name=GPS_Enabled]').click(function () { + console.log('GPS_Enabled clicked'); + + msg = {setting: 'GPS_Enabled', state: $('input[name=GPS_Enabled]').prop('checked') }; + socket.send(JSON.stringify(msg)); + }); + + $('input[name=AHRS_Enabled]').click(function () { + console.log('AHRS_Enabled clicked'); + + msg = {setting: 'AHRS_Enabled', state: $('input[name=AHRS_Enabled]').prop('checked') }; + socket.send(JSON.stringify(msg)); + }); + +}); diff --git a/pool/shard010/JavaScript/0067390_MouseWheel.js b/pool/shard010/JavaScript/0067390_MouseWheel.js new file mode 100644 index 0000000000000000000000000000000000000000..5fdf0b36f20fbe526982e120fd57cbd7ca7fb16d --- /dev/null +++ b/pool/shard010/JavaScript/0067390_MouseWheel.js @@ -0,0 +1,124 @@ +/** + * MouseWheel.js + * Zero dependency ridiculous fast mousewheel handler + * either direct or captured into another element. No lib requirements. + * Compatible with: IE8, FireFox, Chrome, Safari,Opera, iOS, Android + * + * MouseWheel rewrites itself the first time it is triggered in order to perform faster for the environment it is being used in + * @param {HTMLElement} element + * @param {HTMLElement} [scrollElement] default element + * @param {Number} [verticalPixels] default 20 + * @param {Number} [horizontalPixels] default 10 + * @constructor + */ +var MouseWheel = (function(window) { + function Constructor (element, scrollElement, verticalPixels, horizontalPixels) { + this.element = element; + this.scrollElement = element.scrollElement = scrollElement || element; + this.verticalPixels = verticalPixels || 20; + this.horizontalPixels = horizontalPixels || 10; + + //initial binding, which will await the first trigger of mousewheel, then rewrite itself. + this.bindMouseWheel(element, this.initialHandler); + + element.mW = this; + } + + Constructor.prototype = { + initialHandler: function (e) { + e = e || window.event; + + var mousewheel, + mW = this.mW, + horizontalPixels = mW.horizontalPixels, + verticalPixels = mW.verticalPixels; + + if (e.type === "mousewheel") { + //chrome sometimes + if (e.wheelDeltaX !== undefined) { + this.mWType = 1; + mousewheel = function(e) { + e = e || window.event; + + var deltaY = e.wheelDeltaY, + deltaX = e.wheelDeltaX, + scrollElement = this.scrollElement; + + if (deltaY !== 0) { + scrollElement.scrollTop += deltaY < 0 ? horizontalPixels : -horizontalPixels; + } + + else if (deltaX !== 0) { + scrollElement.scrollLeft += deltaX < 0 ? verticalPixels : -verticalPixels; + } + + return false; + }; + } else { + //IE + this.mWType = 2; + mousewheel = function(e) { + e = e || window.event; + + var delta = e.wheelDelta, + scrollElement = this.scrollElement; + + if (delta !== 0) { + scrollElement.scrollTop += delta < 0 ? horizontalPixels : -horizontalPixels; + } + + return false; + }; + } + } else { + //firefox & chrome + this.mWType = 3; + mousewheel = function(e) { + e.preventDefault(); + + var detail, + top = 0, + left = 0, + scrollElement = this.scrollElement; + + if (e.deltaX !== 0) { + scrollElement.scrollLeft += e.deltaX > 0 ? horizontalPixels : -horizontalPixels; + + } + + else if (e.deltaY !== 0) { + scrollElement.scrollTop += e.deltaY > 0 ? verticalPixels : -verticalPixels; + } + + else if (detail = this.detail = e.detail) { + + (9 < detail ? detail = 3 : -9 > detail && (detail = -3)); + + switch (detail) { + case 1: + case -1: + left = detail * horizontalPixels; + scrollElement.scrollLeft += left; + break; + case 3: + case -3: + top = (detail / 3) * verticalPixels; + scrollElement.scrollTop += top; + break; + } + } + + return false; + }; + } + + Constructor.prototype.bindMouseWheel(this, mousewheel); + return false; + }, + bindMouseWheel: function(el, fn) { + el.onwheel = el.onmousewheel = el.onDOMMouseScroll = el.onMozMousePixelScroll = fn; + } + }; + + return Constructor; +})(window); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067391_ProtocolEditorGridPanel.js b/pool/shard010/JavaScript/0067391_ProtocolEditorGridPanel.js new file mode 100644 index 0000000000000000000000000000000000000000..6a57e0e23a26fbf810026987e7dfb78929788fb4 --- /dev/null +++ b/pool/shard010/JavaScript/0067391_ProtocolEditorGridPanel.js @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2013-2014 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 + */ +/** + * Created to allow a custom row editor plugin and column that summarize observations + */ +Ext4.define('EHR.grid.ProtocolEditorGridPanel', { + extend: 'EHR.grid.Panel', + alias: 'widget.ehr-protocoleditorgridpanel', + editable: false, + + initComponent: function(){ + this.callParent(arguments); + + this.protocolStore = this.store.storeCollection.getClientStoreByName('protocol'); + LDK.Assert.assertNotEmpty('Unable to find protocol store', this.protocolStore); + + this.mon(this.protocolStore, 'update', this.onprotocolStoreChange, this, {buffer: 400}); + this.mon(this.protocolStore, 'remove', this.onprotocolStoreChange, this, {buffer: 400}); + this.mon(this.protocolStore, 'add', this.onprotocolStoreChange, this, {buffer: 400}); + + + }, + + onprotocolStoreChange: function(store, rec){ + console.log('refresh remark grid'); + this.getView().refresh(); + }, + + getRowEditorPlugin: function(){ + if (this.rowEditorPlugin) + return this.rowEditorPlugin; + + this.rowEditorPlugin = Ext4.create('EHR.plugin.ProtocolRowEditor', { + cmp: this + }); + + return this.rowEditorPlugin; + }, + + configureColumns: function(){ + this.callParent(arguments); + + this.columns.push({ + name: 'protocol', + header: 'Protocol', + width: 400, + renderer: function(value, cellMetaData, record, rowIndex, colIndex, store){ + if (!this.protocolStore){ + this.protocolStore = store.storeCollection.getClientStoreByName('protocol'); + } + LDK.Assert.assertNotEmpty('Unable to find protocol store', this.protocolStore); + + if (this.protocolStore){ + var protocol = record.get('protocol'); + var inves = record.get('inves'); + var approve = record.get('approve'); + var contacts = record.get('contacts'); + //var date = record.get('date') ? record.get('date').format('Y-m-d') : null; + var data = this.protocolStore.snapshot || this.protocolStore.data; + + var lines = []; + data.each(function(r){ + var rowDate = r.get('approve') ? r.get('approve').format('Y-m-d') : null; + + }, this); + + return lines.join('
    '); + } + + return ''; + } + }); + }, + handleSectionChangeEvent: function(sm,models){ + + } +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067401_date-range-picker.js b/pool/shard010/JavaScript/0067401_date-range-picker.js new file mode 100644 index 0000000000000000000000000000000000000000..4c1fe7e379de4e9a94b10602f209dfafad7a7c5c --- /dev/null +++ b/pool/shard010/JavaScript/0067401_date-range-picker.js @@ -0,0 +1,207 @@ +/** + * Copyright 2017 The AMP HTML 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. + */ + +import {map,omit} from '../../../src/utils/object'; +import {requireExternal} from '../../../src/module'; +import {withDatePickerCommon} from './date-picker-common'; + + +/** + * Create a DateRangePicker React component + * @return {function(new:React.Component, !Object)} A date range picker component class + */ +function createDateRangePickerBase() { + const React = requireExternal('react'); + const moment = requireExternal('moment'); + const { + ANCHOR_LEFT, + HORIZONTAL_ORIENTATION, + } = requireExternal('react-dates/constants'); + const { + DateRangePicker: DatePicker, + DateRangePickerPhrases, + } = requireExternal('react-dates'); + + React.options.syncComponentUpdates = false; + + const defaultProps = map({ + // example props for the demo + autoFocus: false, + autoFocusEndDate: false, + initialStartDate: null, + initialEndDate: null, + + // input related props + startDateId: 'start-date', + startDatePlaceholderText: 'Start Date', + endDateId: 'end-date', + endDatePlaceholderText: 'End Date', + disabled: false, + required: false, + screenReaderInputMessage: '', + showClearDates: false, + showDefaultInputIcon: false, + customInputIcon: null, + customArrowIcon: null, + customCloseIcon: null, + + // calendar presentation and interaction related props + renderMonth: null, + orientation: HORIZONTAL_ORIENTATION, + anchorDirection: ANCHOR_LEFT, + horizontalMargin: 0, + withPortal: false, + withFullScreenPortal: false, + initialVisibleMonth: null, + numberOfMonths: 2, + keepOpenOnDateSelect: false, + reopenPickerOnClearDates: false, + isRTL: false, + + // navigation related props + navPrev: null, + navNext: null, + onPrevMonthClick() {}, + onNextMonthClick() {}, + + // day presentation and interaction related props + renderDay: null, + minimumNights: 1, + enableOutsideDays: false, + isDayBlocked: () => false, + isOutsideRange: () => false, + isDayHighlighted: () => false, + + // internationalization + displayFormat: () => moment.localeData().longDateFormat('L'), + monthFormat: 'MMMM YYYY', + + // TODO(cvializ): make these configurable for i18n + phrases: Object.assign({}, DateRangePickerPhrases, { + chooseAvailableStartDate: ({date}) => `Choose ${date} as the first date.`, + chooseAvailableEndDate: ({date}) => `Choose ${date} as the last date.`, + dateIsUnavailable: ({date}) => `The date ${date} is unavailable.`, + dateIsSelected: ({date}) => `The date ${date} is selected.`, + }), + registerAction: null, + }); + + class DateRangePickerBase extends React.Component { + /** + * @param {!Object} props + */ + constructor(props) { + super(props); + + let focusedInput = null; + if (props.autoFocus) { + focusedInput = 'startDate';//this.props.startDateId; + } else if (props.autoFocusEndDate) { + focusedInput = 'endDate';//this.props.endDateId; + } + + this.state = { + focusedInput, + startDate: props.initialStartDate && moment(props.initialStartDate), + endDate: props.initialEndDate && moment(props.initialEndDate), + }; + + this.onDatesChange = this.onDatesChange.bind(this); + this.onFocusChange = this.onFocusChange.bind(this); + + if (this.props.registerAction) { + this.props.registerAction('setDates', invocation => { + const {startDate, endDate} = invocation.args; + const state = {}; + if (startDate) { + state.startDate = moment(startDate); + } + if (endDate) { + state.endDate = moment(endDate); + } + + // TODO(cvializ): check if valid date, blocked, outside range, etc + this.setState(state); + }); + this.props.registerAction('clear', () => { + this.setState({startDate: null, endDate: null}); + }); + } + } + + /** + * @param {!Object} details + */ + onDatesChange({startDate, endDate}) { + const {onDatesChange} = this.props; + + this.setState({startDate, endDate}); + + if (onDatesChange) { + onDatesChange({startDate, endDate}); + } + } + + /** + * @param {?string} focusedInput + */ + onFocusChange(focusedInput) { + if (this.props.emitUpdate) { + this.props.emitUpdate(); + } + this.setState({focusedInput}); + } + + /** @override */ + render() { + const {focusedInput, startDate, endDate} = this.state; + + const props = omit(this.props, [ + 'autoFocus', + 'autoFocusEndDate', + 'initialStartDate', + 'initialEndDate', + 'onDatesChange', + ]); + + return React.createElement(DatePicker, Object.assign({}, props, { + onDatesChange: this.onDatesChange, + onFocusChange: this.onFocusChange, + focusedInput, + startDate, + endDate, + })); + } + } + + DateRangePickerBase.defaultProps = defaultProps; + + return withDatePickerCommon(DateRangePickerBase); +} + +/** @private {?function(new:React.Component, !Object)} */ +let DateRangePicker_ = null; + +/** + * Creates a date range picker, injecting its dependencies. + * @return {function(new:React.Component, !Object)} A date range picker component class + */ +export function createDateRangePicker() { + if (!DateRangePicker_) { + DateRangePicker_ = createDateRangePickerBase(); + } + return DateRangePicker_; +} diff --git a/pool/shard010/JavaScript/0067404_up.js b/pool/shard010/JavaScript/0067404_up.js new file mode 100644 index 0000000000000000000000000000000000000000..4a8f1bb6f4f952bb900782bae64af3751952f2f9 --- /dev/null +++ b/pool/shard010/JavaScript/0067404_up.js @@ -0,0 +1,33 @@ +function click_button_up() +{ + document.body.scrollTop = 0; + document.documentElement.scrollTop = 0; +} + +$(function() { + $.fn.scrollToTop = function() { + $(this).hide().removeAttr("href"); + if ($(window).scrollTop() >= "250") $(this).fadeIn("slow") + var scrollDiv = $(this); + $(window).scroll(function() { + if ($(window).scrollTop() <= "250") $(scrollDiv).fadeOut("slow") + else $(scrollDiv).fadeIn("slow") + }); + $(this).click(function() { + $("html, body").animate({scrollTop: 0}, "slow") + }) + } +}); + +$(function() { + $("#Go_Top").scrollToTop(); +}); + + +onload = function() { + +//document.body.firstChild.data = ""; + +} + + diff --git a/pool/shard010/JavaScript/0067405_cartItem.js b/pool/shard010/JavaScript/0067405_cartItem.js new file mode 100644 index 0000000000000000000000000000000000000000..cb09f3552dea72244d097251ebfab81cf4e19782 --- /dev/null +++ b/pool/shard010/JavaScript/0067405_cartItem.js @@ -0,0 +1,20 @@ +'use strict' +const Sequelize = require('sequelize') +const db = require('./index.js') + + +module.exports = (db) => db.define('cartItem', { + quantity: { + type: Sequelize.INTEGER, + validation: { + min: 1 + } + }, + price: { + type: Sequelize.DECIMAL(10, 2), + }, +}) + +module.exports.associations = (CartItem, {Product}) => { + CartItem.belongsTo(Product) +} diff --git a/pool/shard010/JavaScript/0067411_netflix.user.js b/pool/shard010/JavaScript/0067411_netflix.user.js new file mode 100644 index 0000000000000000000000000000000000000000..c4b191621bd45a30e33672e0948aadbab1fa9a02 --- /dev/null +++ b/pool/shard010/JavaScript/0067411_netflix.user.js @@ -0,0 +1,139 @@ +// ==UserScript== +// @name Netflix ScrubRub +// @match *://www.netflix.com/WiPlayer?* +// @author Stuart P. Bentley +// ==/UserScript== + +(function(){ +var nfi; + +if (typeof netflix != 'undefined') { + if (netflix.cadmium) { + nfi = { + player: netflix.cadmium.objects.videoPlayer(), + imageRoot: netflix.cadmium.metadata.getActiveVideo().progressImageRoot + }; + } +} + +if (nfi) { + initScrubRub(nfi); +} + +function initScrubRub(nfi) { + var np = document.getElementById("netflix-player"); + var vp = nfi.player; + var imgroot = nfi.imageRoot; + function getFrame(t) { + t = Math.floor(t/10000).toString(10); + var f = '00000'.slice(t.length)+t; + return imgroot + f + '.jpg'; + } + var filmstrip = document.createElement('div'); + filmstrip.style.display = 'flex'; + filmstrip.style.justifyContent = 'center'; + filmstrip.style.alignItems = 'center'; + filmstrip.style.overflow = 'hidden'; + filmstrip.style.opacity = 0; + filmstrip.hidden = true; + filmstrip.style.backgroundColor = 'rgba(0,0,0,0.5)'; + filmstrip.style.zIndex = 1000; + filmstrip.style.position = 'absolute'; + filmstrip.style.top = 0; + filmstrip.style.left = 0; + filmstrip.style.bottom = 0; + filmstrip.style.right = 0; + filmstrip.style.pointerEvents = 'none'; + + var thumb = document.createElement('img'); + filmstrip.appendChild(thumb); + + var originTime = 0; + var lastTouchId = null; + var lastTouchX = null; + var totalDelta = 0; + var currentDelta = 0; + var wasPaused; + + function targetTime() { + return originTime - totalDelta * 5; + } + + function selectTouch(touch) { + totalDelta += currentDelta; + lastTouchId = touch.identifier; + lastTouchX = touch.clientX; + currentDelta = 0; + } + + function startRub(evt) { + if (!vp.getBusy()) { + wasPaused = vp.getPaused(); + vp.pause(); + originTime = vp.getCurrentTime(); + totalDelta = 0; + currentDelta = 0; + selectTouch(evt.touches[0]); + thumb.src = getFrame(originTime); + filmstrip.style.opacity = 1; + filmstrip.hidden = false; + } + } + + function endRub(evt) { + if (!vp.getBusy()) { + lastTouchId = null; + lastTouchX = null; + filmstrip.style.opacity = 0; + filmstrip.hidden = true; + vp.seek(targetTime()); + // it seems sometimes wasPaused can get set to true during playback + // when scrubbing, inadvertantly putting us into a paused state + // so for now, just always resume + if(!wasPaused || true) { + vp.play(); + } + } + } + + function upRub(evt) { + thumb.src = getFrame(targetTime()); + } + + function touchStart(evt) { + if (!lastTouchId) { + startRub(evt); + } + evt.preventDefault(); + } + + function touchStop(evt) { + if (evt.touches.length == 0) { + totalDelta += currentDelta; + endRub(evt); + } else { + selectTouch(touches[0]); + } + evt.preventDefault(); + } + + function touchMove(evt) { + var touch = evt.touches[0]; + if (touch.identifier == lastTouchId) { + currentDelta = touch.clientX - lastTouchX; + } + else { + selectTouch(touch); + } + upRub(); + evt.preventDefault(); + } + + np.appendChild(filmstrip); + np.addEventListener('touchstart', touchStart, true); + np.addEventListener('touchend', touchStop, true); + np.addEventListener('touchleave', touchStop, true); + np.addEventListener('touchcancel', touchStop, true); + np.addEventListener('touchmove', touchMove, true); +} +})() diff --git a/pool/shard010/JavaScript/0067413_screenshot-test.js b/pool/shard010/JavaScript/0067413_screenshot-test.js new file mode 100644 index 0000000000000000000000000000000000000000..49272bfff754ac21b20976293e78fceedf8e2ee0 --- /dev/null +++ b/pool/shard010/JavaScript/0067413_screenshot-test.js @@ -0,0 +1,20 @@ +import path from 'path'; +import del from 'del'; +import { expect } from 'chai'; +import { statSync } from 'fs'; +import { tmpNameSync as getTempFileName } from 'tmp'; + + +fixture `Screenshot` + .page('https://google.com') + .before(() => del('.screenshots/*')) + .after(() => del('.screenshots/*')); + +test('Take screenshot', async t => { + var screenshotName = getTempFileName({ template: 'screenshot-XXXXXX.png' }); + var screenshotPath = path.join('.screenshots', screenshotName); + + await t.takeScreenshot(screenshotName); + + expect(statSync(screenshotPath).isFile()).to.be.true; +}); diff --git a/pool/shard010/JavaScript/0067417_index.spec.js b/pool/shard010/JavaScript/0067417_index.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..cc3ce2b80eebe6d56f2c10f01a785f2a654cc552 --- /dev/null +++ b/pool/shard010/JavaScript/0067417_index.spec.js @@ -0,0 +1,66 @@ +import React from 'react'; +import InviteVenueAdmin from './index'; + +describe('', function() { + let props; + + beforeEach(function() { + this.sandbox = sandbox.create(); + props = { + router: { + push: this.sandbox.stub() + }, + venues: [] + }; + }); + + afterEach(function() { + this.sandbox.restore(); + }); + + describe('handleCheckboxChange', function() { + let id; + let inviteNewAdmin; + + beforeEach(function() { + id = faker.random.number(); + inviteNewAdmin = shallow(); + }); + + context('when the box is checked', function() { + let checkboxParams; + + beforeEach(function() { + checkboxParams = { + target: { + checked: true, + value: id + } + }; + return inviteNewAdmin.instance().handleCheckboxChange(checkboxParams); + }); + + it('add the id to state.venueIdsForSubmission', function() { + expect(inviteNewAdmin.state().venueIdsForSubmission).to.include(id); + }); + }); + + context('when the box is not checked', function() { + let checkboxParams; + + beforeEach(function() { + checkboxParams = { + target: { + checked: false, + value: id + } + }; + return inviteNewAdmin.instance().handleCheckboxChange(checkboxParams); + }); + + it('does not add the id to state.venueIdsForSubmission', function() { + expect(inviteNewAdmin.state().venueIdsForSubmission).not.to.include(id); + }); + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067420_directivesSpec.js b/pool/shard010/JavaScript/0067420_directivesSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..2cdc6d1d1512e57d69572b9ab79d35cd14c1c325 --- /dev/null +++ b/pool/shard010/JavaScript/0067420_directivesSpec.js @@ -0,0 +1,84 @@ +'use strict'; + +/* jasmine specs for directives go here */ + +describe('Unit testing', function() { + var $compile, + $httpBackend, + $rootScope; + + // Load the myApp module, which contains the directive + beforeEach(module('cvApp')); + + // Store references to $rootScope and $compile + // so they are available to all tests in this describe block + beforeEach(inject(function(_$compile_, _$httpBackend_, _$rootScope_) { + // The injector unwraps the underscores (_) from around the parameter names when matching + $compile = _$compile_; + $httpBackend = _$httpBackend_; + $rootScope = _$rootScope_; + })); + + describe("experience", function() { + var experienceTemplate = function() { + return "

    Professional Experience

    "; + }, + experienceData = function() { + return [{ + "abbreviation": "classroom", + "company": "Classroom Publications Limited", + "location": "Hong Kong", + "start_date": "2012-09-26", + "end_date": "2016-02-26", + "url": "classroom.com.hk", + "role": "Web Programmer for an ever expanding number of projects including eMagazine, Idiom World, Pink Office Solution and more.", + "skill": "Applications are developed using ASP.NET MVC and Web Forms with C#, PHP, HTML5, CSS3, javascript, jQuery and Bootstrap. Most of the time I lead the development of the project with our manager and designer. I use Visual Studio as IDE. I use MS SQL Server, MySQL and MS Access as database, and I develop web service to communicate between the database and the application. TSQL written in store procedure is often used to increase the performance and readability of the web service." + }]; + }; + + beforeEach(function() { + $httpBackend.expectGET('partials/cv-experience.html').respond(experienceTemplate()); + $httpBackend.expectGET('data/experiences.json').respond(experienceData()); + }); + + it('Replaces the element with the appropriate content', function() { + // Compile a piece of HTML containing the directive + var element = $compile("")($rootScope); + // fire all the watches, so the scope expression {{1 + 1}} will be evaluated + //$rootScope.$digest(); + $httpBackend.flush(); + // Check that the compiled element contains the templated content + expect(element.html()).toContain("Professional Experience"); + + }); + }); + + describe("skill", function() { + var skillTemplate = function() { + return "

    Skills

    "; + }, + skillData = function() { + return [{ + "abbreviation": "code", + "name": "Web Development Languages", + "items": ["ASP.NET MVC and Web Forms", "C#", "Html", "CSS", "Javascript", "jQuery", "Bootstrap", "AngularJs", "NodeJS", "Jasmine", "Protractor"] + }]; + }; + + beforeEach(function() { + $httpBackend.expectGET('partials/cv-skill.html').respond(skillTemplate()); + $httpBackend.expectGET('data/skills.json').respond(skillData()); + }); + + it('Replaces the element with the appropriate content', function() { + // Compile a piece of HTML containing the directive + var element = $compile("")($rootScope); + // fire all the watches, so the scope expression {{1 + 1}} will be evaluated + //$rootScope.$digest(); + $httpBackend.flush(); + // Check that the compiled element contains the templated content + expect(element.html()).toContain("Skills"); + + }); + }); +}); diff --git a/pool/shard010/JavaScript/0067421_populateDatabase.js b/pool/shard010/JavaScript/0067421_populateDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..cdc3a7827fdb2dbcd0d4349a8e278adfbeb2c803 --- /dev/null +++ b/pool/shard010/JavaScript/0067421_populateDatabase.js @@ -0,0 +1,53 @@ +const app = require('./app'); + +const submissionsService = app.service('/submissions'); +const usersService = app.service('/users'); +const projectsService = app.service('/projects'); + +usersService.create({ + userName: 'userone', + bio: 'test data 1', + password: 'password', + email: 'user1@user.com' + }) + .then((project)=>{ + console.log('users success'); + }) + .catch((error) =>{ + console.log(error); + }); + +projectsService.create({ + name: 'test project2', + description: 'test project2 this is a test of the emergency broadcasting system. nothing is going wrong, don;t worry about anything. ignore the giant creature in the bay. Have a nice day', + bounty: 10000, + videoUrl: 'testdata', + endDate: '2017/01/01', + awarded: false, + image: 'null', + userId: 1 + }) + .then((project)=>{ + console.log('projects success'); + }) + .catch((error) =>{ + console.log(error); + }); + +submissionsService.create({ + title: 'test project2', + description: 'test project2 this is a test of the emergency broadcasting system. nothing is going wrong, don;t worry about anything. ignore the giant creature in the bay. Have a nice day', + videoLink: 'null', + repoLink: 'null', + win: false, + userid: 1, + projectid: 1, + + }) + .then((project)=>{ + console.log('submission success'); + }) + .catch((error) =>{ + console.log(error); + }); + diff --git a/pool/shard010/JavaScript/0067422_test.js b/pool/shard010/JavaScript/0067422_test.js new file mode 100644 index 0000000000000000000000000000000000000000..f0286825851c5167415339d5fc16c86539cccd22 --- /dev/null +++ b/pool/shard010/JavaScript/0067422_test.js @@ -0,0 +1,31 @@ +import glob from 'glob'; +import path from 'path'; +import test from 'tape'; +import load from 'load-json-file'; +import pointOnLine from '.'; + +test('turf-boolean-point-on-line', t => { + // True Fixtures + glob.sync(path.join(__dirname, 'test', 'true', '**', '*.geojson')).forEach(filepath => { + const name = path.parse(filepath).name; + const geojson = load.sync(filepath); + const options = geojson.propeties; + const feature1 = geojson.features[0]; + const feature2 = geojson.features[1]; + const result = pointOnLine(feature1, feature2, options); + + t.true(result, '[true] ' + name); + }); + // False Fixtures + glob.sync(path.join(__dirname, 'test', 'false', '**', '*.geojson')).forEach(filepath => { + const name = path.parse(filepath).name; + const geojson = load.sync(filepath); + const options = geojson.properties; + const feature1 = geojson.features[0]; + const feature2 = geojson.features[1]; + const result = pointOnLine(feature1, feature2, options); + + t.false(result, '[false] ' + name); + }); + t.end(); +}); diff --git a/pool/shard010/JavaScript/0067423_gulpfile.js b/pool/shard010/JavaScript/0067423_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..50184056e3e06cae518b9f96bf7d0f5af4eb6fdd --- /dev/null +++ b/pool/shard010/JavaScript/0067423_gulpfile.js @@ -0,0 +1,95 @@ +/** + * saoGulp - gulpfile.js + * Created by hzl + */ + +'use strict'; + + + +var gulp = require('gulp'); +var setting = require('./config'); +var mainBuild = require('./tasks/main'); +var fs = require('fs'); +var file =require('./tasks/file'); + +// MD5戳 +//var rev = require('gulp-rev'); +//var revCollector = require('gulp-rev-collector'); +var runSequence = require('run-sequence'); + +var clean = require('gulp-clean'); +//监控 +gulp.task('watch',function(){ + mainBuild.watch(); +}); +//开始服务 +gulp.task('server',function(){ + mainBuild.server(); +}); +//本地开发环境 +gulp.task('local',function(){ + mainBuild.img(function(){ + mainBuild.sprite(function(){ + mainBuild.less(function(){ + mainBuild.js(function(){ + mainBuild.html(function(){ + mainBuild.fonts(function(){ + mainBuild.tpl(function(){ + gulp.start(['watch','server']); + }) + }); + }); + }); + }); + }); + }); +}); +//打包 压缩 资源整合 + +var publish = function(callback){ + mainBuild.less(function(){ + mainBuild.js(function(){ + mainBuild.img(function(){ + mainBuild.fonts(function(){ + mainBuild.html(function(){ + callback(); + }); + }); + }); + }); + }); +}; + +gulp.task('release',function(){ + var _startTime = (new Date()).getTime(); + publish(function(){ + var _endTime = (new Date()).getTime(); + console.log("耗时:" + (_endTime - _startTime) / 1000 + "s..."); + }) +}); + +//清理垃圾 +gulp.task('clean',function(done){ + if(setting.env == 'local'){ + file.rmdirSync('build'); + }else{ + file.rmdirSync('dist'); + } +}); + +gulp.task('default',function(){ + if(setting.env == 'local'){ + runSequence([ + 'clean', + 'local' + ]); + }else{ + runSequence([ + 'clean', + 'release' + ]); + } +}); + + diff --git a/pool/shard010/JavaScript/0067425_angulartics-gtm.js b/pool/shard010/JavaScript/0067425_angulartics-gtm.js new file mode 100644 index 0000000000000000000000000000000000000000..721b3c42539ff7ddb5077d9530bf830ca79d942a --- /dev/null +++ b/pool/shard010/JavaScript/0067425_angulartics-gtm.js @@ -0,0 +1,75 @@ +/** + * @license Angulartics + * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics + * Google Tag Manager Plugin Contributed by http://github.com/danrowe49 + * License: MIT + */ + +(function(angular){ +'use strict'; + + +/** + * @ngdoc overview + * @name angulartics.google.analytics + * Enables analytics support for Google Tag Manager (http://google.com/tagmanager) + */ + +angular.module('angulartics.google.tagmanager', ['angulartics']) +.config(['$analyticsProvider', function($analyticsProvider){ + + /** + * Send content views to the dataLayer + * + * @param {string} path Required 'content name' (string) describes the content loaded + */ + + $analyticsProvider.registerPageTrack(function(path){ + var dataLayer = window.dataLayer = window.dataLayer || []; + dataLayer.push({ + 'event': 'content-view', + 'content-name': path + }); + }); + + /** + * Send interactions to the dataLayer, i.e. for event tracking in Google Analytics + * @name eventTrack + * + * @param {string} action Required 'action' (string) associated with the event + * @param {object} properties Comprised of the mandatory field 'category' (string) and optional fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean) + */ + + $analyticsProvider.registerEventTrack(function(action, properties){ + var dataLayer = window.dataLayer = window.dataLayer || []; + properties = properties || {}; + dataLayer.push({ + 'event': properties.event || 'interaction', + 'target': properties.category, + 'action': action, + 'target-properties': properties.label, + 'value': properties.value, + 'interaction-type': properties.noninteraction + }); + + }); + + $analyticsProvider.registerSetUsername( + /** + * Send user's data to the datalayer, i.e. for user tracking in Google Analytics + * @param {string} username login of the username + * @param {object} properties List of attribute of the current username + * @return {void} + */ + function (username, properties) { + var dataLayer = window.dataLayer = window.dataLayer || []; + properties = properties || {}; + dataLayer.push({ + 'username': username, + 'user': properties + }); + } + ); +}]); + +})(angular); diff --git a/pool/shard010/JavaScript/0067426_controller-with-cursor-if-present.js b/pool/shard010/JavaScript/0067426_controller-with-cursor-if-present.js new file mode 100644 index 0000000000000000000000000000000000000000..4d122786a56df6241326ef567f7a05d82c7b30fa --- /dev/null +++ b/pool/shard010/JavaScript/0067426_controller-with-cursor-if-present.js @@ -0,0 +1,31 @@ +AFRAME.registerComponent("controller-with-cursor-if-present", { + schema: {type: 'string'}, + init: function() { + this.el.setAttribute('controller-model-if-present', this.data); + + // Create ray as visible guide for selection. + // NOTE: make sure cursor/raycaster won't intersect! + var ray = document.createElement('a-box'); + ray.setAttribute('class', 'not-clickable'); + ray.setAttribute('width', 0.001); + ray.setAttribute('height', 0.001); + ray.setAttribute('depth', 100); + ray.setAttribute('position', {x:0, y:0, z: -50}); + ray.setAttribute('color', 'green'); + ray.setAttribute('opacity', 0.95); + this.el.appendChild(ray); + + this.el.addEventListener('controllerconnected', function (evt) { + // if we had a raycaster, cursor, etc., attach here + evt.target.setAttribute('controller-cursor', ''); + // need to make ray NOT an intersection target for raycaster! + evt.target.setAttribute('raycaster', 'interval:100; objects:.clickable'); + + // Since we have a controller, remove gaze cursor. + var cameraCursorEl = document.querySelector('a-camera a-entity[cursor]'); + if (cameraCursorEl) { + cameraCursorEl.parentElement.removeChild(cameraCursorEl); + } + }); + } +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067427_javascript.js b/pool/shard010/JavaScript/0067427_javascript.js new file mode 100644 index 0000000000000000000000000000000000000000..2bcfa7cc2e59d4dfe564e7d93ad5bdc8cd61f9bc --- /dev/null +++ b/pool/shard010/JavaScript/0067427_javascript.js @@ -0,0 +1,52 @@ +"use strict"; + +var util = require('util'), + path = require('path'), + jsParser = require('uglify-js').parser, + compressor = require('uglify-js').uglify, + + Asset = require('../Asset'), + JSAsset = function(settings) { + settings.compressor = settings.compressor || 'uglify'; + + this.init(settings); + + var self = this; + + this.on('variantPostRenderFile', function(variant, file, cb) { + var basename = path.basename(file), + contents = variant.getRenderCache(file); + + if (!Asset.COMPRESS) { + variant.setRenderCache(file, contents + "\n\n"); + return cb(); + } + + self.compress(file, contents, function(err, data) { + // errors are already signaled by the compressor + variant.setRenderCache(file, "/* " + basename + " */\n" + data + "\n\n"); + cb(); + }); + }); + }; + +util.inherits(JSAsset, Asset); + +Asset.registerCompressor('uglify', function(filepath, data, cb) { + try { + var ast = compressor.ast_squeeze(compressor.ast_mangle(jsParser.parse(data))); + cb(null, ';' + compressor.gen_code(ast)); + } catch (ex) { + console.error('ERROR: Uglify compressor error in ' + filepath); + console.error(ex); + + // only show the error in the logs...don't stop serving because of this + cb(null, data); + } +}); + +JSAsset.configure = function(opts) { + Asset.configure(opts); +}; + +module.exports = JSAsset; diff --git a/pool/shard010/JavaScript/0067428_Person.js b/pool/shard010/JavaScript/0067428_Person.js new file mode 100644 index 0000000000000000000000000000000000000000..116542d1e5cd0b0f16c446a1f90e69cbb22218a8 --- /dev/null +++ b/pool/shard010/JavaScript/0067428_Person.js @@ -0,0 +1,284 @@ + +var Person = function (x, y, key, name, startDir) { + var that = {}; + + var group = game.add.group(undefined, name + "_grp"); + + var shape = game.add.sprite(x,y, key); + shape.anchor.x = 0.5; + shape.anchor.y = 0.5; + shape.animations.add('left', ['l2','l1','l0','l1'], 9, true); + shape.animations.add('up', ['u0','u1','u2','u1'], 9, true); + shape.animations.add('down', ['d0','d1','d2','d1'], 9, true); + shape.animations.add('right', ['r0','r1','r2','r1'], 9, true); + shape.animations.add('leftidle', ['l1'], 6, true); + shape.animations.add('upidle', ['u1'], 6, true); + shape.animations.add('downidle', ['d1'], 6, true); + shape.animations.add('rightidle', ['r1'], 6, true); + + // for display object sorting + group.add(shape); + + + var thought = Thought(x, y, name); + thought.hide(); + thought.load(name, "script"); + + var moveDir = new Phaser.Point(0,0); + var lookDir = startDir || lookState.down; + var speed = 3; + var moving = false; + + var move = function(x, y) { + moving = true; + moveDir = new Phaser.Point(x,y).normalize(); + if(x > 0 && x > y) + { + look(lookState.right); + } + else if(x < 0 && x < y) + { + look(lookState.left); + } + else if(y < 0 && y < x) + { + look(lookState.up); + } + else + { + look(lookState.down); + } + // FIXME: should we call thought.move as well? + }; + + var look = function(dir) { + lookDir = dir; + }; + + var stop = function() { + moving = false; + moveDir = new Phaser.Point(0,0); + }; + + var think = function(duration, index) { + + var line = ((index === undefined) ? + thought.stream.getNext() : + thought.stream.getAt(index)); + + thought.text.setText(line); + if (!line || line.length === 0) { + thought.hide(); + return; + } + + thought.show(); + thought.redraw(); + + game.time.events.add(duration, function() { + thought.hide(); + }); + }; + + var destroySelf = function() { + console.log("destroy self"); + groups.midGround.remove(group, true); + groups.textGround.remove(thought_group, true); + + minorCharacters.forEach(function(e) { + if(e === that) + { + minorCharacters.remove(minorCharacters.indexOf(e)); + } + }); + characters.forEach(function(e) { + if(e === that) + { + characters.remove(characters.indexOf(e)); + } + }); + }; + + var thoughtTimer = 0; + var currentThought = null; + + var doThought = function () { + if(currentThought === null){ + return; + } + }; + + var actionTimer = 0; + var actionQueue = []; + var repeatAction = null; + var pushAction = function(param) { + actionQueue.push(param); + }; + + // actions always are relative to the duration of the previous action + var doAction = function() { + if(actionQueue.length === 0) { + stop(); + actionTimer = 0; + if(repeatAction !== null) { + if(repeatAction.times < 0) { // it must have started at zero + repeatAction.f(repeatAction.context, repeatAction.pause, + repeatAction.duration, repeatAction.dir, repeatAction.times); + } + else { + repeatAction.f(repeatAction.context, repeatAction.pause, + repeatAction.duration, repeatAction.dir, repeatAction.times - 1); + } + doAction(); + } + return; + } + var action = actionQueue[0]; + if(action.type === "move" && action.pause <= actionTimer) { + moving = true; + move(action.args.x, action.args.y); + } + else if(action.type === "stop") { + stop(); + } + else if(action.type === "look" && action.pause <= actionTimer) { + look(action.args); + } + else if(action.type === "repeat") { + repeatAction = action.args; + } + + doThought(); + + if(action.duration + action.pause <= actionTimer) + { + popAction(); + doAction(); + } + }; + + var popAction = function () { + actionTimer = 0; + stop(); + actionQueue.splice(0,1); + }; + + that.update = function (dt) { + actionTimer += dt; + doAction(); + shape.position.x += moveDir.x*speed*dt * 0.016; + shape.position.y += moveDir.y*speed*dt * 0.016; + + if (thought.text.visible) { + thought.move( + shape.position.x - shape.width * shape.anchor.x, + shape.position.y - shape.height * shape.anchor.y - thought.text.height); + } + + switch(lookDir) { + case lookState.down: + if(moving) shape.animations.play('down', 5, true); + else shape.animations.play('downidle', 5, true); + break; + case lookState.left: + if(moving) shape.animations.play('left', 5, true); + else shape.animations.play('leftidle', 5, true); + break; + case lookState.up: + if(moving) shape.animations.play('up', 5, true); + else shape.animations.play('upidle', 5, true); + break; + case lookState.right: + if(moving) shape.animations.play('right', 5, true); + else shape.animations.play('rightidle', 5, true); + break; + } + }; + + that.group = group; + that.thought_group = thought.group; + + that.shape = shape; + //that.move = move; + //that.stop = stop; + //that.speed = speed; + that.pushAction = pushAction; + that.look = look; + + that.think = think; + that.name = name; + that.thought = thought; + + that.think = think; + return that; +}; + + +var LobbyInit = function () { + minorCharacters.length = 0; + characters.length = 0; + Program.groups.midground.removeAll(); + Program.groups.textground.removeAll(); + + // lobby people + minorCharacters.push(Person(-1400, 1045, 'redwoman', 'Attendent2')); + minorCharacters.push(Person(-1410, 1156, 'suitwoman', 'Queue21', lookState.up)); + minorCharacters.push(Person(-1150, 1038, 'bluewoman', 'Attendent1')); + minorCharacters.push(Person(-1660, 1035, 'blueman', 'Attendent3')); + minorCharacters.push(Person(-1910, 1045, 'bluewoman', 'Attendent4')); + + minorCharacters.push(Person(-1150, 1151, 'blueman', 'Queue11', lookState.up)); + minorCharacters.push(Person(-1150, 1231, 'redwoman', 'Queue12', lookState.up)); + minorCharacters.push(Person(-1160, 1340, 'baldman', 'Queue13', lookState.up)); + + characters.push(Person(-1460, 1270, 'backpack', 'eve', lookState.right)); + characters.push(Person(-1410, 1270, 'backpackman', 'adam', lookState.left)); + + var wait1 = Person(-1690, 1425, 'baldman', 'wait1', lookState.right); + MoveLib.repeat(wait1, 1000, 1000, MoveLib.walkCircleCCW); + minorCharacters.push(wait1); + + var pace1 = Person(-1500, 1615, 'suitman', 'pace1'); + MoveLib.repeat(pace1, 1000, 6000, MoveLib.PaceH); + minorCharacters.push(pace1); + + minorCharacters.push(Person(-880, 1755, 'backpackman', 'tickerWatcher', lookState.up)); + player = Player(characters[0]); + Program.sortGroups(); + Opening.start(); +}; + +var SecurityInit = function () { + minorCharacters.length = 0; + characters.length = 0; + Program.groups.midground.removeAll(); + Program.groups.textground.removeAll(); + + // hallway walkers + var hall3 = Person(-580, 1455, 'blueman', 'hall3'); + minorCharacters.push(hall3); + MoveLib.repeat(hall3, 3000, 24000, MoveLib.PaceH, 1); + + var hall4 = Person(500, 1600, 'backpack', 'hall4'); + minorCharacters.push(hall4); + MoveLib.repeat(hall4, 2000, 15000, MoveLib.PaceH, -1); + + var hall1 = Person(-770, 1629, 'suitman', 'hall1'); + minorCharacters.push(hall1); + MoveLib.repeat(hall1, 1000, 30000, MoveLib.PaceH, 1); + + var hall5 = Person(10, 1690, 'backpackman', 'hall5'); + minorCharacters.push(hall5); + MoveLib.repeat(hall5, 1000, 21000, MoveLib.PaceH, 1); + + var hall2 = Person(1440, 1719, 'redwoman', 'hall2'); + minorCharacters.push(hall2); + MoveLib.repeat(hall2, 2000, 19000, MoveLib.PaceH, -1); + + if(Program.isDebugMode) + { + player = Player(hall5); + } + Program.sortGroups(); + Security.start(); +}; diff --git a/pool/shard010/JavaScript/0067429_ExternalProcessWindowMenu.js b/pool/shard010/JavaScript/0067429_ExternalProcessWindowMenu.js new file mode 100644 index 0000000000000000000000000000000000000000..af2e5fa8a88800fc7dccf2ae270f0604059a4189 --- /dev/null +++ b/pool/shard010/JavaScript/0067429_ExternalProcessWindowMenu.js @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2013 CoNWeT Lab., Universidad Politécnica de Madrid + * + * This file is part of Wirecloud Platform. + * + * Wirecloud Platform 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. + * + * Wirecloud 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 Wirecloud Platform. If not, see + * . + * + */ + +/*global gettext, StyledElements, Wirecloud*/ + +(function () { + + "use strict"; + + var detect_close_finish, open_external_window; + + detect_close_finish = function detect_close() { + if (this.external_window.closed) { + this.external_window = null; + clearInterval(this.interval); + this.interval = null; + this.start_button.enable(); + this.start_button.focus(); + } else if ('href' in this.external_window.location && this.options.return_uri(this.external_window.location.href)) { + + if (typeof this.options.onSuccess === 'function') { + try { + this.options.onSuccess(this.external_window.location.href); + } catch (e) { + } + } + + this.hide(); + } + }; + + open_external_window = function open_external_window(url) { + this.external_window = window.open(url, '_blank'); + this.interval = setInterval(detect_close_finish.bind(this), 200); + }; + + /** + * This window menu eases the creation of modal windows that will wait for + * a external process to finish. This window will show a message warning + * that the process will continue on another browser window/tab. + * + * The external process should finish using the same domain of the current + * web page for being able to detect this event. + */ + var ExternalProcessWindowMenu = function ExternalProcessWindowMenu(title, url, msg, options) { + Wirecloud.ui.WindowMenu.call(this, title); + + if (options != null) { + this.options = options; + } else { + this.options = {}; + } + this.url = url; + + this.msgElement = document.createElement('div'); + this.msgElement.className = "msg"; + this.msgElement.textContent = msg; + this.windowContent.appendChild(this.msgElement); + + if (this.options.return_uri == null) { + this.options.return_uri = function return_uri(uri) { + return uri !== 'about:blank'; + }; + } else if (typeof this.options.return_uri !== 'function') { + var base_uri = this.options.return_uri; + this.options.return_uri = function return_uri(uri) { + return uri.startsWith(base_uri); + }; + } + + // Start button + this.start_button = new StyledElements.Button({ + text: gettext('Start'), + 'class': 'btn-primary' + }); + this.start_button.insertInto(this.windowBottom); + this.start_button.addEventListener("click", function () { + this.start_button.disable(); + this.cancel_button.focus(); + + open_external_window.call(this, this.url); + }.bind(this)); + + // Cancel button + this.cancel_button = new StyledElements.Button({ + text: gettext('Cancel'), + 'class': 'btn-danger' + }); + this.cancel_button.insertInto(this.windowBottom); + this.cancel_button.addEventListener("click", this._closeListener); + }; + ExternalProcessWindowMenu.prototype = new Wirecloud.ui.WindowMenu(); + + ExternalProcessWindowMenu.prototype.setFocus = function setFocus() { + this.start_button.focus(); + }; + + ExternalProcessWindowMenu.prototype._closeListener = function _closeListener() { + if (typeof this.options.onCancel === 'function') { + try { + this.options.onCancel(); + } catch (e) { + } + } + Wirecloud.ui.WindowMenu.prototype._closeListener.call(this); + }; + + ExternalProcessWindowMenu.prototype.hide = function hide() { + Wirecloud.ui.WindowMenu.prototype.hide.call(this); + if (this.external_window) { + this.external_window.close(); + this.external_window = null; + } + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + }; + + ExternalProcessWindowMenu.prototype.show = function show(parentWindow) { + Wirecloud.ui.WindowMenu.prototype.show.call(this, parentWindow); + }; + Wirecloud.ui.ExternalProcessWindowMenu = ExternalProcessWindowMenu; + +})(); diff --git a/pool/shard010/JavaScript/0067433_Bond.js b/pool/shard010/JavaScript/0067433_Bond.js new file mode 100644 index 0000000000000000000000000000000000000000..4f0258283de981043865a8e308894b8cdfd31e16 --- /dev/null +++ b/pool/shard010/JavaScript/0067433_Bond.js @@ -0,0 +1,18 @@ +Clazz.declarePackage ("J.adapter.smarter"); +Clazz.load (["J.adapter.smarter.AtomSetObject"], "J.adapter.smarter.Bond", null, function () { +c$ = Clazz.decorateAsClass (function () { +this.atomIndex1 = 0; +this.atomIndex2 = 0; +this.order = 0; +this.radius = -1; +this.colix = -1; +this.uniqueID = -1; +Clazz.instantialize (this, arguments); +}, J.adapter.smarter, "Bond", J.adapter.smarter.AtomSetObject); +Clazz.makeConstructor (c$, +function (atomIndex1, atomIndex2, order) { +this.atomIndex1 = atomIndex1; +this.atomIndex2 = atomIndex2; +this.order = order; +}, "~N,~N,~N"); +}); diff --git a/pool/shard010/JavaScript/0067436_dialog.js b/pool/shard010/JavaScript/0067436_dialog.js new file mode 100644 index 0000000000000000000000000000000000000000..c314ffc2b7f61d437b15e731a452ef237529a847 --- /dev/null +++ b/pool/shard010/JavaScript/0067436_dialog.js @@ -0,0 +1,54 @@ +var MoodleEmoticonDialog = { + + init : function() { + // Register event handlers for the table rows. + tinymce.each(tinymce.DOM.select('tr.emoticoninfo', document), function(row) { + + tinymce.dom.Event.add(row, 'mouseover', function(e) { + this.style.backgroundColor = 'white'; + }, row); + + tinymce.dom.Event.add(row, 'mouseout', function(e) { + this.style.backgroundColor = 'transparent'; + }, row); + + tinymce.dom.Event.add(row, 'click', function(e) { + var matches = /^emoticoninfo emoticoninfo-index-([0-9]+)$/.exec(this.className); + if (matches.length != 2) { + // continue with the next row + return true; + } + var index = matches[1]; + MoodleEmoticonDialog.insert(index); + }, row); + + }); + }, + + insert : function(index) { + emoticons = tinyMCEPopup.editor._emoticons; + i = 0; + for (var emoticon in emoticons) { + if (i == index) { + if (tinymce.isIE) { + tinyMCEPopup.restoreSelection(); + } + tinyMCEPopup.editor.execCommand('mceInsertContent', false, emoticons[emoticon]); + tinyMCEPopup.close(); + return; + } + i++; + } + }, + + highlight : function(row) { + row.style.backgroundColor="white"; + }, + + unhighlight : function(row) { + row.style.backgroundColor="transparent"; + } + +}; + +tinyMCEPopup.onInit.add(MoodleEmoticonDialog.init, MoodleEmoticonDialog); diff --git a/pool/shard010/JavaScript/0067440_Icon.spec.js b/pool/shard010/JavaScript/0067440_Icon.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e1982157911f3e96e71cf0e3bf76a544dcdbb32c --- /dev/null +++ b/pool/shard010/JavaScript/0067440_Icon.spec.js @@ -0,0 +1,25 @@ +/* @flow */ +import React from 'react'; +import { shallow } from 'enzyme'; +import Icon from '../Icon'; +import examples from '../../../website/app/demos/Icon/Icon/examples'; +import testDemoExamples from '../../../../utils/testDemoExamples'; + +function shallowIcon(props = {}) { + const iconProps = { + ...props + }; + return shallow(); +} + +describe('Icon', () => { + testDemoExamples(examples, { + exclude: ['categories'] + }); + + it('renders', () => { + const icon = shallowIcon(); + + expect(icon.exists()).toEqual(true); + }); +}); diff --git a/pool/shard010/JavaScript/0067444_server.js b/pool/shard010/JavaScript/0067444_server.js new file mode 100644 index 0000000000000000000000000000000000000000..622c814dfdcc364c011a456b5c89788cbe6333bf --- /dev/null +++ b/pool/shard010/JavaScript/0067444_server.js @@ -0,0 +1,85 @@ +// modules ================================================= +var express = require('express'); +var app = express(); +var path = require('path'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var methodOverride = require('method-override'); +var morgan = require('morgan'); +var mongoose = require('mongoose'); +var passport = require('passport'); +var session = require('express-session'); +var apiRouter = require('./api'); +var authRouter = require('./auth'); +var salt = require('./config').salt; +var fs = require('fs'); + +//mongoose connect +mongoose.connect('mongodb://localhost/mean2-starter'); + +// set our port +var port = process.env.PORT || 3000; + +app.use(morgan('dev')); + +app.use(bodyParser.json()); +app.use(bodyParser.json({ type: 'application/vnd.api+json' })); +app.use(bodyParser.urlencoded({ extended: true })); +app.use(methodOverride('X-HTTP-Method-Override')); +app.use(cookieParser()); + +app.use(express.static(path.resolve('./dist'))); +app.use('/upload', express.static('upload')); +app.use('/node_modules', express.static('node_modules')); + +app.use(session({ + secret: salt, + saveUninitialized: true, + resave: true +})); + +app.use(passport.initialize()); +app.use(passport.session()); +app.use(passport.authenticate('remember-me')); + +app.use('/auth', authRouter.router); +app.use('/api', authRouter.isAuthenticated, apiRouter); +app.get('*', function(req, res, next) { + res.sendFile(path.resolve('./dist/index.html')); +}); + + +// start app =============================================== +// startup our app at http://localhost:8080 +app.listen(port); + +// shoutout to the user +console.log('Magic happens on port ' + port); + +//insert dummy_user profile picture +var uploadFolder = process.env.UPLOAD_PATH; +if (!fs.existsSync(uploadFolder)) { + console.log('creating upload directory'); + fs.mkdirSync(uploadFolder); +} + +if (!fs.readdirSync(uploadFolder).length) { + var Upload = require('./api/upload/upload.model'); + var srcPath = './image/dummy_user.png'; + var targetPath = path.resolve(uploadFolder, 'dummy_user.png'); + + fs.link(srcPath, targetPath, function(err) { + if (err) { + return console.error(err.toString()); + } + + targetPath = targetPath.substring(targetPath.indexOf('upload')); + Upload.createUpload(targetPath) + .catch(function(err) { + console.error(err.toString()); + }); + }); +} + +// expose app +exports = module.exports = app; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067445_SelectProject.js b/pool/shard010/JavaScript/0067445_SelectProject.js new file mode 100644 index 0000000000000000000000000000000000000000..c8cd9847ed1507fa71ff4be5d8a551fadc948c57 --- /dev/null +++ b/pool/shard010/JavaScript/0067445_SelectProject.js @@ -0,0 +1,87 @@ +GO.projects2.SelectProject = function(config){ + + var config = config || {}; + //Ext.apply(this, config); + + Ext.applyIf(config,{ + minHeight: 300, + displayField: 'path', + hiddenName:'project_id', + valueField: 'id', + emptyText:GO.lang.none, + triggerAction:'all', + mode:'remote', + editable: true, + tpl: new Ext.XTemplate( +// '{[this.currentKey = null]}' + + '{[this.resetCurrentKey()]}'+ + ''+ + '' + + '' + + '' + + '
    {[this.name]}
    ', + '
    ', + { + shouldShowHeader: function(path){ + + var pathArr = path.split('/'); + this.name = pathArr.pop(); // remove + + + return this.currentKey !== pathArr.join('/'); + }, + showHeader: function(path){ + var pathArr = path.split('/'); + pathArr.pop(); // remove project + this.currentKey = pathArr.join('/'); + return this.currentKey; + }, + resetCurrentKey: function() { + this.currentKey=null; + return ''; + } + } + ), +// selectOnFocus:true, +// forceSelection: true, +// typeAhead: true, + disabled:false, + store:GO.projects2.selectProjectStore, + fieldLabel:GO.projects2.lang.project, + pageSize: parseInt(GO.settings['max_rows_list']) + }); + + + if(config.storeBaseParams) + config.store.baseParams = config.storeBaseParams; + + GO.projects2.SelectProject.superclass.constructor.call(this,config); + + this.store.setDefaultSort('path', 'asc'); + +}; +Ext.extend(GO.projects2.SelectProject, GO.form.ComboBoxReset,{ + + restrictHeight : function(){ + this.innerList.dom.style.height = ''; + var inner = this.innerList.dom, + pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight, + h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight), + ha = this.getPosition()[1]-Ext.getBody().getScroll().top, + hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height, + space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5; + + h = Math.min(h, space, this.maxHeight); + + //added this because of a bug that didn't show one record with a group + if(h<60){ + h=60; + } + + this.innerList.setHeight(h); + this.list.beginUpdate(); + this.list.setHeight(h+pad); + this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign)); + this.list.endUpdate(); + } +}); diff --git a/pool/shard010/JavaScript/0067447_unusedImports3.js b/pool/shard010/JavaScript/0067447_unusedImports3.js new file mode 100644 index 0000000000000000000000000000000000000000..e968ac64062f92bc1d979f003f04aa5a5322cfd5 --- /dev/null +++ b/pool/shard010/JavaScript/0067447_unusedImports3.js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/unusedImports3.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import {Calculator, test, test2} from "./file1" + +test(); +test2(); + +//// [file1.js] +"use strict"; +exports.__esModule = true; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; +exports.__esModule = true; +var file1_1 = require("./file1"); +file1_1.test(); +file1_1.test2(); diff --git a/pool/shard010/JavaScript/0067448_serialization.js b/pool/shard010/JavaScript/0067448_serialization.js new file mode 100644 index 0000000000000000000000000000000000000000..6f77d7e21ef1fbe873075580c71631fca02e702f --- /dev/null +++ b/pool/shard010/JavaScript/0067448_serialization.js @@ -0,0 +1,96 @@ +/* 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/. */ + + + +const keys = require("../core/key"); +const { Shortcut } = require("../core/shortcut"); +const { Modifiers } = require("../core/modifiers"); + +let serialize = exports.serialize = function (data) { + if (!data) { + return; + } + + let Overlay = require("../core/overlay").Overlay; + + if (data instanceof Overlay) { + return { + _type: "overlay", + key: serialize(data.key), + shortcut: serialize(data.shortcut) + }; + } + + if (data instanceof keys.Key) { + return { + _type: "key", + id: data.id + }; + } + + if (data instanceof Shortcut) { + return ((data.disabled && { + _type: "shortcut", + disabled: true + }) || { + _type: "shortcut", + key: data.key, + keycode: data.keycode, + code: data.code, + modifiers: serialize(data.modifiers) + }); + } + if (data instanceof Modifiers) { + return { + _type: "modifiers", + modifiers: data.modifiers + }; + } + + return data; +} + +let unserialize = exports.unserialize = function (data) { + if (!data) return; + + let Overlay = require("../core/overlay").Overlay; + let Overlays = require("../core/overlay").Overlays; + + if ("overlay" == data._type) return new Overlay({ + key: unserialize(data.key), + shortcut: unserialize(data.shortcut) + }, { + dontStore: true + }); + + if ("key" == data._type) { + return keys.find(data.id); + + } + + if ("shortcut" == data._type) { + if (!data.disabled) { + var short_instance = new Shortcut({ + key: data.key, + keycode: data.keycode, + code: data.code, + modifiers: unserialize(data.modifiers) + }); + } else { + var short_instance = new Shortcut({ + disabled: true + }); + } + return short_instance; + } + + if ("modifiers" == data._type) { + return new Modifiers({ + modifiers: data.modifiers + }); + } + + return data; +} diff --git a/pool/shard010/JavaScript/0067449_quickWear.js b/pool/shard010/JavaScript/0067449_quickWear.js new file mode 100644 index 0000000000000000000000000000000000000000..6156be887782eb9a4c7d3d201f3a10135bc93c4f --- /dev/null +++ b/pool/shard010/JavaScript/0067449_quickWear.js @@ -0,0 +1,144 @@ +import './quickWear.css'; +import createDiv from '../../common/cElement/createDiv'; +import createQuickWear from './createQuickWear'; +import daLoadInventory from '../../_dataAccess/daLoadInventory'; +import equipItem from '../../ajax/equipItem'; +import eventHandler5 from '../../common/eventHandler5'; +import fshTabSet from './fshTabSet'; +import getArrayByClassName from '../../common/getArrayByClassName'; +import getValue from '../../system/getValue'; +import hasClass from '../../common/hasClass'; +import hasClasses from '../../common/hasClasses'; +import insertElement from '../../common/insertElement'; +import insertHtmlBeforeEnd from '../../common/insertHtmlBeforeEnd'; +import isArray from '../../common/isArray'; +import jConfirm from '../../common/jConfirm'; +import jQueryPresent from '../../common/jQueryPresent'; +import onclick from '../../common/onclick'; +import { pCC } from '../../support/layout'; +import partial from '../../common/partial'; +import selfIdIs from '../../common/selfIdIs'; +import sendEvent from '../../analytics/sendEvent'; +import setInnerHtml from '../../dom/setInnerHtml'; +import setText from '../../dom/setText'; +import setValue from '../../system/setValue'; +import showAHInvManager from './showAHInvManager'; +import { simpleCheckboxHtml } from '../../settings/simpleCheckbox'; +import { subscribeOnce } from '../../support/pubsub'; +import toggleForce from '../../common/toggleForce'; +import useItem from '../../ajax/useItem'; + +const defDisableQuickWearPrompts = 'disableQuickWearPrompts'; +let disableQuickWearPrompts; +let itemList; + +function actionResult(target, verb, data) { + if (data.r !== 0) { return; } + setInnerHtml(`${verb}`, target.parentNode); +} + +function doAction(target, fn, verb) { // jQuery.min + sendEvent('QuickWear', `doAction - ${verb}`); + setText('', target); + target.classList.remove('smallLink'); + target.classList.add('fshSpinner', 'fshSpin12'); + fn(target.dataset.itemid).then(partial(actionResult, target, verb)); +} + +function doUseItem(target) { + doAction(target, useItem, 'Used'); +} + +function useProfileInventoryItem(target) { + if (disableQuickWearPrompts) { + doUseItem(target); + } else { + jConfirm( + 'Use/Extract Item', + 'Are you sure you want to use/extract the item?', + partial(doUseItem, target), + ); + } +} + +function equipProfileInventoryItem(target) { + doAction(target, equipItem, 'Worn'); +} + +function processItems(folderId, thisFolder, o) { + const tr = o.dom; + if (folderId === '0') { + tr.classList.remove('fshHide'); + } else { + const force = folderId !== thisFolder.toString(); + toggleForce(tr, force); + } +} + +function processFolder(folderId, aFolder) { + const thisFolder = aFolder.id; + aFolder.items.forEach(partial(processItems, folderId, thisFolder)); +} + +function hideFolders(target) { + const folderId = target.dataset.folder; + itemList.r.inventories.forEach(partial(processFolder, folderId)); +} + +function togglePref() { + disableQuickWearPrompts = !disableQuickWearPrompts; + setValue(defDisableQuickWearPrompts, disableQuickWearPrompts); +} + +function evts5() { + return [ + [partial(hasClasses, ['smallLink', 'fshEq']), equipProfileInventoryItem], + [partial(hasClasses, ['smallLink', 'fshUse']), useProfileInventoryItem], + [partial(hasClass, 'fshFolder'), hideFolders], + [selfIdIs(defDisableQuickWearPrompts), togglePref], + ]; +} + +function goodData(appInv) { + return appInv && appInv.s && isArray(appInv.r?.inventories); +} + +function makePref(thisList) { + insertElement(thisList, createDiv({ + className: 'qwPref', + innerHTML: simpleCheckboxHtml(defDisableQuickWearPrompts), + })); +} + +function injectContent(thisFn, appInv, thisDiv) { + insertElement(thisDiv, thisFn(appInv)); +} + +function buildQuickWear(content, appInv) { + subscribeOnce('qwtab-header', makePref); + subscribeOnce('qwtab0', partial(injectContent, createQuickWear, appInv)); + subscribeOnce('qwtab1', partial(injectContent, showAHInvManager, appInv)); + fshTabSet(content, ['Quick Wear / Use / Extract
    Manager', + 'Inventory Manager Counter
    filtered by AH Quick Search'], 'qwtab'); + onclick(content, eventHandler5(evts5())); +} + +function showQuickWear(content, appInv) { + if (goodData(appInv)) { + itemList = appInv; + buildQuickWear(content, appInv); + } +} + +function hasJquery(injector) { // jQuery.min + const content = injector || pCC; + if (!content) { return; } + insertHtmlBeforeEnd(content, 'Getting item list from backpack...'); + daLoadInventory().then(partial(showQuickWear, content)); + disableQuickWearPrompts = getValue(defDisableQuickWearPrompts); + getArrayByClassName('ui-dialog-titlebar-close').forEach((e) => e.blur()); +} + +export default function quickWear(injector) { + if (jQueryPresent()) { hasJquery(injector); } +} diff --git a/pool/shard010/JavaScript/0067451_search.js b/pool/shard010/JavaScript/0067451_search.js new file mode 100644 index 0000000000000000000000000000000000000000..96a4dc2e917b470327e4a4e04ebe83521f5f23a8 --- /dev/null +++ b/pool/shard010/JavaScript/0067451_search.js @@ -0,0 +1,154 @@ +'use strict'; + +const request = require('./utils/request'); +const cheerio = require('cheerio'); + +function getClp (html) { + // Try to find clp from "next page" html elem. + let match = html.match(/\?clp=(.*?)">/); + // ... if we don't have it, we're probably on innerPage; + // try to parse it from search_collection_more_results_cluster instead + // var curl='https://play.google.com/store/apps/collection/search_collection_more_results_cluster?clp\x3dggENCgVwYW5kYRABGgIIAA%3D%3D:S:ANO1ljKV8KM'; + if (!match) match = html.match(/\?clp\\x3d(.*?)';/); + return match && match[1].replace(/%3D/g, '='); +} + +function getNextToken (html) { + // extract the token for the next page request + // for the record, I hate regexps + // const s = html.match(/\\42(GAE.+?)\\42/); + const s = html.match(/\\x22-p6(.*?):S:(.*?)\\x22/g); + if (!s) { + return undefined; + } + return s[0].replace(/\\\\u003d/g, '=').replace(/\\x22/g, ''); +} + +/* + * Extract navigation tokens for next pages, parse results and call + * `checkFinished` to repeat the process with next page if necessary. + */ +function processAndRecur (html, opts, savedApps, clp) { + const nextToken = getNextToken(html); + clp = clp || getClp(html); + + const $ = cheerio.load(html); + return opts + .getParseList(opts)($) + .then(newApps => savedApps.concat(newApps)) + .then(apps => checkFinished(opts, apps, nextToken, clp)); +} + +/* + * If already have requested results or there are no more pages, return current + * app list, otherwise request the ajax endpoint of the next page and process + * the results. + */ +function checkFinished (opts, savedApps, nextToken, clp) { + if (savedApps.length >= opts.num || !nextToken) { + return savedApps.slice(0, opts.num); + } + + const requestOptions = Object.assign( + { + url: + 'https://play.google.com/store/apps/collection/search_results_cluster_apps', + method: 'POST', + form: { + num: savedApps.length === 49 ? 0 : 48, // confirm if always 48 works + start: savedApps.length - 49, + pagTok: nextToken, + clp, + pagtt: 3, + hl: opts.lang, + gl: opts.country + }, + // we need an unescaped qs for the requests to work + qsStringifyOptions: { encode: false }, + followAllRedirects: true + }, + opts.requestOptions + ); + + return request(requestOptions, opts.throttle).then(html => + processAndRecur(html, opts, savedApps, clp) + ); +} + +/* + * Make the first search request as in the browser and call `checkfinished` to + * process the next pages. + */ +function initialRequest (opts) { + // sometimes the first result page is a cluster of subsections, + // need to skip to the full results page + function skipClusterPage (html) { + const match = html.match( + /href="\/store\/apps\/collection\/search_collection_more_results_cluster?(.*?)"/ + ); + if (match) { + const innerUrl = + 'https://play.google.com/' + (match[0] || '').split(/"/)[1]; + return request( + Object.assign( + { + url: innerUrl + }, + opts.requestOptions + ), + opts.throttle + ); + } + return html; + } + + const url = `https://play.google.com/store/search?c=apps&q=${opts.term}&hl=${ + opts.lang + }&gl=${opts.country}&price=${opts.price}`; + return request(Object.assign({ url }, opts.requestOptions), opts.throttle) + .then(skipClusterPage) + .then(html => processAndRecur(html, opts, [])); +} + +function getPriceGoogleValue (value) { + switch (value.toLowerCase()) { + case 'free': + return 1; + case 'paid': + return 2; + case 'all': + default: + return 0; + } +} + +function search (getParseList, opts) { + return new Promise(function (resolve, reject) { + if (!opts || !opts.term) { + throw Error('Search term missing'); + } + + if (opts.num && opts.num > 250) { + throw Error("The number of results can't exceed 250"); + } + + opts = { + term: encodeURIComponent(opts.term), + lang: opts.lang || 'en', + country: opts.country || 'us', + num: opts.num || 20, + fullDetail: opts.fullDetail, + price: opts.price ? getPriceGoogleValue(opts.price) : 0, + throttle: opts.throttle, + cache: opts.cache, + getParseList, + requestOptions: opts.requestOptions + }; + + initialRequest(opts) + .then(resolve) + .catch(reject); + }); +} + +module.exports = search; diff --git a/pool/shard010/JavaScript/0067454_UserRouter.js b/pool/shard010/JavaScript/0067454_UserRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..8c0eeb1876d64e07e7f217a5e0a4c7bc072b0745 --- /dev/null +++ b/pool/shard010/JavaScript/0067454_UserRouter.js @@ -0,0 +1,37 @@ +import Router from 'koa-66'; +import Qs from 'qs'; + +let log = require('logfilename')(__filename); + +export function UserHttpController(app, userApi){ + log.debug("UserHttpController"); + + let respond = app.utils.http.respond; + return { + async getAll(context) { + return respond( + context, + userApi, + userApi.getAll, + [Qs.parse(context.request.querystring)]); + }, + async getOne(context) { + let userId = context.params.id; + return respond(context, userApi, userApi.getOne, [userId]); + } + }; +} + +export default function UserRouter(app, userApi){ + let router = new Router(); + let userHttpController = UserHttpController(app, userApi); + + router.use(app.server.auth.isAuthenticated); + router.use(app.server.auth.isAuthorized); + + router.get('/', userHttpController.getAll); + router.get('/:id', userHttpController.getOne); + + app.server.baseRouter().mount("/users", router); + return router; +} diff --git a/pool/shard010/JavaScript/0067456_mocha-qa.js b/pool/shard010/JavaScript/0067456_mocha-qa.js new file mode 100644 index 0000000000000000000000000000000000000000..ebcc80d0f91f473835fe475525932a6a15f05b54 --- /dev/null +++ b/pool/shard010/JavaScript/0067456_mocha-qa.js @@ -0,0 +1,305 @@ +/* jshint node:true */ +/* global it, before, beforeEach, after, afterEach, window */ +'use strict'; + + +var _ = require('lodash'); + +// +// Argument handling has been derived from the way +// angular $injector is parsing function arguments: +// https://github.com/angular/angular.js/blob/master/src/auto/injector.js#L71 +// +var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; +var FN_ARG_SPLIT = /,/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + + +function callbackRequiresDone (fnc) { + var fncText = fnc.toString().replace(STRIP_COMMENTS, ''); + var matches = fncText.match(FN_ARGS); + + if (!matches) { + return false; + } + + var args = matches[1].replace(/ /g, '').split(FN_ARG_SPLIT); + + return _.contains(args, 'done'); +} + +function PromiseRejectedError (message) { + this.name = 'PromiseRejectedError'; + this.message = message; +} +PromiseRejectedError.prototype = Error.prototype; + +function PromiseResolvedError (message) { + this.name = 'PromiseResolvedError'; + this.message = message; +} +PromiseResolvedError.prototype = Error.prototype; + +function UnsupportedEnvironmentError (message) { + this.name = 'UnsupportedEnvironmentError'; + this.message = message; +} +UnsupportedEnvironmentError.prototype = Error.prototype; + +/** + * + * Attaches then / catch callbacks to a given promise. + * + * Will call done() on promise resolution and done(error) + * on rejection. + * + */ +function attachPromiseHandlers (fnc, done) { + + function resolve () { + done(); + } + + function reject (error) { + if (!error) { + error = new PromiseRejectedError('Test failed. Expected promise to be resolved (No error provided).'); + } + done(error); + } + + try { + var promise = fnc.apply(null, [done]); + if (promise && _.isFunction(promise.then) && _.isFunction(promise.catch)) { + return promise + .then(resolve) + .catch(reject); + } + else if (promise && _.isFunction(promise.then)) { + return promise + .then(resolve, reject); + } + + resolve(); + } + catch (error) { + reject(error); + } +} + +/** + * + * Attaches then / catch callbacks to a given promise. + * + * Will call done(error) on promise resolution and + * done() on rejection, thus resolving the test whenever + * the promise gets rejected. + * + */ +function attachErrorHandlers (fnc, done) { + function resolve () { + done(); + } + + function reject (error) { + if (!_.isError(error)) { + error = new PromiseResolvedError('Test failed. Expected promise to be rejected (No error provided).'); + } + + done(error); + } + + try { + var promise = fnc.apply(null, [done]); + if (promise && _.isFunction(promise.then) && _.isFunction(promise.catch)) { + return promise + .then(reject) + .catch(resolve); + } + else if (promise && _.isFunction(promise.then)) { + return promise + .then(reject, resolve); + } + reject(); + } + catch (error) { + resolve(); + } +} + +var doneFnc; + +var itFnc = it; +var beforeFnc = before; +var beforeEachFnc = beforeEach; +var afterFnc = after; +var afterEachFnc = afterEach; + +/** + * + * Promise wrapper around the mocha.js library. + * + * Adds a number of convenience methods for handling + * promises as results of tests. + * + */ +module.exports = { + + _test: function setDone(fnc, done) { + doneFnc = done; + + itFnc = fnc; + beforeFnc = fnc; + afterFnc = fnc; + beforeEachFnc = fnc; + afterEachFnc = fnc; + }, + + /** + * + * Promise variant of the default it-test. + * + * Handles a returned promise and + * calls done() to conclude the test in case of + * a positive resolution. + * + * Fails the the test if the promise gets rejected + * or any of the assertions within the test run fails. + * + */ + it: function promiseIt (description, fnc) { + if (callbackRequiresDone(fnc)) { + return itFnc(description, fnc); + } + + return itFnc(description, function (done) { + return attachPromiseHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Convenience variant for testing promise rejections. + * + * Handles a returned promise and + * calls done() to conclude the test in case of + * a negative resolution, i.e., the catch block + * of the promise handling chain is triggered. + * + * Fails the the test if the promise gets resolved. + * + */ + catchIt: function catchIt (description, fnc) { + return itFnc(description, function (done) { + return attachErrorHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Promise variant of the default before-hook. + * + * Handles a returned promise and + * calls done() to conclude the hook in case of + * a positive resolution. + * + * Fails the the hook if the promise gets rejected. + * + */ + before: function promiseBefore(fnc) { + if (callbackRequiresDone(fnc)) { + return beforeFnc(fnc); + } + + return beforeFnc(function (done) { + return attachPromiseHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Promise variant of the default beforeEach-hook. + * + * Handles a returned promise and + * calls done() to conclude the hook in case of + * a positive resolution. + * + * Fails the the hook if the promise gets rejected. + * + */ + beforeEach: function promiseBeforeEach(fnc) { + if (callbackRequiresDone(fnc)) { + return beforeEachFnc(fnc); + } + + return beforeEachFnc(function (done) { + return attachPromiseHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Promise variant of the default after-hook. + * + * Handles a returned promise and + * calls done() to conclude the hook in case of + * a positive resolution. + * + * Fails the the hook if the promise gets rejected. + * + */ + after: function promiseAfter(fnc) { + if (callbackRequiresDone(fnc)) { + return afterFnc(fnc); + } + + return afterFnc(function (done) { + return attachPromiseHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Promise variant of the default afterEach-hook. + * + * Handles a returned promise and + * calls done() to conclude the hook in case of + * a positive resolution. + * + * Fails the the hook if the promise gets rejected. + * + */ + afterEach: function promiseAfterEach(fnc) { + if (callbackRequiresDone(fnc)) { + return afterEachFnc(fnc); + } + + return afterEachFnc(function (done) { + return attachPromiseHandlers(fnc, doneFnc || done); + }); + }, + + /** + * + * Adds all promise hooks as global variables + * + */ + global: function makeGlobal () { + + var global = typeof window === 'undefined' ? GLOBAL : window; + + if (global) { + global.it = this.it; + global.catchIt = this.catchIt; + global.before = this.before; + global.beforeEach = this.beforeEach; + global.after = this.after; + global.afterEach = this.afterEach; + } + else { + throw new UnsupportedEnvironmentError('Could not recognize global process. It seems as if your current environment setup does not support globalizing.'); + } + + return this; + } + +}; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067459_check-setting.js b/pool/shard010/JavaScript/0067459_check-setting.js new file mode 100644 index 0000000000000000000000000000000000000000..64a81a378c88c02ef4b79755ff1911abe86efbae --- /dev/null +++ b/pool/shard010/JavaScript/0067459_check-setting.js @@ -0,0 +1,39 @@ +/** + * Created by kriz on 28/04/16. + */ + +/** + * Check meteor setting and exit if not exists + * @param path - path to the setting like 'email.from' + * @param defaultValue - default value, exit if option and default value not specified + * @param description - description to log if path not exists + * @returns {*} - setting value + */ +export default function checkSetting(path, defaultValue, description) { + const hasDefault = arguments.length === 3; + if (!hasDefault) { + description = defaultValue; + defaultValue = undefined; + } + + var settings = Meteor.settings; + + if (_.isEmpty(settings)) { + Log.error('Please include settings on meteor command line with --settings or METEOR_SETTINGS enveronment variable'); + process.exit(1); + } + + var args = path.split('.'); + var value = Meteor._get(settings, ...args); + if (value === undefined) { + if (hasDefault) { + value = defaultValue; + Log.warn(`${path} (${description}) is not set on settings, using default: ${value}`); + } else { + Log.error(new Error(`Please set ${path} on Meteor settings: ${description}`).stack); + process.exit(1); + } + } + + return value; +}; diff --git a/pool/shard010/JavaScript/0067460_bootstrap.js b/pool/shard010/JavaScript/0067460_bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..d960bfa960ade5d6ab92ccdfe869dbd2fb83d53d --- /dev/null +++ b/pool/shard010/JavaScript/0067460_bootstrap.js @@ -0,0 +1,76 @@ +(function() { + this.addElement = function(container, tagName, attrs) { + var fjs, k, tag, v; + if (attrs === null) { + attrs = {}; + } + if (attrs.id && container.getElementById(attrs.id)) { + return container.getElementById(attrs.id); + } + fjs = container.getElementsByTagName(tagName)[0]; + tag = container.createElement(tagName); + for (k in attrs) { + v = attrs[k]; + tag[k] = v; + } + fjs.parentNode.insertBefore(tag, fjs); + return tag; + }; + + + + + Storage.prototype.setObject = function(key, value) { + return this.setItem(key, JSON.stringify(value)); + }; + + Storage.prototype.getObject = function(key) { + var value; + if (!(value = this.getItem(key))) { + return; + } + return JSON.parse(value); + }; + + if (window.GLOBALS === null) { + window.GLOBALS = {}; + } + + window._RIPPLE = false; + + window._CORDOVA = !location.hostname; + + ionic.Platform.ready(function() { + window._RIPPLE = window.tinyHippos !== void 0; + window._CORDOVA = window.cordova !== void 0; + window.currLocation = { + coords: { + accuracy: 30, + altitude: null, + altitudeAccuracy: null, + heading: null, + latitude: 37.783692599999995, + longitude: -122.409235, + speed: null + } + }; + window.locality = { + latitude: 37.783692599999995, + longitude: 122.409235 + } + if(window.cordova && window.cordova.plugins.Keyboard) { + cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); + } + if(window.StatusBar) { + // Set the statusbar to use the default style, tweak this to + // remove the status bar on iOS or change it to use white instead of dark colors. + StatusBar.styleDefault(); + } + + return window.navigator.geolocation.getCurrentPosition(function(location) { + window.currLocation = location; + return console.log('Location from Phonegap', location); + }); + }); + +}).call(this); diff --git a/pool/shard010/JavaScript/0067463_boomSprite.js b/pool/shard010/JavaScript/0067463_boomSprite.js new file mode 100644 index 0000000000000000000000000000000000000000..88946e7e3665fedc32e9fecfc935ebe4062203e5 --- /dev/null +++ b/pool/shard010/JavaScript/0067463_boomSprite.js @@ -0,0 +1,27 @@ +var BoomSprite = cc.Sprite.extend({ + + ctor: function () { + + var frame = '#boom00.png'; + this._super(frame); + }, + play: function () { + var animFrames = []; + for (var i = 0; i < 19; i++) { + var str = 'boom' + formatStr(i, 2) + '.png'; + var frame = cc.spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + var animation = new cc.Animation(animFrames, 0.1); + + this.runAction(cc.sequence( + cc.animate(animation), + cc.callFunc(this.destroy, this) + )); + + }, + + destroy: function () { + g_GPTouchLayer.texBoomBatch.removeChild(this); + } +}); diff --git a/pool/shard010/JavaScript/0067467_lookup-test.js b/pool/shard010/JavaScript/0067467_lookup-test.js new file mode 100644 index 0000000000000000000000000000000000000000..ece5724c9304c4762a86c8f5b2e550be2e0d4bc3 --- /dev/null +++ b/pool/shard010/JavaScript/0067467_lookup-test.js @@ -0,0 +1,45 @@ +import Ember from 'ember'; +import { moduleFor, test } from 'ember-qunit'; +import FormTest from 'dummy/forms/form-test'; + +moduleFor('form:-lookup','Integration | Utils | Lookup', { + integration: true, + setup() { + var owner=Ember.getOwner(this); + owner.factoryFor('initializer:furnace-forms').class.initialize(owner); + } +}); + +test('Lookup',function(assert) { + var object,formClass,formInstance,method; + + object=Ember.Object.create(Ember.getOwner(this).ownerInjection()); + + method=Ember.getOwner(this).lookup('form:-lookup'); + + assert.ok(typeof method ==='function','Lookup registered'); + + assert.ok(formClass=method.call(object,'form-test'),'Get FormTest form'); + + Ember.run(()=>{ + formInstance=formClass.create(Ember.getOwner(this).ownerInjection()); + }); + + assert.ok(formInstance instanceof FormTest,'Got FormTest form'); + + var orgAssert=Ember.assert; + + var didAssert=false; + + Ember.assert=function() { + didAssert=true; + } + + formClass=method.call(object,'no-such-form-test'); + + assert.ok(!formClass,'No form'); + + assert.ok(didAssert,'Asserted'); + + Ember.assert=orgAssert; +}); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067473_thtp.test.js b/pool/shard010/JavaScript/0067473_thtp.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4063cfe826cee5de2520497b3f75f610f50b9f72 --- /dev/null +++ b/pool/shard010/JavaScript/0067473_thtp.test.js @@ -0,0 +1,220 @@ +var expect = require('chai').expect; +var concat = require('concat-stream'); +var httplib = require('http'); +var telehash = require('../../lib/mesh.js'); +var lob = require('lob-enc'); +var stream = require('../../ext/stream.js'); +var thtp = require('../../ext/thtp.js'); +var fs = require("fs") + +describe('telehash/thtp', function(){ + var idA = {"keys":{"1a":"akndnx5kbansip6xphxymwckpqkjj26fcm"},"secrets":{"1a":"ksxslm5mmtymnbph7nvxergb7oy3r35u"},"hashname":"5uegloufcyvnf34jausszmsabbfbcrg6fyxpcqzhddqxeefuapvq"}; + var idB = {"keys":{"1a":"apkoh54rkobkeela6d62hblhqd7grqd5dm"},"secrets":{"1a":"ljfm3ov42x2fl6gsg6bxiqgtstnxls7r"},"hashname":"fvifxlr3bsaan2jajo5qqn4au5ldy2ypiweazmuwjtgtg43tirkq"}; + + it('should export an extension', function(){ + expect(thtp).to.be.a('object'); + expect(thtp.name).to.be.equal('thtp'); + expect(thtp.mesh).to.be.a('function'); + }); + + it('should create a new extension', function(done){ + var mesh = {}; + thtp.mesh(mesh, function(err, ext){ + expect(err).to.not.exist; + expect(ext).to.be.a('object'); + expect(ext.link).to.be.a('function'); + expect(mesh.proxy).to.be.a('function'); + expect(mesh.request).to.be.a('function'); + var link = {}; + ext.link(link, function(err){ + expect(err).to.not.exist; + expect(link.proxy).to.be.a('function'); + expect(link.request).to.be.a('function'); + done(); + }) + }); + }); + + it('should receive an internal proxy request', function(done){ +// telehash.log({debug:console.log}); + var meshA = telehash.mesh({id:idA,extensions:{stream:stream,thtp:thtp}}); + expect(meshA).to.exist; + var meshB = telehash.mesh({id:idB,extensions:{stream:stream,thtp:thtp}}); + expect(meshB).to.exist; + + // pair them + meshA.mesh(meshB); + var linkAB = meshA.link(meshB.hashname); + + // dummy proxy + var proxy = {emit:function(on, req, res){ + expect(on).to.be.equal('request'); + expect(req.method).to.be.equal('POST'); + expect(req.url).to.be.equal('/'); + req.pipe(concat(function(body){ + expect(body).to.exist; + expect(body.toString()).to.be.equal('test'); + done(); + })); + }}; + meshB.proxy(proxy); + + // send request + linkAB.request({method:'post',path:'/'}, function(err){ + expect(err).to.not.exist; + }).end('test'); + + }); + + it('should proxy to a real server', function(done){ +// telehash.log({debug:console.log}); + var meshA = telehash.mesh({id:idA,extensions:{stream:stream,thtp:thtp}}); + expect(meshA).to.exist; + var meshB = telehash.mesh({id:idB,extensions:{stream:stream,thtp:thtp}}); + expect(meshB).to.exist; + + // pair them + meshA.mesh(meshB); + var linkAB = meshA.link(meshB.hashname); + + // dummy proxy + var proxy = httplib.createServer(function(req, res){ + expect(req.url).to.be.equal('/test'); + res.end('test'); + }); + meshB.proxy(proxy); + + // send request and gather response + linkAB.request('/test', function(err, res){ + expect(err).to.not.exist; + console.log("got res") + res.on('data',function(dat){ + console.log("got resdata", dat.toString()) + }) + res.pipe(concat(function(body){ + console.log("got res body") + expect(body.toString()).to.be.equal('test'); + done(); + })); + }); + }); + + it('should handle piping to response', function(done){ +// telehash.log({debug:console.log}); + var meshA = telehash.mesh({id:idA,extensions:{stream:stream,thtp:thtp}}); + expect(meshA).to.exist; + var meshB = telehash.mesh({id:idB,extensions:{stream:stream,thtp:thtp}}); + expect(meshB).to.exist; + + // pair them + meshA.mesh(meshB); + var linkAB = meshA.link(meshB.hashname); + var ch = 0 + // dummy proxy + var proxy = httplib.createServer(function(req, res){ + expect(req.url).to.be.equal('/test'); + var fss = + fs + .createReadStream(__dirname + "/thtp.test.js"); + fss.pipe(res) + fss.on('end',function(){ + res.end( ) + }) + }); + meshB.proxy(proxy); + + // send request and gather response + linkAB.request('/test', function(err, res){ + expect(err).to.not.exist; + res.pipe(concat(function(body){ + fs + .createReadStream(__dirname + "/thtp.test.js") + .pipe(concat(function(comp){ + expect(body.toString()).to.be.equal(comp.toString()) + done() + })); + })) + }); + }); + + it("should proxy to a url", function(done){ + var meshA = telehash.mesh({id:idA,extensions:{stream:stream,thtp:thtp}}); + expect(meshA).to.exist; + var meshB = telehash.mesh({id:idB,extensions:{stream:stream,thtp:thtp}}); + expect(meshB).to.exist; + + // pair them + meshA.mesh(meshB); + var linkAB = meshA.link(meshB.hashname); + + + // dummy proxy + var proxy = httplib.createServer(function(req, res){ + expect(req.url).to.be.equal('/test'); + res.end('test') + }) + proxy.listen(9876); + + meshB.proxy("http://localhost:9876"); + setTimeout(function(){ + + linkAB.request("http://localhost:9876/test", function(err, res){ + expect(err).to.not.exist; + res.pipe(concat(function(body){ + expect(body.toString()).to.be.equal('test'); + done(); + })); + }) + },100) + // send request and gather response + + }) + + it("should handle large response bodies", function(done){ + this.timeout(100000) + var meshA = telehash.mesh({id:idA,extensions:{stream:stream,thtp:thtp}}); + expect(meshA).to.exist; + var meshB = telehash.mesh({id:idB,extensions:{stream:stream,thtp:thtp}}); + expect(meshB).to.exist; + + // pair them + meshA.mesh(meshB); + var linkAB = meshA.link(meshB.hashname); + + var ch = 0; + + // dummy proxy + var proxy = httplib.createServer(function(req, res){ + expect(req.url).to.be.equal('/test'); + var fss = + fs + .createReadStream(__dirname + "/thtp.test.js") + .pipe(concat(function(body){ + ch = body.length + var fss = + fs + .createReadStream(__dirname + "/thtp.test.js"); + fss + .pipe(res) + fss.on('end',function(){ + res.end( ) + }) + })) + + }).listen(8765); + meshB.proxy("http://localhost:8765"); + + // send request and gather response + linkAB.request("http://localhost:8765/test", function(err, res){ + expect(err).to.not.exist; + res.pipe(concat(function(body){ + expect(body.length).to.be.equal(ch); + done(); + })); + }); + }) + + + + +}); diff --git a/pool/shard010/JavaScript/0067475_descAndImagesField.js b/pool/shard010/JavaScript/0067475_descAndImagesField.js new file mode 100644 index 0000000000000000000000000000000000000000..ec3510b3b7e4d3aead0a427e1a21ddb3f09cdc8a --- /dev/null +++ b/pool/shard010/JavaScript/0067475_descAndImagesField.js @@ -0,0 +1,22 @@ +import React, { PropTypes } from 'react'; +import RichContent from 'modules/common/richContent'; + +const descAndImagesField = ({ desc, images }) => ( +
    + { images.input.onChange(newImages); }} + onDescChange={(newDesc) => desc.input.onChange(newDesc)} + allowGallery + /> +
    + ); + +descAndImagesField.propTypes = { + desc: PropTypes.object.isRequired, + images: PropTypes.object.isRequired, +}; + +export default descAndImagesField; diff --git a/pool/shard010/JavaScript/0067479_contact_me.js b/pool/shard010/JavaScript/0067479_contact_me.js new file mode 100644 index 0000000000000000000000000000000000000000..7e3454e253c9fca4c9d0b5428d81efa5479c5bdd --- /dev/null +++ b/pool/shard010/JavaScript/0067479_contact_me.js @@ -0,0 +1,71 @@ +$(function () { + + $("input,textarea").jqBootstrapValidation({ + preventSubmit: true, + submitError: function ($form, event, errors) { + // additional error messages or events + }, + submitSuccess: function ($form, event) { + event.preventDefault(); // prevent default submit behaviour + // get values from FORM + var name = $("input#name").val(); + var email = $("input#email").val(); + var phone = $("input#phone").val(); + var message = $("textarea#message").val(); + var firstName = name; // For Success/Failure Message + // Check for white space in name for Success/Fail message + if (firstName.indexOf(' ') >= 0) { + firstName = name.split(' ').slice(0, -1).join(' '); + } + $.ajax({ + url: "././mail/contact_me.php", + type: "POST", + data: { + name: name, + phone: phone, + email: email, + message: message + }, + cache: false, + success: function () { + // Success message + $('#success').html("
    "); + var $alertSuccess = $('#success > .alert-success'); + $alertSuccess + .html(""); + $alertSuccess + .append("Your message has been sent. "); + $alertSuccess + .append('
    '); + + //clear all fields + $('#contactForm').trigger("reset"); + }, + error: function () { + // Fail message + $('#success').html("
    "); + $('#success > .alert-danger').html(""); + $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); + $('#success > .alert-danger').append('
    '); + //clear all fields + $('#contactForm').trigger("reset"); + } + }) + }, + filter: function () { + return $(this).is(":visible"); + } + }); + + $("a[data-toggle=\"tab\"]").click(function (e) { + e.preventDefault(); + $(this).tab("show"); + }); +}); + +/*When clicking on Full hide fail/success boxes */ +$('#name').focus(function () { + $('#success').html(''); +}); diff --git a/pool/shard010/JavaScript/0067480_storefront-service.js b/pool/shard010/JavaScript/0067480_storefront-service.js new file mode 100644 index 0000000000000000000000000000000000000000..e236fd4093d987ffe710d6a9e27314f0d9c5edb5 --- /dev/null +++ b/pool/shard010/JavaScript/0067480_storefront-service.js @@ -0,0 +1,94 @@ +var Promise = require('bluebird') +var models = require('../../app/models') + +function StorefrontService() { + this.listingService = require('./listing-service'); + this.included_listing_fields = this.listingService.included_listing_fields; +} + +function get_storefront_recommended() { + return new Promise((resolve, reject) => { + models.ozpcenter_listing + .findAll({include:this.included_listing_fields, limit: 10}) + .then(result => { return resolve(result) }); + } + ) +} + +function get_storefront_most_popular() { + return new Promise((resolve, reject) => { + models.ozpcenter_listing + .findAll({include:this.included_listing_fields, limit: 36}) + .then(result => { return resolve(result) }); + } + ) +} + +function get_storefront_featured(){ + return new Promise((resolve, reject) => { + models.ozpcenter_listing + .findAll({include:this.included_listing_fields, limit: 10}) + .then(result => { return resolve(result) }); + } + ) +} + +function get_storefront_recent(){ + return new Promise((resolve, reject) => { + models.ozpcenter_listing + .findAll({include:this.included_listing_fields, limit: 24}) + .then(result => { return resolve(result) }); + } + ) +} + +// GET /api/storefront +// Get a list of all system-wide Storefront entries +function listStorefront() { + return [{}]; +} + +// GET /api/storefront/{pk} +// Find an Storefront Entry by ID +function getStorefront(id) { + return { id: id }; +} + +// POST /api/storefront/ +// Add an Storefront +function postStorefront(storefrontObject) { + return { id: id }; +} + + +// PUT /api/storefront/{pk} +// Update an Storefront Entry by ID +function updateStorefront(id) { + return { id: id }; +} + + +// PATCH /api/storefront/{pk} +// Update (Partial) an Storefront Entry by ID +function partialUpdateStorefront(id) { + return { id: id }; +} + + +// DELETE /api/storefront/{pk} +// Delete an Storefront Entry by ID +function deleteUpdateStorefront(id) { + return { id: id }; +} + + +StorefrontService.prototype = { + listStorefront: listStorefront, + getStorefront: getStorefront, + postStorefront: postStorefront, + updateStorefront: updateStorefront, + partialUpdateStorefront: partialUpdateStorefront, + deleteUpdateStorefront: deleteUpdateStorefront +}; + +module.exports = StorefrontService; diff --git a/pool/shard010/JavaScript/0067481_button.js b/pool/shard010/JavaScript/0067481_button.js new file mode 100644 index 0000000000000000000000000000000000000000..73039a744affd86721aa61330e86b32e52b51cdf --- /dev/null +++ b/pool/shard010/JavaScript/0067481_button.js @@ -0,0 +1,144 @@ +/*! + * Angular Material Design + * https://github.com/angular/material + * @license MIT + * v1.0.0-rc3 + */ +(function( window, angular, undefined ){ +"use strict"; + +/** + * @ngdoc module + * @name material.components.button + * @description + * + * Button + */ +angular + .module('material.components.button', [ 'material.core' ]) + .directive('mdButton', MdButtonDirective); + +/** + * @ngdoc directive + * @name mdButton + * @module material.components.button + * + * @restrict E + * + * @description + * `` is a button directive with optional ink ripples (default enabled). + * + * If you supply a `href` or `ng-href` attribute, it will become an `` element. Otherwise, it will + * become a `'; + } + } + + function postLink(scope, element, attr) { + var node = element[0]; + $mdTheming(element); + $mdButtonInkRipple.attach(scope, element); + + var elementHasText = node.textContent.trim(); + if (!elementHasText) { + $mdAria.expect(element, 'aria-label'); + } + + // For anchor elements, we have to set tabindex manually when the + // element is disabled + if (isAnchor(attr) && angular.isDefined(attr.ngDisabled) ) { + scope.$watch(attr.ngDisabled, function(isDisabled) { + element.attr('tabindex', isDisabled ? -1 : 0); + }); + } + + // disabling click event when disabled is true + element.on('click', function(e){ + if (attr.disabled === true) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + }); + + // restrict focus styles to the keyboard + scope.mouseActive = false; + element.on('mousedown', function() { + scope.mouseActive = true; + $timeout(function(){ + scope.mouseActive = false; + }, 100); + }) + .on('focus', function() { + if (scope.mouseActive === false) { + element.addClass('md-focused'); + } + }) + .on('blur', function(ev) { + element.removeClass('md-focused'); + }); + } + +} +MdButtonDirective.$inject = ["$mdButtonInkRipple", "$mdTheming", "$mdAria", "$timeout"]; + +})(window, window.angular); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067483_app_runtime_custom_bindings.js b/pool/shard010/JavaScript/0067483_app_runtime_custom_bindings.js new file mode 100644 index 0000000000000000000000000000000000000000..267ba0931fad9d4f164ac54d70f0d4dd58e18767 --- /dev/null +++ b/pool/shard010/JavaScript/0067483_app_runtime_custom_bindings.js @@ -0,0 +1,74 @@ +// Copyright 2014 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 chrome.app.runtime API. + +var binding = require('binding').Binding.create('app.runtime'); + +var AppViewInternal = + require('binding').Binding.create('appViewInternal').generate(); +var eventBindings = require('event_bindings'); +var fileSystemHelpers = requireNative('file_system_natives'); +var GetIsolatedFileSystem = fileSystemHelpers.GetIsolatedFileSystem; +var appNatives = requireNative('app_runtime'); +var DeserializeString = appNatives.DeserializeString; +var SerializeToString = appNatives.SerializeToString; +var CreateBlob = appNatives.CreateBlob; +var entryIdManager = require('entryIdManager'); + +eventBindings.registerArgumentMassager('app.runtime.onEmbedRequested', + function(args, dispatch) { + var appEmbeddingRequest = args[0]; + var id = appEmbeddingRequest.guestInstanceId; + delete appEmbeddingRequest.guestInstanceId; + appEmbeddingRequest.allow = function(url) { + AppViewInternal.attachFrame(url, id); + }; + + appEmbeddingRequest.deny = function() { + AppViewInternal.denyRequest(id); + }; + + dispatch([appEmbeddingRequest]); +}); + +eventBindings.registerArgumentMassager('app.runtime.onLaunched', + function(args, dispatch) { + var launchData = args[0]; + if (launchData.items) { + // An onLaunched corresponding to file_handlers in the app's manifest. + var items = []; + var numItems = launchData.items.length; + var itemLoaded = function(err, item) { + if (err) { + console.error('Error getting fileEntry, code: ' + err.code); + } else { + $Array.push(items, item); + } + if (--numItems === 0) { + var data = { isKioskSession: launchData.isKioskSession }; + if (items.length !== 0) { + data.id = launchData.id; + data.items = items; + } + dispatch([data]); + } + }; + $Array.forEach(launchData.items, function(item) { + var fs = GetIsolatedFileSystem(item.fileSystemId); + fs.root.getFile(item.baseName, {}, function(fileEntry) { + entryIdManager.registerEntry(item.entryId, fileEntry); + itemLoaded(null, { entry: fileEntry, type: item.mimeType }); + }, function(fileError) { + itemLoaded(fileError); + }); + }); + } else { + // Default case. This currently covers an onLaunched corresponding to + // url_handlers in the app's manifest. + dispatch([launchData]); + } +}); + +exports.binding = binding.generate(); diff --git a/pool/shard010/JavaScript/0067486_ApproveAction.js b/pool/shard010/JavaScript/0067486_ApproveAction.js new file mode 100644 index 0000000000000000000000000000000000000000..58f7edcbd855627294cb933e8ef4b735c612aa10 --- /dev/null +++ b/pool/shard010/JavaScript/0067486_ApproveAction.js @@ -0,0 +1,72 @@ +/** + * @info : APPROVE ACION + * @author : coverguo + * @date : 2015-01-12 + */ + + +var log4js = require('log4js'), + logger = log4js.getLogger(), + ApproveService = require('../../service/ApproveService'), + LogService = require('../../service/LogService'), + isError = function (res , error){ + if(error){ + res.json({ret : 1 , msg : error}); + return true; + } + return false; + }; + + + + +var approveAction = { + + doApprove: function(params, req , res){ + var approve = params; + approve.createTime = new Date(); + approve.userName = params.user.loginName; + logger.debug('add_approve param :' + approve); + var approveService = new ApproveService(); + var logService = new LogService(); + approveService.add(params, function (err, items) { + if(isError(res, err)){ + return; + } + + + + if(params.applyStatus == 1 || params.applyStatus == 2){ + var pushProject = function (){ + logService.pushProject(function (err){ + if(err){ + logger.warn('push project error ' + err); + }else { + logger.info('push project success from approve '); + } + }); + } + pushProject(); + } + + res.json({ret:0, msg:"审核完成"}); + }); + }, + queryList : function (params,cb) { + var as = new ApproveService(); + as.query(params,cb); + }, + update:function(){ + var as = new ApproveService(); + as.update(params,cb); + }, + remove: function(params , cb){ + var as = new ApproveService(); + as.remove(params,cb); + + } + +}; + +module.exports = approveAction; + diff --git a/pool/shard010/JavaScript/0067487_connector.js b/pool/shard010/JavaScript/0067487_connector.js new file mode 100644 index 0000000000000000000000000000000000000000..fc08f88877ed063a561d5be93671996280b13cb6 --- /dev/null +++ b/pool/shard010/JavaScript/0067487_connector.js @@ -0,0 +1,186 @@ +// +// connector.js +// +// a socket initiator to a remote host +// +// history: +// 2013-09-14 adopted from frontier + + + +/* + + functions: + + addHandler(handlers) + connect(ip_port, onDone) + disconnect(onDone) + isConnectorReady() + send(packet_type, para, expected_response, onResponse) + dispose(onDone) + + config: { + name: 'string', // name of connector (used to get handlers) + onConnect: 'function', // optional connection handler + onDisconnect: 'function', // optional disconnection handler + eventHandler: 'object' // optional event handler (currently unused) + } +*/ + +exports.icConnector = function (config) { + + // check required parameters + if (config === undefined) + config = {}; + if (typeof config.onConnect !== 'function' && typeof config.onDisconnect !== 'function') + LOG.warn('no connection handlers specified in config, connect/disconnect event may not be notified', 'SR.Connector'); + + // + // local variables + // + + // a node.js connection (socket) object + var l_socket = undefined; + + // a connection object encapsulating the socket (used for send messages) + var l_conn = undefined; + + // use a provided, existing event handler set (if name is provided in config), or a new one + var l_eventHandler = SR.Handler.get(config.name); + + // init connection handler + // external app to call when establishing new connection + var l_connHandler = new SR.Conn.ConnHandler(config); + + // socket handler (handling new socket connections) + var l_socketHandler = new SR.Socket(l_connHandler, l_eventHandler); + + // + // public functions + // + + // store a handler for incoming events + // handlers should provide the following properties: + // 'handlers' + // 'checkers' + // + // or these methods: + // 'getFormatCheckers' + // 'getMessageHandlers' + // return # of handlers added + var l_addHandler = this.addHandler = function (handlers) { + + // perform loading of checkers & handlers + var num = l_eventHandler.load(handlers); + LOG.sys('adding ' + num + ' handlers', 'SR.Connector.addHandler'); + return num; + }; + + // start processing + // onDone: { + // err: 'object', // error object + // endpoint: 'string' // string of the IP/port of the host + // } + this.connect = function (ip_port, onDone) { + + // shutdown first if already exists + if (l_socket !== undefined) { + try { + l_socket.end(); + } catch (e) { + LOG.error('l_socket.end() exception-' + e, 'SR.Connector'); + } + } + + try { + LOG.warn('init a connection to: ' + ip_port.IP + ':' + ip_port.port + '...', 'SR.Connector'); + + l_socket = SR.net.createConnection(ip_port.port, ip_port.IP, function () { + + // this callback is called when 'connection' event is fired + l_socket.connected = true; + + // store remote address & port + // NOTE: because l_socket.remoteAddress doesn't exist + l_socket.host = ip_port.IP; + l_socket.port = ip_port.port; + + // setup socket's various properties & handling methods + // NOTE: after setup the socket will receive a connID + l_socketHandler.setup(l_socket); + + // record connection object for later use + // TODO: can we simply record & use l_conn instead of l_socket? + l_conn = SR.Conn.getConnObject(l_socket.connID); + + LOG.sys('outgoing connection: ' + l_socket.host + ':' + l_socket.port, 'SR.Connector'); + UTIL.safeCall(onDone, undefined, l_socket); + }); + + l_socket.on('error', function (e) { + LOG.error('socket connection error: ', 'SR.Connector'); + LOG.error(e); + UTIL.safeCall(onDone, e); + }); + } catch (e) { + LOG.error('connector exception-' + e, 'SR.Connector'); + l_disconnect(onDone, e); + } + }; + + //----------------------------------------- + // shutdown all connected sockets (clients) + // NOTE: this can also be called from outside via 'dispose' method + var l_disconnect = this.disconnect = function (onDone) { + + // shutdown connector, if exist + if (l_socket === undefined) + return UTIL.safeCall(onDone); + + try { + l_socket.on('close', function (err) { + if (err) + LOG.warn('connection to [' + l_socket.host + ':' + l_socket.port + '] was closed with error'); + // call callback when connection is fully closed + }); + + l_socket.end(); + l_socket = undefined; + } catch (e) { + LOG.error('l_socket.end() exception-'+e, 'SR.Connector'); + l_socket = undefined; + } + UTIL.safeCall(onDone); + }; + + // check whether connector has successfully connected to remote server + this.isConnectorReady = function () { + return (l_socket !== undefined && l_socket.connected); + }; + + // + // Connector methods + // + + // send something to remote host + this.send = function (packet_type, para, expected_response, onResponse) { + + // see if we need to register responder + // TODO: hide _cid attachment to EventManager + var cid = l_eventHandler.addResponder(expected_response, onResponse); + + // send out message + if (l_conn) + SR.EventManager.send(packet_type, para, [l_conn], cid); + else + LOG.error('no outgoing connection established, cannot send', 'SR.Connector'); + }; + + // end this connector + this.dispose = function (onDone) { + LOG.warn('dispose called...', 'SR.Connector'); + l_disconnect(onDone); + }; + +}; // end icConnector + diff --git a/pool/shard010/JavaScript/0067489_gulpfile.js b/pool/shard010/JavaScript/0067489_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..4c0d93cfb65b55b207374c17eea615d73e2bf74e --- /dev/null +++ b/pool/shard010/JavaScript/0067489_gulpfile.js @@ -0,0 +1,86 @@ +var gulp = require('gulp'), + connect = require('gulp-connect'), + livereload = require('gulp-livereload'), + uglify = require('gulp-uglify'), + rename = require('gulp-rename'), + autoprefixer = require('gulp-autoprefixer'), + cleanCSS = require('gulp-clean-css'); + +// server connect +gulp.task('connect', function () { + connect.server({ + root: '', + livereload: true + }); +}); + +// css +gulp.task('css', function () { + gulp.src('assets/css/*.css') + .pipe(connect.reload()) +}); + +// javascript +gulp.task('js', function () { + gulp.src('assets/js/*.js') + .pipe(connect.reload()) +}); + +// html +gulp.task('html', function () { + gulp.src('index.html') + .pipe(connect.reload()); +}); + +// images +gulp.task('image', function () { + gulp.src('images/*') + .pipe(connect.reload()); +}); + +// watch +gulp.task('watch', function () { + gulp.watch('assets/css/*.css', ['css']) + gulp.watch('index.html', ['html']) + gulp.watch('assets/js/*.js', ['js']) + gulp.watch('images/*', ['image']) +}); + +// default +gulp.task('default', ['connect', 'watch']); + +// <--- BUILD ---> + + +// js-build +gulp.task('js-build', function () { + return gulp.src('plastic-wares/assets/js/main.js') + .pipe(uglify()) + .pipe(rename('min.main.js')) + .pipe(gulp.dest('dist/js/')); +}); + +// css-build +gulp.task('css-build', function () { + return gulp.src('plastic-wares/assets/css/main.css') + .pipe(autoprefixer('last 30 versions')) + .pipe(cleanCSS({compatibility: 'ie8'})) + .pipe(rename('min.main.css')) + .pipe(gulp.dest('dist/css/')); +}); + +// img-build +gulp.task('img-build', function () { + return gulp.src('plastic-wares/images/*') + .pipe(gulp.dest('dist/img/')) +}); + +// html-build +gulp.task('html-build', function () { + return gulp.src('plastic-wares/*.html') + .pipe(gulp.dest('dist/')) +}); + + +// build +gulp.task('build', ['js-build', 'css-build', 'img-build', 'html-build']); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067490_03_regions.js b/pool/shard010/JavaScript/0067490_03_regions.js new file mode 100644 index 0000000000000000000000000000000000000000..8b716e84a996e9aee85af5501a61637219111e00 --- /dev/null +++ b/pool/shard010/JavaScript/0067490_03_regions.js @@ -0,0 +1,16 @@ +'use strict'; + +exports.up = function(knex) { + return knex.schema.createTable('regions', (table) => { + table.increments('id').primary(); + table.integer('country_id').references('countries.id'); + table.string('name').notNullable().defaultTo(''); + table.decimal('lat', 11, 7); + table.decimal('long', 11, 7); + table.timestamps(true, true); + }); +}; + +exports.down = function(knex) { + return knex.schema.dropTable('regions'); +} diff --git a/pool/shard010/JavaScript/0067491_ModuleScanner.js b/pool/shard010/JavaScript/0067491_ModuleScanner.js new file mode 100644 index 0000000000000000000000000000000000000000..00b55c7beb877efc73785e12e4c3895a86dc53b1 --- /dev/null +++ b/pool/shard010/JavaScript/0067491_ModuleScanner.js @@ -0,0 +1,151 @@ +var fs = require('fs'); + +var RouterCallbackWrapper = require(_path.lib + "/RouterCallbackWrapper.js"); + +var ModuleScanner = function() +{ + if(ModuleScanner.caller != ModuleScanner.getInstance) + throw Error('this ModuleScanner cannot be instanciated'); + + this.requestPaths = ""; + + this._log = { + debug : function(string){ + console.log(string); + } + }; +}; + +ModuleScanner.prototype.setLogger = function(log) +{ + this._log = log; +} + +ModuleScanner.prototype.scanRouter = function(dir) +{ + this._log.debug("================================================="); + this._log.debug("time : " + new Date().toString()); + this._log.debug("-------------------------------------------------"); + this._log.debug(" # Router Scaning #"); + this._log.debug(" -- " + dir); + + var files = fs.readdirSync(dir); + + for(var i=0; i { this.server.start(cb); }, + stopFn: (cb) => { this.server.stop(cb); } + }); + + this.events.emit("status", __("Starting Server")); + + this.server = new Server({ + logger: this.logger, + buildDir: this.buildDir, + events: this.events, + host: this.host, + port: this.port, + fs: this.fs, + openBrowser: this.webServerConfig.openBrowser, + protocol: this.webServerConfig.protocol, + certOptions : this.webServerConfig.certOptions + }); + + this.listenToCommands(); + this.registerConsoleCommands(); + this.init(); + } + + init() { + this.events.on('webserver:config:change', () => { + this.embark.config.webServerConfig = null; + this.embark.config.loadWebServerConfigFile(); + this.webServerConfig = this.embark.config.webServerConfig; + this.protocol = this.webServerConfig.protocol; + this.host = this.webServerConfig.host; + this.port = this.webServerConfig.port; + this.server.host = this.host; + this.server.port = this.port; + this.server.protocol = this.webServerConfig.protocol; + this.server.certOptions = this.webServerConfig.certOptions; + + this.testPort(() => { + this.events.request('processes:stop', 'webserver', _err => { + this.events.request('processes:launch', 'webserver', (_err, message, port) => { + this.logger.info(message); + this.port = port; + this.events.request('browser:open', () => {}); + }); + }); + }); + }); + + // findNextPort(this.port).then((newPort) => { + // this.server.port = newPort; + // this.events.request('processes:launch', 'webserver', (_err, message, port) => { + // this.logger.info(message); + // this.port = port; + // }); + // }); + this.setServiceCheck(); + + this.events.on('check:wentOffline:Webserver', () => { + this.logger.info(__("Webserver is offline")); + }); + this.events.on('check:backOnline:Webserver', () => { + this.logger.info(__("Webserver is online")); + }); + } + + setServiceCheck() { + if (!this.isServiceRegistered) { + this.isServiceRegistered = true; + this.events.request("services:register", 'Webserver', (cb) => { + let url = this.protocol + '://' + canonicalHost(this.host) + ':' + this.port; + checkIsAvailable(url, function (available) { + let devServer = __('Webserver') + ' (' + url + ')'; + let serverStatus = (available ? 'on' : 'off'); + return cb({name: devServer, status: serverStatus}); + }); + }); + } + } + + listenToCommands() { + this.events.setCommandHandler('placeholder:build', (cb) => this.buildPlaceholderPage(cb)); + this.events.setCommandHandler('browser:open', (cb) => this.openBrowser(cb)); + // TODO: remove this in v5 + this.events.setCommandHandler('webserver:start', (cb) => { + this.logger.warn(__("The event 'webserver:start' has been deprecated and will be removed in future versions.")); + this.events.request('processes:launch', 'webserver', cb); + }); + // TODO: remove this in v5 + this.events.setCommandHandler('webserver:stop', (cb) => { + this.logger.warn(__("The event 'webserver:stop' has been deprecated and will be removed in future versions.")); + this.events.request('processes:stop', 'webserver', cb); + }); + this.events.setCommandHandler('logs:webserver:enable', (cb) => this.server.enableLogging(cb)); + this.events.setCommandHandler('logs:webserver:disable', (cb) => this.server.disableLogging(cb)); + } + + // TODO: remove this in v5 + registerConsoleCommands() { + this.embark.registerConsoleCommand({ + usage: "webserver start/stop", + description: __("Start or stop the websever"), + matches: ['webserver start'], + process: (cmd, callback) => { + const message = __("The command 'webserver:start' has been deprecated in favor of 'service webserver on' and will be removed in future versions."); + this.logger.warn(message); // logs to Embark's console + this.events.request('processes:launch', 'webserver', (_err, msg) => { + callback(_err || msg); // logs to Cockpit's console + }); + } + }); + + // TODO: remove this in v5 + this.embark.registerConsoleCommand({ + matches: ['webserver stop'], + process: (cmd, callback) => { + const message = __("The command 'webserver:stop' has been deprecated in favor of 'service webserver off' and will be removed in future versions."); + this.logger.warn(message); // logs to Embark's console + this.events.request('processes:stop', 'webserver', (_err, msg) => { + callback(_err || msg); // logs to Cockpit's console + }); + } + }); + + this.embark.registerConsoleCommand({ + description: __("Open a browser window at the Dapp's url"), + matches: ['browser open'], + process: (cmd, callback) => { + this.events.request('browser:open', callback); + } + }); + + this.embark.registerConsoleCommand({ + matches: ['log webserver on'], + process: (cmd, callback) => { + this.events.request('logs:webserver:enable', callback); + } + }); + + this.embark.registerConsoleCommand({ + matches: ['log webserver off'], + process: (cmd, callback) => { + this.events.request('logs:webserver:disable', callback); + } + }); + } + + buildPlaceholderPage(cb) { + let html = Templates.embark_building_placeholder({buildingMsg: __('Embark is building, please wait...')}); + this.fs.mkdirpSync(this.buildDir); // create buildDir if it does not exist + this.fs.writeFile(joinPath(this.buildDir, 'index.html'), html, cb); + } + + openBrowser(cb) { + const _cb = () => { cb(); }; + return open( + `${this.protocol}://${canonicalHost(this.server.hostname)}:${this.server.port}` + ).then(_cb, _cb); // fail silently, e.g. in a docker container + } +} + +module.exports = WebServer; diff --git a/pool/shard010/JavaScript/0067493_gulpfile.js b/pool/shard010/JavaScript/0067493_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..87e23159f0a7ffd913e59235fe086b1343004d92 --- /dev/null +++ b/pool/shard010/JavaScript/0067493_gulpfile.js @@ -0,0 +1,43 @@ +var gulp = require('gulp'); +var jscs = require('gulp-jscs'); +var jshint = require('gulp-jshint'); +var nodemon = require('gulp-nodemon'); +var shell = require('gulp-shell'); + +var sourceFiles = [ + 'controllers/*.js', + 'definitions/*.js', + 'models/*.js', + 'tests/*.js' +]; + +gulp.task('clean', ['lint', 'syntax']); + +// Starts the develop mode of Totaljs and monitors for JS changes +// restarting when changes are detected. +gulp.task('develop', function() { + nodemon({script: 'debug.js', ext: 'js'}); +}); + +gulp.task('lint', function() { + return gulp.src(sourceFiles, {base: './'}) + .pipe(jshint()) + .pipe(jshint.reporter('jshint-stylish')) + .pipe(jshint.reporter('fail')); +}); + +// Starts TotalJS in release mode +gulp.task('release', shell.task('node release.js')); + +gulp.task('syntax', function() { + return gulp.src(sourceFiles, {base: './'}) + .pipe(jscs({fix: true})) + .pipe(jscs.reporter()) + .pipe(jscs.reporter('fail')) + .pipe(gulp.dest('./')); +}); + +// Starts TotalJS in test mode +gulp.task('test', ['clean'], shell.task('node test.js')); + + diff --git a/pool/shard010/JavaScript/0067497_parallelogram.js b/pool/shard010/JavaScript/0067497_parallelogram.js new file mode 100644 index 0000000000000000000000000000000000000000..4df42af994a43ee30ea807688721f8972620759b --- /dev/null +++ b/pool/shard010/JavaScript/0067497_parallelogram.js @@ -0,0 +1,127 @@ +/*globals require, module*/ +var vertices = require('./parallelogramVertexSet'); +var vectorOps = require('../utilities/vectorOperations'); + +/** + * @typedef {Object} ParallelogramVectors + * @property {Victor} AB Vector from A to B + * @property {Victor} AD Vector from A to D + */ + +/* @class Parallelogram with the following + vertices + A _______ B + | | + |_______| + D C + * @public @property {number} width + * @public @property {number} height + * @public @property {ParallelogramVertexSet} vertices The points in space of our rectangle + * @private @property {ParallelogramVertexSet} __previousStateVertices + */ +function Parallelogram() { + 'use strict'; + this.width = 0; + this.height = 0; + this.vertices = new vertices.ParallelogramVertexSet(); + this.__previousStateVertices = new vertices.ParallelogramVertexSet(); + this.__isReady = false; +} + +/** @function innerVectors + * Whatever vectors we need to do our algorithm to find a point inside + * the Parallelogram + * (0']; + var rootElement = this.description._root; + rootElement._pushRenderedHTML( + this, + true, // rendering form + this.document, + '', // empty name suffix + this._validationFailures[rootElement.name], + output + ); + output.push("
    "); + return output.join(""); + }, + + renderDocument: function() { + var output = []; + this.description._root._pushRenderedHTML( + this, + false, // rendering document + this.document, + '', // empty name suffix + undefined, // no validation failures + output + ); + return output.join(""); + }, + + // Request data-uname elements on output HTML in forms and documents. + setIncludeUniqueElementNamesInHTML: function(include) { + this._includeUniqueElementNamesInHTML = !!include; + }, + + documentWouldValidate: function() { + return this.description._root._wouldValidate(this, this.document); + }, + + update: function(submittedDataFn) { + this.valid = false; + this._validationFailures = {}; + this._rerenderData = {}; + this.description._root._updateDocument(this, this.document, '' /* empty name suffix */, function(name) { + // Wrap the given submittedDataFn so if it doesn't find a value for a given name, it returns the empty string. + // This makes sure everthing works with Internet Explorer. + return submittedDataFn(name) || ''; + }); + if(_.isEmpty(this._validationFailures)) { this.valid = true; } + }, + + choices: function(name, choices) { + var c = this._instanceChoices; + if(!c) { this._instanceChoices = c = {}; } + c[name] = choices; + }, + + customValidation: function(name, fn) { + var c = this._customValidationFns; + if(!c) { this._customValidationFns = c = {}; } + if(typeof(fn) !== 'function') { complain("must pass function to customValidation()"); } + c[name] = fn; + }, + + externalData: function(externalData) { + _.extend(this._externalData, externalData||{}); + }, + + getExternalData: function() { + return Object.create(this._externalData); + }, + + // Make a version of the document which contains displayable strings + makeView: function() { + var clonedDocument = deepCloneForJSON(this.document); + this.description._root._replaceValuesForView(this, clonedDocument); + return clonedDocument; + }, + + // ---------------------------------------------------------------------------------------- + // Functions for the other interfaces + _renderTemplate: function(templateName, view, output) { + // -------------------------- + // NOTE: This may be replaced entirely by the delegate if it implements the formPushRenderedTemplate() function. + // -------------------------- + // Fetch the template + var template; + // First try the delegate, so the caller can specify their own templates and override the default templates + var delegate = this.description.delegate; + if(delegate.formGetTemplate) { + template = delegate.formGetTemplate(templateName); + } + // Then try the standard templates + if(!template) { template = standardTemplates[templateName]; } + if(!template) { complain("template", "No such template: "+templateName); } + // Render template using chosen template renderer + _templateRendererImpl(template, view, output); + } +}); diff --git a/pool/shard010/JavaScript/0067503_AccordionLayout.js b/pool/shard010/JavaScript/0067503_AccordionLayout.js new file mode 100644 index 0000000000000000000000000000000000000000..9dc5f0b008d9cb4b42552a8d7d836b013da2ccde --- /dev/null +++ b/pool/shard010/JavaScript/0067503_AccordionLayout.js @@ -0,0 +1,202 @@ +/*! + * Ext JS Library 3.1.1 + * Copyright(c) 2006-2010 Ext JS, LLC + * licensing@extjs.com + * http://www.extjs.com/license + */ +/** + * @class Ext.layout.AccordionLayout + * @extends Ext.layout.FitLayout + *

    This is a layout that manages multiple Panels in an expandable accordion style such that only + * one Panel can be expanded at any given time. Each Panel has built-in support for expanding and collapsing.

    + *

    Note: Only Ext.Panels and all subclasses of Ext.Panel may be used in an accordion layout Container.

    + *

    This class is intended to be extended or created via the {@link Ext.Container#layout layout} + * configuration property. See {@link Ext.Container#layout} for additional details.

    + *

    Example usage:

    + *
    
    +var accordion = new Ext.Panel({
    +    title: 'Accordion Layout',
    +    layout:'accordion',
    +    defaults: {
    +        // applied to each contained panel
    +        bodyStyle: 'padding:15px'
    +    },
    +    layoutConfig: {
    +        // layout-specific configs go here
    +        titleCollapse: false,
    +        animate: true,
    +        activeOnTop: true
    +    },
    +    items: [{
    +        title: 'Panel 1',
    +        html: '<p>Panel content!</p>'
    +    },{
    +        title: 'Panel 2',
    +        html: '<p>Panel content!</p>'
    +    },{
    +        title: 'Panel 3',
    +        html: '<p>Panel content!</p>'
    +    }]
    +});
    +
    + */ +Ext.layout.AccordionLayout = Ext.extend(Ext.layout.FitLayout, { + /** + * @cfg {Boolean} fill + * True to adjust the active item's height to fill the available space in the container, false to use the + * item's current height, or auto height if not explicitly set (defaults to true). + */ + fill : true, + /** + * @cfg {Boolean} autoWidth + * True to set each contained item's width to 'auto', false to use the item's current width (defaults to true). + * Note that some components, in particular the {@link Ext.grid.GridPanel grid}, will not function properly within + * layouts if they have auto width, so in such cases this config should be set to false. + */ + autoWidth : true, + /** + * @cfg {Boolean} titleCollapse + * True to allow expand/collapse of each contained panel by clicking anywhere on the title bar, false to allow + * expand/collapse only when the toggle tool button is clicked (defaults to true). When set to false, + * {@link #hideCollapseTool} should be false also. + */ + titleCollapse : true, + /** + * @cfg {Boolean} hideCollapseTool + * True to hide the contained panels' collapse/expand toggle buttons, false to display them (defaults to false). + * When set to true, {@link #titleCollapse} should be true also. + */ + hideCollapseTool : false, + /** + * @cfg {Boolean} collapseFirst + * True to make sure the collapse/expand toggle button always renders first (to the left of) any other tools + * in the contained panels' title bars, false to render it last (defaults to false). + */ + collapseFirst : false, + /** + * @cfg {Boolean} animate + * True to slide the contained panels open and closed during expand/collapse using animation, false to open and + * close directly with no animation (defaults to false). Note: to defer to the specific config setting of each + * contained panel for this property, set this to undefined at the layout level. + */ + animate : false, + /** + * @cfg {Boolean} sequence + * Experimental. If animate is set to true, this will result in each animation running in sequence. + */ + sequence : false, + /** + * @cfg {Boolean} activeOnTop + * True to swap the position of each panel as it is expanded so that it becomes the first item in the container, + * false to keep the panels in the rendered order. This is NOT compatible with "animate:true" (defaults to false). + */ + activeOnTop : false, + + type: 'accordion', + + renderItem : function(c){ + if(this.animate === false){ + c.animCollapse = false; + } + c.collapsible = true; + if(this.autoWidth){ + c.autoWidth = true; + } + if(this.titleCollapse){ + c.titleCollapse = true; + } + if(this.hideCollapseTool){ + c.hideCollapseTool = true; + } + if(this.collapseFirst !== undefined){ + c.collapseFirst = this.collapseFirst; + } + if(!this.activeItem && !c.collapsed){ + this.setActiveItem(c, true); + }else if(this.activeItem && this.activeItem != c){ + c.collapsed = true; + } + Ext.layout.AccordionLayout.superclass.renderItem.apply(this, arguments); + c.header.addClass('x-accordion-hd'); + c.on('beforeexpand', this.beforeExpand, this); + }, + + onRemove: function(c){ + Ext.layout.AccordionLayout.superclass.onRemove.call(this, c); + if(c.rendered){ + c.header.removeClass('x-accordion-hd'); + } + c.un('beforeexpand', this.beforeExpand, this); + }, + + // private + beforeExpand : function(p, anim){ + var ai = this.activeItem; + if(ai){ + if(this.sequence){ + delete this.activeItem; + if (!ai.collapsed){ + ai.collapse({callback:function(){ + p.expand(anim || true); + }, scope: this}); + return false; + } + }else{ + ai.collapse(this.animate); + } + } + this.setActive(p); + if(this.activeOnTop){ + p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild); + } + // Items have been hidden an possibly rearranged, we need to get the container size again. + this.layout(); + }, + + // private + setItemSize : function(item, size){ + if(this.fill && item){ + var hh = 0, i, ct = this.getRenderedItems(this.container), len = ct.length, p; + // Add up all the header heights + for (i = 0; i < len; i++) { + if((p = ct[i]) != item){ + hh += p.header.getHeight(); + } + }; + // Subtract the header heights from the container size + size.height -= hh; + // Call setSize on the container to set the correct height. For Panels, deferedHeight + // will simply store this size for when the expansion is done. + item.setSize(size); + } + }, + + /** + * Sets the active (expanded) item in the layout. + * @param {String/Number} item The string component id or numeric index of the item to activate + */ + setActiveItem : function(item){ + this.setActive(item, true); + }, + + // private + setActive : function(item, expand){ + var ai = this.activeItem; + item = this.container.getComponent(item); + if(ai != item){ + if(item.rendered && item.collapsed && expand){ + item.expand(); + }else{ + if(ai){ + ai.fireEvent('deactivate', ai); + } + this.activeItem = item; + item.fireEvent('activate', item); + } + } + } +}); +Ext.Container.LAYOUTS.accordion = Ext.layout.AccordionLayout; + +//backwards compat +Ext.layout.Accordion = Ext.layout.AccordionLayout; \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067504_iosBeforePrepareHook.js b/pool/shard010/JavaScript/0067504_iosBeforePrepareHook.js new file mode 100644 index 0000000000000000000000000000000000000000..14d8fed5e2111df94b2fcd17b4d538865f0e1fb2 --- /dev/null +++ b/pool/shard010/JavaScript/0067504_iosBeforePrepareHook.js @@ -0,0 +1,78 @@ +/* +Hook executed before the 'prepare' stage. Only for iOS project. +It will check if project name has changed. If so - it will change the name of the .entitlements file to remove that file duplicates. +If file name has no changed - hook would not do anything. +*/ + +var path = require('path'), + fs = require('fs'), + ConfigXmlHelper = require('./lib/configXmlHelper.js'); + +module.exports = function(ctx) { + run(ctx); +}; + +/** + * Run the hook logic. + * + * @param {Object} ctx - cordova context object + */ +function run(ctx) { + var projectRoot = ctx.opts.projectRoot, + iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios'), + configXmlHelper = new ConfigXmlHelper(ctx), + oldProjectName = getOldProjectName(iosProjectFilePath), + newProjectName = configXmlHelper.getProjectName(); + + // if name has not changed - do nothing + if (oldProjectName.length > 0 && oldProjectName === newProjectName) { + return; + } + + console.log('Project name has changed. Renaming .entitlements file.'); + + // if it does - rename it + var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements'), + newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements'); + + try { + fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath); + } catch (err) { + console.warn('Failed to rename .entitlements file.'); + console.warn(err); + } +} + +// region Private API + +/** + * Get old name of the project. + * Name is detected by the name of the .xcodeproj file. + * + * @param {String} projectDir absolute path to ios project directory + * @return {String} old project name + */ +function getOldProjectName(projectDir) { + var files = [], + projectName = ''; + + try { + files = fs.readdirSync(projectDir); + } catch (err) { + return ''; + } + + // find file with .xcodeproj extension, use it as an old project name + files.some(function(fileName) { + if (path.extname(fileName) === '.xcodeproj') { + projectName = path.basename(fileName, '.xcodeproj'); + return true; + } + + return false; + }); + + return projectName; +} + +// endregion diff --git a/pool/shard010/JavaScript/0067505_sortable.inline.dragndrop.js b/pool/shard010/JavaScript/0067505_sortable.inline.dragndrop.js new file mode 100644 index 0000000000000000000000000000000000000000..c97db92c00c7b1cbac31a76e99783c32e1053369 --- /dev/null +++ b/pool/shard010/JavaScript/0067505_sortable.inline.dragndrop.js @@ -0,0 +1,57 @@ +const SortableListDrag = (function () { + 'use strict'; + + var widgets; + + var cls = { + draggable: 'admin-sort-row', + handle: 'admin-sort-drag', + inlines: 'admin-sort-draganddrop-inline' + }; + + domready(init); + + function init() { + widgets = document.querySelectorAll('.' + cls.inlines); + if (widgets.length) { + for (let i = 0; i < widgets.length; ++i) { + init_widget(widgets[i]); + } + } + }; + + function init_widget(widget) { + widget._field = widget.dataset['admin-sort-position-field']; + + }; + + function init_rows(widget) { + + }; + + function init_sortable(widget) { + widget._sortable = new Sortable(inl.$set[0], { + draggable: '.' + cls.draggable, + handle: '.' + cls.handle, + onUpdate: set_positions, + ghostClass: 'admin-sort-ghost', + chosenClass: 'admin-sort-chosen', + }); + }; + + function set_positions(e) { + + }; + + + // Utilities ------------------------------------------------------------- + + function domready(callback) { + if (document.readyState != 'loading') { + callback(); + } else { + document.addEventListener('DOMContentLoaded', callback); + } + }; + +})(); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067508_verticalStack.js b/pool/shard010/JavaScript/0067508_verticalStack.js new file mode 100644 index 0000000000000000000000000000000000000000..40dfd634f72fcbd065da71b596d8eeb9a3264d05 --- /dev/null +++ b/pool/shard010/JavaScript/0067508_verticalStack.js @@ -0,0 +1,40 @@ +/** + * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components + * @version v10.0.0 + * @link http://www.ag-grid.com/ + * @license MIT + */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var VerticalStack = (function () { + function VerticalStack() { + this.isLayoutPanel = true; + this.childPanels = []; + this.eGui = document.createElement('div'); + this.eGui.style.height = '100%'; + } + VerticalStack.prototype.addPanel = function (panel, height) { + var component; + if (panel.isLayoutPanel) { + this.childPanels.push(panel); + component = panel.getGui(); + } + else { + component = panel; + } + if (height) { + component.style.height = height; + } + this.eGui.appendChild(component); + }; + VerticalStack.prototype.getGui = function () { + return this.eGui; + }; + VerticalStack.prototype.doLayout = function () { + for (var i = 0; i < this.childPanels.length; i++) { + this.childPanels[i].doLayout(); + } + }; + return VerticalStack; +}()); +exports.VerticalStack = VerticalStack; diff --git a/pool/shard010/JavaScript/0067509_Client.js b/pool/shard010/JavaScript/0067509_Client.js new file mode 100644 index 0000000000000000000000000000000000000000..d15ab4cf1016f5495f02ecac55cd730688c48feb --- /dev/null +++ b/pool/shard010/JavaScript/0067509_Client.js @@ -0,0 +1,156 @@ + + +function NarrativeJobProxy(url, auth, auth_cb) { + + this.url = url; + var _url = url; + var deprecationWarningSent = false; + + function deprecationWarning() { + if (!deprecationWarningSent) { + deprecationWarningSent = true; + if (!window.console) return; + console.log( + "DEPRECATION WARNING: '*_async' method names will be removed", + "in a future version. Please use the identical methods without", + "the'_async' suffix."); + } + } + + if (typeof(_url) != "string" || _url.length == 0) { + _url = "http://localhost:7068"; + } + var _auth = auth ? auth : { 'token' : '', 'user_id' : ''}; + var _auth_cb = auth_cb; + + + this.ver = function (_callback, _errorCallback) { + return json_call_ajax("NarrativeJobProxy.ver", + [], 1, _callback, _errorCallback); +}; + + this.ver_async = function (_callback, _error_callback) { + deprecationWarning(); + return json_call_ajax("NarrativeJobProxy.ver", [], 1, _callback, _error_callback); + }; + + this.get_detailed_error = function (job, _callback, _errorCallback) { + return json_call_ajax("NarrativeJobProxy.get_detailed_error", + [job], 1, _callback, _errorCallback); +}; + + this.get_detailed_error_async = function (job, _callback, _error_callback) { + deprecationWarning(); + return json_call_ajax("NarrativeJobProxy.get_detailed_error", [job], 1, _callback, _error_callback); + }; + + this.get_job_info = function (job, _callback, _errorCallback) { + return json_call_ajax("NarrativeJobProxy.get_job_info", + [job], 1, _callback, _errorCallback); +}; + + this.get_job_info_async = function (job, _callback, _error_callback) { + deprecationWarning(); + return json_call_ajax("NarrativeJobProxy.get_job_info", [job], 1, _callback, _error_callback); + }; + + this.check_app_state = function (job_id, _callback, _errorCallback) { + return json_call_ajax("NarrativeJobProxy.check_app_state", + [job_id], 1, _callback, _errorCallback); +}; + + this.check_app_state_async = function (job_id, _callback, _error_callback) { + deprecationWarning(); + return json_call_ajax("NarrativeJobProxy.check_app_state", [job_id], 1, _callback, _error_callback); + }; + + this.get_job_logs = function (params, _callback, _errorCallback) { + return json_call_ajax("NarrativeJobProxy.get_job_logs", + [params], 1, _callback, _errorCallback); +}; + + this.get_job_logs_async = function (params, _callback, _error_callback) { + deprecationWarning(); + return json_call_ajax("NarrativeJobProxy.get_job_logs", [params], 1, _callback, _error_callback); + }; + + + /* + * JSON call using jQuery method. + */ + function json_call_ajax(method, params, numRets, callback, errorCallback) { + var deferred = $.Deferred(); + + if (typeof callback === 'function') { + deferred.done(callback); + } + + if (typeof errorCallback === 'function') { + deferred.fail(errorCallback); + } + + var rpc = { + params : params, + method : method, + version: "1.1", + id: String(Math.random()).slice(2), + }; + + var beforeSend = null; + var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb() + : (_auth.token ? _auth.token : null); + if (token != null) { + beforeSend = function (xhr) { + xhr.setRequestHeader("Authorization", token); + } + } + + var xhr = jQuery.ajax({ + url: _url, + dataType: "text", + type: 'POST', + processData: false, + data: JSON.stringify(rpc), + beforeSend: beforeSend, + success: function (data, status, xhr) { + var result; + try { + var resp = JSON.parse(data); + result = (numRets === 1 ? resp.result[0] : resp.result); + } catch (err) { + deferred.reject({ + status: 503, + error: err, + url: _url, + resp: data + }); + return; + } + deferred.resolve(result); + }, + error: function (xhr, textStatus, errorThrown) { + var error; + if (xhr.responseText) { + try { + var resp = JSON.parse(xhr.responseText); + error = resp.error; + } catch (err) { // Not JSON + error = "Unknown error - " + xhr.responseText; + } + } else { + error = "Unknown Error"; + } + deferred.reject({ + status: 500, + error: error + }); + } + }); + + var promise = deferred.promise(); + promise.xhr = xhr; + return promise; + } +} + + diff --git a/pool/shard010/JavaScript/0067510_javascript-gist.js b/pool/shard010/JavaScript/0067510_javascript-gist.js new file mode 100644 index 0000000000000000000000000000000000000000..d34021afa540c395cece0b6ae21da8653867fa7b --- /dev/null +++ b/pool/shard010/JavaScript/0067510_javascript-gist.js @@ -0,0 +1,15 @@ +angular.module('play', ['ionic']) + + .controller("HelloCtrl", function ($scope, $timeout) { + var names = ['Kosala', 'Hasith', 'Chatura', 'Jehan', 'Rashmika', 'Suranga', 'Ruzaik']; + + $scope.firstname = names[0]; + + $scope.refresh = function () { + $timeout(function () { + $scope.firstname = names[Math.floor(Math.random() * names.length)]; + $scope.$broadcast('scroll.refreshComplete'); + }, 1500); + }; + + }); \ No newline at end of file diff --git a/pool/shard010/JavaScript/0067512_Pages.js b/pool/shard010/JavaScript/0067512_Pages.js new file mode 100644 index 0000000000000000000000000000000000000000..1016a10139fd5bb9be1e8e2a3090ef90cb20936a --- /dev/null +++ b/pool/shard010/JavaScript/0067512_Pages.js @@ -0,0 +1,169 @@ +import React, { Component, PropTypes } from 'react'; +import { Link } from 'react-router'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; +import _ from 'underscore'; +import Breadcrumbs from '../../components/Breadcrumbs'; +import Button from '../../components/Button'; +import InputSearch from '../../components/form/InputSearch'; +import { fetchPages, deletePage } from '../../actions/pages'; +import { search } from '../../actions/utils'; +import { filterBySearchInput } from '../../reducers/pages'; +import { + getLeaveMessage, getDeleteMessage, getNotFoundMessage +} from '../../constants/lang'; +import { ADMIN_PREFIX } from '../../constants'; + +export class Pages extends Component { + + componentDidMount() { + const { fetchPages, params } = this.props; + fetchPages(params.splat); + } + + componentWillReceiveProps(nextProps) { + const { fetchPages } = nextProps; + if (this.props.params.splat !== nextProps.params.splat) { + fetchPages(nextProps.params.splat); + } + } + + handleClickDelete(filename) { + const { deletePage, params } = this.props; + const confirm = window.confirm(getDeleteMessage(filename)); + if (confirm) { + deletePage(params.splat, filename); + } + } + + renderTable() { + return ( +
    +
    + + + + + + + {this.renderRows()} +
    FilenameActions
    + + ); + } + + renderFileRow(file) { + const { name, path, api_url, http_url, title } = file; + const to = `${ADMIN_PREFIX}/pages/${path}`; + return ( + + + + +