", "verify the secret using the hash")
+ .options({
+ a: {
+ default: hashy.DEFAULT_ALGO,
+ describe: "algorithm to use for hashing",
+ },
+ h: {
+ alias: "help",
+ boolean: true,
+ describe: "display this help message",
+ },
+ v: {
+ alias: "version",
+ boolean: true,
+ describe: "display the version number",
+ },
+ c: {
+ alias: "cost",
+ describe: "cost for Bcrypt",
+ },
+ })
+ .parse(argv);
+
+ if (options.help) {
+ return yargs.help();
+ }
+
+ if (options.version) {
+ const pkg = require("./package");
+ return "Hashy version " + pkg.version;
+ }
+
+ if (options.cost) {
+ hashy.options.bcrypt.cost = +options.cost;
+ }
+
+ const args = options._;
+
+ if (args.length === 1) {
+ return hashy.hash(args[0], options.a).then(console.log);
+ }
+
+ if (args.length === 2) {
+ const password = args[0];
+ const hash = args[1];
+
+ return hashy.verify(password, hash).then(function(success) {
+ if (success) {
+ if (hashy.needsRehash(hash, options.a)) {
+ return "ok but password should be rehashed";
+ }
+
+ return "ok";
+ }
+
+ throw new Error("not ok");
+ });
+ }
+
+ throw new Error("incorrect number of arguments");
+}
+exports = module.exports = main;
+
+// ====================================================================
+
+if (!module.parent) {
+ require("exec-promise")(main);
+}
diff --git a/pool/shard000/JavaScript/0002396_Frustum.js b/pool/shard000/JavaScript/0002396_Frustum.js
new file mode 100644
index 0000000000000000000000000000000000000000..16a2c022435bfafe8a3fbf8f6ef235e51856b80d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002396_Frustum.js
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2014 United States Government as represented by the Administrator of the
+ * National Aeronautics and Space Administration. All Rights Reserved.
+ */
+/**
+ * @exports Frustum
+ * @version $Id: Frustum.js 2919 2015-03-22 20:46:59Z tgaskins $
+ */
+define([
+ '../error/ArgumentError',
+ '../geom/Matrix',
+ '../geom/Plane',
+ '../util/Logger'
+ ],
+ function (ArgumentError,
+ Matrix,
+ Plane,
+ Logger) {
+ "use strict";
+
+ /**
+ * Constructs a frustum.
+ * @alias Frustum
+ * @constructor
+ * @classdesc Represents a six-sided view frustum in Cartesian coordinates.
+ * @param {Plane} left The frustum's left plane.
+ * @param {Plane} right The frustum's right plane.
+ * @param {Plane} bottom The frustum's bottom plane.
+ * @param {Plane} top The frustum's top plane.
+ * @param {Plane} near The frustum's near plane.
+ * @param {Plane} far The frustum's far plane.
+ * @throws {ArgumentError} If any specified plane is null or undefined.
+ */
+ var Frustum = function (left, right, bottom, top, near, far) {
+ if (!left || !right || !bottom || !top || !near || !far) {
+ throw new ArgumentError(
+ Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "constructor", "missingPlane"));
+ }
+
+ // Internal. Intentionally not documented. See property accessors below for public interface.
+ this._left = left;
+ this._right = right;
+ this._bottom = bottom;
+ this._top = top;
+ this._near = near;
+ this._far = far;
+
+ // Internal. Intentionally not documented.
+ this._planes = [this._left, this._right, this._top, this._bottom, this._near, this._far];
+ };
+
+ // These accessors are defined in order to prevent changes that would make the properties inconsistent with the
+ // planes array.
+ Object.defineProperties(Frustum.prototype, {
+ /**
+ * This frustum's left plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ left: {
+ get: function() {
+ return this._left;
+ }
+ },
+ /**
+ * This frustum's right plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ right: {
+ get: function() {
+ return this._right;
+ }
+ },
+ /**
+ * This frustum's bottom plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ bottom: {
+ get: function() {
+ return this._bottom;
+ }
+ },
+ /**
+ * This frustum's top plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ top: {
+ get: function() {
+ return this._top;
+ }
+ },
+ /**
+ * This frustum's near plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ near: {
+ get: function() {
+ return this._near;
+ }
+ },
+ /**
+ * This frustum's far plane.
+ * @memberof Frustum.prototype
+ * @type {Plane}
+ * @readonly
+ */
+ far: {
+ get: function() {
+ return this._far;
+ }
+ }
+ });
+
+ /**
+ * Transforms this frustum by a specified matrix.
+ * @param {Matrix} matrix The matrix to apply to this frustum.
+ * @returns {Frustum} This frustum set to its original value multiplied by the specified matrix.
+ * @throws {ArgumentError} If the specified matrix is null or undefined.
+ */
+ Frustum.prototype.transformByMatrix = function (matrix) {
+ if (!matrix) {
+ throw new ArgumentError(
+ Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "transformByMatrix", "missingMatrix"));
+ }
+
+ this._left.transformByMatrix(matrix);
+ this._right.transformByMatrix(matrix);
+ this._bottom.transformByMatrix(matrix);
+ this._top.transformByMatrix(matrix);
+ this._near.transformByMatrix(matrix);
+ this._far.transformByMatrix(matrix);
+
+ return this;
+ };
+
+ /**
+ * Normalizes the plane vectors of the planes composing this frustum.
+ * @returns {Frustum} This frustum with its planes normalized.
+ */
+ Frustum.prototype.normalize = function () {
+ this._left.normalize();
+ this._right.normalize();
+ this._bottom.normalize();
+ this._top.normalize();
+ this._near.normalize();
+ this._far.normalize();
+
+ return this;
+ };
+
+ /**
+ * Returns a new frustum with each of its planes 1 meter from the center.
+ * @returns {Frustum} The new frustum.
+ */
+ Frustum.unitFrustum = function () {
+ return new Frustum(
+ new Plane(1, 0, 0, 1), // left
+ new Plane(-1, 0, 0, 1), // right
+ new Plane(0, 1, 1, 1), // bottom
+ new Plane(0, -1, 0, 1), // top
+ new Plane(0, 0, -1, 1), // near
+ new Plane(0, 0, 1, 1) // far
+ );
+ };
+
+ /**
+ * Extracts a frustum from a projection matrix.
+ *
+ * This method assumes that the specified matrix represents a projection matrix. If it does not represent a projection matrix
+ * the results are undefined.
+ *
+ * A projection matrix's view frustum is a Cartesian volume that contains everything visible in a scene displayed
+ * using that projection matrix.
+ *
+ * @param {Matrix} matrix The projection matrix to extract the frustum from.
+ * @return {Frustum} A new frustum containing the projection matrix's view frustum, in eye coordinates.
+ * @throws {ArgumentError} If the specified matrix is null or undefined.
+ */
+ Frustum.fromProjectionMatrix = function (matrix) {
+ if (!matrix) {
+ throw new ArgumentError(
+ Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "fromProjectionMatrix", "missingMatrix"));
+ }
+
+ var x, y, z, w, d, left, right, top, bottom, near, far;
+
+ // Left Plane = row 4 + row 1:
+ x = matrix[12] + matrix[0];
+ y = matrix[13] + matrix[1];
+ z = matrix[14] + matrix[2];
+ w = matrix[15] + matrix[3];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ left = new Plane(x / d, y / d, z / d, w / d);
+
+ // Right Plane = row 4 - row 1:
+ x = matrix[12] - matrix[0];
+ y = matrix[13] - matrix[1];
+ z = matrix[14] - matrix[2];
+ w = matrix[15] - matrix[3];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ right = new Plane(x / d, y / d, z / d, w / d);
+
+ // Bottom Plane = row 4 + row 2:
+ x = matrix[12] + matrix[4];
+ y = matrix[13] + matrix[5];
+ z = matrix[14] + matrix[6];
+ w = matrix[15] + matrix[7];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ bottom = new Plane(x / d, y / d, z / d, w / d);
+
+ // Top Plane = row 4 - row 2:
+ x = matrix[12] - matrix[4];
+ y = matrix[13] - matrix[5];
+ z = matrix[14] - matrix[6];
+ w = matrix[15] - matrix[7];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ top = new Plane(x / d, y / d, z / d, w / d);
+
+ // Near Plane = row 4 + row 3:
+ x = matrix[12] + matrix[8];
+ y = matrix[13] + matrix[9];
+ z = matrix[14] + matrix[10];
+ w = matrix[15] + matrix[11];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ near = new Plane(x / d, y / d, z / d, w / d);
+
+ // Far Plane = row 4 - row 3:
+ x = matrix[12] - matrix[8];
+ y = matrix[13] - matrix[9];
+ z = matrix[14] - matrix[10];
+ w = matrix[15] - matrix[11];
+ d = Math.sqrt(x * x + y * y + z * z); // for normalizing the coordinates
+ far = new Plane(x / d, y / d, z / d, w / d);
+
+ return new Frustum(left, right, bottom, top, near, far);
+ };
+
+ Frustum.prototype.containsPoint = function (point) {
+ if (!point) {
+ throw new ArgumentError(
+ Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "containsPoint", "missingPoint"));
+ }
+
+ // See if the point is entirely within the frustum. The dot product of the point with each plane's vector
+ // provides a distance to each plane. If this distance is less than 0, the point is clipped by that plane and
+ // neither intersects nor is contained by the space enclosed by this Frustum.
+
+ if (this._far.dot(point) <= 0)
+ return false;
+ if (this._left.dot(point) <= 0)
+ return false;
+ if (this._right.dot(point) <= 0)
+ return false;
+ if (this._top.dot(point) <= 0)
+ return false;
+ if (this._bottom.dot(point) <= 0)
+ return false;
+ if (this._near.dot(point) <= 0)
+ return false;
+
+ return true;
+ };
+
+ /**
+ * Determines whether a line segment intersects this frustum.
+ *
+ * @param {Vec3} pointA One end of the segment.
+ * @param {Vec3} pointB The other end of the segment.
+ *
+ * @return {boolean} true if the segment intersects or is contained in this frustum,
+ * otherwise false.
+ *
+ * @throws {ArgumentError} If either point is null or undefined.
+ */
+ Frustum.prototype.intersectsSegment = function (pointA, pointB) {
+ if (!pointA || !pointB) {
+ throw new ArgumentError(
+ Logger.logMessage(Logger.LEVEL_SEVERE, "Frustum", "containsPoint", "missingPoint"));
+ }
+
+ // First do a trivial accept test.
+ if (this.containsPoint(pointA) || this.containsPoint(pointB))
+ return true;
+
+ if (pointA.equals(pointB))
+ return false;
+
+ for (var i = 0, len = this._planes.length; i < len; i++) {
+
+ // See if both points are behind the plane and therefore not in the frustum.
+ if (this._planes[i].onSameSide(pointA, pointB) < 0)
+ return false;
+
+ // See if the segment intersects the plane.
+ if (this._planes[i].clip(pointA, pointB) != null)
+ return true;
+ }
+
+ return false; // segment does not intersect frustum
+ };
+
+ return Frustum;
+ });
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002403_index.js b/pool/shard000/JavaScript/0002403_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..30aa308104368d3be9e27bf3bf5e9bc021845301
--- /dev/null
+++ b/pool/shard000/JavaScript/0002403_index.js
@@ -0,0 +1,17 @@
+const debug = require('debug')('swagger-test:index')
+const express = require('express')
+const app = express()
+const apiRouter = require('./api/api_routes')
+
+const PORT = 3008
+
+app.use(apiRouter.v1.rest)
+
+app.set('port', PORT)
+app.listen(PORT, err => {
+ if (err) {
+ console.log(`app listen error: ${err.message}`)
+ } else {
+ console.log(`app listen on port : ${PORT}`)
+ }
+})
diff --git a/pool/shard000/JavaScript/0002404_addPoliciesPath.controller.js b/pool/shard000/JavaScript/0002404_addPoliciesPath.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..552d5bb1900994a76c08610fec04294a85c0ad7f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002404_addPoliciesPath.controller.js
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
+ *
+ * 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.
+ */
+class AddPoliciesPathController {
+ constructor($mdDialog, $scope, paths, apiKeyPolicy, rootCtrl) {
+ 'ngInject';
+ this.paths = paths;
+ this.scope = $scope;
+ this.mdDialog = $mdDialog;
+ this.apiKeyPolicy = apiKeyPolicy;
+ this.rootCtrl = rootCtrl;
+ this.newPath = {
+ path: "",
+ copyFromRootPath: true
+ };
+ }
+
+ hide() {
+ this.mdDialog.cancel();
+ }
+
+ add() {
+ if (this.newPath.copyFromRootPath) {
+ this.paths[this.newPath.path] = _.cloneDeep(this.paths["/"]);
+ _.forEach(this.paths[this.newPath.path], (policy) => {
+ delete policy.$$hashKey;
+ });
+ } else {
+ this.paths[this.newPath.path] = [this.apiKeyPolicy];
+ }
+ this.mdDialog.hide(this.paths);
+ }
+}
+
+export default AddPoliciesPathController;
diff --git a/pool/shard000/JavaScript/0002406_2d.composite.image.destination-in.worker.js b/pool/shard000/JavaScript/0002406_2d.composite.image.destination-in.worker.js
new file mode 100644
index 0000000000000000000000000000000000000000..58d40492a046e61240ede301eb4bbf5abb052ba9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002406_2d.composite.image.destination-in.worker.js
@@ -0,0 +1,40 @@
+// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
+// OffscreenCanvas test in a worker:2d.composite.image.destination-in
+// Description:
+// Note:
+
+importScripts("/resources/testharness.js");
+importScripts("/html/canvas/resources/canvas-tests.js");
+
+var t = async_test("");
+var t_pass = t.done.bind(t);
+var t_fail = t.step_func(function(reason) {
+ throw reason;
+});
+t.step(function() {
+
+var canvas = new OffscreenCanvas(100, 50);
+var ctx = canvas.getContext('2d');
+
+
+ctx.fillStyle = 'rgba(0, 255, 255, 0.5)';
+ctx.fillRect(0, 0, 100, 50);
+ctx.globalCompositeOperation = 'destination-in';
+var promise = new Promise(function(resolve, reject) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", '/images/yellow75.png');
+ xhr.responseType = 'blob';
+ xhr.send();
+ xhr.onload = function() {
+ resolve(xhr.response);
+ };
+});
+promise.then(function(response) {
+ createImageBitmap(response).then(bitmap => {
+ ctx.drawImage(bitmap, 0, 0);
+ _assertPixelApprox(canvas, 50,25, 0,255,255,96, "50,25", "0,255,255,96", 5);
+ }, t_fail);
+}).then(t_pass, t_fail);
+
+});
+done();
diff --git a/pool/shard000/JavaScript/0002407_flight-orientation.js b/pool/shard000/JavaScript/0002407_flight-orientation.js
new file mode 100644
index 0000000000000000000000000000000000000000..771c65a45b16bb2ca0e5c2256e7a013437a3a7c0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002407_flight-orientation.js
@@ -0,0 +1,58 @@
+define(function (require) {
+
+ 'use strict';
+
+ /**
+ * Module dependencies
+ */
+
+ var defineComponent = require('flight/lib/component');
+
+ /**
+ * Module exports
+ */
+
+ return defineComponent(flightOrientation);
+
+ /**
+ * Module function
+ */
+
+ function flightOrientation() {
+
+ this.orientation = function(e) {
+ this.trigger('orientation-update', this.orientationData(e.originalEvent));
+ };
+
+ this.orientationData = function(data) {
+ if (this.isMozilla) {
+ return {
+ tiltLR: data.x * 90,
+ tiltFB: data.y * -90,
+ direction: null, // Not provided by MozOrientation
+ verticalAcceleration: data.z
+ }
+ } else {
+ return {
+ tiltLR: data.gamma,
+ tiltFB: data.beta,
+ direction: data.alpha,
+ verticalAcceleration: null // Not provided by DeviceOrientation
+ }
+ }
+ };
+
+ this.after('initialize', function () {
+ var supported = window.DeviceOrientationEvent || window.OrientationEvent;
+ if (supported) {
+ this.isMozilla = window.OrientationEvent;
+
+ this.trigger('orientation-supported');
+ this.on(window, 'deviceorientation MozOrientation', this.orientation);
+ } else {
+ this.trigger('orientation-unsupported');
+ }
+ });
+ }
+
+});
diff --git a/pool/shard000/JavaScript/0002408_menuList.js b/pool/shard000/JavaScript/0002408_menuList.js
new file mode 100644
index 0000000000000000000000000000000000000000..a1fdf2be6ff4f21c1cf99417d5fad4ff397efb16
--- /dev/null
+++ b/pool/shard000/JavaScript/0002408_menuList.js
@@ -0,0 +1,152 @@
+/**
+ * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
+ * @version v5.0.1
+ * @link http://www.ag-grid.com/
+ * @license MIT
+ */
+var __extends = (this && this.__extends) || function (d, b) {
+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+};
+var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+};
+var __metadata = (this && this.__metadata) || function (k, v) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
+};
+var component_1 = require("./component");
+var context_1 = require("../context/context");
+var utils_1 = require("../utils");
+var popupService_1 = require("./popupService");
+var menuItemComponent_1 = require("./menuItemComponent");
+var MenuList = (function (_super) {
+ __extends(MenuList, _super);
+ function MenuList() {
+ _super.call(this, MenuList.TEMPLATE);
+ this.timerCount = 0;
+ }
+ MenuList.prototype.clearActiveItem = function () {
+ this.removeActiveItem();
+ this.removeOldChildPopup();
+ };
+ MenuList.prototype.addMenuItems = function (menuItems, defaultMenuItems) {
+ var _this = this;
+ if (utils_1.Utils.missing(menuItems)) {
+ return;
+ }
+ menuItems.forEach(function (listItem) {
+ if (listItem === 'separator') {
+ _this.addSeparator();
+ }
+ else {
+ var menuItem;
+ if (typeof listItem === 'string') {
+ menuItem = defaultMenuItems[listItem];
+ }
+ else {
+ menuItem = listItem;
+ }
+ _this.addItem(menuItem);
+ }
+ });
+ };
+ MenuList.prototype.addItem = function (params) {
+ var _this = this;
+ var cMenuItem = new menuItemComponent_1.MenuItemComponent(params);
+ this.context.wireBean(cMenuItem);
+ this.getGui().appendChild(cMenuItem.getGui());
+ cMenuItem.addEventListener(menuItemComponent_1.MenuItemComponent.EVENT_ITEM_SELECTED, function (event) {
+ if (params.childMenu) {
+ _this.showChildMenu(params, cMenuItem);
+ }
+ else {
+ _this.dispatchEvent(menuItemComponent_1.MenuItemComponent.EVENT_ITEM_SELECTED, event);
+ }
+ });
+ cMenuItem.addGuiEventListener('mouseenter', this.mouseEnterItem.bind(this, params, cMenuItem));
+ cMenuItem.addGuiEventListener('mouseleave', function () { return _this.timerCount++; });
+ if (params.childMenu) {
+ this.addDestroyFunc(function () { return params.childMenu.destroy(); });
+ }
+ };
+ MenuList.prototype.mouseEnterItem = function (menuItemParams, menuItem) {
+ if (menuItemParams.disabled) {
+ return;
+ }
+ if (this.activeMenuItemParams !== menuItemParams) {
+ this.removeOldChildPopup();
+ }
+ this.removeActiveItem();
+ this.activeMenuItemParams = menuItemParams;
+ this.activeMenuItem = menuItem;
+ utils_1.Utils.addCssClass(this.activeMenuItem.getGui(), 'ag-menu-option-active');
+ if (menuItemParams.childMenu) {
+ this.addHoverForChildPopup(menuItemParams, menuItem);
+ }
+ };
+ MenuList.prototype.removeActiveItem = function () {
+ if (this.activeMenuItem) {
+ utils_1.Utils.removeCssClass(this.activeMenuItem.getGui(), 'ag-menu-option-active');
+ this.activeMenuItem = null;
+ this.activeMenuItemParams = null;
+ }
+ };
+ MenuList.prototype.addHoverForChildPopup = function (menuItemParams, menuItem) {
+ var _this = this;
+ var timerCountCopy = this.timerCount;
+ setTimeout(function () {
+ var shouldShow = timerCountCopy === _this.timerCount;
+ var showingThisMenu = _this.showingChildMenu === menuItemParams.childMenu;
+ if (shouldShow && !showingThisMenu) {
+ _this.showChildMenu(menuItemParams, menuItem);
+ }
+ }, 500);
+ };
+ MenuList.prototype.showChildMenu = function (menuItemParams, menuItem) {
+ this.removeOldChildPopup();
+ var ePopup = utils_1.Utils.loadTemplate('
');
+ ePopup.appendChild(menuItemParams.childMenu.getGui());
+ this.childPopupRemoveFunc = this.popupService.addAsModalPopup(ePopup, true);
+ this.popupService.positionPopupForMenu({
+ eventSource: menuItem.getGui(),
+ ePopup: ePopup
+ });
+ this.showingChildMenu = menuItemParams.childMenu;
+ };
+ MenuList.prototype.addSeparator = function () {
+ this.getGui().appendChild(utils_1.Utils.loadTemplate(MenuList.SEPARATOR_TEMPLATE));
+ };
+ MenuList.prototype.removeOldChildPopup = function () {
+ if (this.childPopupRemoveFunc) {
+ this.showingChildMenu.clearActiveItem();
+ this.childPopupRemoveFunc();
+ this.childPopupRemoveFunc = null;
+ this.showingChildMenu = null;
+ }
+ };
+ MenuList.prototype.destroy = function () {
+ this.removeOldChildPopup();
+ _super.prototype.destroy.call(this);
+ };
+ MenuList.TEMPLATE = '';
+ MenuList.SEPARATOR_TEMPLATE = '';
+ __decorate([
+ context_1.Autowired('context'),
+ __metadata('design:type', context_1.Context)
+ ], MenuList.prototype, "context", void 0);
+ __decorate([
+ context_1.Autowired('popupService'),
+ __metadata('design:type', popupService_1.PopupService)
+ ], MenuList.prototype, "popupService", void 0);
+ return MenuList;
+})(component_1.Component);
+exports.MenuList = MenuList;
diff --git a/pool/shard000/JavaScript/0002411_DepthTextureAttachment.js b/pool/shard000/JavaScript/0002411_DepthTextureAttachment.js
new file mode 100644
index 0000000000000000000000000000000000000000..1b65688d2478caf725d613537382d50fd8aaf256
--- /dev/null
+++ b/pool/shard000/JavaScript/0002411_DepthTextureAttachment.js
@@ -0,0 +1,96 @@
+/**
+ * Copyright (c) 2015, Alexander Orzechowski.
+ *
+ * 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.
+ */
+
+
+/**
+ * Currently in beta stage. Changes can and will be made to the core mechanic
+ * making this not backwards compatible.
+ *
+ * Github: https://github.com/Need4Speed402/tessellator
+ */
+
+Tessellator.TextureModel.AttachmentDepthTexture = function (filter){
+ this.filter = filter;
+};
+
+Tessellator.copyProto(Tessellator.TextureModel.AttachmentDepthTexture, Tessellator.Texture);
+
+Tessellator.TextureModel.AttachmentDepthTexture.prototype.setup = function (texture){
+ if (this.tessellator && this.tessellator !== texture.tessellator){
+ throw "cannot mix resources between multiple contexts";
+ };
+
+ if (!texture.tessellator.extensions.get("WEBGL_depth_texture")){
+ throw "depth texture is not supported!";
+ };
+
+ if (!this.tessellator){
+ this.super(texture.tessellator);
+ };
+
+ this.width = texture.width;
+ this.height = texture.height;
+
+ if (!this.filter){
+ this.filter = Tessellator.getAppropriateTextureFilter(texture.width, texture.height);
+ };
+
+ if (texture.bindingAttachment.constructor === Tessellator.TextureDummy){
+ texture.bindingAttachment = this;
+ };
+
+ this.dispose();
+ this.clearTracking();
+ this.setReady();
+};
+
+Tessellator.TextureModel.AttachmentDepthTexture.prototype.configure = function (parent, target, track){
+ var gl = parent.tessellator.GL;
+
+ var tex;
+
+ if (!track || track.constructor === Tessellator.RenderMatrix){
+ if (track){
+ track.dirty();
+ };
+
+ track = null;
+
+
+ if (!this.isTracking(track)){
+ gl.bindTexture(gl.TEXTURE_2D, this.texture = gl.createTexture());
+ this.filter(parent.tessellator, this);
+ };
+
+ tex = this.texture;
+ };
+
+ if (!this.isTracking(track)){
+ if (!tex){
+ tex = track.glTexture;
+ };
+
+ gl.texImage2D(target, 0, gl.DEPTH_COMPONENT, this.width, this.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, target, tex, 0);
+
+ this.track(track);
+ };
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002417_singleselect.combo.test.js b/pool/shard000/JavaScript/0002417_singleselect.combo.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..b1faa526b9628008a6241f11fe5572832c7f87d9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002417_singleselect.combo.test.js
@@ -0,0 +1,121 @@
+/**
+ * @author windy
+ * @version 2.0
+ * Created by windy on 2020/1/16
+ */
+describe("single_select_combo", function () {
+
+ var items = BI.map(BI.makeArray(1000, null), function(idx, v) {
+ return {
+ text: idx,
+ value: idx,
+ title: idx
+ };
+ });
+
+ var itemSelectorGetter = function (array) {
+ return BI.map(array, function (idx, num) {
+ return ".bi-single-select-popup-view .bi-loader .bi-button-group .bi-single-select-item:nth-child(" + num + ")";
+ });
+ };
+
+ var searchItemSelectorGetter = function (array) {
+ return BI.map(array, function (idx, num) {
+ return ".bi-single-select-search-pane .bi-loader .bi-button-group .bi-single-select-item:nth-child(" + num + ")";
+ });
+ };
+
+ /**
+ * test_author_windy
+ **/
+ it("setValue", function () {
+ var widget = BI.Test.createWidget({
+ type: "bi.single_select_combo",
+ width: 220,
+ itemsCreator: function (op, callback) {
+ callback(items);
+ }
+ });
+ widget.setValue(1);
+ expect(widget.getValue()).to.equal(1);
+ widget.destroy();
+ });
+
+ /**
+ * test_author_windy
+ **/
+ it("getValue", function () {
+ var widget = BI.Test.createWidget({
+ type: "bi.single_select_combo",
+ width: 220,
+ itemsCreator: function (op, callback) {
+ callback(items);
+ },
+ value: 1
+ });
+ expect(widget.getValue()).to.equal(1);
+ widget.destroy();
+ });
+
+ /**
+ * test_author_windy
+ **/
+ it("点选选值", function (done) {
+ var widget = BI.Test.createWidget({
+ type: "bi.single_select_combo",
+ allowNoSelect: true,
+ width: 220,
+ itemsCreator: function (op, callback) {
+ callback({
+ items: items,
+ hasNext: false
+ });
+ }
+ });
+ widget.populate();
+ widget.element.find(".bi-single-select-trigger").click();
+ // 为什么要delay 300呢,因为按钮有debounce
+ BI.delay(function () {
+ // 点选1
+ BI.each(itemSelectorGetter([1]), function (idx, selector) {
+ widget.element.find(selector).click();
+ });
+ expect(widget.getValue()).to.equal(0);
+ widget.destroy();
+ done();
+ }, 300);
+ });
+
+ /**
+ * test_author_windy
+ **/
+ it("搜索选值", function (done) {
+ var widget = BI.Test.createWidget({
+ type: "bi.single_select_combo",
+ allowNoSelect: true,
+ width: 220,
+ itemsCreator: function (op, callback) {
+ callback({
+ items: items,
+ hasNext: false
+ });
+ }
+ });
+ BI.nextTick(function () {
+ widget.element.find(".bi-single-select-trigger .tip-text-style").click();
+ // 这边为啥要加呢,因为input的setValue中有nextTick
+ BI.nextTick(function () {
+ BI.Test.triggerKeyDown(widget.element.find(".bi-single-select-trigger .bi-input"), "2", 50, function () {
+ BI.nextTick(function () {
+ BI.each(searchItemSelectorGetter([3]), function (idx, selector) {
+ widget.element.find(selector).click();
+ });
+ expect(widget.getValue()).to.equal(2);
+ widget.destroy();
+ done();
+ });
+ });
+ });
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002418_Format-With-Placeholders.js b/pool/shard000/JavaScript/0002418_Format-With-Placeholders.js
new file mode 100644
index 0000000000000000000000000000000000000000..59e9608b4c3eb4e4407ae9827b889e4dd5433459
--- /dev/null
+++ b/pool/shard000/JavaScript/0002418_Format-With-Placeholders.js
@@ -0,0 +1,20 @@
+function solve(args) {
+ const options = JSON.parse(args[0], (key, value) =>
+ typeof value === 'number' ? +value : value);
+ const text = args[1];
+
+ String.prototype.format = function (obj) {
+ let text = this;
+ for (let prop in obj) {
+ let regex = new RegExp(`#{${prop}}`, 'g');
+ text = text.replace(regex, `${obj[prop]}`);
+ }
+
+ return text;
+ }
+ console.log(text.format(options));
+}
+solve([
+ '{ "name": "John", "age": 13 }',
+ "My name is #{name} and I am #{age}-years-old"
+]);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002421_observe-enumeration-spec.js b/pool/shard000/JavaScript/0002421_observe-enumeration-spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b45b9d5c9a86f6da38c9ff6dc1f3f8fa04f0ae4
--- /dev/null
+++ b/pool/shard000/JavaScript/0002421_observe-enumeration-spec.js
@@ -0,0 +1,56 @@
+
+var bind = require("../bind");
+
+describe("observe enumeration", function () {
+
+ it("simple pipeline", function () {
+ var input = ['a', 'b', 'c'];
+ var output = [];
+ var cancel = bind(output, "rangeContent()", {
+ "<-": "enumerate()",
+ source: input
+ });
+ var a = output[0];
+ var b = output[1];
+ var c = output[2];
+ expect(output).toEqual([
+ [0, 'a'],
+ [1, 'b'],
+ [2, 'c']
+ ]);
+ input.unshift('z');
+ expect(output).toEqual([
+ [0, 'z'],
+ [1, 'a'],
+ [2, 'b'],
+ [3, 'c']
+ ]);
+ expect(a[0]).toEqual(1);
+ });
+
+ it("complex pipeline", function () {
+ var input = ['b', 'c', 'd', 'e'];
+ var output = [];
+ var cancel = bind(output, "rangeContent()", {
+ "<-": "enumerate().map{!(.0 % 2)}",
+ source: input
+ });
+ expect(output).toEqual([true, false, true, false]);
+ input.unshift('a');
+ expect(output).toEqual([true, false, true, false, true]);
+ });
+
+ it("values at even indexes", function () {
+ var input = ['b', 'c', 'd', 'e'];
+ var output = [];
+ var cancel = bind(output, "rangeContent()", {
+ "<-": "enumerate().filter{!(.0 % 2)}.map{.1}",
+ source: input
+ });
+ expect(output).toEqual(['b', 'd']);
+ input.unshift('a');
+ expect(output).toEqual(['a', 'c', 'e']);
+ });
+
+});
+
diff --git a/pool/shard000/JavaScript/0002422_dataService.js b/pool/shard000/JavaScript/0002422_dataService.js
new file mode 100644
index 0000000000000000000000000000000000000000..04de453b0178472557545c29e2f4e78c6f0c49e8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002422_dataService.js
@@ -0,0 +1,55 @@
+/**
+ * Created by Ákos on 2014.12.11..
+ */
+
+/*jshint loopfunc: true */
+/*global BASE_URL:true,_:true */
+
+
+(function () {
+ "use strict";
+
+ if (BASE_URL === undefined) {
+ BASE_URL = '/';
+ }
+
+ angular.module('gate')
+ .factory('dataService', dataService);
+
+ function dataService($http, $q) {
+
+ var _gateEvents = [];
+ var _lastGateEvent = null;
+
+ var _getGateEvents = function () {
+ return _gateEvents;
+ };
+
+
+ var _addGateEvent = function (gate, barcode) {
+ var deferred = $q.defer();
+ $http({
+ url : BASE_URL + '/gate/gate-event',
+ method: "GET",
+ params: {gate: gate, barcode: barcode}
+ })
+ .then(function (result) {
+ _lastGateEvent = result.data;
+ _gateEvents.unshift(_lastGateEvent);
+ deferred.resolve();
+ }, function (e) {
+ var error=$('.alert',e.data).html().trim();
+ _gateEvents.unshift({error:error});
+ deferred.reject();
+ });
+ return deferred.promise;
+ };
+
+
+ return {
+ getGateEvents: _getGateEvents,
+ addGateEvent : _addGateEvent
+ };
+ }
+
+})();
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002424_cart.js b/pool/shard000/JavaScript/0002424_cart.js
new file mode 100644
index 0000000000000000000000000000000000000000..2ea3ff82cd70cc9105b6a1ca3de4ed5d1906ff7c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002424_cart.js
@@ -0,0 +1,68 @@
+import Vue from 'vue';
+import template from './cart.html';
+import './cart.scss';
+
+import { postsResource } from 'src/util/resources';
+
+export default Vue.extend({
+ template,
+
+ data() {
+ return {
+
+ posts: [],
+
+ result: []
+ }
+ },
+ props: ['items'],
+
+ created(){
+ this.fetchPosts();
+ },
+
+ computed: {
+ total() {
+ var total = 0;
+ this.result.forEach(function(item, i) {
+ total += item.price*item.count;
+ });
+ return total.toFixed(2);
+ }
+ },
+
+ methods: {
+ fetchPosts(){
+ return postsResource.get('/')
+ .then((response) => {
+ this.posts = response.data;
+
+ this.posts.forEach(function(item, i) {
+ item.count = 0;
+ });
+
+ var result = [];
+ var array = this.posts.slice();
+ var items = this.items.slice();
+
+ array.forEach(function(item, i) {
+ items.forEach(function(item2, j) {
+ if(item.id == item2.id) {
+ result.push(item);
+ result[result.length-1].count = item2.count;
+ }
+ });
+ });
+
+ this.result = result;
+ console.log(this.result);
+
+ })
+ .catch((errorResponse) => {
+ // Handle error...
+ console.log('API responded with:', errorResponse);
+ });
+ }
+ }
+
+});
diff --git a/pool/shard000/JavaScript/0002426_sechash.js b/pool/shard000/JavaScript/0002426_sechash.js
new file mode 100644
index 0000000000000000000000000000000000000000..82e056786ebd242938195750244480e4e7a88849
--- /dev/null
+++ b/pool/shard000/JavaScript/0002426_sechash.js
@@ -0,0 +1,148 @@
+'use strict';
+
+/**
+ * sechash
+ *
+ * Secure password hashing using salt and keystretching
+ *
+ * @author James Brumond
+ * @version 0.2.0
+ * @copyright Copyright 2012 James Brumond
+ * @license Dual licensed under MIT and GPL
+ */
+
+var crypto = require('crypto');
+var Promise = require('any-promise');
+
+var defaultOptions = {
+ algorithm: 'sha1',
+ iterations: 2000,
+ includeMeta: true,
+ intervalLength: 500,
+ salt: function() {
+ return hash(this.algorithm, String(Math.random())).substring(0, 6);
+ }
+};
+
+// ----------------------------------------------------------------------------
+// Public functions
+
+exports.basicHash = function(alg, str) {
+ return hash(alg, str);
+};
+
+exports.testBasicHash = function(alg, str, testHash) {
+ return (hash(alg, str) === testHash);
+};
+
+exports.strongHashSync = function(str, opts) {
+ opts = getOptions(opts);
+ for (var i = 0; i < opts.iterations; i++) {
+ str = hash(opts.algorithm, str + opts.salt);
+ }
+ return opts.meta + str;
+};
+
+exports.strongHash = function(str, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = null;
+ }
+ opts = getOptions(opts);
+
+ var promise = new Promise(function(resolve, reject) {
+ asyncFor(opts.iterations, opts.intervalLength,
+ function() {
+ str = hash(opts.algorithm, str + opts.salt);
+ },
+ function() {
+ resolve(opts.meta + str)
+ }
+ );
+ });
+
+ return asCallback(promise, callback);
+};
+
+exports.testHashSync = function(str, hash, opts) {
+ opts = getOptions(opts, hash);
+ return (exports.strongHashSync(str, opts) === hash);
+};
+
+exports.testHash = function(str, hash, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = null;
+ }
+ opts = getOptions(opts, hash);
+
+ var promise = new Promise(function(resolve, reject) {
+ exports.strongHash(str, opts, function(err, result) {
+ if (err) return reject(err);
+ resolve(hash === result);
+ });
+ });
+
+ return asCallback(promise, callback);
+};
+
+
+
+// ------------------------------------------------------------------
+// Helpers
+function asCallback(promise, callback) {
+ if (typeof callback !== 'function') return promise;
+
+ return promise.then(function(result) {
+ callback(null, result);
+ }, function(reason) {
+ callback(reason);
+ });
+}
+
+function hash(alg, str) {
+ var hashsum = crypto.createHash(alg);
+ hashsum.update(str);
+ return hashsum.digest('hex');
+}
+
+function getOptions(opts, hash) {
+ var result = { };
+ Object.keys(defaultOptions).forEach(function(key) {
+ result[key] = defaultOptions[key];
+ });
+ Object.keys(opts || { }).forEach(function(key) {
+ result[key] = opts[key];
+ });
+ if (typeof result.salt === 'function') {
+ result.salt = result.salt();
+ }
+ if (result.includeMeta) {
+ result.meta = result.salt + ':' + result.algorithm + ':' + result.iterations + ':'
+ } else {
+ result.meta = '';
+ }
+ if (hash && hash.indexOf(':') >= 0) {
+ hash = hash.split(':');
+ result.salt = hash[0];
+ result.algorithm = hash[1];
+ result.iterations = Number(hash[2]);
+ }
+ return result;
+}
+
+function asyncFor(count, intervalLength, func, callback) {
+ function runLoop() {
+ for (var i = 0; (i < intervalLength && count); i++, count--) {
+ func(count, i);
+ }
+ if (count) {
+ process.nextTick(runLoop);
+ } else {
+ callback();
+ }
+ }
+ runLoop();
+}
+
+/* End of file sechash.js */
diff --git a/pool/shard000/JavaScript/0002435_index.js b/pool/shard000/JavaScript/0002435_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..be56396bce704bdeed220361f1ee5614580d43f8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002435_index.js
@@ -0,0 +1,241 @@
+'use strict';
+/*global require, module, __plugin, __dirname, echo, persist, isOp, events, Packages, command, global */
+var utils = require('utils'),
+ watcher = require('watcher'),
+ autoload = require('plugin').autoload,
+ foreach = utils.foreach,
+ watchDir = watcher.watchDir,
+ unwatchDir = watcher.unwatchDir,
+ playersDir = __dirname + '/../../players/',
+ serverAddress = utils.serverAddress();
+
+/************************************************************************
+## Classroom Plugin
+
+The `classroom` object contains a couple of utility functions for use
+in a classroom setting. The goal of these functions is to make it
+easier for tutors to facilitate ScriptCraft for use by students in a
+classroom environment. Although granting ScriptCraft access to
+students on a shared server is potentially risky (Students can
+potentially abuse it), it is slighlty less risky than granting
+operator privileges to each student. (Enterprising students will
+quickly realise how to grant themselves and others operator privileges
+once they have access to ScriptCraft).
+
+The goal of this module is not so much to enforce restrictions
+(security or otherwise) but to make it easier for tutors to setup a
+shared server so students can learn Javascript. When scripting is
+turned on, every player who joins the server will have a dedicated
+directory into which they can save scripts. All scripts in such
+directories are automatically watched and loaded into a global
+variable named after the player.
+
+So for example, if player 'walterh' joins the server, a `walterh`
+global variable is created. If a file `greet.js` with the following
+content is dropped into the `scriptcraft/players/walterh`
+directory...
+
+```javascript
+exports.hi = function( player ){
+ echo( player, 'Hi ' + player.name);
+};
+```
+
+... then it can be invoked like this: `/js walterh.hi( self )` . This
+lets every player/student create their own functions without having
+naming collisions.
+
+It's strongly recommended that the
+`scriptcraft/players/` directory is shared so that
+others can connect to it and drop .js files into their student
+directories. On Ubuntu, select the folder in Nautilus (the default
+file browser) then right-click and choose *Sharing Options*, check the
+*Share this folder* checkbox and the *Allow others to create and
+delete files* and *Guest access* checkboxes. Click *Create Share*
+button to close the sharing options dialog. Students can then access
+the shared folder as follows...
+
+ * Windows: Open Explorer, Go to \\{serverAddress}\players\
+ * Macintosh: Open Finder, Go to smb://{serverAddress}/players/
+ * Linux: Open Nautilus, Go to smb://{serverAddress}/players/
+
+... where {serverAddress} is the ip address of the server (this is
+displayed to whoever invokes the classroom.allowScripting() function.)
+
+### jsp classroom command
+The `jsp classroom` command makes it easy for tutors to turn on or off
+classroom mode. This command can only be used by server operators. To
+turn on classroom mode (enable scripting for all players):
+
+ jsp classroom on
+
+To turn off classroom mode (disable scripting for all players):
+
+ jsp classroom off
+
+The `jsp classroom` command is provided as an easier way to turn on or
+off classroom mode. This should be used in preference to the
+classroom.allowScripting() function which is provided only for
+programmatically enabling or disabling classroom mode.
+
+### classroom.allowScripting() function
+
+Allow or disallow anyone who connects to the server (or is already
+connected) to use ScriptCraft. This function is preferable to granting 'ops' privileges
+to every student in a Minecraft classroom environment.
+
+Whenever any file is added/edited or removed from any of the players/
+directories the contents are automatically reloaded. This is to
+facilitate quick turnaround time for students getting to grips with
+Javascript.
+
+#### Parameters
+
+ * canScript : true or false
+
+#### Example
+
+To allow all players (and any players who connect to the server) to
+use the `js` and `jsp` commands...
+
+ /js classroom.allowScripting( true, self )
+
+To disallow scripting (and prevent players who join the server from using the commands)...
+
+ /js classroom.allowScripting( false, self )
+
+Only ops users can run the classroom.allowScripting() function - this is so that students
+don't try to bar themselves and each other from scripting.
+
+***/
+var store = persist('classroom', { enableScripting: false }),
+ File = java.io.File;
+
+function revokeScripting ( player ) {
+ if (__plugin.bukkit){
+ foreach( player.getEffectivePermissions(), function( perm ) {
+ if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) {
+ if ( perm.attachment ) {
+ perm.attachment.remove();
+ }
+ }
+ });
+ }
+ if (__plugin.canary){
+ //
+ var Canary = Packages.net.canarymod.Canary;
+ Canary.permissionManager().removePlayerPermission('scriptcraft.evaluate',player);
+ }
+ var playerName = '' + player.name;
+ playerName = playerName.replace(/[^a-zA-Z0-9_\-]/g,'');
+ var playerDir = new File( playersDir + playerName );
+ unwatchDir( playerDir );
+}
+var autoloadTime = {};
+
+var playerEventHandlers = {};
+
+function reloadPlayerModules( playerContext, playerDir ){
+ /*
+ wph 20150118 first unregister any event handlers registered by the player
+ */
+ var playerDirPath = ''+ playerDir.getAbsolutePath();
+ var eventHandlers = playerEventHandlers[playerDirPath];
+ if (eventHandlers){
+ for (var i = 0;i < eventHandlers.length; i++){
+ eventHandlers[i].unregister();
+ }
+ eventHandlers.length = 0;
+ } else {
+ playerEventHandlers[playerDirPath] = [];
+ eventHandlers = playerEventHandlers[playerDirPath];
+ }
+ /*
+ override events.on() so that the listener is stored here so it can be unregistered.
+ */
+ var oldOn = events.on;
+ var newOn = function( eventType, fn, priority){
+ var handler = oldOn(eventType, fn, priority);
+ eventHandlers.push(handler);
+ };
+ events.on = newOn;
+ autoload( playerContext, playerDir, { cache: false });
+ events.on = oldOn;
+}
+function grantScripting( player ) {
+ console.log('Enabling scripting for player ' + player.name);
+ var playerName = '' + player.name;
+ playerName = playerName.replace(/[^a-zA-Z0-9_\-]/g,'');
+ var playerDir = new File( playersDir + playerName );
+ playerDir.mkdirs();
+ if (__plugin.bukkit){
+ player.addAttachment( __plugin, 'scriptcraft.*', true );
+ }
+ if (__plugin.canary){
+ player.permissionProvider.addPermission('scriptcraft.evaluate',true);
+ }
+ var playerContext = {};
+ reloadPlayerModules( playerContext, playerDir );
+ global[playerName] = playerContext;
+ watchDir( playerDir, function( changedDir ){
+ var currentTime = new java.util.Date().getTime();
+ //this check is here because this callback might get called multiple times for the watch interval
+ //one call for the file change and another for directory change
+ //(this happens only in Linux because in Windows the folder lastModifiedTime is not changed)
+ if (currentTime - autoloadTime[playerName]>1000 ) {
+ reloadPlayerModules(playerContext, playerDir );
+ }
+ autoloadTime[playerName] = currentTime;
+ });
+
+/*
+ echo( player, 'Create your own minecraft mods by adding javascript (.js) files');
+ echo( player, ' Windows: Open Explorer, go to \\\\' + serverAddress + '\\players\\' + player.name);
+ echo( player, ' Macintosh: Open Finder, Go to smb://' + serverAddress + '/players/' + player.name);
+ echo( player, ' Linux: Open Nautilus, Go to smb://' + serverAddress + '/players/' + player.name);
+*/
+
+}
+
+var _classroom = {
+ allowScripting: function (/* boolean: true or false */ canScript, sender ) {
+ sender = utils.player(sender);
+ if ( !sender ) {
+ console.log( 'Attempt to set classroom scripting without credentials' );
+ console.log( 'classroom.allowScripting(boolean, sender)' );
+ return;
+ }
+ /*
+ only operators should be allowed run this function
+ */
+ if ( !isOp(sender) ) {
+ console.log( 'Attempt to set classroom scripting without credentials: ' + sender.name );
+ echo( sender, 'Only operators can use this function');
+ return;
+ }
+ utils.players(function(player){
+ if (!isOp(player)){
+ canScript ? grantScripting(player) : revokeScripting(player);
+ }
+ });
+ store.enableScripting = canScript;
+
+ echo( sender, 'Scripting turned ' + ( canScript ? 'on' : 'off' ) +
+ ' for all players on server ' + serverAddress);
+ }
+};
+
+if (__plugin.canary){
+ events.connection( function( event ) {
+ if ( store.enableScripting ) {
+ grantScripting(event.player);
+ }
+ }, 'CRITICAL');
+} else {
+ events.playerJoin( function( event ) {
+ if ( store.enableScripting ) {
+ grantScripting(event.player);
+ }
+ }, 'HIGHEST');
+}
+module.exports = _classroom;
diff --git a/pool/shard000/JavaScript/0002439_ErrorAlert-test.js b/pool/shard000/JavaScript/0002439_ErrorAlert-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..be9d4755b30129ac01fb0dc7b20ff3ea75ed1c6d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002439_ErrorAlert-test.js
@@ -0,0 +1,54 @@
+/**
+ * # ErrorAlert-test.js
+ * This class validates that the SimpleAlert class will display the
+ * correct error message
+ *
+ * *Note:* if you want to understand the structures here, add a
+ * ```console.log``` and then ```npm test```.
+ *
+ */
+'use strict'
+/**
+ * ## Mock
+ * Mock the simpledialog, see: 'src/__mocks__/react-native-simpledialog-android.js'
+ */
+
+jest.mock('react-native-simpledialog-android')
+
+/**
+ * This will load in the mocked version
+ */
+const SimpleAlert = require('react-native-simpledialog-android')
+
+/**
+ * ## Under test
+ * Object under test
+ */
+var ErrorAlert = require('../ErrorAlert')
+
+/**
+ * ## Test
+ */
+describe('ErrorAlert', () => {
+ it('should be fine', () => {
+ /**
+ * ### defaults
+ */
+ const errorAlertProps = {
+ error: {
+ error: 'Error occurred'
+ }
+ }
+
+ /**
+ * Invoke the ErrorAlert constructor and pass in the mocked
+ * version
+ * Then call the method that processes the error
+ * check that the title is 'Error' which is a hard coded constant
+ * and the alert matches the props error
+ */
+ new ErrorAlert().checkError(errorAlertProps)
+ expect(SimpleAlert.alert.mock.calls[0][0]).toEqual('Error')
+ expect(SimpleAlert.alert.mock.calls[0][1]).toEqual(errorAlertProps.error.error)
+ })
+})// describe ErrorAlert
diff --git a/pool/shard000/JavaScript/0002441_tv.js b/pool/shard000/JavaScript/0002441_tv.js
new file mode 100644
index 0000000000000000000000000000000000000000..adc71aeced195c0e1b760aa55a2227282fcad477
--- /dev/null
+++ b/pool/shard000/JavaScript/0002441_tv.js
@@ -0,0 +1,22 @@
+// icon-tv
+export default {
+ functional: true,
+ render: function (h, { props }) {
+ let width = props.width || 20
+ let height = props.height || 20
+ const viewBox = props.viewBox || '0 0 20 20'
+
+ return h('svg', {
+ attrs: {
+ version: '1.1',
+ meta: 'vk-icons-tv',
+ width: width,
+ height: height,
+ viewBox: viewBox
+ },
+ domProps: {
+ innerHTML: ' '
+ }
+ })
+ }
+}
diff --git a/pool/shard000/JavaScript/0002442_PollListController.js b/pool/shard000/JavaScript/0002442_PollListController.js
new file mode 100644
index 0000000000000000000000000000000000000000..13e2ca6c5ffcfd492c532e0d8cbe02de16da1f71
--- /dev/null
+++ b/pool/shard000/JavaScript/0002442_PollListController.js
@@ -0,0 +1,59 @@
+'use strict';
+
+angular.module('pollListController', ['translationService', 'constantService', 'sharePointService'])
+ .controller('PollListController', function ($scope, TranslationService, ConstantService, SharePointService) {
+
+ //SP.SOD.executeOrDelayUntilScriptLoaded(executeCode, "SP.js");
+
+ function executeCode() {
+
+ TranslationService.getStrings($scope, 1033); // TODO
+ ConstantService.getConstant($scope);
+
+ $scope.polls = [];
+
+
+
+ $scope.disableAdd = false;
+
+ $scope.viewExported = function ($event) {
+ $event.preventDefault();
+ document.location.href = [PeshOS.Common.queryString('SPAppWebUrl'), '/lists/', $scope.CONSTANT.ExportList].join('');
+ };
+
+ $scope.addPoll = function ($event) {
+
+ };
+
+ $scope.configure = function ($event) {
+ $event.preventDefault();
+ document.location.href = [document.location.href.replace('poll.html', 'poll-details.html'), '&pollId=', $event.currentTarget.attributes.data.value].join('');
+ };
+
+ $scope.refresh = function ($event) {
+ SharePointService.getListItems($scope.CONSTANT.ConfigurationList).then(
+ function (items) {
+ var i = 0,
+ maxI = items.length;
+
+ for (i; i < maxI; ++i) {
+ $scope.polls.push(
+ {
+ Id: items[i].get_id(),
+ Name: items[i].get_item('PeshOSName'),
+ ActiveFrom: items[i].get_item('PeshOSStart') == null ? '' : items[i].get_item('PeshOSStart').format('dd MMM yyyy'),
+ ActiveTo: items[i].get_item('PeshOSEnd') == null ? '' : items[i].get_item('PeshOSEnd').format('dd MMM yyyy')
+ }
+ );
+ }
+ },
+ function (sender, args) {
+ $('#alertReadingConfigurations').show();
+ });
+ };
+
+ $scope.refresh();
+ };
+
+ executeCode();
+ });
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002444_todo-service.js b/pool/shard000/JavaScript/0002444_todo-service.js
new file mode 100644
index 0000000000000000000000000000000000000000..8e396e3af1e160e8f530f4c26f9418c5fed0d8c0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002444_todo-service.js
@@ -0,0 +1,23 @@
+angular.module('myApp').factory('Todo', ['$http', '$q', 'Restangular', function( $http, $q, Restangular ){
+
+ var Todo;
+
+ var _resource = Restangular.withConfig(function(RestangularConfigurer){
+ RestangularConfigurer.setBaseUrl('http://angular-db-api.aws.af.cm/api');
+
+ RestangularConfigurer.setRestangularFields({
+ id: '_id'
+ });
+
+ RestangularConfigurer.addElementTransformer('todos', false, function( element ) {
+ //add methods to instances here element.method = function(){}
+ element.id = element._id;
+
+ return element;
+ });
+ });
+
+ Todo = _resource.all('todos');
+
+ return Todo;
+}]);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002445_index.js b/pool/shard000/JavaScript/0002445_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..4f8c649feb01fd9911439d73603a0fd12b1f22b6
--- /dev/null
+++ b/pool/shard000/JavaScript/0002445_index.js
@@ -0,0 +1,267 @@
+/* eslint-disable no-await-in-loop */
+const fs = require('fs');
+const mysql = require('mysql');
+const sqlLimiter = require('sql-limiter');
+const { formatSchemaQueryResults } = require('../utils');
+const appLog = require('../../lib/app-log');
+
+const id = 'mysql';
+const name = 'MySQL';
+
+function getSchemaSql(database) {
+ const whereSql = database
+ ? `WHERE t.table_schema = '${database}'`
+ : `WHERE t.table_schema NOT IN (
+ 'mysql',
+ 'performance_schema',
+ 'information_schema'
+ )`;
+ return `
+ SELECT
+ t.table_schema,
+ t.table_name,
+ c.column_name,
+ c.data_type,
+ c.column_comment as column_description
+ FROM
+ INFORMATION_SCHEMA.TABLES t
+ JOIN INFORMATION_SCHEMA.COLUMNS c ON t.table_schema = c.table_schema AND t.table_name = c.table_name
+ ${whereSql}
+ ORDER BY
+ t.table_schema,
+ t.table_name,
+ c.ordinal_position
+ `;
+}
+
+class Client {
+ constructor(connection) {
+ this.connection = connection;
+ this.client = null; // AKA myConnection
+ }
+
+ /**
+ * Establish db client connection if not already connected
+ */
+ async connect() {
+ if (this.client) {
+ return;
+ }
+ const { connection } = this;
+
+ const myConfig = {
+ host: connection.host,
+ port: connection.port ? connection.port : 3306,
+ user: connection.username,
+ password: connection.password,
+ database: connection.database,
+ insecureAuth: connection.mysqlInsecureAuth,
+ timezone: 'Z',
+ supportBigNumbers: true,
+ ssl: connection.mysqlSsl,
+ preQueryStatements: connection.preQueryStatements,
+ flags: '+INTERACTIVE',
+ dateStrings: true,
+ };
+
+ // TODO cache key/cert values
+ if (connection.mysqlKey && connection.mysqlCert) {
+ myConfig.ssl = {
+ key: fs.readFileSync(connection.mysqlKey),
+ cert: fs.readFileSync(connection.mysqlCert),
+ };
+ if (connection.mysqlCA) {
+ myConfig.ssl['ca'] = fs.readFileSync(connection.mysqlCA);
+ }
+ }
+
+ this.client = mysql.createConnection(myConfig);
+
+ this.client.on('error', (err) => {
+ appLog.error(err);
+ });
+
+ await new Promise((resolve, reject) => {
+ this.client.connect(async (err) => {
+ if (err) {
+ return reject(err);
+ }
+ resolve();
+ });
+ });
+
+ // Run pre query statements
+ // Statements split by JS because MySQL multipleStatements is turned off
+ if (myConfig.preQueryStatements) {
+ // sqlLimiter may return empty statements so they should be stripped out
+ const statements = sqlLimiter
+ .getStatements(connection.preQueryStatements)
+ .map((s) => sqlLimiter.removeTerminator(s))
+ .filter((s) => s && s.trim() !== '');
+
+ for (const statement of statements) {
+ await new Promise((resolve, reject) => {
+ this.client.query(statement, (err) => {
+ if (err) {
+ return reject(err);
+ }
+ return resolve();
+ });
+ });
+ }
+ }
+ }
+
+ /**
+ * Disconnect the underlying client if connected
+ */
+ async disconnect() {
+ if (this.client) {
+ // Immediately destroys underlying socket.
+ // No additional callbacks are called.
+ this.client.destroy();
+ this.client = null;
+ }
+ }
+
+ /**
+ * Run query using underlying connection
+ * @param {string} query
+ */
+ async runQuery(query) {
+ if (!this.client) {
+ throw new Error('Must be connected');
+ }
+
+ const { maxRows } = this.connection;
+ const maxRowsPlusOne = maxRows + 1;
+ const limitedQuery = sqlLimiter.limit(
+ query,
+ ['limit', 'fetch'],
+ maxRowsPlusOne
+ );
+
+ return new Promise((resolve, reject) => {
+ // TODO - use fields from driver to return columns
+ // eslint-disable-next-line no-unused-vars
+ return this.client.query(limitedQuery, (error, rows, fields) => {
+ if (error) {
+ return reject(error);
+ }
+ if (rows.length >= maxRowsPlusOne) {
+ return resolve({ rows: rows.slice(0, maxRows), incomplete: true });
+ }
+ return resolve({ rows, incomplete: false });
+ });
+ });
+ }
+}
+
+/**
+ * Run query for connection
+ * Should return { rows, incomplete }
+ * @param {string} query
+ * @param {object} connection
+ */
+async function runQuery(query, connection) {
+ const client = new Client(connection);
+ await client.connect();
+ try {
+ const result = await client.runQuery(query);
+ await client.disconnect();
+ return result;
+ } catch (error) {
+ await client.disconnect();
+ throw error;
+ }
+}
+
+/**
+ * Test connectivity of connection
+ * @param {*} connection
+ */
+function testConnection(connection) {
+ const query = "SELECT 'success' AS TestQuery;";
+ return runQuery(query, connection);
+}
+
+/**
+ * Get schema for connection
+ * @param {*} connection
+ */
+function getSchema(connection) {
+ const schemaSql = getSchemaSql(connection.database);
+ return runQuery(schemaSql, connection).then((queryResult) =>
+ formatSchemaQueryResults(queryResult)
+ );
+}
+
+const fields = [
+ {
+ key: 'host',
+ formType: 'TEXT',
+ label: 'Host/Server/IP Address',
+ },
+ {
+ key: 'port',
+ formType: 'TEXT',
+ label: 'Port (optional)',
+ },
+ {
+ key: 'database',
+ formType: 'TEXT',
+ label: 'Database',
+ },
+ {
+ key: 'username',
+ formType: 'TEXT',
+ label: 'Database Username',
+ },
+ {
+ key: 'password',
+ formType: 'PASSWORD',
+ label: 'Database Password',
+ },
+ {
+ key: 'mysqlSsl',
+ formType: 'CHECKBOX',
+ label: 'Use SSL',
+ },
+ {
+ key: 'mysqlCert',
+ formType: 'TEXT',
+ label: 'Database Certificate Path',
+ },
+ {
+ key: 'mysqlKey',
+ formType: 'TEXT',
+ label: 'Database Key Path',
+ },
+ {
+ key: 'mysqlCA',
+ formType: 'TEXT',
+ label: 'Database CA Path',
+ },
+ {
+ key: 'mysqlInsecureAuth',
+ formType: 'CHECKBOX',
+ label: 'Use old/insecure pre 4.1 Auth System',
+ },
+ {
+ key: 'preQueryStatements',
+ formType: 'TEXTAREA',
+ label: 'Pre-query Statements (Optional)',
+ placeholder:
+ 'Use to enforce session variables like:\n SET max_statement_time = 15;\n SET max_execution_time = 15;\n\nDeny multiple statements per query to avoid overwritten values.',
+ },
+];
+
+module.exports = {
+ id,
+ name,
+ fields,
+ getSchema,
+ runQuery,
+ testConnection,
+ Client,
+};
diff --git a/pool/shard000/JavaScript/0002447_1.ProcessURLsGetListOfShorts-new.js b/pool/shard000/JavaScript/0002447_1.ProcessURLsGetListOfShorts-new.js
new file mode 100644
index 0000000000000000000000000000000000000000..779f4c5868591ff30709e756797e0315cc44bf1f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002447_1.ProcessURLsGetListOfShorts-new.js
@@ -0,0 +1,66 @@
+/* new: Code to get list of shares that are currently shorted*/
+
+/*get list of companies from shorttracker.co.uk*/
+var shortArray = [];
+shortDataGrabber('http://shorttracker.co.uk/company');
+
+function shortDataGrabbertest(url)
+{
+ var share=url.toString();
+ share=share.substring(share.indexOf("company/")+8
+,share.lastIndexOf("/all"));
+ console.log(share);
+}
+
+function shortDataGrabber(url)
+{
+/* function to grab short data and write to a file for data import */
+
+var sjs = require('../../../src/Scraper')
+
+/*
+ Get all the links in a page.
+ */
+sjs.StaticScraper
+ .create()
+ .onStatusCode(function(code) {
+ console.log(code);
+ })
+ .scrape(function($) {
+ return $('tr').map(function() {
+ return $(this).html();
+ }).get();
+ }, function(links) {
+ links.forEach(function(link) {
+ // console.log(url);
+ //var share=url.toString();
+ //share=share.substring(share.indexOf("/j")+1
+//,share.lastIndexOf("/placement"));
+ //console.log(share);
+ //var string=link.substring(link.lastIndexOf("Company ")+1,link.lastIndexOf(""));
+ /*fix data issues*/
+if (link.indexOf("0.00%") < 0)
+{
+var string=link;
+string = string.replace(/Company<\/th>[\n\r] % short<\/th>[\n\r]/, "");
+string = string.replace(/ /, ",");
+string = string.replace(/<\/a><\/td>[\n\r] /, ",");
+string = string.replace(/%<\/td>/, "%");
+string = string.replace(/[\n\r]/, "");
+//console.log(link);
+
+/* write to file */
+
+var fs = require('fs');
+fs.appendFile('companies.txt', string, function (err) {});
+
+/* end write to file */
+}
+
+ });
+ })
+ .get(url);
+
+
+};
diff --git a/pool/shard000/JavaScript/0002448_controller.js b/pool/shard000/JavaScript/0002448_controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..b20b0952c1c2ba3d715ebdedf03db790fed25c8a
--- /dev/null
+++ b/pool/shard000/JavaScript/0002448_controller.js
@@ -0,0 +1,298 @@
+const ChannelModel = require('./model')
+const RootController = require('structure-root-controller')
+const slug = require('paradigm-slugs')
+
+/**
+ * ChannelsController Class
+ *
+ * @public
+ * @class ChannelsController
+ */
+class Controller extends RootController {
+
+ /**
+ * ChannelsController constructor
+ *
+ * @public
+ * @constructor
+ * @param {Object} options - Options
+ */
+ constructor(options = {}) {
+ super(Object.assign({}, {
+ name: 'channels'
+ }, options))
+ }
+
+ /**
+ * Create new channel
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ async create(req, res) {
+
+ const applicationId = req.headers.applicationid
+ const organizationId = req.headers.organizationid
+
+ const channelModel = new ChannelModel({
+ applicationId,
+ logger: this.logger,
+ organizationId
+ })
+
+ const pkg = req.body
+
+ return new Promise( async (resolve, reject) => {
+
+ try {
+
+ pkg.slug = slug(pkg.slug || pkg.title)
+ pkg.status = 'active'
+
+ if(!pkg.applicationId) {
+ pkg.applicationId = applicationId
+ }
+
+ if(!pkg.organizationId) {
+ pkg.organizationId = organizationId
+ }
+
+ const doc = await channelModel.getBySlug(pkg.slug)
+
+ // Don't re-create the same channel
+ if(doc) {
+ return reject({
+ code: 'CHANNEL_EXISTS'
+ })
+ }
+
+ const channel = await channelModel.create(pkg)
+
+ resolve(channel)
+
+ } catch(e) {
+
+ this.logger.error(e)
+ reject(e)
+
+ }
+
+ })
+
+ }
+
+ deleteById(req, res) {
+
+ const channel = new ChannelModel({
+ logger: this.logger,
+ })
+
+ return channel.deleteById(req.params.id)
+
+ }
+
+ /**
+ * Get all channels
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ getAll(req, res) {
+
+ const channel = new ChannelModel({
+ applicationId: req.headers.applicationid,
+ logger: this.logger,
+ organizationId: req.headers.organizationid
+ })
+
+ return channel.getAll([])
+
+ }
+
+ /**
+ * Get channel by id
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ getById(req, res) {
+
+ const channel = new ChannelModel({
+ logger: this.logger,
+ })
+
+ return channel.getById(req.params.id)
+
+ }
+
+ /**
+ * Get channel by slug
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ getBySlug(req, res) {
+
+ const channel = new ChannelModel({
+ applicationId: req.headers.applicationid,
+ logger: this.logger,
+ organizationId: req.headers.organizationid
+ })
+
+ return channel.getBySlug(req.params.slug)
+
+ }
+
+ /**
+ * Get resouces of channel
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ getResources(req, res) {
+
+ const channel = new ChannelModel({
+ applicationId: req.headers.applicationid,
+ logger: this.logger,
+ organizationId: req.headers.organizationid,
+ })
+
+ return new Promise( async (resolve, reject) => {
+
+ try {
+
+ let items = []
+
+ // Get single resource
+ if(req.params.resource) {
+
+ items = await channel.getSingleResource(req.params, req.query)
+
+ // Get all resources
+ } else {
+
+ items = await channel.getAllResources(req.params, req.query)
+
+ }
+
+ const pkg = {
+ resources: items.resources
+ }
+
+ resolve(pkg)
+
+ } catch(e) {
+
+ this.logger.error(e)
+ reject(e)
+
+ }
+
+ })
+
+ }
+
+ /**
+ * Get RSS data for channel
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ getRSS(req, res) {
+
+ const channel = new ChannelModel({
+ applicationId: req.headers.applicationid,
+ logger: this.logger,
+ organizationId: req.headers.organizationid,
+ })
+
+ return new Promise( async (resolve, reject) => {
+
+ try {
+
+ let items = []
+
+ items = await channel.getAllResources(req.params, req.query, {
+ rss: true
+ })
+
+ const pkg = {
+ resources: items.resources
+ }
+
+ resolve(pkg)
+
+ } catch(e) {
+
+ this.logger.error(e)
+ reject(e)
+
+ }
+
+ })
+
+ }
+
+ /**
+ * Match channel by slug
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ matchBySlug(req, res) {
+
+ const channel = new ChannelModel({
+ applicationId: req.headers.applicationid,
+ logger: this.logger,
+ organizationId: req.headers.organizationid
+ })
+
+ return channel.matchBySlug(req.params.slug)
+
+ }
+
+ /**
+ * Update a channel
+ *
+ * @public
+ * @param {Object} req - Express req
+ * @param {Object} res - Express res
+ */
+ updateById(req, res) {
+
+ const channelModel = new ChannelModel({
+ logger: this.logger,
+ })
+ const pkg = req.body
+ if(pkg.slug) pkg.slug = slug(pkg.slug)
+
+ return new Promise( async (resolve, reject) => {
+
+ try {
+
+ const channel = await channelModel.updateById(req.params.id, pkg)
+
+ resolve(channel)
+
+ } catch(e) {
+
+ this.logger.error(e)
+ reject(e)
+
+ }
+
+ })
+
+
+ }
+
+}
+
+module.exports = Controller
diff --git a/pool/shard000/JavaScript/0002450_index.js b/pool/shard000/JavaScript/0002450_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..5af7331c6503c2f88fcbc9e472e3fe41abf30848
--- /dev/null
+++ b/pool/shard000/JavaScript/0002450_index.js
@@ -0,0 +1,37 @@
+var fs = require('fs');
+var test = require('testit');
+var seed = require('seed-random');
+var gbp = require('../');
+
+var random = seed('whatever');
+
+try {
+ fs.mkdirSync(__dirname + '/actual');
+} catch (ex) {
+ if (ex.code !== 'EEXIST') throw ex;
+}
+
+test('small numbers', function () {
+ var results = '';
+ for (var i = -1000; i < 1000; i++) {
+ results += i + ' => ' + gbp(i) + ' or ' + gbp(i, {excludeZeroPennies: true}) + '\n';
+ }
+ fs.writeFileSync(__dirname + '/actual/small.txt', results);
+ var expected = fs.readFileSync(__dirname + '/expected/small.txt', 'utf8');
+ if (expected.trim() !== results.trim()) {
+ throw new Error('Some results were incorrect');
+ }
+});
+
+test('random numbers', function () {
+ var results = '';
+ for (var i = 0; i < 10000; i += 7) {
+ var val = (random() * Math.pow(10, 9)) | 0;
+ results += val + ' => ' + gbp(val) + ' or ' + gbp(val, {excludeZeroPennies: true}) + '\n';
+ }
+ fs.writeFileSync(__dirname + '/actual/random.txt', results);
+ var expected = fs.readFileSync(__dirname + '/expected/random.txt', 'utf8');
+ if (expected.trim() !== results.trim()) {
+ throw new Error('Some results were incorrect');
+ }
+});
diff --git a/pool/shard000/JavaScript/0002452_browser-providers.js b/pool/shard000/JavaScript/0002452_browser-providers.js
new file mode 100644
index 0000000000000000000000000000000000000000..8a7e98502125e91d59708583f2787af07d2067fc
--- /dev/null
+++ b/pool/shard000/JavaScript/0002452_browser-providers.js
@@ -0,0 +1,66 @@
+'use strict';
+
+/*
+ * Browser Configuration for the different jobs in the CI.
+ * Target can be either: BS (Browserstack) | SL (Saucelabs) | null (To not run at all)
+ */
+const browserConfig = {
+ 'Chrome': { unitTest: {target: 'SL', required: true }},
+ 'Firefox': { unitTest: {target: 'SL', required: true }},
+ 'ChromeBeta': { unitTest: {target: 'SL', required: false }},
+ 'FirefoxBeta': { unitTest: {target: null, required: false }},
+ 'ChromeDev': { unitTest: {target: null, required: true }},
+ 'FirefoxDev': { unitTest: {target: null, required: true }},
+ 'IE9': { unitTest: {target: null, required: false }},
+ 'IE10': { unitTest: {target: null, required: true }},
+ 'IE11': { unitTest: {target: 'SL', required: true }},
+ 'Edge': { unitTest: {target: 'SL', required: true }},
+ 'Android4.1': { unitTest: {target: null, required: false }},
+ 'Android4.2': { unitTest: {target: null, required: false }},
+ 'Android4.3': { unitTest: {target: null, required: false }},
+ 'Android4.4': { unitTest: {target: null, required: false }},
+ 'Android5': { unitTest: {target: 'SL', required: false }},
+ 'Safari7': { unitTest: {target: null, required: false }},
+ 'Safari8': { unitTest: {target: null, required: false }},
+ 'Safari9': { unitTest: {target: 'BS', required: false }},
+ 'Safari10': { unitTest: {target: 'SL', required: false }},
+ 'iOS7': { unitTest: {target: null, required: false }},
+ 'iOS8': { unitTest: {target: null, required: false }},
+ 'iOS9': { unitTest: {target: 'BS', required: true }},
+ 'WindowsPhone': { unitTest: {target: 'BS', required: false }}
+};
+
+/** Exports all available remote browsers. */
+exports.customLaunchers = require('./remote_browsers.json');
+
+/** Exports a map of configured browsers, which should run on the CI. */
+exports.platformMap = {
+ 'saucelabs': {
+ required: buildConfiguration('unitTest', 'SL', true),
+ optional: buildConfiguration('unitTest', 'SL', false)
+ },
+ 'browserstack': {
+ required: buildConfiguration('unitTest', 'BS', true),
+ optional: buildConfiguration('unitTest', 'BS', false)
+ },
+};
+
+/** Build a list of configuration (custom launcher names). */
+function buildConfiguration(type, target, required) {
+ return Object.keys(browserConfig)
+ .map(item => [item, browserConfig[item][type]])
+ .filter(([, conf]) => conf.required === required && conf.target === target)
+ .map(([item]) => `${target}_${item.toUpperCase()}`);
+}
+
+/** Decode the token for Travis to use. */
+function decodeToken(token) {
+ return (token || '').split('').reverse().join('');
+}
+
+
+/** Ensures that the Travis access keys work properly. */
+if (process.env.TRAVIS) {
+ process.env.SAUCE_ACCESS_KEY = decodeToken(process.env.SAUCE_ACCESS_KEY);
+ process.env.BROWSER_STACK_ACCESS_KEY = decodeToken(process.env.BROWSER_STACK_ACCESS_KEY);
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002455_index.js b/pool/shard000/JavaScript/0002455_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..356a78aae4cfb9356f8376fb55c6c387633d6039
--- /dev/null
+++ b/pool/shard000/JavaScript/0002455_index.js
@@ -0,0 +1,90 @@
+import zipObject from './internal/zip-object';
+import tryInvoke from './internal/try-invoke';
+import mapFilter from './internal/map-filter';
+
+
+export function allObject(object) {
+ const keys = Object.keys(object);
+ return Promise.all(keys.map(key => object[key])).then(values => zipObject(keys, values));
+}
+
+
+export function series(factories) {
+ const promises = [];
+ let promise = Promise.resolve();
+ factories.forEach(f => {
+ promise = promise.then(() => f());
+ promises.push(promise);
+ });
+ return Promise.all(promises);
+}
+
+
+export function parallel(factories) {
+ return Promise.all(factories.map(tryInvoke));
+}
+
+
+export function map(array, closure) {
+ try {
+ return Promise.all(array.map((value, index) => closure(value, index)));
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+
+
+export function mapSeries(array, closure) {
+ try {
+ return series(array.map((value, index) => () => closure(value, index)));
+ }
+ catch (err) {
+ return Promise.reject(err);
+ }
+}
+
+
+export function filter(array, closure) {
+ return mapFilter(map, array, closure);
+}
+
+
+export function filterSeries(array, closure) {
+ return mapFilter(mapSeries, array, closure);
+}
+
+
+export function entangledCallback(optional_value_resolver) {
+ let resolve_fn;
+ let reject_fn;
+
+ const promise = new Promise((resolve, reject) => {
+ resolve_fn = resolve;
+ reject_fn = reject;
+ });
+
+ const callback = (err, ...values) => {
+ if (err) {
+ reject_fn(err);
+ return;
+ }
+
+ if (!optional_value_resolver) {
+ resolve_fn(values[0]);
+ return;
+ }
+
+ let value;
+ try {
+ value = optional_value_resolver(...values);
+ }
+ catch (value_resolver_err) {
+ reject_fn(value_resolver_err);
+ return;
+ }
+ resolve_fn(value);
+ };
+
+ return [promise, callback];
+}
diff --git a/pool/shard000/JavaScript/0002457_actions.js b/pool/shard000/JavaScript/0002457_actions.js
new file mode 100644
index 0000000000000000000000000000000000000000..c7b74560714a0d0dd939c5e6771db4fb5c740267
--- /dev/null
+++ b/pool/shard000/JavaScript/0002457_actions.js
@@ -0,0 +1,27 @@
+import { JETPACK_SCAN_UPDATE, JETPACK_SCAN_ENQUEUE_REQUEST } from 'calypso/state/action-types';
+import { requestScanStatus } from 'calypso/state/jetpack-scan/actions';
+
+import 'calypso/state/data-layer/wpcom/sites/scan/enqueue';
+import 'calypso/state/jetpack-scan/init';
+
+export const requestJetpackScanEnqueue = ( siteId ) => ( {
+ type: JETPACK_SCAN_ENQUEUE_REQUEST,
+ siteId,
+ meta: {
+ dataLayer: {
+ trackRequest: true,
+ },
+ },
+} );
+
+export const startScanOptimistically = ( siteId ) => {
+ return ( dispatch ) => {
+ dispatch( {
+ type: JETPACK_SCAN_UPDATE,
+ siteId,
+ payload: { state: 'scanning' },
+ } );
+
+ setTimeout( () => dispatch( requestScanStatus( siteId ) ), 5 * 1000 );
+ };
+};
diff --git a/pool/shard000/JavaScript/0002460_init.js b/pool/shard000/JavaScript/0002460_init.js
new file mode 100644
index 0000000000000000000000000000000000000000..dee78cfda2717c700979e59e9dfce7962b2f38bb
--- /dev/null
+++ b/pool/shard000/JavaScript/0002460_init.js
@@ -0,0 +1,96 @@
+ var $ = jQuery.noConflict();
+
+ $().ready(function() {
+ $('.jqmWindow#vimeo-info').jqm({trigger: 'a#modal-vimeo-info', overlay:60});
+ $('.jqmWindow#youtube-info').jqm({trigger: 'a#modal-youtube-info', overlay:60});
+ $('.jqmWindow#vimeo-info').jqmAddClose('a.close');
+ });
+
+ $(document).ready(function() {
+ try {
+ $( ".datepicker" ).datepicker({
+ altField: ".datepickeralt",
+ altFormat: "DD, d MM, yy"
+ });
+ } catch(e) {
+
+ }
+
+ $('.modal-trigger').click(function(){
+ var modalPos = $(window).scrollTop() + 70;
+ $('.jqmWindow').css('top', modalPos + 'px');
+ });
+
+ if ($.browser.msie && $.browser.version.substr(0,1)<8) {
+ $('#le-iexploder').show();
+ }
+
+ $('.colorpicker').jPicker({window:{expandable: true}});
+
+ $('input.colorpicker, span.jPicker').click(function(){
+ var modalPos = $(window).scrollTop() + 70;
+ $('div.jPicker.Container').css('top', modalPos + 'px');
+ });
+
+ $('span.expand').click(function(){
+
+ var thisID = $(this).attr('id');
+
+ if($(this).parent('.le-title').parent('.le-section').hasClass('open')) {
+ $(this).parent('.le-title').parent('.le-section').removeClass('open');
+ $(this).text('+');
+ $.cookie(thisID, 'collapsered');
+ } else {
+ $(this).parent('.le-title').parent('.le-section').addClass('open');
+ $(this).text('-');
+ $.cookie(thisID, 'expandered');
+ }
+ });
+
+ $('a#collapse-all').click(function(){
+ $('.le-section').removeClass('open');
+ $('span.expand').text('+');
+ $.cookie('span.expand', 'collapsered');
+ });
+
+ var cooky = $.cookie();
+
+ $.each(cooky, function(key, value) {
+
+ if(value == 'expandered') {
+ $('span.expand#' + key).parent('.le-title').parent('.le-section').addClass('open');
+ $('span.expand#' + key).text('-');
+ }
+
+ if(value == 'collapsered') {
+ $('span.expand').parent('.le-title').parent('.le-section').removeClass('open');
+ $('span.expand').text('+');
+ }
+
+ });
+
+ $('.le-select_webfont select').each(function(){
+ var selectVal = $(this).find('option:selected').attr('value');
+ if(selectVal.length > 0) {
+ $(this).parent().children('ul').children('li.' + $(this).find('option:selected').attr('class')).show();
+ }
+ });
+
+ $('.le-select_webfont select').change(function(){
+
+ var selectVal = $(this).find('option:selected').attr('value');
+
+ if(selectVal.length > 0) {
+ $(this).parent().children('ul').children('li').hide();
+ $(this).parent().children('ul').children('li.' + $(this).find('option:selected').attr('class')).show();
+ } else {
+ $(this).parent().children('ul').children('li').hide();
+ }
+
+ });
+
+
+
+ $('#footer').hide();
+
+ });
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002464_radiant.ckeditor.js b/pool/shard000/JavaScript/0002464_radiant.ckeditor.js
new file mode 100644
index 0000000000000000000000000000000000000000..ca858d6bb73826c70975129b00dae18563f4c1a1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002464_radiant.ckeditor.js
@@ -0,0 +1,129 @@
+function instantiateCkEditor(partIndex){
+ // Fixes parts with underscores or spaces in the name
+ partIndex = partIndex.replace(/(_| )/g,'-');
+
+ CKEDITOR.config.extraPlugins = 'autogrow,codemirror,scayt,showblocks';
+
+ CKEDITOR.config.startupOutlineBlocks = true;
+ CKEDITOR.config.autoParagraph = false;
+ CKEDITOR.config.skin = "moono";
+ CKEDITOR.config.colorButton_enableMore = false;
+ // Code Cleanup
+ CKEDITOR.config.protectedSource.push(/.*<\/r:\1>/g);
+ CKEDITOR.config.protectedSource.push(/\/]*\/>/g);
+ CKEDITOR.config.emailProtection = "encode";
+ CKEDITOR.config.forcePasteAsPlainText = true;
+ CKEDITOR.config.pasteFromWordPromptCleanup = true;
+ CKEDITOR.config.pasteFromWordNumberedHeadingToList = true;
+ // Auto Spell correct
+ CKEDITOR.config.scayt_autoStartup = true;
+ // Autogrow settings
+ CKEDITOR.config.height = 300;
+ CKEDITOR.config.autoGrow_onStartup = true;
+ CKEDITOR.config.autoGrow_maxHeight = 800;
+ CKEDITOR.config.autoGrow_minHeight = 300;
+ CKEDITOR.config.autoGrow_bottomSpace = 20;
+ // For allowing classes on divs - http://docs.ckeditor.com/#!/api/CKEDITOR.config
+ CKEDITOR.config.allowedContent = true;
+ // Nice source highlighting
+ CKEDITOR.config.codemirror = {
+ highlightActiveLine: false,
+ theme: 'rubyblue'
+ };
+ // Your custom stylesheet
+ // CKEDITOR.config.contentsCss = '/stylesheets/bootstrap.css';
+ CKEDITOR.config.toolbar =
+ [
+ ['Format'],
+ ['Bold','Italic','Strike','-','Subscript','Superscript'],
+ ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
+ ['Undo','Redo','-','Find','Replace','-', 'Paste', 'RemoveFormat'],
+ ['Link','Unlink','Anchor'],
+ ['Image','Table','HorizontalRule','SpecialChar','-','ShowBlocks'],
+ ['Source']
+ ],
+ CKEDITOR.on('instanceReady',
+ function( evt ) {
+ var editor = evt.editor;
+ var ck_holder = $("cke_" + editor.name);
+ if(ck_holder){
+ Droppables.add(ck_holder, {
+ accept: 'asset',
+ onDrop: function(element) {
+ var link = element.select('a.bucket_link')[0];
+ var classes = element.className.split(' ');
+ var tag_type = classes[0];
+ if(tag_type == 'image') {
+ var tag = ' ';
+ }
+ else {
+ var asset_id = element.id.split('_').last();
+ var tag = ''+ link.title +' ';
+ }
+ var element = CKEDITOR.dom.element.createFromHtml(tag);
+ editor.insertElement(element);
+ }
+ });
+ }
+ }
+ );
+
+ var usedFilter = $('part_' + partIndex +'_filter_id');
+ if(usedFilter.value == 'CKEditor'){
+ putInEditor(partIndex);
+ }
+
+ var timer = setInterval(function() {
+ // Make image asset draggable
+ Asset.MakeDraggables;
+ // Make asset bucket thumbnails draggable
+ $$('div.resized').each(function(element){
+ if(!element.hasClassName("move"));
+ new Draggable(element, { revert: true });
+ element.addClassName('move');
+ });
+ }, 5000);
+
+}
+
+function toggleEditor(partIndex){
+ var filterId = $('part_' + partIndex + '_filter_id');
+ if(filterId.value == 'CKEditor'){
+ putInEditor(partIndex);
+ } else {
+ removeEditor(partIndex);
+ }
+}
+
+function removeEditor(partIndex){
+ var instance = CKEDITOR.instances['part_'+ partIndex +'_content'];
+ instance.destroy();
+}
+
+function putInEditor(partIndex){
+ var textarea = $('part_' + partIndex + '_content');
+ CKEDITOR.replace(textarea);
+}
+
+InsertIntoCk = Behavior.create({
+ onclick: function(e) {
+ if (e) e.stop();
+ var part_name = TabControlBehavior.instances[0].controller.selected.caption;
+ var textbox = $('part_' + part_name + '_content');
+
+ var tag_parts = this.element.getAttribute('rel').split('_');
+ var href = this.element.getAttribute('href');
+ var tag_name = tag_parts[0];
+ var asset_size = tag_parts[1];
+ var asset_id = tag_parts[2];
+
+ if($('part_' + part_name + '_filter_id').value == 'CKEditor'){
+ editor = CKEDITOR.instances['part_'+ part_name +'_content'];
+ if(tag_name == 'image') {
+ editor.insertHtml(" ");
+ } else {
+ editor.insertHtml("" + this.element.up(".back").down(".title").innerHTML + " ");
+ }
+ }
+ }
+});
diff --git a/pool/shard000/JavaScript/0002465_content.js b/pool/shard000/JavaScript/0002465_content.js
new file mode 100644
index 0000000000000000000000000000000000000000..50b9600eff0bf0d81bc837d5bec4207cd4e43bb0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002465_content.js
@@ -0,0 +1,99 @@
+/* Copyright 2014 Mozilla Foundation
+ *
+ * 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-env mozilla/frame-script */
+
+"use strict";
+
+(function contentScriptClosure() {
+ // we need to use closure here -- we are running in the global context
+
+ const Cc = Components.classes;
+ const Ci = Components.interfaces;
+ const Cm = Components.manager;
+ const Cu = Components.utils;
+ const Cr = Components.results;
+
+ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+ Cu.import("resource://gre/modules/Services.jsm");
+
+ var isRemote = Services.appinfo.processType ===
+ Services.appinfo.PROCESS_TYPE_CONTENT;
+
+ // Factory that registers/unregisters a constructor as a component.
+ function Factory() {
+ }
+
+ Factory.prototype = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory]),
+ _targetConstructor: null,
+
+ register: function register(targetConstructor) {
+ this._targetConstructor = targetConstructor;
+ var proto = targetConstructor.prototype;
+ var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
+ registrar.registerFactory(proto.classID, proto.classDescription,
+ proto.contractID, this);
+ },
+
+ unregister: function unregister() {
+ var proto = this._targetConstructor.prototype;
+ var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
+ registrar.unregisterFactory(proto.classID, this);
+ this._targetConstructor = null;
+ },
+
+ // nsIFactory
+ createInstance: function createInstance(aOuter, iid) {
+ if (aOuter !== null) {
+ throw Cr.NS_ERROR_NO_AGGREGATION;
+ }
+ return (new (this._targetConstructor)()).QueryInterface(iid);
+ },
+
+ // nsIFactory
+ lockFactory: function lockFactory(lock) {
+ // No longer used as of gecko 1.7.
+ throw Cr.NS_ERROR_NOT_IMPLEMENTED;
+ },
+ };
+
+ var pdfStreamConverterFactory = new Factory();
+
+ function startup() {
+ Cu.import("resource://pdf.js/PdfjsContentUtils.jsm");
+ PdfjsContentUtils.init();
+
+ Cu.import("resource://pdf.js/PdfStreamConverter.jsm");
+ pdfStreamConverterFactory.register(PdfStreamConverter);
+ }
+
+ function shutdown() {
+ // Remove the contract/component.
+ pdfStreamConverterFactory.unregister();
+ // Unload the converter
+ Cu.unload("resource://pdf.js/PdfStreamConverter.jsm");
+
+ PdfjsContentUtils.uninit();
+ Cu.unload("resource://pdf.js/PdfjsContentUtils.jsm");
+ }
+
+ if (isRemote) {
+ startup();
+
+ addMessageListener("PDFJS:Child:shutdown", function() {
+ shutdown();
+ });
+ }
+})();
diff --git a/pool/shard000/JavaScript/0002471_server.js b/pool/shard000/JavaScript/0002471_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..ccbd3c17d11c1a97625fe23b158b5148d67e5e4e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002471_server.js
@@ -0,0 +1,209 @@
+var express = require('express');
+var path = require('path');
+var logger = require('morgan');
+var cookieParser = require('cookie-parser');
+var bodyParser = require('body-parser');
+var async = require('async');
+var request = require('request');
+var xml2js = require('xml2js');
+var _ = require('lodash');
+
+var mongoose = require('mongoose');
+
+// Mongoose Sechema for thetvb.com API
+
+var showSchema = new mongoose.Schema({
+ _id: Number,
+ name: String,
+ airsDayOfWeek: String,
+ airsTime: String,
+ firstAired: Date,
+ genre: [String],
+ network: String,
+ overview: String,
+ rating: Number,
+ ratingCount: Number,
+ status: String,
+ poster: String,
+ subscribers: [{
+ type: mongoose.Schema.Types.ObjectId, ref: 'User'
+ }],
+ episodes: [{
+ season: Number,
+ episodeNumber: Number,
+ episodeName: String,
+ firstAired: Date,
+ overview: String
+ }]
+});
+
+var userSchema = new mongoose.Schema({
+ email: { type: String, unique: true },
+ password: String
+});
+
+userSchema.pre('save', function(next) {
+ var user = this;
+ if (!user.isModified('password')) return next();
+ bcrypt.genSalt(10, function(err, salt) {
+ if (err) return next(err);
+ bcrypt.hash(user.password, salt, function(err, hash) {
+ if (err) return next(err);
+ user.password = hash;
+ next();
+ });
+ });
+});
+
+userSchema.methods.comparePassword = function(candidatePassword, cb) {
+ bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
+ if (err) return cb(err);
+ cb(null, isMatch);
+ });
+};
+
+var User = mongoose.model('User', userSchema);
+var Show = mongoose.model('Show', showSchema);
+
+mongoose.connect('localhost');
+
+var bcrypt = require('bcryptjs');
+
+var app = express();
+
+app.set('port', process.env.PORT || 3000);
+app.use(logger('dev'));
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded());
+app.use(cookieParser());
+app.use(express.static(path.join(__dirname, 'public')));
+
+// Express routes for shows
+
+app.get('/api/shows', function(req, res, next) {
+ var query = Show.find();
+ if (req.query.genre) {
+ query.where({ genre: req.query.genre });
+ } else if (req.query.alphabet) {
+ query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
+ } else {
+ query.limit(12);
+ }
+ query.exec(function(err, shows) {
+ if (err) return next(err);
+ res.send(shows);
+ });
+});
+
+
+app.get('/api/shows/:id', function(req, res, next) {
+ Show.findById(req.params.id, function(err, show) {
+ if (err) return next(err);
+ res.send(show);
+ });
+});
+
+// Add TV Show routes with API keys
+
+app.post('/api/shows', function(req, res, next) {
+ var apiKey = '9EF1D1E7D28FDA0B';
+ var parser = xml2js.Parser({
+ explicitArray: false,
+ normalizeTags: true
+ });
+ var seriesName = req.body.showName
+ .toLowerCase()
+ .replace(/ /g, '_')
+ .replace(/[^\w-]+/g, '');
+
+ async.waterfall([
+ function(callback) {
+ request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + seriesName, function(error, response, body) {
+ if (error) return next(error);
+ parser.parseString(body, function(err, result) {
+ if (!result.data.series) {
+ return res.send(404, { message: req.body.showName + ' was not found.' });
+ }
+ var seriesId = result.data.series.seriesid || result.data.series[0].seriesid;
+ callback(err, seriesId);
+ });
+ });
+ },
+ function(seriesId, callback) {
+ request.get('http://thetvdb.com/api/' + apiKey + '/series/' + seriesId + '/all/en.xml', function(error, response, body) {
+ if (error) return next(error);
+ parser.parseString(body, function(err, result) {
+ var series = result.data.series;
+ var episodes = result.data.episode;
+ var show = new Show({
+ _id: series.id,
+ name: series.seriesname,
+ airsDayOfWeek: series.airs_dayofweek,
+ airsTime: series.airs_time,
+ firstAired: series.firstaired,
+ genre: series.genre.split('|').filter(Boolean),
+ network: series.network,
+ overview: series.overview,
+ rating: series.rating,
+ ratingCount: series.ratingcount,
+ runtime: series.runtime,
+ status: series.status,
+ poster: series.poster,
+ episodes: []
+ });
+ _.each(episodes, function(episode) {
+ show.episodes.push({
+ season: episode.seasonnumber,
+ episodeNumber: episode.episodenumber,
+ episodeName: episode.episodename,
+ firstAired: episode.firstaired,
+ overview: episode.overview
+ });
+ });
+ callback(err, show);
+ });
+ });
+ },
+ function(show, callback) {
+ var url = 'http://thetvdb.com/banners/' + show.poster;
+ request({ url: url, encoding: null }, function(error, response, body) {
+ show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
+ callback(error, show);
+ });
+ }
+ ], function(err, show) {
+ if (err) return next(err);
+ show.save(function(err) {
+ if (err) {
+ if (err.code == 11000) {
+ return res.send(409, { message: show.name + ' already exists.' });
+ }
+ return next(err);
+ }
+ res.send(200);
+ });
+ });
+});
+
+
+// A route redirect
+app.get('*', function(req, res) {
+ res.redirect('/#' + req.originalUrl);
+});
+
+// Error middleware to return JSON message to console
+
+app.use(function(err, req, res, next) {
+ console.error(err.stack);
+ res.send(500, { message: err.message });
+});
+
+
+
+
+
+
+
+app.listen(app.get('port'), function() {
+ console.log('Express server listening on port ' + app.get('port'));
+});
diff --git a/pool/shard000/JavaScript/0002472_test_access_level_flag.js b/pool/shard000/JavaScript/0002472_test_access_level_flag.js
new file mode 100644
index 0000000000000000000000000000000000000000..e80c7e2b2248d62f73bf07b2772ad93ad0b50ef9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002472_test_access_level_flag.js
@@ -0,0 +1,83 @@
+const path = require("path");
+const should = require("should");
+const { assert } = require("node-opcua-assert");
+const { BinaryStream } = require("node-opcua-binary-stream");
+const { findBuiltInType } = require("node-opcua-factory");
+
+const {
+ convertAccessLevelFlagToByte,
+ AccessLevelFlag,
+ makeAccessLevelFlag,
+ accessLevelFlagToString,
+ randomAccessLevel,
+ encodeAccessLevelFlag,
+ decodeAccessLevelFlag
+} = require("..");
+
+describe("Testing AccessLevelFlag", function () {
+ it("should create a access level flags from a string", function () {
+ makeAccessLevelFlag("CurrentRead").should.equal(0x01);
+ makeAccessLevelFlag("CurrentWrite").should.equal(0x02);
+ makeAccessLevelFlag("CurrentRead | CurrentWrite").should.equal(0x03);
+ makeAccessLevelFlag("CurrentWrite | CurrentRead").should.equal(0x03);
+
+ AccessLevelFlag[0x1].should.eql("CurrentRead");
+ AccessLevelFlag[0x2].should.eql("CurrentWrite");
+ // todo AccessLevelFlag[0x3].should.eql("CurrentRead | CurrentWrite");
+
+ makeAccessLevelFlag(makeAccessLevelFlag("CurrentRead")).should.equal(0x01);
+ });
+
+ it("should create a flag with no bit set", function () {
+ const accessLevel = makeAccessLevelFlag("");
+ accessLevel.should.eql(AccessLevelFlag.NONE);
+ (accessLevel & AccessLevelFlag.CurrentRead).should.eql(0);
+ (accessLevel & AccessLevelFlag.CurrentWrite).should.eql(0);
+ });
+ it("should create a flag with no bit set -> 0", function () {
+ const accessLevel = makeAccessLevelFlag(0);
+ accessLevel.should.eql(AccessLevelFlag.NONE);
+ (accessLevel & AccessLevelFlag.CurrentRead).should.eql(0);
+ (accessLevel & AccessLevelFlag.CurrentWrite).should.eql(0);
+ });
+ it("should have a accessLevel Flag Basic Type", function () {
+ (findBuiltInType("AccessLevelFlag") !== null && typeof findBuiltInType("AccessLevelFlag") === "object").should.equal(true);
+ });
+
+ it("should provide a easy way to check if a flag is set or not", function () {
+ const accessLevel = makeAccessLevelFlag("CurrentWrite | CurrentRead");
+ (accessLevel & AccessLevelFlag.CurrentWrite).should.be.eql(AccessLevelFlag.CurrentWrite);
+ (accessLevel & AccessLevelFlag.CurrentRead).should.be.eql(AccessLevelFlag.CurrentRead);
+ (accessLevel & AccessLevelFlag.HistoryRead).should.be.eql(0);
+ });
+
+ it("convertAccessLevelFlagToByte", () => {
+ convertAccessLevelFlagToByte(AccessLevelFlag.CurrentRead).should.eql(1);
+ convertAccessLevelFlagToByte(AccessLevelFlag.CurrentRead | AccessLevelFlag.CurrentWrite).should.eql(3);
+ });
+ it("accessLevelFlagToString", () => {
+ accessLevelFlagToString(AccessLevelFlag.HistoryRead).should.eql("HistoryRead");
+ accessLevelFlagToString(AccessLevelFlag.HistoryRead | AccessLevelFlag.CurrentRead).should.eql("CurrentRead | HistoryRead");
+ accessLevelFlagToString(0x3f | AccessLevelFlag.TimestampWrite).should.eql(
+ "CurrentRead | CurrentWrite | StatusWrite | TimestampWrite | HistoryRead | HistoryWrite | SemanticChange"
+ );
+ accessLevelFlagToString(0).should.eql("None");
+ });
+ it("randomAccessLevel", () => {
+ const flag = randomAccessLevel();
+ const str = accessLevelFlagToString(flag);
+ const checked = makeAccessLevelFlag(str);
+ checked.should.eql(flag);
+ });
+
+ it("encode/decode", () => {
+ const stream = new BinaryStream();
+ const flag = randomAccessLevel();
+
+ encodeAccessLevelFlag(flag, stream);
+
+ stream.rewind();
+ const verify = decodeAccessLevelFlag(stream);
+ verify.should.eql(flag);
+ });
+});
diff --git a/pool/shard000/JavaScript/0002473_createMuiTheme.test.js b/pool/shard000/JavaScript/0002473_createMuiTheme.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..df758ca208ff1494dba574aca614190fd36fe57c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002473_createMuiTheme.test.js
@@ -0,0 +1,116 @@
+import { assert } from 'chai';
+import createMuiTheme from './createMuiTheme';
+import { deepOrange, green } from '../colors';
+import consoleErrorMock from 'test/utils/consoleErrorMock';
+
+describe('createMuiTheme', () => {
+ it('should have a palette', () => {
+ const muiTheme = createMuiTheme();
+ assert.strictEqual(typeof createMuiTheme, 'function');
+ assert.strictEqual(typeof muiTheme.palette, 'object');
+ });
+
+ it('should have the custom palette', () => {
+ const muiTheme = createMuiTheme({
+ palette: { primary: { main: deepOrange[500] }, secondary: { main: green.A400 } },
+ });
+ assert.strictEqual(muiTheme.palette.primary.main, deepOrange[500]);
+ assert.strictEqual(muiTheme.palette.secondary.main, green.A400);
+ });
+
+ it('should allow providing a partial structure', () => {
+ const muiTheme = createMuiTheme({ transitions: { duration: { shortest: 150 } } });
+ assert.notStrictEqual(muiTheme.transitions.duration.shorter, undefined);
+ });
+
+ it('should use the defined spacing unit for the gutters mixin', () => {
+ const unit = 100;
+ const muiTheme = createMuiTheme({ spacing: { unit } });
+ assert.strictEqual(muiTheme.mixins.gutters().paddingLeft, unit * 2);
+ });
+
+ describe('shadows', () => {
+ it('should provide the default array', () => {
+ const muiTheme = createMuiTheme();
+ assert.strictEqual(
+ muiTheme.shadows[2],
+ '0px 1px 5px 0px rgba(0,0,0,0.2),' +
+ '0px 2px 2px 0px rgba(0,0,0,0.14),0px 3px 1px -2px rgba(0,0,0,0.12)',
+ );
+ });
+
+ it('should override the array as expected', () => {
+ const shadows = [
+ 'none',
+ 1,
+ 1,
+ 1,
+ 2,
+ 3,
+ 3,
+ 4,
+ 5,
+ 5,
+ 6,
+ 6,
+ 7,
+ 7,
+ 7,
+ 8,
+ 8,
+ 8,
+ 9,
+ 9,
+ 10,
+ 10,
+ 10,
+ 11,
+ 11,
+ ];
+ const muiTheme = createMuiTheme({ shadows });
+ assert.strictEqual(muiTheme.shadows, shadows);
+ });
+ });
+
+ describe('props', () => {
+ it('should have the props as expected', () => {
+ const props = {
+ MuiDialog: {
+ fullScreen: true,
+ fullWidth: false,
+ },
+ MuiButtonBase: {
+ disableRipple: true,
+ },
+ MuiPopover: {
+ container: document.createElement('div'),
+ },
+ };
+ const muiTheme = createMuiTheme({ props });
+ assert.deepEqual(muiTheme.props, props);
+ });
+ });
+
+ describe('overrides', () => {
+ beforeEach(() => {
+ consoleErrorMock.spy();
+ });
+
+ afterEach(() => {
+ consoleErrorMock.reset();
+ });
+
+ it('should warn when trying to override an internal state the wrong way', () => {
+ createMuiTheme({ overrides: { Button: { disabled: { color: 'blue' } } } });
+ assert.strictEqual(consoleErrorMock.args().length, 0);
+ createMuiTheme({ overrides: { MuiButton: { root: { color: 'blue' } } } });
+ assert.strictEqual(consoleErrorMock.args().length, 0);
+ createMuiTheme({ overrides: { MuiButton: { disabled: { color: 'blue' } } } });
+ assert.strictEqual(consoleErrorMock.args().length, 1);
+ assert.match(
+ consoleErrorMock.args()[0][0],
+ /the `MuiButton` component increases the CSS specificity of the `disabled` internal state./,
+ );
+ });
+ });
+});
diff --git a/pool/shard000/JavaScript/0002476_productCategory.js b/pool/shard000/JavaScript/0002476_productCategory.js
new file mode 100644
index 0000000000000000000000000000000000000000..bc9577eb54743e1b1a7fc6606d9027061569641f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002476_productCategory.js
@@ -0,0 +1,21 @@
+const Sequelize = require('sequelize');
+const db = require('APP/db');
+
+const ProductCategory = db.define('productCategory', {
+ name: Sequelize.STRING,
+ description: Sequelize.TEXT,
+ imageUrl: Sequelize.STRING
+}, {
+ hooks: {
+ beforeValidate: function(category) {
+ //made assumption about file location, name, type
+ let fileName = category.name
+ .toLowerCase()
+ .split(' ')
+ .join('-');
+ category.imageUrl = `/img/${fileName}.jpg`;
+ }
+ }
+})
+
+module.exports = ProductCategory
diff --git a/pool/shard000/JavaScript/0002477_ext-code_lens.js b/pool/shard000/JavaScript/0002477_ext-code_lens.js
new file mode 100644
index 0000000000000000000000000000000000000000..604de4b1d0cba3bae97556e2d8e0c73ef76ce308
--- /dev/null
+++ b/pool/shard000/JavaScript/0002477_ext-code_lens.js
@@ -0,0 +1,248 @@
+define("ace/ext/code_lens", ["require", "exports", "module", "ace/line_widgets", "ace/lib/event", "ace/lib/lang", "ace/lib/dom", "ace/editor", "ace/config"], function(require, exports, module) {
+ "use strict";
+ var LineWidgets = require("../line_widgets").LineWidgets;
+ var event = require("../lib/event");
+ var lang = require("../lib/lang");
+ var dom = require("../lib/dom");
+
+ function clearLensElements(renderer) {
+ var textLayer = renderer.$textLayer;
+ var lensElements = textLayer.$lenses;
+ if (lensElements)
+ lensElements.forEach(function(el) {
+ el.remove();
+ });
+ textLayer.$lenses = null;
+ }
+
+ function renderWidgets(changes, renderer) {
+ var changed = changes & renderer.CHANGE_LINES ||
+ changes & renderer.CHANGE_FULL ||
+ changes & renderer.CHANGE_SCROLL ||
+ changes & renderer.CHANGE_TEXT;
+ if (!changed)
+ return;
+
+ var session = renderer.session;
+ var lineWidgets = renderer.session.lineWidgets;
+ var textLayer = renderer.$textLayer;
+ var lensElements = textLayer.$lenses;
+ if (!lineWidgets) {
+ if (lensElements)
+ clearLensElements(renderer);
+ return;
+ }
+
+ var textCells = renderer.$textLayer.$lines.cells;
+ var config = renderer.layerConfig;
+ var padding = renderer.$padding;
+
+ if (!lensElements)
+ lensElements = textLayer.$lenses = [];
+
+
+ var index = 0;
+ for (var i = 0; i < textCells.length; i++) {
+ var row = textCells[i].row;
+ var widget = lineWidgets[row];
+ var lenses = widget && widget.lenses;
+
+ if (!lenses || !lenses.length) continue;
+
+ var lensContainer = lensElements[index];
+ if (!lensContainer) {
+ lensContainer = lensElements[index] = dom.buildDom(["div", {
+ class: "ace_codeLens"
+ }], renderer.container);
+ }
+ lensContainer.style.height = config.lineHeight + "px";
+ index++;
+
+ for (var j = 0; j < lenses.length; j++) {
+ var el = lensContainer.childNodes[2 * j];
+ if (!el) {
+ if (j != 0) lensContainer.appendChild(dom.createTextNode("\xa0|\xa0"));
+ el = dom.buildDom(["a"], lensContainer);
+ }
+ el.textContent = lenses[j].title;
+ el.lensCommand = lenses[j];
+ }
+ while (lensContainer.childNodes.length > 2 * j - 1)
+ lensContainer.lastChild.remove();
+
+ var top = renderer.$cursorLayer.getPixelPosition({
+ row: row,
+ column: 0
+ }, true).top - config.lineHeight * widget.rowsAbove - config.offset;
+ lensContainer.style.top = top + "px";
+
+ var left = renderer.gutterWidth;
+ var indent = session.getLine(row).search(/\S|$/);
+ if (indent == -1)
+ indent = 0;
+ left += indent * config.characterWidth;
+ left -= renderer.scrollLeft;
+ lensContainer.style.paddingLeft = padding + left + "px";
+ }
+ while (index < lensElements.length)
+ lensElements.pop().remove();
+ }
+
+ function clearCodeLensWidgets(session) {
+ if (!session.lineWidgets) return;
+ var widgetManager = session.widgetManager;
+ session.lineWidgets.forEach(function(widget) {
+ if (widget && widget.lenses)
+ widgetManager.removeLineWidget(widget);
+ });
+ }
+
+ exports.setLenses = function(session, lenses) {
+ var firstRow = Number.MAX_VALUE;
+
+ clearCodeLensWidgets(session);
+ lenses && lenses.forEach(function(lens) {
+ var row = lens.start.row;
+ var column = lens.start.column;
+ var widget = session.lineWidgets && session.lineWidgets[row];
+ if (!widget || !widget.lenses) {
+ widget = session.widgetManager.$registerLineWidget({
+ rowCount: 1,
+ rowsAbove: 1,
+ row: row,
+ column: column,
+ lenses: []
+ });
+ }
+ widget.lenses.push(lens.command);
+ if (row < firstRow)
+ firstRow = row;
+ });
+ session._emit("changeFold", {
+ data: {
+ start: {
+ row: firstRow
+ }
+ }
+ });
+ };
+
+ function attachToEditor(editor) {
+ editor.codeLensProviders = [];
+ editor.renderer.on("afterRender", renderWidgets);
+ if (!editor.$codeLensClickHandler) {
+ editor.$codeLensClickHandler = function(e) {
+ var command = e.target.lensCommand;
+ if (command)
+ editor.execCommand(command.id, command.arguments);
+ };
+ event.addListener(editor.container, "click", editor.$codeLensClickHandler, editor);
+ }
+ editor.$updateLenses = function() {
+ var session = editor.session;
+ if (!session) return;
+
+ if (!session.widgetManager) {
+ session.widgetManager = new LineWidgets(session);
+ session.widgetManager.attach(editor);
+ }
+
+ var providersToWaitNum = editor.codeLensProviders.length;
+ var lenses = [];
+ editor.codeLensProviders.forEach(function(provider) {
+ provider.provideCodeLenses(session, function(err, payload) {
+ if (err) return;
+ payload.forEach(function(lens) {
+ lenses.push(lens);
+ });
+ providersToWaitNum--;
+ if (providersToWaitNum == 0) {
+ applyLenses();
+ }
+ });
+ });
+
+ function applyLenses() {
+ var cursor = session.selection.cursor;
+ var oldRow = session.documentToScreenRow(cursor);
+ exports.setLenses(session, lenses);
+
+ var lastDelta = session.$undoManager && session.$undoManager.$lastDelta;
+ if (lastDelta && lastDelta.action == "remove" && lastDelta.lines.length > 1)
+ return;
+ var row = session.documentToScreenRow(cursor);
+ var lineHeight = editor.renderer.layerConfig.lineHeight;
+ var top = session.getScrollTop() + (row - oldRow) * lineHeight;
+ session.setScrollTop(top);
+ }
+ };
+ var updateLenses = lang.delayedCall(editor.$updateLenses);
+ editor.$updateLensesOnInput = function() {
+ updateLenses.delay(250);
+ };
+ editor.on("input", editor.$updateLensesOnInput);
+ }
+
+ function detachFromEditor(editor) {
+ editor.off("input", editor.$updateLensesOnInput);
+ editor.renderer.off("afterRender", renderWidgets);
+ if (editor.$codeLensClickHandler)
+ editor.container.removeEventListener("click", editor.$codeLensClickHandler);
+ }
+
+ exports.registerCodeLensProvider = function(editor, codeLensProvider) {
+ editor.setOption("enableCodeLens", true);
+ editor.codeLensProviders.push(codeLensProvider);
+ editor.$updateLensesOnInput();
+ };
+
+ exports.clear = function(session) {
+ exports.setLenses(session, null);
+ };
+
+ var Editor = require("../editor").Editor;
+ require("../config").defineOptions(Editor.prototype, "editor", {
+ enableCodeLens: {
+ set: function(val) {
+ if (val) {
+ attachToEditor(this);
+ }
+ else {
+ detachFromEditor(this);
+ }
+ }
+ }
+ });
+
+ dom.importCssString("\
+.ace_codeLens {\
+ position: absolute;\
+ color: #aaa;\
+ font-size: 88%;\
+ background: inherit;\
+ width: 100%;\
+ display: flex;\
+ align-items: flex-end;\
+ pointer-events: none;\
+}\
+.ace_codeLens > a {\
+ cursor: pointer;\
+ pointer-events: auto;\
+}\
+.ace_codeLens > a:hover {\
+ color: #0000ff;\
+ text-decoration: underline;\
+}\
+.ace_dark > .ace_codeLens > a:hover {\
+ color: #4e94ce;\
+}\
+", "");
+
+});
+(function() {
+ window.require(["ace/ext/code_lens"], function(m) {
+ if (typeof module == "object" && typeof exports == "object" && module) {
+ module.exports = m;
+ }
+ });
+})();
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002478_Space.js b/pool/shard000/JavaScript/0002478_Space.js
new file mode 100644
index 0000000000000000000000000000000000000000..35fcac770057fa5422f816eb14ae45619489c2b2
--- /dev/null
+++ b/pool/shard000/JavaScript/0002478_Space.js
@@ -0,0 +1,49 @@
+ka.DashboardWidgets.Space = new Class({
+ Extends: ka.DashboardWidgets.Base,
+
+ streamPath: 'admin/space',
+
+ gauges: [],
+
+ create: function () {
+ this.header = new Element('h3', {
+ text: ka.tc('dashboardWidget.space', 'Space')
+ })
+ .inject(this.main);
+
+ this.load = new Element('div', {
+ style: 'padding: 5px; text-align: center',
+ text: ' '
+ }).inject(this.main);
+
+ },
+
+ update: function (value) {
+ if (0 === this.gauges.length) {
+ this.toElement().addClass('ka-Dashboard-widget-grid-' + value.length);
+
+ Array.each(value, function (space, id) {
+ this.gauges.push(
+ new ka.ui.Speedmeter(this.main, {
+ title: 'HDD ' + space.name,
+ label: 'GB',
+ max: (space.size / 1024 / 1024).toFixed(0),
+ value: (space.used / 1024 / 1024).toFixed(0)
+ })
+ )
+ }.bind(this));
+ }
+
+ var total = 0;
+ var used = 0;
+ Array.each(value, function (space, id) {
+ this.gauges[id].setValue((space.used / 1024 / 1024).toFixed(0));
+ total += space.size;
+ used += space.used;
+ }.bind(this));
+
+ this.load.set('text',
+ tf('Total %s / %s', ka.bytesToSize(used * 1024), ka.bytesToSize(total * 1024))
+ );
+ }
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002480_icl_translate_editor.js b/pool/shard000/JavaScript/0002480_icl_translate_editor.js
new file mode 100644
index 0000000000000000000000000000000000000000..4181c6b5e0b94e4c523f56eeb39c744af3615796
--- /dev/null
+++ b/pool/shard000/JavaScript/0002480_icl_translate_editor.js
@@ -0,0 +1,104 @@
+// $Id: icl_translate_editor.js,v 1.1 2010/06/30 08:22:07 brucepearson Exp $
+
+$(document).ready(function() {
+
+ // Bind focus to fields
+ // Show/hide original content
+ $('textarea, input[id^=edit-field-data-translated]').bind('focus', function() {
+ var hide = $(this).parents('fieldset').find('.original_data');
+ if (hide.is(':hidden')) {
+ $('.original_data:visible').slideUp();
+ hide.slideDown();
+ }
+ });
+
+ // Check if all translated
+ // Focus to first untranslated field
+ iclTranslateEditorCheckFinished();
+
+ // Sets autosave interval
+ iclAjaxAutoSave('#icl-translate-editor', 60000); // 60 sec.
+
+ // Binds click to 'finished'
+ // Submits AJAX autosave
+ // Focuses and scrolls to next/first untranslated field
+ $('#icl-translate-editor .finished').click(function() {
+ iclAjaxSubmit('#icl-translate-editor');
+
+ // If unchecked focus to it's field
+ if ($(this).is(':checked') == false) {
+ $(this).parents('fieldset').find('[id^=edit-field-data-translated]').focus();
+ $('#edit-action').attr('disabled', 1);
+ // Else find next field
+ } else {
+ var fieldset = $(this).parents('fieldset').next('fieldset');
+ var finished = fieldset.find('.finished');
+
+ // If next fieldset not found check all/find first untranslated field
+ if (finished.length == 0) {
+ iclTranslateEditorCheckFinished();
+ }
+ // If next not marked as translated focus
+ else if (finished.is(':checked') == false) {
+ iclTranslateFocus(fieldset.find('[id^=edit-field-data-translated]'));
+ $('#edit-action').attr('disabled', 1);
+ // Check other fields
+ } else {
+ iclTranslateEditorCheckFinished();
+ }
+ }
+ });
+
+
+
+ // Replaces translated conent with autosaved content
+ $('.icl_translate_editor_load_autosave').click(function() {
+ var toLoad = $(this).children('div');
+ var toLoadData = toLoad.html();
+ var toReplace = $(this).parent().children().find('[id^=edit-field-data-translated]');
+ var toReplaceData = toReplace.val();
+ toReplace.val('...');
+ var timerCallback = function() {
+ toReplace.val(toLoadData);
+ toLoad.html(toReplaceData);
+ };
+ setTimeout(timerCallback, 200);
+ });
+
+ // Disable format change
+ $('[id^=edit-body-field-data-translated-format]').find('input').each(function() {
+ $(this).attr('disabled', 'disabled');
+ $(this).unbind('click');
+ if ($(this).is(':checked') == false) {
+ $(this).parent().parent().css('display','none');
+ }
+ }
+ );
+
+});
+
+ /**
+ * Checks if all translations are finished
+ * Enables submit button
+ * Focuses/scrolls to first untranslated field
+ */
+function iclTranslateEditorCheckFinished() {
+ $('#icl-translate-editor .finished').each(function(e) {
+ if ($(this).is(':checked') == false) {
+ $('#edit-action').attr('disabled', 1);
+ iclTranslateFocus($(this).parents('fieldset').find('[id^=edit-field-data-translated]'));
+ return false;
+ } else {
+ $('#edit-action').attr('disabled', 0);
+ }
+ });
+}
+
+/**
+ * Focuses and scrolls to field
+ */
+function iclTranslateFocus(focusTo) {
+ var x = focusTo.offset().top - 100; // 100 provides buffer in viewport
+ $('html,body').animate({scrollTop: x}, 500);
+ focusTo.focus();
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002487_index.js b/pool/shard000/JavaScript/0002487_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..30b027dff16147410cbfd749daba54aec6df2b21
--- /dev/null
+++ b/pool/shard000/JavaScript/0002487_index.js
@@ -0,0 +1,34 @@
+"use strict";
+
+var util = require('util');
+var through = require('through');
+var path = require('path');
+
+function strictify(file, opts) {
+ opts = opts || {};
+ opts.exclude = ['json'].concat(opts.exclude||[]);
+
+ var stream = through(write, end);
+ var applied = false;
+
+ var filetype = path.extname(file).replace('.', '');
+ var excluded = (opts.exclude).some(function (excludedExt) {
+ return filetype == excludedExt.replace('.', '');
+ });
+
+ return stream;
+
+ function write(buf) {
+ if (!applied && !excluded) {
+ stream.queue('"use strict";\n');
+ applied = true;
+ }
+ stream.queue(buf);
+ }
+
+ function end() {
+ stream.queue(null);
+ }
+}
+
+module.exports = strictify;
diff --git a/pool/shard000/JavaScript/0002492_schemalistitem.spec.js b/pool/shard000/JavaScript/0002492_schemalistitem.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..9e797042a3adcabf60658531231b8d0e4d0cad78
--- /dev/null
+++ b/pool/shard000/JavaScript/0002492_schemalistitem.spec.js
@@ -0,0 +1,41 @@
+'use strict';
+
+describe('Directive: schemaListItem', function () {
+
+ // load the directive's module
+ beforeEach(module('polestar', function($provide) {
+ // mock vega
+ $provide.constant('vg', {
+ parse: {
+ spec: function(spec, callback) {
+ callback(function(opt) {
+
+ return {
+ width: function() {},
+ height: function() {},
+ update: function() {},
+ renderer: function() {},
+ on: function() {}
+ };
+ });
+ }
+ }
+ });
+ $provide.constant('vl', vl);
+ }));
+
+
+ var element,
+ scope;
+
+ beforeEach(inject(function ($rootScope) {
+ scope = $rootScope.$new();
+ }));
+
+ it('should make hidden element visible', inject(function ($compile) {
+ element = angular.element(' ');
+ element = $compile(element)(scope);
+ scope.$digest();
+ expect(element.find('span.field-info').length).toBe(1);
+ }));
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002493_RatingIcon.js b/pool/shard000/JavaScript/0002493_RatingIcon.js
new file mode 100644
index 0000000000000000000000000000000000000000..b8285bda736c96a45898676580662f21322b4b77
--- /dev/null
+++ b/pool/shard000/JavaScript/0002493_RatingIcon.js
@@ -0,0 +1,135 @@
+import _extends from 'babel-runtime/helpers/extends';
+import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
+import _createClass from 'babel-runtime/helpers/createClass';
+import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
+import _inherits from 'babel-runtime/helpers/inherits';
+import cx from 'classnames';
+import PropTypes from 'prop-types';
+import React, { Component } from 'react';
+
+import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, keyboardKey } from '../../lib';
+
+/**
+ * An internal icon sub-component for Rating component
+ */
+
+var RatingIcon = function (_Component) {
+ _inherits(RatingIcon, _Component);
+
+ function RatingIcon() {
+ var _ref;
+
+ var _temp, _this, _ret;
+
+ _classCallCheck(this, RatingIcon);
+
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = RatingIcon.__proto__ || Object.getPrototypeOf(RatingIcon)).call.apply(_ref, [this].concat(args))), _this), _this.defaultProps = {
+ as: 'i'
+ }, _this.handleClick = function (e) {
+ var onClick = _this.props.onClick;
+
+
+ if (onClick) onClick(e, _this.props);
+ }, _this.handleKeyUp = function (e) {
+ var _this$props = _this.props,
+ onClick = _this$props.onClick,
+ onKeyUp = _this$props.onKeyUp;
+
+
+ if (onKeyUp) onKeyUp(e, _this.props);
+
+ if (onClick) {
+ switch (keyboardKey.getCode(e)) {
+ case keyboardKey.Enter:
+ case keyboardKey.Spacebar:
+ e.preventDefault();
+ onClick(e, _this.props);
+ break;
+ default:
+ }
+ }
+ }, _this.handleMouseEnter = function (e) {
+ var onMouseEnter = _this.props.onMouseEnter;
+
+
+ if (onMouseEnter) onMouseEnter(e, _this.props);
+ }, _temp), _possibleConstructorReturn(_this, _ret);
+ }
+
+ _createClass(RatingIcon, [{
+ key: 'render',
+ value: function render() {
+ var _props = this.props,
+ active = _props.active,
+ className = _props.className,
+ selected = _props.selected;
+
+ var classes = cx(useKeyOnly(active, 'active'), useKeyOnly(selected, 'selected'), 'icon', className);
+ var rest = getUnhandledProps(RatingIcon, this.props);
+ var ElementType = getElementType(RatingIcon, this.props);
+
+ return React.createElement(ElementType, _extends({}, rest, {
+ className: classes,
+ onClick: this.handleClick,
+ onKeyUp: this.handleKeyUp,
+ onMouseEnter: this.handleMouseEnter,
+ tabIndex: 0,
+ role: 'radio'
+ }));
+ }
+ }]);
+
+ return RatingIcon;
+}(Component);
+
+RatingIcon._meta = {
+ name: 'RatingIcon',
+ parent: 'Rating',
+ type: META.TYPES.MODULE
+};
+RatingIcon.handledProps = ['active', 'as', 'className', 'index', 'onClick', 'onKeyUp', 'onMouseEnter', 'selected'];
+export default RatingIcon;
+RatingIcon.propTypes = process.env.NODE_ENV !== "production" ? {
+ /** An element type to render as (string or function). */
+ as: customPropTypes.as,
+
+ /** Indicates activity of an icon. */
+ active: PropTypes.bool,
+
+ /** Additional classes. */
+ className: PropTypes.string,
+
+ /** An index of icon inside Rating. */
+ index: PropTypes.number,
+
+ /**
+ * Called on click.
+ *
+ * @param {SyntheticEvent} event - React's original SyntheticEvent.
+ * @param {object} data - All props.
+ */
+ onClick: PropTypes.func,
+
+ /**
+ * Called on keyup.
+ *
+ * @param {SyntheticEvent} event - React's original SyntheticEvent.
+ * @param {object} data - All props.
+ */
+ onKeyUp: PropTypes.func,
+
+ /**
+ * Called on mouseenter.
+ *
+ * @param {SyntheticEvent} event - React's original SyntheticEvent.
+ * @param {object} data - All props.
+ */
+ onMouseEnter: PropTypes.func,
+
+ /** Indicates selection of an icon. */
+ selected: PropTypes.bool
+} : {};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002494_productList.js b/pool/shard000/JavaScript/0002494_productList.js
new file mode 100644
index 0000000000000000000000000000000000000000..1747b58f8ddb0e079fa99d8f2d456d1514e52326
--- /dev/null
+++ b/pool/shard000/JavaScript/0002494_productList.js
@@ -0,0 +1,54 @@
+/**
+ * Created by hxsd on 2016/6/1.
+ */
+// 注册一个控制器
+angular.module("myapp")
+ .constant("activeClass", "btn-primary") // 定义一个常量
+ .constant("pageCount",3) // 页面大小
+ // 依赖注入外部的常量
+ .controller("productListCtrl", function ($scope, activeClass,pageCount) {
+ var selectedCategory = null; // 保存当前的商品类别
+
+ // 当单击类别按钮时
+ $scope.selectCategory = function (categoryName) {
+ selectedCategory = categoryName; // 保存传过来的被单击的那个类别的名称
+ $scope.currentPage = 1; // 恢复当前页码为默认1
+ //alert(selectedCategory);
+ };
+
+ // 自定义一个过滤器函数 - 返回true或false
+ // 函数的参数,是filter过滤的数组元素
+ $scope.categoryFilter = function (item) {
+ return selectedCategory == null || selectedCategory == item.category;
+ //if(selectedCategory == null){
+ // // 说明选择的是"首页"按钮
+ // return true;
+ //}else if(selectedCategory == item.category){
+ // // 如果当前选中的类别和当前正在过滤判断的商品的类别一致
+ // return true; // 让这个商品显示
+ //}else{
+ // return false;
+ //}
+ };
+
+ // 自定义一个函数: 返回一个合适的class名称
+ $scope.activeClass = function (categoryName) {
+ // 如果当前的类别是被选中的类别,就返回"btn-primary";否则,返回""
+ //return selectedCategory == categoryName ? "btn-primary" : "";
+ return selectedCategory == categoryName ? activeClass : "";
+ };
+
+ // 定义用于分页的变量
+ $scope.currentPage = 1; // 当前页码
+ $scope.pageSize = pageCount; // 每页显示商品的数量(页面大小)
+
+ // 分页按钮单击响应事件,参数为当前要求显示的页码数
+ $scope.selectPage = function(page){
+ $scope.currentPage = page; // 将当前页面改为传过来要显示的页面
+ };
+
+ // 高亮显示 - 获取active class,参数为页码数
+ $scope.activePageClass = function(page){
+ return $scope.currentPage == page ? activeClass : "";
+ };
+ });
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002495_index.js b/pool/shard000/JavaScript/0002495_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..1cf3b15d9830231e15374caccc33cc8df98606ab
--- /dev/null
+++ b/pool/shard000/JavaScript/0002495_index.js
@@ -0,0 +1,17 @@
+require('dotenv').load({ silent: true });
+
+const http = require('http');
+
+require('./lib/geoip-service');
+
+const server = http.createServer((request, response) => {
+ response.writeHead(200, { 'Content-Type': 'text/plain' });
+ response.write('1');
+ response.end();
+});
+
+server.listen((process.env.PORT || 3000), () => {
+ const msg = `${process.env.AMQP_QUEUE}${process.env.LOCAL_QUEUE || ''} \
+service can be healthchecked on port ${process.env.PORT || 3000}`;
+ console.log(msg); // eslint-disable-line no-console
+});
diff --git a/pool/shard000/JavaScript/0002496_handleEventDispatch.js b/pool/shard000/JavaScript/0002496_handleEventDispatch.js
new file mode 100644
index 0000000000000000000000000000000000000000..1f001f283ceb433495578058bcde3f3bfea119de
--- /dev/null
+++ b/pool/shard000/JavaScript/0002496_handleEventDispatch.js
@@ -0,0 +1,56 @@
+var virt = require("@nathanfaucett/virt"),
+ isNullOrUndefined = require("@nathanfaucett/is_null_or_undefined"),
+ getNodeById = require("../utils/getNodeById");
+
+
+var traverseAncestors = virt.traverseAncestors;
+
+
+module.exports = handleEventDispatch;
+
+
+function handleEventDispatch(childHash, events, topLevelType, targetId, event) {
+ var target = childHash[targetId],
+ eventType = events[topLevelType],
+ global, ret, i, il;
+
+ if (eventType) {
+ global = eventType.global;
+
+ if (target) {
+ target = target.component;
+ } else {
+ target = null;
+ }
+
+ if (global) {
+ i = -1;
+ il = global.length - 1;
+ event.currentTarget = event.componentTarget = event.currentComponentTarget = target;
+ while (i++ < il && ret !== false) {
+ ret = global[i](event);
+ if (!isNullOrUndefined(ret)) {
+ ret = event.returnValue;
+ }
+ }
+ }
+
+ traverseAncestors(targetId, function traverseAncestor(currentTargetId) {
+ var ret;
+
+ if (eventType[currentTargetId]) {
+ event.currentTarget = getNodeById(currentTargetId);
+ event.componentTarget = target;
+ event.currentComponentTarget = childHash[currentTargetId].component;
+ ret = eventType[currentTargetId](event);
+ return !isNullOrUndefined(ret) ? ret : event.returnValue;
+ } else {
+ return true;
+ }
+ });
+
+ if (event && event.isPersistent !== true) {
+ event.destroy();
+ }
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002497_ChangePasswordForm.js b/pool/shard000/JavaScript/0002497_ChangePasswordForm.js
new file mode 100644
index 0000000000000000000000000000000000000000..0a64c55695f3fbcf026d3c37089b07af6ba7d8f7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002497_ChangePasswordForm.js
@@ -0,0 +1,127 @@
+import PropTypes from 'prop-types';
+import React from 'react';
+import { Field, reduxForm } from 'redux-form';
+import { Row, Col } from 'react-flexbox-grid/lib';
+import { FormattedMessage } from 'react-intl';
+import AppButton from '../common/AppButton';
+import messages from '../../resources/messages';
+import { emptyString, passwordTooShort, stringsDoNotMatch } from '../../lib/formValidators';
+import withIntlForm from '../common/hocs/IntlForm';
+
+const localMessages = {
+ missingOldPassword: { id: 'user.missingOldPassword', defaultMessage: 'You need to enter your old password.' },
+ missingNewPassword: { id: 'user.missingNewPassword', defaultMessage: 'You need to enter a new password.' },
+ failed: { id: 'user.passwordChange.failed', defaultMessage: 'Sorry, something went wrong.' },
+};
+
+const ChangePasswordContainer = (props) => {
+ const { handleSubmit, onSubmit, pristine, submitting, renderTextField, titleMsg, buttonMsg, showOldPassword } = props;
+ const { formatMessage } = props.intl;
+ let oldPasswordContent = null;
+ if (showOldPassword) {
+ oldPasswordContent = (
+
+
+
+
+
+ );
+ }
+ return (
+
+ );
+};
+
+ChangePasswordContainer.propTypes = {
+ // from composition
+ intl: PropTypes.object.isRequired,
+ location: PropTypes.object,
+ redirect: PropTypes.string,
+ handleSubmit: PropTypes.func.isRequired,
+ renderTextField: PropTypes.func.isRequired,
+ pristine: PropTypes.bool.isRequired,
+ submitting: PropTypes.bool.isRequired,
+ // from parent
+ showOldPassword: PropTypes.bool,
+ titleMsg: PropTypes.object.isRequired,
+ buttonMsg: PropTypes.object.isRequired,
+ onSubmit: PropTypes.func.isRequired,
+};
+
+// in-browser validation callback
+function validate(values) {
+ const errors = {};
+ if (emptyString(values.old_password)) {
+ errors.old_password = localMessages.missingOldPassword;
+ }
+ if (passwordTooShort(values.old_password)) {
+ errors.old_password = messages.passwordTooShort;
+ }
+ if (emptyString(values.new_password)) {
+ errors.new_password = localMessages.missingNewPassword;
+ }
+ if (passwordTooShort(values.new_password)) {
+ errors.new_password = messages.passwordTooShort;
+ }
+ if (stringsDoNotMatch(values.new_password, values.confirm_password)) {
+ errors.confirm_password = messages.passwordsMismatch;
+ }
+ return errors;
+}
+
+const reduxFormConfig = {
+ form: 'change-password-form',
+ validate,
+};
+
+export default
+withIntlForm(
+ reduxForm(reduxFormConfig)(
+ ChangePasswordContainer
+ )
+);
diff --git a/pool/shard000/JavaScript/0002498_event-detail.client.controller.test.js b/pool/shard000/JavaScript/0002498_event-detail.client.controller.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..b714d960b71250d38b1c6798d43aed8444d79fe4
--- /dev/null
+++ b/pool/shard000/JavaScript/0002498_event-detail.client.controller.test.js
@@ -0,0 +1,58 @@
+'use strict';
+
+(function() {
+ // Event detail Controller Spec
+ describe('Event detail Controller Tests', function() {
+ // Initialize global variables
+ var EventDetailController,
+ scope,
+ $httpBackend,
+ $stateParams,
+ $location;
+
+ // The $resource service augments the response object with methods for updating and deleting the resource.
+ // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
+ // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
+ // When the toEqualData matcher compares two objects, it takes only object properties into
+ // account and ignores methods.
+ beforeEach(function() {
+ jasmine.addMatchers({
+ toEqualData: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ return {
+ pass: angular.equals(actual, expected)
+ };
+ }
+ };
+ }
+ });
+ });
+
+ // Then we can start by loading the main application module
+ beforeEach(module(ApplicationConfiguration.applicationModuleName));
+
+ // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
+ // This allows us to inject a service but then attach it to a variable
+ // with the same name as the service.
+ beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
+ // Set a new global scope
+ scope = $rootScope.$new();
+
+ // Point global variables to injected services
+ $stateParams = _$stateParams_;
+ $httpBackend = _$httpBackend_;
+ $location = _$location_;
+
+ // Initialize the Event detail controller.
+ EventDetailController = $controller('EventDetailController', {
+ $scope: scope
+ });
+ }));
+
+ it('Should do some controller test', inject(function() {
+ // The test logic
+ // ...
+ }));
+ });
+}());
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002499_amqp.js b/pool/shard000/JavaScript/0002499_amqp.js
new file mode 100644
index 0000000000000000000000000000000000000000..53dbecb16d5dd781e0903eed417b20d402673524
--- /dev/null
+++ b/pool/shard000/JavaScript/0002499_amqp.js
@@ -0,0 +1,25 @@
+var Promise = require('promise');
+var eve = require('../../index');
+var HelloAgent = require('./../agents/HelloAgent');
+
+// Configure eve
+// Example AMQP configurations:
+// {type: 'amqp', url: 'amqp://localhost'} or
+// {type: 'amqp', host: 'dev.rabbitmq.com'}
+eve.system.init({
+ transports: [
+ {
+ type: 'amqp',
+ host: 'localhost'
+ }
+ ]
+});
+
+// create two agents
+var agent1 = new HelloAgent('agent1');
+var agent2 = new HelloAgent('agent2');
+
+// once both agents are connected, send a message to agent1
+Promise.all([agent1.ready, agent2.ready]).then(function () {
+ agent2.send('agent1', 'Hello agent1!');
+});
diff --git a/pool/shard000/JavaScript/0002501_logger.js b/pool/shard000/JavaScript/0002501_logger.js
new file mode 100644
index 0000000000000000000000000000000000000000..132cb21ff927191342c8608e8d3698935ef5e222
--- /dev/null
+++ b/pool/shard000/JavaScript/0002501_logger.js
@@ -0,0 +1,42 @@
+var bunyan = require('bunyan');
+var PrettyStream = require('bunyan-prettystream');
+var _ = require('lodash');
+
+var Logger = function(options) {
+ var self = this;
+ var DEFAULT_LOG_LEVEL = 'info';
+ var defaultConsoleStream = {stream: process.stdout};
+ var bunyanOptions = {
+ name: (options && options.name) ? options.name : 'untitled-app-log',
+ streams: []
+ };
+
+ if(!options) { return bunyan.createLogger(bunyanOptions); }
+
+ if(options.console) { // TODO: Check for enabled: false
+ var stream = null;
+ if(options.console.pretty) {
+ var prettyStdOut = new PrettyStream();
+ prettyStdOut.pipe(process.stdout);
+ stream = {
+ level: options.console.level || DEFAULT_LOG_LEVEL,
+ type: 'raw',
+ stream: prettyStdOut
+ };
+ }
+ else {
+ var stream = defaultConsoleStream;
+ _.assign(stream, options.Console);
+ }
+ bunyanOptions.streams.push(stream);
+ }
+
+ return bunyan.createLogger(bunyanOptions);
+};
+
+// Exports:
+module.exports = Logger;
+
+module.exports.createLogger = function createLogger(options) {
+ return new Logger(options);
+};
diff --git a/pool/shard000/JavaScript/0002502_multifile.js b/pool/shard000/JavaScript/0002502_multifile.js
new file mode 100644
index 0000000000000000000000000000000000000000..1136e549429951d39d7b0b74f374b00d4d6f9899
--- /dev/null
+++ b/pool/shard000/JavaScript/0002502_multifile.js
@@ -0,0 +1,166 @@
+/**
+ * Convert a single file-input element into a 'multiple' input list
+ *
+ * Usage:
+ *
+ * 1. Create a file input element (no name)
+ * eg.
+ *
+ * 2. Create a DIV for the output to be written to
+ * eg.
+ *
+ * 3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
+ * eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
+ *
+ * 4. Add the first element
+ * eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
+ *
+ * 5. That's it.
+ *
+ * You might (will) want to play around with the addListRow() method to make the output prettier.
+ *
+ * You might also want to change the line
+ * element.name = 'file_' + this.count;
+ * ...to a naming convention that makes more sense to you.
+ *
+ * Licence:
+ * Use this however/wherever you like, just don't blame me if it breaks anything.
+ *
+ * Credit:
+ * If you're nice, you'll leave this bit:
+ *
+ * Class by Stickman -- http://www.the-stickman.com
+ * with thanks to:
+ * [for Safari fixes]
+ * Luis Torrefranca -- http://www.law.pitt.edu
+ * and
+ * Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
+ * [for duplicate name bug]
+ * 'neal'
+ */
+function MultiSelector( list_target, max ){
+
+ // Where to write the list
+ this.list_target = list_target;
+ // How many elements?
+ this.count = 0;
+ // How many elements?
+ this.id = 0;
+ // Is there a maximum?
+ if( max ){
+ this.max = max;
+ } else {
+ this.max = -1;
+ };
+
+ this.resetall = function () {
+ this.count = 0;
+ this.id = 0;
+ }
+
+ /**
+ * Add a new file input element
+ */
+ this.addElement = function( element ){
+
+ // Make sure it's a file input element
+ if( element.tagName == 'INPUT' && element.type == 'file' ){
+
+ // Element name -- what number am I?
+ element.name = 'file_' + this.id++;
+
+ // Add reference to this object
+ element.multi_selector = this;
+
+ // What to do when a file is selected
+ element.onchange = function(){
+
+ // New file input
+ var new_element = document.createElement( 'input' );
+ new_element.type = 'file';
+
+ // Add new element
+ this.parentNode.insertBefore( new_element, this );
+
+ // Apply 'update' to element
+ this.multi_selector.addElement( new_element );
+
+ // Update list
+ this.multi_selector.addListRow( this );
+
+ // Hide this: we can't use display:none because Safari doesn't like it
+ this.style.position = 'absolute';
+ this.style.left = '-1000px';
+
+ };
+ // If we've reached maximum number, disable input element
+ if( this.max != -1 && this.count >= this.max ){
+ element.disabled = true;
+ };
+
+ // File element counter
+ this.count++;
+ // Most recent element
+ this.current_element = element;
+
+ } else {
+ // This can only be applied to file input elements!
+ alert( 'Error: not a file input element' );
+ };
+
+ };
+
+ /**
+ * Add a new row to the list of files
+ */
+ this.addListRow = function( element ){
+
+ // Row div
+ var new_row = document.createElement( 'div' );
+
+ // Delete button
+ var new_row_button = document.createElement( 'input' );
+ new_row_button.type = 'button';
+ new_row_button.value = 'x';
+
+ // References
+ new_row.element = element;
+
+ // Delete function
+ new_row_button.onclick= function(){
+
+ // Remove element from form
+ this.parentNode.element.parentNode.removeChild( this.parentNode.element );
+
+ // Remove this row from the list
+ this.parentNode.parentNode.removeChild( this.parentNode );
+
+ // Decrement counter
+ this.parentNode.element.multi_selector.count--;
+
+ // Re-enable input element (if it's disabled)
+ this.parentNode.element.multi_selector.current_element.disabled = false;
+
+ // Appease Safari
+ // without it Safari wants to reload the browser window
+ // which nixes your already queued uploads
+ return false;
+ };
+
+ // Set row value
+ element_name = element.value.split('/');
+ element_name = element_name[element_name.length-1];
+
+ element_name = element_name.split('\\');
+ element_name = element_name[element_name.length-1];
+
+ new_row.innerHTML = element_name + ' ';
+
+ // Add button
+ new_row.appendChild( new_row_button );
+
+ // Add it to the list
+ this.list_target.appendChild( new_row );
+
+ };
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002503_geolocation_html5.js b/pool/shard000/JavaScript/0002503_geolocation_html5.js
new file mode 100644
index 0000000000000000000000000000000000000000..266f8b9fe3e04eda53454bcfb3bf396cdf43d466
--- /dev/null
+++ b/pool/shard000/JavaScript/0002503_geolocation_html5.js
@@ -0,0 +1,93 @@
+
+/**
+ * @file
+ * Javascript for Geolocation Field.
+ */
+(function ($) {
+ function latitudeToMercator(latitude) {
+ return Math.log(Math.tan(latitude * Math.PI / 180) + 1 / Math.cos(latitude * Math.PI / 180));
+ }
+
+ Drupal.latitudeToPx = function (latitude, topLatitude, bottomLatitude, height) {
+ return (latitudeToMercator(latitude) - latitudeToMercator(bottomLatitude)) / (latitudeToMercator(topLatitude) - latitudeToMercator(bottomLatitude)) * height;
+ }
+
+ Drupal.longitudeToPx = function (longitude, leftLongitude, width) {
+ return (longitude - leftLongitude + 360) / 360 % 1 * width;
+ }
+
+ function plot(widgetParentElement) {
+ var thisMap = $('.geolocation-html5-map', widgetParentElement);
+ var latitude = $('input.geolocation-lat', widgetParentElement).attr('value');
+ var longitude = $('input.geolocation-lng', widgetParentElement).attr('value');
+
+ if (latitude == 0 && longitude == 0) {
+ return;
+ }
+
+ var latPx = Math.round( Drupal.latitudeToPx(latitude, 78, -58, thisMap.height()) );
+ var lngPx = Math.round( Drupal.longitudeToPx(longitude, -168, thisMap.width()) );
+
+ // Plot coords on map.
+ $('.dot', thisMap).show();
+ $('.dot', thisMap).css('bottom', latpx + 'px');
+ $('.dot', thisMap).css('left', lngpx + 'px');
+ }
+
+ function getLocation(widgetParentElement) {
+ var thisMap = $('.geolocation-html5-map', widgetParentElement);
+ var messages = $('.geolocation-html5-messages', widgetParentElement);
+ var busyMessage = $('.geolocating', messages);
+ if ($('.form-type-checkbox input', widgetParentElement).attr('checked')) {
+ thisMap.slideDown('fast', function() {
+ // Get position
+ busyMessage.show();
+ navigator.geolocation.getCurrentPosition(function (position) {
+ // Save coords to hidden inputs.
+ $('input.geolocation-lat', widgetParentElement).attr('value', position.coords.latitude);
+ $('input.geolocation-lng', widgetParentElement).attr('value', position.coords.longitude);
+
+ plot(widgetParentElement);
+ busyMessage.hide();
+ }, function () { // getCurrentPosition error callback
+ busyMessage.hide();
+ $('.form-type-checkbox input', widgetParentElement).attr('checked', false).change();
+ $('.form-type-checkbox input', widgetParentElement).attr('disabled', true);
+ },
+ {
+ maximumAge: Infinity
+ });
+ });
+ }
+ else { // Location not checked
+ busyMessage.hide();
+ $('.dot', thisMap).attr('style', '');
+ $('input.geolocation-lat', widgetParentElement).attr('value', '');
+ $('input.geolocation-lng', widgetParentElement).attr('value', '');
+ thisMap.slideUp('fast');
+ }
+ }
+
+ Drupal.behaviors.GeolocationHTML5 = {
+ attach: function(context, settings) {
+ if (navigator.geolocation) {
+ $('.field-type-geolocation-latlng .form-type-checkbox input:not(.geolocation-html5-processed)', context)
+ .change(function () {
+ var widgetParentElement = $(this).parent().parent();
+ getLocation(widgetParentElement);
+ })
+ .each(function () {
+ $(this).addClass('geolocation-html5-processed');
+ var widgetParentElement = $(this).parent().parent();
+ $('.form-type-checkbox .description', widgetParentElement).html(Drupal.t('Your location will be saved and may be shared.'));
+ getLocation(widgetParentElement);
+ });
+ }
+ else { // HTML5 Geolocation not supported
+ // Hide all map widgets and disable checkboxes.
+ $('.geolocation-html5-map').hide();
+ $('.field-type-geolocation-latlng .form-type-checkbox input').attr('disabled', true);
+ }
+ }
+ };
+})(jQuery);
diff --git a/pool/shard000/JavaScript/0002506_index.js b/pool/shard000/JavaScript/0002506_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..89af86c36d8e7553c1dca79defb597070350eee9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002506_index.js
@@ -0,0 +1,85 @@
+var camelize = require('camelize')
+var cspBuilder = require('content-security-policy-builder')
+var platform = require('platform')
+var containsFunction = require('./lib/contains-function')
+var getHeaderKeysForBrowser = require('./lib/get-header-keys-for-browser')
+var transformDirectivesForBrowser = require('./lib/transform-directives-for-browser')
+var parseDynamicDirectives = require('./lib/parse-dynamic-directives')
+var ALL_HEADERS = require('./lib/all-headers')
+
+module.exports = function csp (options) {
+ options = options || {}
+
+ var originalDirectives = camelize(options.directives || {})
+ var directivesAreDynamic = containsFunction(originalDirectives)
+ var shouldBrowserSniff = options.browserSniff !== false
+
+ if (options.reportOnly && !originalDirectives.reportUri) {
+ throw new Error('Please remove reportOnly or add a report-uri.')
+ }
+
+ if (shouldBrowserSniff) {
+ return function csp (req, res, next) {
+ var userAgent = req.headers['user-agent']
+
+ var browser
+ if (userAgent) {
+ browser = platform.parse(userAgent)
+ } else {
+ browser = {}
+ }
+
+ var headerKeys
+ if (options.setAllHeaders || !userAgent) {
+ headerKeys = ALL_HEADERS
+ } else {
+ headerKeys = getHeaderKeysForBrowser(browser, options)
+ }
+
+ if (headerKeys.length === 0) {
+ next()
+ return
+ }
+
+ var directives = transformDirectivesForBrowser(browser, originalDirectives)
+
+ if (directivesAreDynamic) {
+ directives = parseDynamicDirectives(directives, [req, res])
+ }
+
+ var policyString = cspBuilder({ directives: directives })
+
+ headerKeys.forEach(function (headerKey) {
+ if (options.reportOnly) {
+ headerKey += '-Report-Only'
+ }
+ res.setHeader(headerKey, policyString)
+ })
+
+ next()
+ }
+ } else {
+ var headerKeys
+ if (options.setAllHeaders) {
+ headerKeys = ALL_HEADERS
+ } else {
+ headerKeys = ['Content-Security-Policy']
+ }
+
+ if (options.reportOnly) {
+ headerKeys = headerKeys.map(function (headerKey) {
+ return headerKey + '-Report-Only'
+ })
+ }
+
+ return function csp (req, res, next) {
+ var directives = parseDynamicDirectives(originalDirectives, [req, res])
+ var policyString = cspBuilder({ directives: directives })
+
+ headerKeys.forEach(function (headerKey) {
+ res.setHeader(headerKey, policyString)
+ })
+ next()
+ }
+ }
+}
diff --git a/pool/shard000/JavaScript/0002507_sync.js b/pool/shard000/JavaScript/0002507_sync.js
new file mode 100644
index 0000000000000000000000000000000000000000..9e762ac64aaf5c827445801a4b991ce456aeffc5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002507_sync.js
@@ -0,0 +1,147 @@
+var mongo = require('mongodb');
+
+module.exports = {
+
+ // __connect:__ connects the underlaying database.
+ //
+ // `storage.connect(callback)`
+ //
+ // - __callback:__ `function(err, storage){}`
+ connect: function(options, callback) {
+
+ this.isConnected = false;
+
+ if (typeof options === 'function')
+ callback = options;
+
+ var defaults = {
+ host: 'localhost',
+ port: 27017,
+ dbName: 'i18next',
+ resCollectionName: 'resources'
+ };
+
+ options = mergeOptions(options, defaults);
+
+ var self = this;
+
+ var server = new mongo.Server(options.host, options.port, {});
+ new mongo.Db(options.dbName , server, {}).open(function(err, client) {
+ if (err) {
+ if (callback) callback(err);
+ } else {
+ self.isConnected = true;
+ self.client = client;
+
+ self.resources = new mongo.Collection(client, options.resCollectionName);
+
+ if (callback) callback(null, self);
+ }
+ });
+ },
+
+ saveResourceSet: function(lng, ns, resourceSet, cb) {
+ if (!resourceSet._id) resourceSet._id = ns + '_' + lng;
+ if (!resourceSet.lng) resourceSet.lng = lng;
+ if (!resourceSet.namespace) resourceSet.namespace = ns;
+
+ this.resources.save(resourceSet, { safe: true }, cb);
+ },
+
+ loadResourceSet: function(lng, ns, cb) {
+
+ var _id = ns + '_' + lng;
+
+ var self = this;
+ this.resources.findOne({ _id: _id }, function(err, obj) {
+ if (err) {
+ cb(err);
+ } else {
+ if(!obj) {
+ cb(null, { resources: {} });
+ } else {
+ self.functions.log('loaded from mongoDb: ' + _id);
+ cb(null, obj);
+ }
+ }
+ });
+ },
+
+ fetchOne: function(lng, ns, cb) {
+
+ this.loadResourceSet(lng, ns, function(err, obj) {
+ if (!obj) {
+ cb(err);
+ } else {
+ cb(err, obj.resources);
+ }
+ });
+ },
+
+ postMissing: function(ns, key, defaultValue) {
+ var self = this;
+
+ this.loadResourceSet(this.options.fallbackLng, ns, function(err, res) {
+ // add key to resStore
+ var keys = key.split('.');
+ var x = 0;
+ var value = res.resources;
+ while (keys[x]) {
+ if (x === keys.length - 1) {
+ value = value[keys[x]] = defaultValue;
+ } else {
+ value = value[keys[x]] = value[keys[x]] || {};
+ }
+ x++;
+ }
+
+ self.saveResourceSet(self.options.fallbackLng, ns, res, function(err) {
+ if (err) {
+ self.functions.log('error saving missingKey `' + key + '` to mongoDb');
+ } else {
+ self.functions.log('saved missingKey `' + key + '` with value `' + defaultValue + '` to mongoDb');
+ }
+ });
+ });
+ },
+
+ postChange: function(ns, lng, key, newValue) {
+ var self = this;
+
+ this.loadResourceSet(lng, ns, function(err, res) {
+ // add key to resStore
+ var keys = key.split('.');
+ var x = 0;
+ var value = res.resources;
+ while (keys[x]) {
+ if (x === keys.length - 1) {
+ value = value[keys[x]] = newValue;
+ } else {
+ value = value[keys[x]] = value[keys[x]] || {};
+ }
+ x++;
+ }
+
+ self.saveResourceSet(lng, ns, res, function(err) {
+ if (err) {
+ self.functions.log('error updating key `' + key + '` to mongoDb');
+ } else {
+ self.functions.log('updated key `' + key + '` with value `' + defaultValue + '` to mongoDb');
+ }
+ });
+ });
+ }
+
+};
+
+// helper
+var mergeOptions = function(options, defaultOptions) {
+ if (!options || typeof options === 'function') {
+ return defaultOptions;
+ }
+
+ var merged = {};
+ for (var attrname in defaultOptions) { merged[attrname] = defaultOptions[attrname]; }
+ for (attrname in options) { if (options[attrname]) merged[attrname] = options[attrname]; }
+ return merged;
+};
diff --git a/pool/shard000/JavaScript/0002508_fr-phone.js b/pool/shard000/JavaScript/0002508_fr-phone.js
new file mode 100644
index 0000000000000000000000000000000000000000..16633f75d8bfb4139c16600c7f209da1e3793ddd
--- /dev/null
+++ b/pool/shard000/JavaScript/0002508_fr-phone.js
@@ -0,0 +1,23 @@
+var StringMask = require('string-mask');
+var maskFactory = require('mask-factory');
+
+var phoneMaskFR = new StringMask('00 00 00 00 00');
+
+module.exports = maskFactory({
+ clearValue: function(rawValue) {
+ return rawValue.toString().replace(/[^0-9]/g, '');
+ },
+ format: function(cleanValue) {
+ var formattedValue;
+
+ formattedValue = phoneMaskFR.apply(cleanValue) || '';
+
+ return formattedValue.trim().replace(/[^0-9]$/, '');
+ },
+ validations: {
+ frPhoneNumber: function(value) {
+ var valueLength = value && value.toString().length;
+ return valueLength === 10;
+ }
+ }
+});
diff --git a/pool/shard000/JavaScript/0002510_main_page.js b/pool/shard000/JavaScript/0002510_main_page.js
new file mode 100644
index 0000000000000000000000000000000000000000..54046b2d04334c78cd325a8f16b152ced3bffea2
--- /dev/null
+++ b/pool/shard000/JavaScript/0002510_main_page.js
@@ -0,0 +1,74 @@
+// This is a page-object for the main page
+
+var MainPage = function() {
+ var url = 'http://localhost:6543',
+ paramBlocks = element.all(by.repeater('simulation in simulations')),
+ addParameterButton = element(by.id('add-parameters-btn')),
+ deleteButtons = element.all(by.buttonText('delete')),
+ parameterForms = element.all(by.className('parameter-set-form')),
+ visibilityButtons = element.all(by.className('hide-show-parameters')),
+ inclusionButtons = element.all(by.className('include-exclude-parameters')),
+ runSimulationButton = element(by.buttonText('Run simulation')),
+ resultsChart = element(by.id('software-development-rate-chart'))
+ ;
+
+ this.get = function() {
+ return browser.get(url);
+ };
+
+ this.paramCount = function () {
+ return paramBlocks.count();
+ };
+
+ this.addParameter = function () {
+ return addParameterButton.click();
+ };
+
+ this.deleteParameter = function(index) {
+ return deleteButtons.get(index).click();
+ };
+
+ this.showParameters = function(index, show) {
+ var button = visibilityButtons.get(index);
+ var opened = button.evaluate('opened');
+ if (opened != show) {
+ return button.click();
+ }
+ return button;
+ };
+
+ this.parametersVisible = function(index) {
+ return parameterForms.get(index).isDisplayed();
+ };
+
+ this.includeParameters = function(index, include) {
+ var button = inclusionButtons.get(index);
+ if (this.parametersIncluded(index) != include) {
+ return button.click();
+ }
+ return button;
+ };
+
+ this.parametersIncluded = function(index) {
+ var button = inclusionButtons.get(index);
+ return button.evaluate('simulation.included');
+ };
+
+ this.chartIsEmpty = function(index) {
+ var emptyChartURL = "return document.createElement('canvas').toDataURL();";
+ var realChartURL = "return document.getElementById('software-development-rate-chart').toDataURL();";
+ return browser.executeScript(emptyChartURL).then(
+ function(emptyURL) {
+ return browser.executeScript(realChartURL).then(
+ function(actualURL) {
+ return emptyURL == actualURL;
+ });
+ });
+ };
+
+ this.runSimulation = function() {
+ return runSimulationButton.click();
+ };
+};
+
+module.exports = MainPage;
diff --git a/pool/shard000/JavaScript/0002511_v1_1_0.js b/pool/shard000/JavaScript/0002511_v1_1_0.js
new file mode 100644
index 0000000000000000000000000000000000000000..36c10385c56ceff95fd4ba80b3c638d92e8ae566
--- /dev/null
+++ b/pool/shard000/JavaScript/0002511_v1_1_0.js
@@ -0,0 +1,68 @@
+/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
+ * full list of contributors). Published under the Clear BSD license.
+ * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
+ * full text of the license. */
+
+/**
+ * @requires OpenLayers/Protocol/WFS/v1.js
+ * @requires OpenLayers/Format/WFST/v1_1_0.js
+ */
+
+/**
+ * Class: OpenLayers.Protocol.WFS.v1_1_0
+ * A WFS v1.1.0 protocol for vector layers. Create a new instance with the
+ * constructor.
+ *
+ * Differences from the v1.0.0 protocol:
+ * - uses Filter Encoding 1.1.0 instead of 1.0.0
+ * - uses GML 3 instead of 2 if no format is provided
+ *
+ * Inherits from:
+ * -
+ */
+OpenLayers.Protocol.WFS.v1_1_0 = OpenLayers.Class(OpenLayers.Protocol.WFS.v1, {
+
+ /**
+ * Property: version
+ * {String} WFS version number.
+ */
+ version: "1.1.0",
+
+ /**
+ * Constructor: OpenLayers.Protocol.WFS.v1_1_0
+ * A class for giving layers WFS v1.1.0 protocol.
+ *
+ * Parameters:
+ * options - {Object} Optional object whose properties will be set on the
+ * instance.
+ *
+ * Valid options properties:
+ * featureType - {String} Local (without prefix) feature typeName (required).
+ * featureNS - {String} Feature namespace (optional).
+ * featurePrefix - {String} Feature namespace alias (optional - only used
+ * if featureNS is provided). Default is 'feature'.
+ * geometryName - {String} Name of geometry attribute. Default is 'the_geom'.
+ * outputFormat - {String} Optional output format to use for WFS GetFeature
+ * requests. This can be any format advertized by the WFS's
+ * GetCapabilities response. If set, an appropriate readFormat also
+ * has to be provided, unless outputFormat is GML3, GML2 or JSON.
+ * readFormat - {} An appropriate format parser if
+ * outputFormat is none of GML3, GML2 or JSON.
+ */
+ initialize: function(options) {
+ OpenLayers.Protocol.WFS.v1.prototype.initialize.apply(this, arguments);
+ if (this.outputFormat && !this.readFormat) {
+ if (this.outputFormat.toLowerCase() == "gml2") {
+ this.readFormat = new OpenLayers.Format.GML.v2({
+ featureType: this.featureType,
+ featureNS: this.featureNS,
+ geometryName: this.geometryName
+ });
+ } else if (this.outputFormat.toLowerCase() == "json") {
+ this.readFormat = new OpenLayers.Format.GeoJSON();
+ }
+ }
+ },
+
+ CLASS_NAME: "OpenLayers.Protocol.WFS.v1_1_0"
+});
diff --git a/pool/shard000/JavaScript/0002513_blog-dialog.controller.js b/pool/shard000/JavaScript/0002513_blog-dialog.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..bed8d6b04655e4f28385fe8d8ea9bae9f8cc290c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002513_blog-dialog.controller.js
@@ -0,0 +1,47 @@
+(function() {
+ 'use strict';
+
+ angular
+ .module('bloggerApp')
+ .controller('BlogDialogController', BlogDialogController);
+
+ BlogDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'entity', 'Blog', 'User'];
+
+ function BlogDialogController ($timeout, $scope, $stateParams, $uibModalInstance, entity, Blog, User) {
+ var vm = this;
+
+ vm.blog = entity;
+ vm.clear = clear;
+ vm.save = save;
+ vm.users = User.query();
+
+ $timeout(function (){
+ angular.element('.form-group:eq(1)>input').focus();
+ });
+
+ function clear () {
+ $uibModalInstance.dismiss('cancel');
+ }
+
+ function save () {
+ vm.isSaving = true;
+ if (vm.blog.id !== null) {
+ Blog.update(vm.blog, onSaveSuccess, onSaveError);
+ } else {
+ Blog.save(vm.blog, onSaveSuccess, onSaveError);
+ }
+ }
+
+ function onSaveSuccess (result) {
+ $scope.$emit('bloggerApp:blogUpdate', result);
+ $uibModalInstance.close(result);
+ vm.isSaving = false;
+ }
+
+ function onSaveError () {
+ vm.isSaving = false;
+ }
+
+
+ }
+})();
diff --git a/pool/shard000/JavaScript/0002515_gulpfile.js b/pool/shard000/JavaScript/0002515_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..68cb80ab3a076bf3cfe5be40e188bb18960e2720
--- /dev/null
+++ b/pool/shard000/JavaScript/0002515_gulpfile.js
@@ -0,0 +1,98 @@
+/* eslint-disable no-var, strict, prefer-arrow-callback */
+'use strict';
+
+var gulp = require('gulp');
+var gutil = require('gulp-util');
+var eslint = require('gulp-eslint');
+var tslint = require("gulp-tslint");
+var yargs = require("yargs").argv;
+
+var less = require('./gulp/less');
+var webpack = require('./gulp/webpack');
+var staticFiles = require('./gulp/staticFiles');
+var tests = require('./gulp/tests');
+var clean = require('./gulp/clean');
+var inject = require('./gulp/inject');
+
+var isDebug = yargs.mode === "Debug";
+
+var eslintSrcs = ['./gulp/**/*.js'];
+var tslintSrcs = ['./src/**/*.ts', './test/**/*.ts', '!**/*.d.ts'];
+
+gulp.task('delete-dist-contents', function (done) {
+ clean.run(done);
+});
+
+gulp.task('build-process.env.NODE_ENV', function () {
+ process.env.NODE_ENV = 'production';
+});
+
+gulp.task('build-less', ['delete-dist-contents', 'build-process.env.NODE_ENV'], function(done) {
+ less.build().then(function() { done(); });
+});
+
+gulp.task('build-js', ['delete-dist-contents', 'build-process.env.NODE_ENV'], function (done) {
+ webpack.build().then(function () { done(); });
+});
+
+gulp.task('build-other', ['delete-dist-contents', 'build-process.env.NODE_ENV'], function () {
+ staticFiles.build();
+});
+
+gulp.task('run-tests', [], function (done) {
+ tests.run(done);
+});
+
+gulp.task('build-release', ['build-less', 'build-js', 'build-other', 'eslint', 'tslint'], function () {
+ inject.build();
+});
+
+gulp.task('build', isDebug ? [] : ['build-release'], function () {
+ if (isDebug) {
+ gutil.log(gutil.colors.red("In debug mode so not building client side code; your gulp watch task should be running. Type 'npm run watch' at the command prompt in the project directory"));
+ }
+});
+
+gulp.task('eslint', function () {
+ return gulp.src(eslintSrcs)
+ .pipe(eslint())
+ .pipe(eslint.format());
+});
+
+gulp.task('tslint', function () {
+ return gulp.src(tslintSrcs)
+ .pipe(tslint({
+ formatter: "verbose"
+ }))
+ .pipe(tslint.report({
+ emitError: false
+ }))
+});
+
+gulp.task('watch', ['delete-dist-contents'], function (done) {
+ process.env.NODE_ENV = 'development';
+ Promise.all([
+ webpack.watch(),
+ less.watch()
+ ]).then(function () {
+ gutil.log('Now that initial assets (js and css) are generated injection starts...');
+ inject.watch();
+ done();
+ }).catch(function (error) {
+ gutil.log('Problem generating initial assets (js and css)', error);
+ });
+
+ gulp.watch(eslintSrcs, ['eslint']);
+ gulp.watch(tslintSrcs, ['tslint']);
+ staticFiles.watch();
+ tests.watch();
+});
+
+gulp.task('serve', ['watch'], function() {
+ // local as not required for build
+ var express = require('express')
+ var app = express()
+
+ app.use(express.static('dist', {'index': 'index.html'}))
+ app.listen(7777);
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002516_jquery.ammo.js b/pool/shard000/JavaScript/0002516_jquery.ammo.js
new file mode 100644
index 0000000000000000000000000000000000000000..528521300593e6535c93d82a90e936989c636c3b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002516_jquery.ammo.js
@@ -0,0 +1,149 @@
+(function($){
+
+ $.fn.ammo = function(options){
+
+ var $this = $(this);
+ var clientWidth = parseInt(GetClientDim('width'));
+
+ // -- GET CLIENT DIMENSIONS
+ function GetClientDim(param){
+ if (param == 'width'){
+ return parseInt($(window).width());
+ } else if (param == 'height'){
+ return parseInt($(window).height());
+ }
+ }
+
+ // -- SET DEFAULTS
+ function SetDefault(val){
+ if ((val == '') || (val == null) || (val == 'UNDEFINED')){
+ return null;
+ } else {
+ return val;
+ }
+ }
+
+ // -- ANIMATION FRAME
+ if (!window.requestAnimationFrame){
+ window.requestAnimationFrame = (function(){
+ return window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback, element ){ window.setTimeout( callback, 1000 / 60 ); };
+ })();
+ }
+
+ // -- SET DEFAULT VALUES
+ var speed = SetDefault(options.speed);
+ if (speed == null){
+ speed = 50;
+ }
+
+ var screenEdges = SetDefault(options.screenEdges);
+ if (screenEdges == null){
+ screenEdges = 150;
+ }
+ /*
+ var delay = SetDefault(options.delay);
+ if (delay == null){
+ delay = 0;
+ }
+ */
+
+ var destination = SetDefault(options.destination);
+ if (destination == null){
+ destination = 'toRight';
+ }
+
+ var curDestState = null;
+ if (destination == 'toRight'){
+ curDestState = 'right';
+ } else if (destination == 'toLeft'){
+ curDestState = 'left';
+ }
+
+ var rightEdge = Math.round((clientWidth/2)+screenEdges);
+ var leftEdge = Math.round(0-clientWidth-screenEdges);
+ var StartPosPX = Math.round(0-clientWidth);
+ var counter = 0;
+ var curPosX = 0;
+
+ // SET START POSITION
+ function SetPosition(posX, scale){
+ var crossBrowsePrefix = [/* Chrome, Safari 3.1+ */'-webkit-', /* Firefox 3.5-15 */'-moz-', /* IE 9 */'-ms-', /* Opera 10.50-12.00 */'-o-'];
+ var prefixCounter = 0;
+ while (prefixCounter <= (crossBrowsePrefix.length-1)){
+ $this.css((crossBrowsePrefix[prefixCounter]+'transform'),'translateX('+posX+'px) scaleX('+scale+')');
+ prefixCounter++;
+ }
+ }
+
+ function animate(){
+
+ requestAnimationFrame(animate);
+
+ if (destination == 'toRight'){
+ if (curDestState == 'right'){
+
+ if (curPosX <= rightEdge){
+ curPosX = StartPosPX+(counter*(speed/10));
+ SetPosition(curPosX, 1);
+ counter++;
+ } else if (curPosX > rightEdge){
+ counter--;
+ SetPosition(curPosX, -1);
+ curDestState = 'left';
+ }
+
+ } else if (curDestState == 'left'){
+
+ if (leftEdge <= curPosX){
+ curPosX = StartPosPX+(counter*(speed/10));
+ SetPosition(curPosX, -1);
+ counter--;
+ } else if (leftEdge > curPosX){
+ counter++;
+ SetPosition(curPosX, 1);
+ curDestState = 'right';
+ }
+
+ }
+
+ } else if (destination == 'toLeft'){
+
+ if (curDestState == 'right'){
+
+ if (curPosX <= rightEdge){
+ curPosX = Math.abs(StartPosPX)+(counter*(speed/10));
+ SetPosition(curPosX, -1);
+ counter++;
+ } else if (curPosX > rightEdge){
+ counter--;
+ SetPosition(curPosX, 1);
+ curDestState = 'left';
+ }
+
+ } else if (curDestState == 'left'){
+
+ if (leftEdge <= curPosX){
+ curPosX = Math.abs(StartPosPX)+(counter*(speed/10));
+ SetPosition(curPosX, 1);
+ counter--;
+ } else if (leftEdge > curPosX){
+ counter++;
+ SetPosition(curPosX, -1);
+ curDestState = 'right';
+ }
+
+ }
+
+ }
+
+ }
+
+ animate();
+
+ };
+
+})(jQuery);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002517_geocodings_collection.js b/pool/shard000/JavaScript/0002517_geocodings_collection.js
new file mode 100644
index 0000000000000000000000000000000000000000..986585f65fde347c333bc954d412b0777c1be7f1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002517_geocodings_collection.js
@@ -0,0 +1,108 @@
+var Backbone = require('backbone');
+var _ = require('underscore');
+var pollTimer = 60000;
+var GeocodingModel = require('./geocoding_model');
+
+/**
+ * Geocodings collection
+ *
+ * - Check ongoing geocodings in order to add them
+ * to the collection.
+ *
+ */
+
+module.exports = Backbone.Collection.extend({
+
+ model: GeocodingModel,
+
+ url: function(method) {
+ var version = cdb.config.urlVersion('geocoding', method);
+ return '/api/' + version + '/geocodings';
+ },
+
+ initialize: function(mdls, opts) {
+ this.user = opts.user;
+ this.vis = opts.vis;
+ },
+
+ parse: function(r) {
+ var self = this;
+
+ _.each(r.geocodings, function(data) {
+
+ // Check if that geocoding exists...
+ var geocodings = self.filter(
+ function(mdl) {
+ return mdl.get('id') === data.id
+ }
+ );
+
+ if (geocodings.length === 0) {
+ self._checkOngoingGeocoding(
+ new GeocodingModel(data, { startPollingAutomatically: false })
+ )
+ }
+ });
+
+ return this.models
+ },
+
+ _checkOngoingGeocoding: function(mdl) {
+ if (!this.vis) {
+ // If there is NOT a vis, let's start polling
+ // this geocoding model
+ this.add(mdl);
+ mdl.pollCheck();
+ } else {
+ var self = this;
+ // If there is a vis, let's check if that
+ // geocoding belongs to the visualization
+ this.vis.map.layers.each(function(lyr) {
+ if (lyr.table && lyr.table.id === mdl.get('table_name')) {
+ self.add(mdl);
+ mdl.pollCheck();
+ }
+ })
+ }
+ },
+
+ // Public methods
+
+ canGeocode: function() {
+ return !this.any(function(m) {
+ return m.isOngoing();
+ });
+ },
+
+ fetchGeocodings: function() {
+ var self = this;
+ this.fetch({
+ error: function(e) {
+ self.destroyCheck();
+ }
+ });
+ },
+
+ pollCheck: function(i) {
+ if (this.pollTimer) return;
+
+ var self = this;
+ this.pollTimer = setInterval(function() {
+ self.fetchGeocodings();
+ }, pollTimer);
+
+ this.fetchGeocodings();
+ },
+
+ destroyCheck: function() {
+ clearInterval(this.pollTimer);
+ delete this.pollTimer;
+ },
+
+ failedItems: function() {
+ return this.filter(function(item) {
+ return item.hasFailed();
+ });
+ }
+
+});
diff --git a/pool/shard000/JavaScript/0002520_todo.js b/pool/shard000/JavaScript/0002520_todo.js
new file mode 100644
index 0000000000000000000000000000000000000000..e049cd517faa966c8fe853417d128b84e4e6b763
--- /dev/null
+++ b/pool/shard000/JavaScript/0002520_todo.js
@@ -0,0 +1,86 @@
+$(function(){
+ getList();
+});
+
+//HTMLタグを除去する関数
+function deldiv(str){
+ return $('').html(str).text();
+}
+
+$('#task').submit(function(){
+ postTask();
+ return false;
+});
+
+var title = $("title").text();
+
+function taskHtml(task){
+ var str = null;
+ for(var i=0,size=task.lenght;i
'
+ +''
+ +'
'+task[i].text+'
'
+ +'
期限:'
+ +limit.getFullYear()+'年'
+ +limit.getMonth()+'月'
+ +limit.getDate()+'日
'
+ +'
作成:'
+ +create.getFullYear()+'年'
+ +create.getMonth()+'月'
+ +create.getDate()+'日
'
+ +'
完了
';
+ }else{
+ str = str + '未完了 ';
+ }
+ }
+ return str;
+}
+
+// ToDo一覧を取得して表示する
+function getList(){
+ // すでに表示されている一覧を非表示にして削除する
+ var $list = $('.list');
+ $list.fadeOut(function(){
+ $list.children().remove();
+ // /todo/data/todolist.name にGETアクセスする
+ $.get('/todo/data/'+title, function(todos){
+ // 取得したToDoを追加していく
+ var str = taskHtml(todos);
+ $list.append(str);
+ // 一覧を表示する
+ $list.fadeIn();
+ });
+ });
+}
+
+function toggleTask(listname,tasktext){
+ $.post('/todo/'+listname+'/'+tasktext, {}, function(res){});
+}
+
+
+// フォームに入力されたToDoを追加する
+function postTask(){
+ // フォームに入力された値を取得
+ var name = deldiv($('#text').val());
+ var limitDate = new Date($('#limit').val());
+
+ //入力項目を空にする
+ $('#text').val('');
+ $('#limit').val('');
+
+ // /todoにPOSTアクセスする
+ $.post('/todo/task', {list: title, name: name, limit: limitDate}, function(res){
+ console.log(res);
+ //再度表示する
+ getList();
+ });
+}
diff --git a/pool/shard000/JavaScript/0002523_script.js b/pool/shard000/JavaScript/0002523_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..cefa7d09d968b3e3d1efde93ae425c2572d9700a
--- /dev/null
+++ b/pool/shard000/JavaScript/0002523_script.js
@@ -0,0 +1,74 @@
+var stage = new Kinetic.Stage({
+ container: 'canvas-div',
+ width: 500,
+ height: 350
+});
+
+var canvasWrapper = document.getElementById('canvas-div').firstChild;
+canvasWrapper.style.border = '1px solid black';
+
+var layer = new Kinetic.Layer();
+var ballsCount = 13;
+var balls = [];
+var ballsProps = [];
+for (var i = 0; i < ballsCount; i++) {
+ var ball = new Kinetic.Circle({
+ x: 16 + Math.random() * (stage.getWidth() - 16),
+ y: 16 + Math.random() * (stage.getHeight() - 16),
+ radius: 15,
+ fill: 'yellow',
+ stroke: 'purple'
+ });
+ balls.push(ball);
+
+ ballsProps.push({
+ dirX: 1,
+ dirY: 1,
+ speed: (Math.random() * 5)
+ });
+
+ layer.add(ball);
+}
+
+function checkBallsCollision(ball, index) {
+ return balls.some(function(otherBall, otherIndex) {
+ var firstX = ball.getX();
+ var secondX = otherBall.getX();
+ var firstY = ball.getY();
+ var secondY = otherBall.getY();
+ return (firstX - secondX) * (firstX - secondX) + (firstY - secondY) * (firstY - secondY) - ball.getRadius() * ball.getRadius() * 4 <= 0.000001 && otherIndex !== index;
+ });
+}
+
+function animFrame() {
+ balls.forEach(function(ball, index) {
+ var x = ball.getX();
+ var y = ball.getY();
+ var deltaX = ballsProps[index].speed;
+ var deltaY = ballsProps[index].speed;
+ if (x > stage.getWidth() - ball.getRadius() ||
+ x < 0 + ball.getRadius() ||
+ checkBallsCollision(ball, index)) {
+ ballsProps[index].dirX *= -1;
+ }
+ if (y > stage.getHeight() - ball.getRadius() ||
+ y < 0 + ball.getRadius() ||
+ checkBallsCollision(ball, index)) {
+ ballsProps[index].dirY *= -1;
+ }
+
+ var directionX = ballsProps[index].dirX;
+ var directionY = ballsProps[index].dirY;
+ var newX = x + deltaX * directionX;
+ var newY = y + deltaY * directionY;
+
+ ball.setX(newX);
+ ball.setY(newY);
+ });
+ layer.draw();
+ setTimeout(animFrame, 10);
+}
+
+animFrame();
+
+stage.add(layer);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002525_MainFieldPlugin.js b/pool/shard000/JavaScript/0002525_MainFieldPlugin.js
new file mode 100644
index 0000000000000000000000000000000000000000..66208fcd5c686a81d233a278340462ae37c53eae
--- /dev/null
+++ b/pool/shard000/JavaScript/0002525_MainFieldPlugin.js
@@ -0,0 +1,66 @@
+/*
+ MIT License http://www.opensource.org/licenses/mit-license.php
+ Author Tobias Koppers @sokra
+*/
+"use strict";
+
+const path = require("path");
+
+module.exports = class MainFieldPlugin {
+ constructor(source, options, target) {
+ this.source = source;
+ this.options = options;
+ this.target = target;
+ }
+
+ apply(resolver) {
+ const target = resolver.ensureHook(this.target);
+ resolver
+ .getHook(this.source)
+ .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => {
+ if (request.path !== request.descriptionFileRoot) return callback();
+ if (request.alreadyTriedMainField === request.descriptionFilePath)
+ return callback();
+ const content = request.descriptionFileData;
+ const filename = path.basename(request.descriptionFilePath);
+ let mainModule;
+ const field = this.options.name;
+ if (Array.isArray(field)) {
+ let current = content;
+ for (let j = 0; j < field.length; j++) {
+ if (current === null || typeof current !== "object") {
+ current = null;
+ break;
+ }
+ current = current[field[j]];
+ }
+ if (typeof current === "string") {
+ mainModule = current;
+ }
+ } else {
+ if (typeof content[field] === "string") {
+ mainModule = content[field];
+ }
+ }
+ if (!mainModule) return callback();
+ if (this.options.forceRelative && !/^\.\.?\//.test(mainModule))
+ mainModule = "./" + mainModule;
+ const obj = Object.assign({}, request, {
+ request: mainModule,
+ alreadyTriedMainField: request.descriptionFilePath
+ });
+ return resolver.doResolve(
+ target,
+ obj,
+ "use " +
+ mainModule +
+ " from " +
+ this.options.name +
+ " in " +
+ filename,
+ resolveContext,
+ callback
+ );
+ });
+ }
+};
diff --git a/pool/shard000/JavaScript/0002529_win4.js b/pool/shard000/JavaScript/0002529_win4.js
new file mode 100644
index 0000000000000000000000000000000000000000..ba61a8fbb51243f38935a979d3d395717ad52ab2
--- /dev/null
+++ b/pool/shard000/JavaScript/0002529_win4.js
@@ -0,0 +1,104 @@
+var win = Ti.UI.currentWindow;
+
+win.orientationModes = [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_RIGHT];
+
+var scrollable = Ti.UI.createScrollableView({
+ top:0,
+ bottom:0,
+ showPagingControl:true,
+ pagingControlHeight:20,
+ pagingControlColor:'#000',
+ minZoomScale:1.0,
+ maxZoomScale:3.0
+});
+
+var info = [{image:1, urlTop:'', urlBottom:''},
+ {image:2, urlTop:'http://www.enjoymagazine.net', urlBottom:'http://www.enjoymagazine.net', nameTop:'Enjoy Magazine', nameBottom:'Enjoy Magazine'},
+ {image:3, urlTop:'http://www.bestchoicehome.net/', urlBottom:'http://artbyarmando.com/', nameTop:'Best Choice', nameBottom:'Art by Armando' },
+ {image:4, urlTop:'http://www.celebrationredding.com', urlBottom:'http://www.sydneyann.com', nameTop:'Celebration', nameBottom:'Sydney Ann'},
+ {image:5, urlTop:'http://www.kendraviolin.com', urlBottom:'http://www.acehardware.com/', nameTop:'Kendra Violin', nameBottom:'Valley Ace', typeTop:'mail'},
+ {image:6, urlTop:'http://www.westsideperforming.com', urlBottom:'http://www.riverfrontplayhouse.com', nameTop:'Westside Performing', nameBottom:'Riverfront'},
+ {image:7, urlTop:'http://www.cascadetheatre.org', urlBottom:'http://www.frontandcenterdance-spotlight.com/', nameTop:'Cascade Theatre', nameBottom:'Front & Center'},
+ {image:8, urlTop:'http://www.copperridgecarecenter.com', urlBottom:'http://www.darlingaccounting.com', nameTop:'Copper Ridge', nameBottom:'Darling Accounting', typeTop:'tel', typeBottom:'mail'},
+ {image:9, urlTop:'http://www.cascadetheatre.org', urlBottom:'http://www.cascadetheatre.org', nameTop:'Cascade Theatre', nameBottom:'Cascade Theatre'},
+ {image:10, urlTop:'http://www.cascadetheatre.org/Calendar.asp?View=EVENT&EventID=1938&Date=04/06/2012&SectionID=-1', urlBottom:'http://www.cascadetheatre.org/Calendar.asp?View=EVENT&EventID=1938&Date=04/06/2012&SectionID=-1', nameTop:'Hairspray', nameBottom:'Hairspray'}
+];
+
+var views =[];
+for(var i = 0; i<10; i++){
+ var view = Ti.UI.createImageView({
+ image:'images/sponsors/'+info[i].image+'.jpg',
+ urlTop:info[i].urlTop,
+ urlBottom:info[i].urlBottom,
+ nameTop:info[i].nameTop,
+ nameBottom:info[i].nameBottom,
+ canScale:true,
+ width:Ti.Platform.displayCaps.platformWidth,
+ height:'auto'
+ });
+
+
+ views.push(view);
+}
+
+scrollable.views = views;
+win.add(scrollable);
+
+scrollable.addEventListener('doubletap', function(e){
+
+ var srcUrl;
+ var srcName;
+ if(e.y {
+ let state;
+ beforeEach(() => {
+ state = fromJS({
+ projectId: '',
+ title: 'project title',
+ description: 'project Description',
+ metadata: {
+ key1: 'value1',
+ key2: 'value2',
+ key3: {
+ key4: 'nested1Value1',
+ key5: 'nested1Value2',
+ key6: {
+ key7: 'nested2Value1',
+ },
+ },
+ },
+ dataset: {
+ },
+ });
+ });
+ it('returns the initial state', () => {
+ expect(projectPageReducer(undefined, {})).toEqual(state);
+ });
+ it('modifies project title correctly', () => {
+ const mockProjectTitle = 'mockProjectTitle';
+ const expectedResult = state.set('title', mockProjectTitle);
+ const receivedResult = projectPageReducer(state, makeProjectPageTitle(mockProjectTitle)).set('title', mockProjectTitle);
+ expect(receivedResult).toEqual(expectedResult);
+ });
+ it('modifies project id correctly', () => {
+ const mockProjectId = '1';
+ const expectedResult = state.set('projectId', mockProjectId);
+ expect(projectPageReducer(state, makeProjectPageId(mockProjectId)).set('projectId', mockProjectId)).toEqual(expectedResult);
+ });
+ it('modifies project description correctly', () => {
+ const mockProjectDescription = 'mockProjectDescription';
+ const expectedResult = state.set('description', mockProjectDescription);
+ expect(projectPageReducer(state, makeProjectPageDescription(mockProjectDescription)).set('description', mockProjectDescription)).toEqual(expectedResult);
+ });
+ it('modifies project meta data correctly', () => {
+ const mockProjectMetaData = {
+ projectId: '',
+ title: 'project title',
+ description: 'project Description',
+ metadata: {
+ key1: 'keyValue 1 for testing',
+ key2: 'value2 key for testing',
+ key3: {
+ key4: 'nested1Value1 testing',
+ key5: 'nested1Value2 testing',
+ key6: {
+ key7: 'nested2Value1 testing',
+ },
+ },
+ },
+
+ };
+ const expectedResult = state.set('metadata', mockProjectMetaData);
+ expect(projectPageReducer(state, makeProjectPageMetaData(mockProjectMetaData)).set('metadata', mockProjectMetaData)).toEqual(expectedResult);
+ });
+ });
diff --git a/pool/shard000/JavaScript/0002536_bridge.js b/pool/shard000/JavaScript/0002536_bridge.js
new file mode 100644
index 0000000000000000000000000000000000000000..beb1667685d35f2d64371d2ad8a91908adac4d00
--- /dev/null
+++ b/pool/shard000/JavaScript/0002536_bridge.js
@@ -0,0 +1,97 @@
+/**
+ *
+ * A bridge between a web browser and sclang
+ * =========================================
+ *
+ * websockets <-> OSC
+ *
+ * Adds socket.io to an express app server
+ *
+ * Serves socket.io and scapi.js
+ *
+ * Connects with sclang using OSC
+ *
+ * Listens for websocket connections and relays
+ * calls to sclang, returns responses to the websocket client
+ *
+ * Usage::
+ * bridge = require('supercolliderjs-browser').bridge;
+ * app = express(),
+ * server = http.createServer(app),
+ * bridge.listen(app, server);
+ *
+ * params:
+ * app: an express app
+ * server: an http server created by express
+ * io: optional socket.io connection
+ * You may pass in an already existing one
+ * that is shared with other parts of your application
+ * schost: host that sclang is listening on [default=localhost]
+ * scport: port that sclang is listenting on [default=57120]
+ * scapiJsUrl: the URL that your web page will use to retreive
+ * the browser version of scapi.js
+ * [default=/static/scapi.js]
+ */
+
+var
+ join = require('path').join,
+ socketio = require('socket.io'),
+ express = require('express'),
+ SCAPI = require('./scapi');
+
+
+module.exports = {};
+
+module.exports.listen = function(app, server, io, schost, scport, scapiJsUrl) {
+
+ this.schost = schost ? schost : 'localhost';
+ this.scport = scport ? scport : 57120;
+
+ // hold these so you can unlisten
+ var self = this,
+ scapi = new SCAPI(this.schost, this.scport);
+
+
+ if (!io) {
+ io = socketio.listen(server);
+ }
+
+ // connect to supercollider
+ scapi.connect();
+
+ // handle any errors outside of call/response requests
+ scapi.on('error', function(err) {
+ console.error('Out of band scapi error', err);
+ });
+
+ // serve the client side javascript
+ app.get(scapiJsUrl || '/static/js/scapi.js', function (req, res) {
+ res.sendFile(join(__dirname, '../browser/scapi.js'));
+ });
+
+ // serve socket.io directory which includes various resources
+ // like flash fallbacks
+ app.use('/socket.io',
+ express.static(__dirname + '../node_modules/socket.io/lib'));
+
+ // listen to incoming websockets
+ io.sockets.on('connection', function(socket) {
+ socket.on('call', function (data) {
+ // communicate with sclang
+ var requestId = data['request_id'];
+ scapi.call(requestId, data.path, data.args)
+ .then(function(response) {
+ socket.emit('reply', {
+ 'request_id': requestId,
+ 'result': response.result
+ });
+ }, function(err) {
+ socket.emit('scapi_error', {
+ 'request_id': requestId,
+ 'result': err.result
+ });
+ });
+ });
+ });
+
+};
diff --git a/pool/shard000/JavaScript/0002537_UADataItem.js b/pool/shard000/JavaScript/0002537_UADataItem.js
new file mode 100644
index 0000000000000000000000000000000000000000..0311c020a502abd613b674711284ed595fb16b5f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002537_UADataItem.js
@@ -0,0 +1,74 @@
+"use strict";
+// Release 1.02 5 OPC Unified Architecture, Part 8
+
+// HasProperty Variable Definition String PropertyType Optional
+// HasProperty Variable ValuePrecision Double PropertyType Optional
+
+// Clients may read or write DataItems, or monitor them for value changes. The services needed for
+// these operations are specified in Part 4. Changes are defined as a change in status (quality) or a
+// change in value that exceeds a client - defined range called a Deadband. To detect the value change,
+// the difference between the current value and the last reported value is compared to the Deadband.
+
+
+// Definition is a vendor - specific, human readable string that specifies how the value of this DataItem is
+// calculated. Definition is non - localized and will often contain an equation that can be parsed by
+// certain clients.
+// Example: Definition ::= “(TempA – 25) + TempB”
+
+
+// ValuePrecision specifies the maximum precision that the server can maintain for the item based on
+// restrictions in the target environment.
+// ValuePrecision can be used for the following DataTypes:
+// * For Float and Double values it specifies the number of digits after the decimal place.
+// * For DateTime values it indicates the minimum time difference in nanoseconds. For example,
+// a ValuePrecision of 20 000 000 defines a precision of 20 ms.
+// The ValuePrecision Property is an approximation that is intended to prov ide guidance to a Client. A
+// Server is expected to silently round any value with more precision that it supports. This implies that
+// a Client may encounter cases where the value read back from a Server differs from the value that it
+// wrote to the Server. This difference shall be no more than the difference suggested by this Property
+require("requirish")._(module);
+var assert = require("assert");
+var address_space = require("lib/address_space/address_space");
+var AddressSpace = address_space.AddressSpace;
+var DataType = require("lib/datamodel/variant").DataType;
+var Variant = require("lib/datamodel/variant").Variant;
+var _ = require("underscore");
+
+var definition_Description = "Definition is a vendor - specific, human readable string that specifies how the value of this DataItem is calculated.";
+var valuePrecision_Description = "";
+
+
+function add_dataItem_stuff(variable,options) {
+
+ var address_space = variable.__address_space;
+ assert(address_space instanceof AddressSpace);
+
+ if (options.hasOwnProperty("definition")) {
+
+ variable.$definition = new Variant({ dataType: DataType.String, value: options.definition});
+
+ address_space.addVariable(variable,{
+ browseName:"Definition",
+ description: definition_Description,
+ dataType: "String",
+ typeDefinition: "PropertyType",
+ value: { get: function() { return variable.$definition; }}
+ });
+ }
+
+ if (options.hasOwnProperty("valuePrecision")) {
+
+ assert(_.isNumber(options.valuePrecision));
+ variable.$valuePrecision = new Variant({ dataType: DataType.Double, value: options.valuePrecision});
+
+ address_space.addVariable(variable,{
+ browseName:"ValuePrecision",
+ description: valuePrecision_Description,
+ dataType: "Number",
+ typeDefinition: "PropertyType",
+ value: { get: function() { return variable.$valuePrecision; }}
+ });
+ }
+}
+exports.add_dataItem_stuff = add_dataItem_stuff;
+
diff --git a/pool/shard000/JavaScript/0002539_attractor.js b/pool/shard000/JavaScript/0002539_attractor.js
new file mode 100644
index 0000000000000000000000000000000000000000..beefb4112676118b2e2c5a9547b2be0201a1775d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002539_attractor.js
@@ -0,0 +1,126 @@
+/**
+ * PhysicsJS v0.6.0 - 2014-04-22
+ * A modular, extendable, and easy-to-use physics engine for javascript
+ * http://wellcaffeinated.net/PhysicsJS
+ *
+ * Copyright (c) 2014 Jasper Palfree
+ * Licensed MIT
+ */
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ define(['physicsjs'], factory);
+ } else if (typeof exports === 'object') {
+ module.exports = factory.apply(root, ['physicsjs'].map(require));
+ } else {
+ factory.call(root, root.Physics);
+ }
+}(this, function (Physics) {
+ 'use strict';
+ /**
+ * class AttractorBehavior < Behavior
+ *
+ * `Physics.behavior('attractor')`.
+ *
+ * Attractor behavior attracts bodies to a specific point.
+ *
+ * Additional options include:
+ * - pos: The position of the attraction point
+ * - strength: How strong the attraction is (default: `1`)
+ * - order: The power of the inverse distance (default: `2` because that is newtonian gravity... inverse square)
+ * - max: The maximum distance in which to apply the attraction (default: Infinity)
+ * - min: The minimum distance above which to apply the attraction (default: very small non-zero)
+ **/
+ Physics.behavior('attractor', function( parent ){
+
+ var defaults = {
+
+ pos: null, // default to (0, 0)
+ // how strong the attraction is
+ strength: 1,
+ // power of the inverse distance (2 is inverse square)
+ order: 2,
+ // max distance to apply it to
+ max: false, // infinite
+ // min distance to apply it to
+ min: false // auto calc
+ };
+
+ return {
+
+ // extended
+ init: function( options ){
+
+ var self = this;
+ this._pos = new Physics.vector();
+ // call parent init method
+ parent.init.call( this );
+ this.options.defaults( defaults );
+ this.options.onChange(function( opts ){
+ self._maxDist = opts.max === false ? Infinity : opts.max;
+ self._minDist = opts.min ? opts.min : 10;
+ self.position( opts.pos );
+ });
+ this.options( options );
+ },
+
+ /**
+ * AttractorBehavior#position( [pos] ) -> this|Object
+ * - pos (Vectorish): The position to set
+ * + (Object): Returns the [[Vectorish]] position if no arguments provided
+ * + (this): For chaining
+ *
+ * Get or set the position of the attractor.
+ **/
+ position: function( pos ){
+
+ var self = this;
+
+ if ( pos ){
+ this._pos.clone( pos );
+ return self;
+ }
+
+ return this._pos.values();
+ },
+
+ // extended
+ behave: function( data ){
+
+ var bodies = this.getTargets()
+ ,body
+ ,order = this.options.order
+ ,strength = this.options.strength
+ ,minDist = this._minDist
+ ,maxDist = this._maxDist
+ ,scratch = Physics.scratchpad()
+ ,acc = scratch.vector()
+ ,norm
+ ,g
+ ;
+
+ for ( var j = 0, l = bodies.length; j < l; j++ ){
+
+ body = bodies[ j ];
+
+ // clone the position
+ acc.clone( this._pos );
+ acc.vsub( body.state.pos );
+ // get the distance
+ norm = acc.norm();
+
+ if (norm > minDist && norm < maxDist){
+
+ g = strength / Math.pow(norm, order);
+
+ body.accelerate( acc.normalize().mult( g ) );
+ }
+ }
+
+ scratch.done();
+ }
+ };
+ });
+
+ // end module: behaviors/attractor.js
+ return Physics;
+}));// UMD
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js b/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js
new file mode 100644
index 0000000000000000000000000000000000000000..5ca3200a0b4a62264750d86cdd6904144b4be2db
--- /dev/null
+++ b/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js
@@ -0,0 +1,20 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Custom binding for the image writer private API.
+
+var binding = require('binding').Binding.create('imageWriterPrivate');
+
+binding.registerCustomHook(function(bindingsAPI) {
+ var apiFunctions = bindingsAPI.apiFunctions;
+
+ apiFunctions.setUpdateArgumentsPostValidate(
+ 'writeFromFile', function(device, fileEntry, options, callback) {
+ var fileSystemName = fileEntry.filesystem.name;
+ var relativePath = $String.slice(fileEntry.fullPath, 1);
+ return [device, fileSystemName, relativePath, callback];
+ });
+});
+
+exports.binding = binding.generate();
diff --git a/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js b/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js
new file mode 100644
index 0000000000000000000000000000000000000000..16586bd24b43daf61d23e3c43136d43ecf9e7161
--- /dev/null
+++ b/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js
@@ -0,0 +1,71 @@
+/*
+ * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
+ *
+ * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
+ *
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License along with this program. If not, see .
+ */
+ResolveDashboardFormData = {
+ programsList : function($q, $timeout, $rootScope, UserSupervisedActivePrograms){
+ var deferred = $q.defer();
+ $timeout(function () {
+
+ UserSupervisedActivePrograms.get(function(data){
+ deferred.resolve(data.programs);
+
+ });
+
+ },100);
+
+ return deferred.promise;
+
+ },
+ formInputValue : function(messageService){
+ return {
+ yearOptionAll : messageService.get('input.year.option.all'),
+ programOptionSelect : messageService.get('input.program.option.select'),
+ scheduleOptionSelect : messageService.get('input.schedule.option.select'),
+ geographicZoneNational : messageService.get('input.geographic.zone.national'),
+ facilityOptionSelect : messageService.get('input.facility.option.select'),
+ periodOptionSelect : messageService.get('input.period.option.select')
+ };
+ },
+ userPreferredFilters : function(GetPeriod,localStorageService){
+ var date = new Date();
+ var filterObject = {};
+ var preferredFilterValues = {};
+ for(var prefKey in localStorageKeys.PREFERENCE){
+ preferredFilterValues[localStorageKeys.PREFERENCE[prefKey]] = localStorageService.get(localStorageKeys.PREFERENCE[prefKey]);
+ }
+
+ filterObject.programId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM];
+ filterObject.periodId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PERIOD];
+
+ if(!isUndefined(filterObject.periodId)){
+
+ GetPeriod.get({id:filterObject.periodId}, function(period){
+ if(!isUndefined(period.year)){
+ filterObject.year = period.year;
+ }else{
+ filterObject.year = date.getFullYear() - 1;
+ }
+ });
+ }
+ filterObject.scheduleId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_SCHEDULE];
+
+ filterObject.zoneId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_GEOGRAPHIC_ZONE];
+
+ filterObject.productIdList = !isUndefined(preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PRODUCTS]) ? preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PRODUCTS].split(',') : null;
+
+ filterObject.facilityId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_FACILITY];
+
+ filterObject.facilityId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_FACILITY];
+
+
+ return filterObject;
+ }
+};
diff --git a/pool/shard000/JavaScript/0002556_preventExtensions.js b/pool/shard000/JavaScript/0002556_preventExtensions.js
new file mode 100644
index 0000000000000000000000000000000000000000..a32f71f376be7e832de04415c015966179806daa
--- /dev/null
+++ b/pool/shard000/JavaScript/0002556_preventExtensions.js
@@ -0,0 +1,132 @@
+description(
+"This test checks whether various seal/freeze/preventExtentions work on a regular object."
+);
+
+function obj()
+{
+ // Add an accessor property to check 'isFrozen' returns the correct result for objects with accessors.
+ return Object.defineProperty({ a: 1, b: 2 }, 'g', { get: function() { return "getter"; } });
+}
+
+function test(obj)
+{
+ obj.c =3;
+ obj.b =4;
+ delete obj.a;
+
+ var result = "";
+ for (key in obj)
+ result += ("(" + key + ":" + obj[key] + ")");
+ if (Object.isSealed(obj))
+ result += "S";
+ if (Object.isFrozen(obj))
+ result += "F";
+ if (Object.isExtensible(obj))
+ result += "E";
+ return result;
+}
+
+function seal(obj)
+{
+ Object.seal(obj);
+ return obj;
+}
+
+function freeze(obj)
+{
+ Object.freeze(obj);
+ return obj;
+}
+
+function preventExtensions(obj)
+{
+ Object.preventExtensions(obj);
+ return obj;
+}
+
+function inextensible(){}
+function sealed(){}
+function frozen(){};
+preventExtensions(inextensible);
+seal(sealed);
+freeze(frozen);
+new inextensible;
+new sealed;
+new frozen;
+inextensible.prototype.prototypeExists = true;
+sealed.prototype.prototypeExists = true;
+frozen.prototype.prototypeExists = true;
+
+shouldBeTrue("(new inextensible).prototypeExists");
+shouldBeTrue("(new sealed).prototypeExists");
+shouldBeTrue("(new frozen).prototypeExists");
+
+shouldBe('test(obj())', '"(b:4)(c:3)E"'); // extensible, can delete a, can modify b, and can add c
+shouldBe('test(preventExtensions(obj()))', '"(b:4)"'); // , can delete a, can modify b, and CANNOT add c
+shouldBe('test(seal(obj()))', '"(a:1)(b:4)S"'); // sealed, CANNOT delete a, can modify b, and CANNOT add c
+shouldBe('test(freeze(obj()))', '"(a:1)(b:2)SF"'); // sealed and frozen, CANNOT delete a, CANNOT modify b, and CANNOT add c
+
+// check that we can preventExtensions on a host function.
+shouldBe('Object.preventExtensions(Math.sin)', 'Math.sin');
+
+shouldThrow('var o = {}; Object.preventExtensions(o); o.__proto__ = { newProp: "Should not see this" }; o.newProp;');
+shouldThrow('"use strict"; var o = {}; Object.preventExtensions(o); o.__proto__ = { newProp: "Should not see this" }; o.newProp;');
+
+// check that we can still access static properties on an object after calling preventExtensions.
+shouldBe('Object.preventExtensions(Math); Math.sqrt(4)', '2');
+
+// Should not be able to add properties to a preventExtensions array.
+shouldBeUndefined('var arr = Object.preventExtensions([]); arr[0] = 42; arr[0]');
+shouldBe('var arr = Object.preventExtensions([]); arr[0] = 42; arr.length', '0');
+// In strict mode, this throws.
+shouldThrow('"use strict"; var arr = Object.preventExtensions([]); arr[0] = 42; arr[0]');
+
+// A read-only property on the prototype should prevent a [[Put]] .
+function Constructor() {}
+Constructor.prototype.foo = 1;
+Object.freeze(Constructor.prototype);
+var obj = new Constructor();
+obj.foo = 2;
+shouldBe('obj.foo', '1');
+
+// Check that freezing a function works correctly.
+var func = freeze(function foo(){});
+shouldBeTrue('Object.isFrozen(func)')
+func.prototype = 42;
+shouldBeFalse('func.prototype === 42');
+shouldBeFalse('Object.getOwnPropertyDescriptor(func, "prototype").writable')
+
+// Check that freezing a strict function works correctly.
+var strictFunc = freeze(function foo(){ "use strict"; });
+shouldBeTrue('Object.isFrozen(strictFunc)')
+strictFunc.prototype = 42;
+shouldBeFalse('strictFunc.prototype === 42');
+shouldBeFalse('Object.getOwnPropertyDescriptor(strictFunc, "prototype").writable')
+
+// Check that freezing array objects works correctly.
+var array = freeze([0,1,2]);
+shouldBeTrue('Object.isFrozen(array)')
+array[0] = 3;
+shouldBe('array[0]', '0');
+shouldBeFalse('Object.getOwnPropertyDescriptor(array, "length").writable')
+
+// Check that freezing arguments objects works correctly.
+var args = freeze((function(){ return arguments; })(0,1,2));
+shouldBeTrue('Object.isFrozen(args)')
+args[0] = 3;
+shouldBe('args[0]', '0');
+shouldBeFalse('Object.getOwnPropertyDescriptor(args, "length").writable')
+shouldBeFalse('Object.getOwnPropertyDescriptor(args, "callee").writable')
+
+// Check that freeze still works if preventExtensions has been called on the object.
+function preventExtensionsFreezeIsFrozen(x)
+{
+ Object.preventExtensions(x);
+ Object.freeze(x);
+ return Object.isFrozen(x);
+}
+shouldBeTrue('preventExtensionsFreezeIsFrozen(function foo(){})')
+shouldBeTrue('preventExtensionsFreezeIsFrozen(function foo(){ "use strict"; })')
+shouldBeTrue('preventExtensionsFreezeIsFrozen([0,1,2])')
+shouldBeTrue('preventExtensionsFreezeIsFrozen((function(){ return arguments; })(0,1,2))')
+
diff --git a/pool/shard000/JavaScript/0002562_HomeController.js b/pool/shard000/JavaScript/0002562_HomeController.js
new file mode 100644
index 0000000000000000000000000000000000000000..7a308dbfa2449682e9f21f3d7ac861e4b8dc8a17
--- /dev/null
+++ b/pool/shard000/JavaScript/0002562_HomeController.js
@@ -0,0 +1,79 @@
+(function () {
+ 'use strict';
+ angular.module('app').controller('ParentHomeController', [
+ '$modal', 'ChildService', 'AdmissionService',
+ function ($modal, ChildService, AdmissionService) {
+ var self = this;
+ init();
+
+ self.action = function (actionName, childId) {
+ switch (actionName) {
+ case 'agenda':
+ showAgenda();
+ break;
+ case 'absences':
+ showAbsences(childId || null);
+ break;
+ case 'admin':
+ showAdmin();
+ break;
+ }
+ }
+
+ function showAgenda() {
+ var modalInstance = $modal.open({
+ animation: true,
+ templateUrl: 'WebApp/views/modal/agendaModal.html',
+ controller: 'AgendaModalController as modal',
+ });
+ modalInstance.result.then(function (success) {
+
+ }, function (error) {
+ });
+ }
+
+ function showAbsences(childId) {
+ var modalInstance = $modal.open({
+ animation: true,
+ size: 'lg',
+ templateUrl: 'WebApp/views/modal/addAbsenceModal.html',
+ controller: 'AddAbsenceModalController as modal',
+ resolve: {
+ items: function () {
+ return {
+ childId: childId
+ };
+ }
+ }
+ });
+ modalInstance.result.then(function (success) {
+
+ }, function (error) {
+ });
+
+ }
+
+ function showAdmin() {
+ var modalInstance = $modal.open({
+ animation: true,
+ templateUrl: 'WebApp/views/modal/parentAdministrationModal.html',
+ controller: 'ParentAdministrationModalController as modal',
+ });
+ modalInstance.result.then(function (item) {
+ AdmissionService.save(item);
+ }, function (error) {
+ });
+ }
+
+ function init() {
+
+ //self.children = ["Emmanuelle di Nicola", "Yves Cotton", "Mathieu Wautier"]
+ ChildService.getChildren().then(function (data) {
+ self.children = data.data;
+ });
+ }
+ }
+ ]);
+}
+
+)();
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002563_lang.js b/pool/shard000/JavaScript/0002563_lang.js
new file mode 100644
index 0000000000000000000000000000000000000000..9175cfa059fca0c52e1e27d402e48a51b5336e02
--- /dev/null
+++ b/pool/shard000/JavaScript/0002563_lang.js
@@ -0,0 +1,67 @@
+var Vue = require('vue');
+var VueI18n = require('vue-i18n');
+
+const locales = {
+ en: {
+ message: {
+ name: 'HUE Alarm',
+ menu_status: 'Status',
+ menu_configuration: 'Configuration',
+ config_activation: 'Activation',
+ config_part_of_schedule_name: 'Trigger by part of schedule name',
+ config_username: 'HUE username',
+ config_primary_notification_settings: 'Primary notification settings',
+ config_primary_notification_url: 'Notification URL (GET)',
+ config_primary_notification_speed: 'Notification speed (seconds)',
+ config_primary_notification_test_mode: 'Test mode',
+ config_primary_notification_test: 'Test notification',
+ config_secondary_notification_settings: 'Secundary notification settings',
+ config_smtp_password: "SMTP password",
+ config_smtp_server_name: "SMTP server name",
+ config_smtp_port: "SMTP port",
+ config_from: "FROM email address",
+ config_to: "TO email address",
+ config_message: "Message",
+ enabled: "Enabled",
+ config_admin_password: "Admin password",
+ config_admin_username: "Admin username",
+ config_administration: "Administration"
+ }
+ },
+ nl: {
+ message: {
+ name: 'HUE Alarm',
+ menu_status: 'Status',
+ menu_configuration: 'Instellingen',
+ config_activation: 'Activering',
+ config_part_of_schedule_name: 'Activeer door woord in routine naam',
+ config_username: 'HUE gebruikersnaam',
+ config_primary_notification_settings: 'Hoofd notificatie instellingen',
+ config_primary_notification_url: 'Notificatie URL (GET)',
+ config_primary_notification_speed: 'Notification snelheid (seconden)',
+ config_primary_notification_test_mode: 'Test modus',
+ config_primary_notification_test: 'Test notificatie',
+ config_secondary_notification_settings: 'Secundaire notificatie instellingen',
+ config_smtp_password: 'SMTP wachtwoord',
+ config_smtp_server_name: "SMTP server naam",
+ config_smtp_port: "SMTP poort",
+ config_from: "FROM email adres",
+ config_to: "TO email adres",
+ config_message: "Informatie",
+ enabled: "Enabled",
+ config_admin_password: "Admin wachtwoord",
+ config_admin_username: "Admin gebruikersnaam",
+ config_administration: "Beheer"
+
+ }
+ }
+ };
+
+export function activateLanguage() {
+ Vue.use(VueI18n);
+ Vue.config.lang = 'en';
+
+ Object.keys(locales).forEach(function (lang) {
+ Vue.locale(lang, locales[lang])
+ });
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002564_App.js b/pool/shard000/JavaScript/0002564_App.js
new file mode 100644
index 0000000000000000000000000000000000000000..5882d227506add58c96c89805985bbec7a0bc0cd
--- /dev/null
+++ b/pool/shard000/JavaScript/0002564_App.js
@@ -0,0 +1,93 @@
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+
+import styles from 'styles/base.scss';
+
+import {
+ ALL_ROUTES_PATH,
+ ROUTE_PATH,
+ DIRECTION_PATH,
+ SAVED_PATH,
+} from 'constants/Paths';
+
+import MapLayer from 'components/Map';
+import RouteList from 'components/RouteList';
+import StopList from 'components/StopList';
+import NavBar from 'components/NavBar';
+import Saved from 'components/Saved';
+import VehiclesLoading from 'components/VehiclesLoading';
+
+import { getRoutes, getVehicles, initialVehiclesLoaded } from 'actions/oba';
+import { restoreSavedRoutes } from 'actions/saved';
+
+
+class App extends Component {
+ static propTypes = {
+ globalError: PropTypes.string,
+ route: PropTypes.object,
+ getRoutes: PropTypes.func,
+ getVehicles: PropTypes.func,
+ initialVehiclesLoaded: PropTypes.func,
+ restoreSavedRoutes: PropTypes.func.isRequired,
+ }
+
+ componentDidMount() {
+ this.props.restoreSavedRoutes();
+
+ this.props.getVehicles().then(() => {
+ this.props.initialVehiclesLoaded();
+ });
+ this.watchVehicles = setInterval(this.props.getVehicles, 30000);
+ }
+
+ componentWillUnmount() {
+ clearInterval(this.watchVehicles);
+ }
+
+ _renderGlobalError = () => {this.props.globalError}
;
+
+ _renderGlobalError() {
+ return {this.props.globalError}
;
+ }
+
+ _renderContext = () => {
+ const name = this.props.route.name;
+ switch (name) {
+ case ALL_ROUTES_PATH:
+ return ;
+ case ROUTE_PATH:
+ return ;
+ case DIRECTION_PATH:
+ return ;
+ case SAVED_PATH:
+ return ;
+ default:
+ return null;
+ }
+ }
+
+ render() {
+ return (
+
+
+
+
+ { this._renderContext() }
+
+ );
+ }
+}
+
+const mapDispatchToProps = {
+ getRoutes,
+ getVehicles,
+ initialVehiclesLoaded,
+ restoreSavedRoutes,
+};
+
+const mapStateToProps = (state) => ({
+ globalError: state.ui.globalError,
+ route: state.ui.route,
+});
+
+export default connect(mapStateToProps, mapDispatchToProps)(App);
diff --git a/pool/shard000/JavaScript/0002565_serve.js b/pool/shard000/JavaScript/0002565_serve.js
new file mode 100644
index 0000000000000000000000000000000000000000..53bc464b7822e0da0fb27644647e1637f1d0995d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002565_serve.js
@@ -0,0 +1,39 @@
+module.exports = function (gulp, plugins, config, env) {
+ const browserSync = require('browser-sync');
+
+ function getTask(task) {
+ return require('./tasks/' + task)(gulp, plugins, config, env);
+ }
+
+ gulp.task('ws', () =>
+ browserSync(config.browsersync)
+ );
+
+ gulp.task('watch:html', () =>
+ gulp.watch(config.src.html,
+ gulp.parallel(getTask('html'))
+ )
+ );
+
+ gulp.task('watch:javascript', () =>
+ gulp.watch(config.src.javascript,
+ gulp.parallel(getTask('eslint'), getTask('javascript'))
+ )
+ );
+
+ gulp.task('watch:styles', () =>
+ gulp.watch(config.src.sass,
+ gulp.parallel(getTask('sasslint'), getTask('sass'))
+ )
+ );
+
+ gulp.task('watch:json', () =>
+ gulp.watch(config.src.json,
+ gulp.parallel(getTask('jsonMinify'))
+ )
+ );
+
+ gulp.task('watch',
+ gulp.parallel('watch:html', 'watch:styles', 'watch:javascript', 'watch:json')
+ );
+};
diff --git a/pool/shard000/JavaScript/0002566_hexahedron.js b/pool/shard000/JavaScript/0002566_hexahedron.js
new file mode 100644
index 0000000000000000000000000000000000000000..07bc5dd0d4ac4aeff5b61384777c744437fb2a8e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002566_hexahedron.js
@@ -0,0 +1,29 @@
+let Hexahedron = function () {
+ let _ = Object.create(Primitive);
+
+ _.name = "cube";
+
+ _.getShapeBuilder = function () {
+ let builder = ShapeBuilder.new();
+
+ builder.addVertex([-1, -1, -1]);
+ builder.addVertex([-1, 1, -1]);
+ builder.addVertex([1, 1, -1]);
+ builder.addVertex([1, -1, -1]);
+ builder.addVertex([-1, -1, 1]);
+ builder.addVertex([-1, 1, 1]);
+ builder.addVertex([1, 1, 1]);
+ builder.addVertex([1, -1, 1]);
+
+ builder.addFace([0, 1, 2, 0, 2, 3]); // Front face
+ builder.addFace([7, 6, 5, 7, 5, 4]); // Back face
+ builder.addFace([1, 5, 6, 1, 6, 2]); // Top face
+ builder.addFace([4, 0, 3, 4, 3, 7]); // Bottom face
+ builder.addFace([4, 5, 1, 4, 1, 0]); // Left face
+ builder.addFace([3, 2, 6, 3, 6, 7]); // Right face
+
+ return builder;
+ };
+
+ return _;
+}();
diff --git a/pool/shard000/JavaScript/0002567_AllocationTopbar.js b/pool/shard000/JavaScript/0002567_AllocationTopbar.js
new file mode 100644
index 0000000000000000000000000000000000000000..7c7419fc5f4564a34f3b683353c405366158626b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002567_AllocationTopbar.js
@@ -0,0 +1,68 @@
+import FontIcon from 'material-ui/FontIcon'
+import React, { PureComponent, PropTypes } from 'react'
+import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation'
+import { withRouter } from 'react-router'
+
+const infoIcon = info_outline
+const filesIcon = storage
+const logsIcon = subject
+const rawIcon = code
+
+class _AllocationTopbar extends PureComponent {
+
+ handleActive (tab) {
+ const path = ['nomad', this.props.router.params.region, 'allocations', this.props.allocation.ID, tab]
+ this.props.router.push(path.map(encodeURIComponent).join('/'))
+ }
+
+ getActiveTab () {
+ const location = this.props.location
+ const end = location.pathname.split('/').pop()
+
+ if (end.startsWith('info')) {
+ return 0
+ }
+
+ if (location.query.path && location.query.path.indexOf('alloc/logs') !== -1) {
+ return 2
+ }
+
+ if (end.startsWith('files')) {
+ return 1
+ }
+
+ if (end.startsWith('raw')) {
+ return 3
+ }
+
+ return 0
+ }
+
+ getStyle () {
+ return {
+ borderBottom: '1px solid #e0e0e0',
+ marginBottom: 10
+ }
+ }
+
+ render () {
+ return (
+
+ this.handleActive('info') } />
+ this.handleActive('files') } />
+ this.handleActive('logs') } />
+ this.handleActive('raw') } />
+
+ )
+ }
+}
+
+_AllocationTopbar.propTypes = {
+ router: PropTypes.object.isRequired,
+ location: PropTypes.object.isRequired,
+ allocation: PropTypes.object.isRequired
+}
+
+const AllocationTopbar = withRouter(_AllocationTopbar)
+
+export default AllocationTopbar
diff --git a/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js b/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js
new file mode 100644
index 0000000000000000000000000000000000000000..03387abb1d7d7a2084c6f051b9869d20d408836c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js
@@ -0,0 +1,100 @@
+Ext.ns('CMS.structureEditor');
+
+/**
+ * @class CMS.structureEditor.ChooseBaseLayoutWindow
+ * @extends CMS.MainWindow
+ * Window for choosing the base layout
+ */
+CMS.structureEditor.ChooseBaseLayoutWindow = Ext.extend(CMS.MainWindow, {
+ cls: 'CMSchoosebaselayoutwindow',
+ modal: true,
+ border: false,
+ resizable: false,
+ closable: false,
+ maxWidth: 1100,
+
+ callback: null,
+
+ scope: null,
+
+ baseLayouts: null,
+
+ initComponent: function () {
+ this.title = CMS.i18n(null, 'templateStructureEditor.chooseBaseLayout.title');
+ var store = new Ext.data.JsonStore({
+ autoDestroy: true,
+ fields: [
+ {name: 'id', type: 'string'},
+ {name: 'name', type: 'string'},
+ {name: 'previewImageUrl', type: 'string'},
+ {name: 'type', type: 'string'}
+ ]
+ });
+ store.sort([{
+ field: 'type',
+ direction: 'DESC'
+ }, {
+ field: 'id',
+ direction: 'ASC'
+ }], 'ASC');
+ store.loadData(this.baseLayouts);
+ var tpl = new Ext.XTemplate(
+ '',
+ '',
+ '
',
+ '
{[values.name]}
',
+ '
',
+ '',
+ ' '
+ );
+ Ext.apply(this, {
+ layout: 'fit',
+ items: [{
+ xtype: 'CMSthumbview',
+ itemSelector: 'div.baselayout-wrap',
+ overClass: 'hover',
+ selectedClass: 'selected',
+ singleSelect: true,
+ tpl: tpl,
+ store: store,
+
+ ref: 'thumbView',
+ trackOver: true,
+ scrollOffset: 10,
+ listeners: {
+ click: this.clickHandler,
+ scope: this
+ }
+ }]
+ });
+ CMS.structureEditor.ChooseBaseLayoutWindow.superclass.initComponent.apply(this, arguments);
+ },
+
+ clickHandler: function (dataView) {
+ var baseLayout = dataView.getSelectedRecords()[0].data;
+ this.executeCallback(baseLayout);
+ this.destroy();
+ },
+
+ /**
+ * @private
+ *
+ * Executes the callback function if set with the given param
+ *
+ * @param {Object} baseLayout
+ */
+ executeCallback: function (baseLayout) {
+ //execute handler function
+ if (this.callback) {
+ this.callback.call(this.scope || window, baseLayout, this);
+ }
+ },
+
+ destroy: function () {
+ this.templateSnippetStore = null;
+
+ CMS.structureEditor.ChooseBaseLayoutWindow.superclass.destroy.apply(this, arguments);
+ }
+});
+
+Ext.reg('CMSchoosebaselayoutwindow', CMS.structureEditor.ChooseBaseLayoutWindow);
diff --git a/pool/shard000/JavaScript/0002572_atom-alopex-view.js b/pool/shard000/JavaScript/0002572_atom-alopex-view.js
new file mode 100644
index 0000000000000000000000000000000000000000..5d31c2771a1c07de12bc6c4cb9af3fe8b61fede8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002572_atom-alopex-view.js
@@ -0,0 +1,29 @@
+'use babel';
+
+export default class AtomAlopexView {
+
+ constructor(serializedState) {
+ // Create root element
+ this.element = document.createElement('div');
+ this.element.classList.add('atom-alopex');
+
+ // Create message element
+ const message = document.createElement('div');
+ message.textContent = 'The AtomAlopex package is Alive! It\'s ALIVE!';
+ message.classList.add('message');
+ this.element.appendChild(message);
+ }
+
+ // Returns an object that can be retrieved when package is activated
+ serialize() {}
+
+ // Tear down any state and detach
+ destroy() {
+ this.element.remove();
+ }
+
+ getElement() {
+ return this.element;
+ }
+
+}
diff --git a/pool/shard000/JavaScript/0002577_ionicUpdate.js b/pool/shard000/JavaScript/0002577_ionicUpdate.js
new file mode 100644
index 0000000000000000000000000000000000000000..eb905b6e4f228bcf1eebcccd239d33baf64b877e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002577_ionicUpdate.js
@@ -0,0 +1,122 @@
+angular.module('ionic.services.update', ['ionic.services.common'])
+
+/**
+ * @ngdoc service
+ * @name $ionicUpdate
+ * @module ionic.services.update
+ * @description
+ *
+ * A simple way to push updates to your app.
+ *
+ * Initialize the service with your app id before calling other functions.
+ * Then, use the check, download, extract and load functions to update and/or load
+ * the updated version of your app.
+ *
+ * @usage
+ * ```javascript
+ * $ionicUpdate.initialize('8cdd99a2');
+ *
+ * // Check for updates
+ * $ionicUpdate.check().then(function(response) {
+ * // response will be true/false
+ * if (response) {
+ * // Download the updates
+ * $ionicUpdate.download().then(function() {
+ * // Extract the updates
+ * $ionicUpdate.extract().then(function() {
+ * // Load the updated version
+ * $ionicTrack.load();
+ * }, function(error) {
+ * // Error extracting
+ * }, function(progress) {
+ * // Do something with the zip extraction progress
+ * $scope.extraction_progress = progress;
+ * });
+ * }, function(error) {
+ * // Error downloading the updates
+ * }, function(progress) {
+ * // Do something with the download progress
+ * $scope.download_progress = progress;
+ * });
+ * }
+ * } else {
+ * // No updates, load the most up to date version of the app
+ * $ionicUpdate.load();
+ * }, function(error) {
+ * // Error checking for updates
+ * })
+ * ```
+ */
+.factory('$ionicUpdate', [
+ '$q',
+ function($q) {
+ return {
+ check: function() {
+ var deferred = $q.defer();
+
+ if (typeof IonicUpdate != "undefined") {
+ IonicUpdate.check(function(result) {
+ deferred.resolve(result === 'true');
+ }, function(error) {
+ deferred.reject(error);
+ });
+ } else {
+ deferred.reject("Plugin not loaded");
+ }
+
+ return deferred.promise;
+ },
+
+ download: function() {
+ var deferred = $q.defer();
+
+ if (typeof IonicUpdate != "undefined") {
+ IonicUpdate.download(function(result) {
+ if (result !== 'true' && result !== 'false') {
+ deferred.notify(result);
+ } else {
+ deferred.resolve(result === 'true');
+ }
+ }, function(error) {
+ deferred.reject(error);
+ });
+ } else {
+ deferred.reject("Plugin not loaded");
+ }
+
+ return deferred.promise;
+ },
+
+ extract: function() {
+ var deferred = $q.defer();
+
+ if (typeof IonicUpdate != "undefined") {
+ IonicUpdate.extract(function(result) {
+ if (result !== 'done') {
+ deferred.notify(result);
+ } else {
+ deferred.resolve(result);
+ }
+ }, function(error) {
+ deferred.reject(error);
+ });
+ } else {
+ deferred.reject("Plugin not loaded");
+ }
+
+ return deferred.promise;
+ },
+
+ load: function() {
+ if (typeof IonicUpdate != "undefined") {
+ IonicUpdate.redirect();
+ }
+ },
+
+ initialize: function(app_id) {
+ if (typeof IonicUpdate != "undefined") {
+ IonicUpdate.initialize(app_id);
+ }
+ }
+ }
+}])
diff --git a/pool/shard000/JavaScript/0002580_EnvironmentController.js b/pool/shard000/JavaScript/0002580_EnvironmentController.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b6df800da7263c3b0b7d3866368e7fb1a9f5c6b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002580_EnvironmentController.js
@@ -0,0 +1,157 @@
+(function(){
+
+ define([], function(){
+
+ return function($scope, Environment, Api , $window, library){
+
+ $scope.environment = Environment
+
+ //Initial folder get
+ Api.getFolder().$promise.then(function(data){
+
+
+ $scope.environment.availableFolders = data.folders
+
+ $scope.environment.allFiles = []
+ $scope.environment.availableFolders.map(function(folder){
+
+ folder.files.map(function(file){
+ $scope.environment.allFiles.push(file)
+ })
+ })
+
+ $scope.environment.matchingDatasets =
+ $scope.environment.allFiles
+
+
+ })
+
+ $scope.$watch('environment.selectedFolder', function(newval, oldval){
+ if (newval){
+ $scope.environment.availableFiles = $scope.environment.selectedFolder.files
+ }
+ })
+
+ $scope.$watch('environment.searchTerm', function(newval, oldval){
+ if (newval == "" || typeof newval == 'undefined'){
+ $scope.environment.matchingDatasets = $scope.environment.allFiles
+ return
+ }
+
+ if (newval.length > 2) {
+ var matchingTerms = library.search(newval, -80)
+ var matchingFiles = []
+
+ for (term in matchingTerms){
+
+ for (file in $scope.environment.allFiles) {
+
+ var filetag = $scope.environment.allFiles[file].tag
+
+ var matchingTag = matchingTerms[term].phrase.value
+
+ if (filetag == matchingTag){
+ matchingFiles.push($scope.environment.allFiles[file])
+ }
+ }
+ }
+
+ $scope.environment.matchingDatasets = matchingFiles
+
+ }
+ })
+
+ $scope.$on('visualizeGraph', function(event, file){
+ if (file &&
+ $scope.environment.zScoreThreshold.max &&
+ $scope.environment.zScoreThreshold.min){
+
+ var params = {
+ collection: file.collection,
+ format: "cytoscape",
+ interactionThreshold: 1,
+ zScoreThresholdMin: $scope.environment.zScoreThreshold.min,
+ zScoreThresholdMax: $scope.environment.zScoreThreshold.max,
+ }
+
+ Api.getFile(params).$promise.then(function(data){
+ $scope.environment.graph = data
+ $scope.environment.displayEdges = [].concat(data.elements.edges)
+ })
+ }
+ })
+
+ $scope.$on('geneExplore', function(event, search){
+ if(search.gene &&
+ $scope.environment.zScoreThreshold &&
+ $scope.environment.zScoreThreshold.max &&
+ $scope.environment.zScoreThreshold.min){
+
+ var params = {
+ collection: search.collection,
+ gene: search.gene,
+ interactionThreshold: 1,
+ zScoreThresholdMin: $scope.environment.zScoreThreshold.min,
+ zScoreThresholdMax: $scope.environment.zScoreThreshold.max,
+ format: "cytoscape"
+ }
+
+ Api.getNearby(params).$promise.then(function(data){
+ $scope.environment.graph = data
+ $scope.environment.displayEdges = [].concat(data.elements.edges)
+ })
+ }
+ })
+
+ $scope.$on('downloadGraph', function(event, file){
+ if (file &&
+ $scope.environment.zScoreThreshold.max &&
+ $scope.environment.zScoreThreshold.min){
+
+ var params = {
+ collection: file.collection,
+ format: 'tsv',
+ interactionThreshold: 1,
+ zScoreThresholdMin: $scope.environment.zScoreThreshold.min,
+ zScoreThresholdMax: $scope.environment.zScoreThreshold.max,
+ file: true
+ }
+
+ var string = "collection=" + params.collection
+ + "&file=true&format=tsv&interactionThreshold=1&zScoreThresholdMax="
+ + params.zScoreThresholdMax + "&zScoreThresholdMin="
+ + params.zScoreThresholdMin
+
+ $window.open('/file?' + string)
+ }
+ })
+
+ $scope.visualizeGraph = function(file){
+ if($scope.environment.selectedGene){
+ $scope.$emit('geneExplore', {
+ gene: $scope.environment.selectedGene,
+ collection: file.collection
+ })
+ } else {
+
+ $scope.$emit('visualizeGraph', file)
+ }
+ }
+
+ $scope.downloadGraph = function(file){
+ $scope.$emit('downloadGraph', file)
+ }
+
+ $scope.itemsByPage=15;
+ $scope.getters = {
+ source: function(value){ return value.data.source},
+ target: function(value){ return value.data.target},
+ interaction: function(value){ return value.data.interaction},
+ zScore: function(value){ return value.data.zScore}
+ }
+
+ }
+
+ })
+
+})()
diff --git a/pool/shard000/JavaScript/0002582_toolbar.js b/pool/shard000/JavaScript/0002582_toolbar.js
new file mode 100644
index 0000000000000000000000000000000000000000..a14d67184aea84dc146958e53645b841d953a316
--- /dev/null
+++ b/pool/shard000/JavaScript/0002582_toolbar.js
@@ -0,0 +1,244 @@
+/*!
+ * Angular Material Design
+ * https://github.com/angular/material
+ * @license MIT
+ * v1.1.0-rc4-master-2806ec8
+ */
+goog.provide('ng.material.components.toolbar');
+goog.require('ng.material.components.content');
+goog.require('ng.material.core');
+/**
+ * @ngdoc module
+ * @name material.components.toolbar
+ */
+angular.module('material.components.toolbar', [
+ 'material.core',
+ 'material.components.content'
+])
+ .directive('mdToolbar', mdToolbarDirective);
+
+/**
+ * @ngdoc directive
+ * @name mdToolbar
+ * @module material.components.toolbar
+ * @restrict E
+ * @description
+ * `md-toolbar` is used to place a toolbar in your app.
+ *
+ * Toolbars are usually used above a content area to display the title of the
+ * current page, and show relevant action buttons for that page.
+ *
+ * You can change the height of the toolbar by adding either the
+ * `md-medium-tall` or `md-tall` class to the toolbar.
+ *
+ * @usage
+ *
+ *
+ *
+ *
+ *
+ * My App's Title
+ *
+ *
+ *
+ *
+ *
+ * Right Bar Button
+ *
+ *
+ *
+ *
+ *
+ * Hello!
+ *
+ *
+ *
+ *
+ * @param {boolean=} md-scroll-shrink Whether the header should shrink away as
+ * the user scrolls down, and reveal itself as the user scrolls up.
+ *
+ * _**Note (1):** for scrollShrink to work, the toolbar must be a sibling of a
+ * `md-content` element, placed before it. See the scroll shrink demo._
+ *
+ * _**Note (2):** The `md-scroll-shrink` attribute is only parsed on component
+ * initialization, it does not watch for scope changes._
+ *
+ *
+ * @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's
+ * shrinking by. For example, if 0.25 is given then the toolbar will shrink
+ * at one fourth the rate at which the user scrolls down. Default 0.5.
+ */
+
+function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming, $animate) {
+ var translateY = angular.bind(null, $mdUtil.supplant, 'translate3d(0,{0}px,0)');
+
+ return {
+ template: '',
+ restrict: 'E',
+
+ link: function(scope, element, attr) {
+
+ element.addClass('_md'); // private md component indicator for styling
+ $mdTheming(element);
+
+ if (angular.isDefined(attr.mdScrollShrink)) {
+ setupScrollShrink();
+ }
+
+ function setupScrollShrink() {
+
+ var toolbarHeight;
+ var contentElement;
+ var disableScrollShrink = angular.noop;
+
+ // Current "y" position of scroll
+ // Store the last scroll top position
+ var y = 0;
+ var prevScrollTop = 0;
+ var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5;
+
+ var debouncedContentScroll = $$rAF.throttle(onContentScroll);
+ var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000);
+
+ // Wait for $mdContentLoaded event from mdContent directive.
+ // If the mdContent element is a sibling of our toolbar, hook it up
+ // to scroll events.
+
+ scope.$on('$mdContentLoaded', onMdContentLoad);
+
+ // If the toolbar is used inside an ng-if statement, we may miss the
+ // $mdContentLoaded event, so we attempt to fake it if we have a
+ // md-content close enough.
+
+ attr.$observe('mdScrollShrink', onChangeScrollShrink);
+
+ // If the toolbar has ngShow or ngHide we need to update height immediately as it changed
+ // and not wait for $mdUtil.debounce to happen
+
+ if (attr.ngShow) { scope.$watch(attr.ngShow, updateToolbarHeight); }
+ if (attr.ngHide) { scope.$watch(attr.ngHide, updateToolbarHeight); }
+
+ // If the scope is destroyed (which could happen with ng-if), make sure
+ // to disable scroll shrinking again
+
+ scope.$on('$destroy', disableScrollShrink);
+
+ /**
+ *
+ */
+ function onChangeScrollShrink(shrinkWithScroll) {
+ var closestContent = element.parent().find('md-content');
+
+ // If we have a content element, fake the call; this might still fail
+ // if the content element isn't a sibling of the toolbar
+
+ if (!contentElement && closestContent.length) {
+ onMdContentLoad(null, closestContent);
+ }
+
+ // Evaluate the expression
+ shrinkWithScroll = scope.$eval(shrinkWithScroll);
+
+ // Disable only if the attribute's expression evaluates to false
+ if (shrinkWithScroll === false) {
+ disableScrollShrink();
+ } else {
+ disableScrollShrink = enableScrollShrink();
+ }
+ }
+
+ /**
+ *
+ */
+ function onMdContentLoad($event, newContentEl) {
+ // Toolbar and content must be siblings
+ if (newContentEl && element.parent()[0] === newContentEl.parent()[0]) {
+ // unhook old content event listener if exists
+ if (contentElement) {
+ contentElement.off('scroll', debouncedContentScroll);
+ }
+
+ contentElement = newContentEl;
+ disableScrollShrink = enableScrollShrink();
+ }
+ }
+
+ /**
+ *
+ */
+ function onContentScroll(e) {
+ var scrollTop = e ? e.target.scrollTop : prevScrollTop;
+
+ debouncedUpdateHeight();
+
+ y = Math.min(
+ toolbarHeight / shrinkSpeedFactor,
+ Math.max(0, y + scrollTop - prevScrollTop)
+ );
+
+ element.css($mdConstant.CSS.TRANSFORM, translateY([-y * shrinkSpeedFactor]));
+ contentElement.css($mdConstant.CSS.TRANSFORM, translateY([(toolbarHeight - y) * shrinkSpeedFactor]));
+
+ prevScrollTop = scrollTop;
+
+ $mdUtil.nextTick(function() {
+ var hasWhiteFrame = element.hasClass('md-whiteframe-z1');
+
+ if (hasWhiteFrame && !y) {
+ $animate.removeClass(element, 'md-whiteframe-z1');
+ } else if (!hasWhiteFrame && y) {
+ $animate.addClass(element, 'md-whiteframe-z1');
+ }
+ });
+
+ }
+
+ /**
+ *
+ */
+ function enableScrollShrink() {
+ if (!contentElement) return angular.noop; // no md-content
+
+ contentElement.on('scroll', debouncedContentScroll);
+ contentElement.attr('scroll-shrink', 'true');
+
+ $$rAF(updateToolbarHeight);
+
+ return function disableScrollShrink() {
+ contentElement.off('scroll', debouncedContentScroll);
+ contentElement.attr('scroll-shrink', 'false');
+
+ $$rAF(updateToolbarHeight);
+ }
+ }
+
+ /**
+ *
+ */
+ function updateToolbarHeight() {
+ toolbarHeight = element.prop('offsetHeight');
+ // Add a negative margin-top the size of the toolbar to the content el.
+ // The content will start transformed down the toolbarHeight amount,
+ // so everything looks normal.
+ //
+ // As the user scrolls down, the content will be transformed up slowly
+ // to put the content underneath where the toolbar was.
+ var margin = (-toolbarHeight * shrinkSpeedFactor) + 'px';
+
+ contentElement.css({
+ "margin-top": margin,
+ "margin-bottom": margin
+ });
+
+ onContentScroll();
+ }
+
+ }
+
+ }
+ };
+
+}
+mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming", "$animate"];
+
+ng.material.components.toolbar = angular.module("material.components.toolbar");
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002583_gen-async.js b/pool/shard000/JavaScript/0002583_gen-async.js
new file mode 100644
index 0000000000000000000000000000000000000000..0b335c12e651b0eb9128e2b4f49cb289d224a1fb
--- /dev/null
+++ b/pool/shard000/JavaScript/0002583_gen-async.js
@@ -0,0 +1,20 @@
+// Utility function to simulate async/await through generators
+function gen_async(generatorFunc) {
+ function continuer(verb, arg) {
+ var result;
+ try {
+ result = generator[verb](arg);
+ } catch (err) {
+ return Promise.reject(err);
+ }
+ if (result.done) {
+ return result.value;
+ } else {
+ return Promise.resolve(result.value).then(onFulfilled, onRejected);
+ }
+ }
+ var generator = generatorFunc();
+ var onFulfilled = continuer.bind(continuer, "next");
+ var onRejected = continuer.bind(continuer, "throw");
+ return onFulfilled();
+}
diff --git a/pool/shard000/JavaScript/0002584_index.js b/pool/shard000/JavaScript/0002584_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..13dd8c23b6db052621d2da1244e0379a3abd4b17
--- /dev/null
+++ b/pool/shard000/JavaScript/0002584_index.js
@@ -0,0 +1,73 @@
+import isArray from './util/is-array';
+import isPlainObject from './util/is-plain-object';
+import isString from './util/is-string';
+import extend from './util/extend';
+
+/**
+ * Converts an array of primitives or objects to a plain object.
+ *
+ * @param {Array} array The initial array to convert.
+ * @param {Object} [options] User defined options to override defaults.
+ * @param {String} [options.key] If `array` is an array of objects and each object has a property with the value of `key`, use those as the properties of the result object. By default the index of each item in array is used.
+ * @param {String} [options.keyPrefix=''] A string that prefixes the keys of the result object. If anything than string is provided, it takes the default value ('').
+ * @param {String} [options.keySuffix=''] A string that suffixes the keys of the result object. If anything than string is provided, it takes the default value ('').
+ * @param {Boolean} [options.deleteKey=false] Deletes the property of each item of the result object if `key` is specified and exists in current object. If `key` does not exist in current item or current item is not an object, leaves the property as is.
+ * @param {Boolean} [options.inheritProto=false] Determines if the result object should inherit from the `Object.prototype`.
+ * @throws {TypeError} Will throw if `array` is not an Array.
+ * @return {Object} The converted object.
+ */
+function arr2obj(array, options) {
+ if (!isArray(array)) {
+ throw new TypeError('arr2obj must be called on an Array');
+ }
+
+ /**
+ * Dictionary of default options
+ * @private
+ * @type {Object}
+ */
+ const defaults = {
+ key: null,
+ keyPrefix: '',
+ keySuffix: '',
+ deleteKey: false,
+ inheritProto: false
+ };
+
+ /**
+ * Copy of default and user options
+ * @private
+ * @type {Object}
+ */
+ const settings = isPlainObject(options) ? extend({}, defaults, options) : extend({}, defaults);
+
+ // Extract data from `settings` into dinstict variables.
+ let {key, keyPrefix, keySuffix, deleteKey, inheritProto} = settings;
+
+ // Failsafe if `keyPrefix` or `keySuffix` are not strings.
+ keyPrefix = isString(keyPrefix) ? keyPrefix : '';
+ keySuffix = isString(keySuffix) ? keySuffix : '';
+
+ /**
+ * The converted result object
+ * @private
+ * @type {Object}
+ */
+ const converted = array.reduce(function (accum, current, index) {
+ if (!key || !current[key]) {
+ accum[keyPrefix + index + keySuffix] = current;
+ } else {
+ accum[keyPrefix + current[key] + keySuffix] = current;
+ }
+
+ if (deleteKey && key && isPlainObject(current)) {
+ delete current[key];
+ }
+
+ return accum;
+ }, inheritProto ? {} : Object.create(null));
+
+ return converted;
+}
+
+export default arr2obj;
diff --git a/pool/shard000/JavaScript/0002588_troubleshooterController.js b/pool/shard000/JavaScript/0002588_troubleshooterController.js
new file mode 100644
index 0000000000000000000000000000000000000000..4d93994a4ba312687e9aa704024f8fbd42603acd
--- /dev/null
+++ b/pool/shard000/JavaScript/0002588_troubleshooterController.js
@@ -0,0 +1,43 @@
+angular
+.module( "networkTroubleshooter")
+.controller( "troubleshooterController", function( $scope, $location ){
+
+ $scope.current_guide = {
+ show: false,
+ url: "",
+ name: ""
+ };
+
+ $scope.gotoNextPage = function (url) {
+ $location.path(url);
+ };
+
+ $scope.gotoNextEnquiry = function ( next ){
+ if( next ){
+ $scope.enquiry.historyList.push( $scope.enquiry.current );
+ $scope.enquiry.currentID = next;
+ $scope.enquiry.current = model.issueList[ next ];
+ setTimeout( function () {
+ window.componentHandler.upgradeDom();
+ } , 100 );
+
+ }
+ };
+
+ $scope.historyBacktrack = function ( index ){
+ $scope.enquiry.current = $scope.enquiry.historyList[index];
+ $scope.enquiry.historyList = $scope.enquiry.historyList.slice( 0, index );
+ window.setTimeout( window.componentHandler.upgradeDom, 100 );
+ };
+
+ $scope.showGuide = function (_guide) {
+
+ $scope.current_guide.url = 'partials/guides/' + _guide.url ;
+ $scope.current_guide.name = _guide.name;
+ $scope.current_guide.show = true;
+
+ console.log("Guide URL: ", 'partials/guides/' + _guide.url );
+ };
+
+});
+
diff --git a/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js b/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..b323d1f37375e3d489d930b991eaac8851313867
--- /dev/null
+++ b/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js
@@ -0,0 +1,63 @@
+/**
+ * @aauthor Michael Cuccaro
+ * @see https://github.com/mvcuccaro
+ *
+ * directive to create a 4 checkbox input control for setting crud bits (search 1, insert 2, update 3, remove 4)
+ * The directive binds to an external value via the "bitvalue" attribute which will be the sum of all bits checked in the control
+ *
+ * @return {angular directive} { returns an angular directive}
+ */
+var directive_mvc_crudbits = function() {
+ //app.directive('crudBits', function() {
+ var static_bits = {
+ search: 1,
+ insert: 2,
+ update: 4,
+ remove: 8
+ };
+
+ var controller = function($scope, $element, $attrs){
+ /**
+ * Check the current bit value and see if it contains the bit of the type requested in arg_type
+ *
+ * @param {string} The type of the bit (search, insert, update or remove)
+ * @return {int} The contained bit or zero if bit value does not contain the bit
+ */
+ $scope.checkBitValue = function(arg_type){
+ return $scope.bitvalue & static_bits[arg_type];
+ }
+
+ /**
+ * Add up all the checked bits and set the bound bitvalue to the sum
+ */
+ $scope.updateBitValue = function(){
+ //sets the index to 0 if there is no index provided.
+ var rindex = angular.isUndefined($attrs.rindex) ? 0 : $attrs.rindex;
+
+ //add up all the checked bits
+ var new_bit_value = $element.find('#crud_bits_search_checkbox_' + rindex).prop('checked') == true ? static_bits.search : 0;
+ new_bit_value += $element.find('#crud_bits_insert_checkbox_' + rindex).prop('checked') == true ? static_bits.insert : 0;
+ new_bit_value += $element.find('#crud_bits_update_checkbox_' + rindex).prop('checked') == true ? static_bits.update : 0;
+ new_bit_value += $element.find('#crud_bits_remove_checkbox_' + rindex).prop('checked') == true ? static_bits.remove : 0;
+
+ //update the bound value
+ $scope.bitvalue = new_bit_value;
+ }
+ };
+
+ return {
+ restrict: 'AE',
+ replace: 'true',
+ scope: {
+ bitvalue: '=',
+ rindex: '@'
+ },
+ template: ''
+ + 'S: '
+ + 'I: '
+ + 'U: '
+ + 'R: '
+ + '
',
+ controller: controller
+ };
+};
diff --git a/pool/shard000/JavaScript/0002591_7060.js b/pool/shard000/JavaScript/0002591_7060.js
new file mode 100644
index 0000000000000000000000000000000000000000..ff81682070a853ae99e07ba20227563baedc74fa
--- /dev/null
+++ b/pool/shard000/JavaScript/0002591_7060.js
@@ -0,0 +1,32 @@
+{
+ var imports = doc.querySelectorAll("link[rel=import]");
+ var loaded = 0,
+ l = imports.length;
+
+ function checkDone(d) {
+ if (loaded == l && callback) {
+ callback();
+ }
+ }
+
+ function loadedImport(e) {
+ markTargetLoaded(e);
+ loaded++;
+ checkDone();
+ }
+
+ if (l) {
+ for (var i = 0, imp; i < l && (imp = imports[i]); i++) {
+ if (isImportLoaded(imp)) {
+ loadedImport.call(imp, {
+ target: imp
+ });
+ } else {
+ imp.addEventListener("load", loadedImport);
+ imp.addEventListener("error", loadedImport);
+ }
+ }
+ } else {
+ checkDone();
+ }
+}
diff --git a/pool/shard000/JavaScript/0002593_Retrievable.js b/pool/shard000/JavaScript/0002593_Retrievable.js
new file mode 100644
index 0000000000000000000000000000000000000000..49bdc7c34a563423749720009ff853c0ba310d45
--- /dev/null
+++ b/pool/shard000/JavaScript/0002593_Retrievable.js
@@ -0,0 +1,61 @@
+import { observable, extendObservable, computed, ObservableMap, IObservableArray, isObservableMap, isObservableArray, isObservableObject } from 'mobx';
+
+import _editable from './_editable';
+const toggleBool = (self, propName) => (status) => { self[propName] = typeof status === "boolean" ? status : !self[propName] }
+
+class RetrievableArray {
+
+ @observable noResults = false;
+ @observable showing = false;
+ @observable loading = false;
+
+ constructor(initialData = []) {
+ extendObservable(this, _editable(this), {
+ data: initialData,
+ });
+ }
+
+ // TODO: Fix this
+ @computed
+ get length() {
+ return this.data.length;
+ }
+
+ map = (fn) => this.data.map(fn);
+ filter = (fn) => this.data.filter(fn);
+ some = (fn) => this.data.some(fn);
+ unshift = (item) => { this.data.unshift(item) }
+ push = (item) => {this.data.push(item) }
+ replace = (data = []) => { this.data.replace(data) }
+
+ toggleShow = toggleBool(this, "showing");
+ toggleLoading = toggleBool(this, "loading");
+}
+
+class RetrievableMap extends ObservableMap {
+
+ type;
+ @observable data;
+ @observable adding = false;
+ @observable loading = false;
+ @observable editing = false;
+ @observable removing = false;
+ @observable noResults = false;
+ @observable showing = false;
+
+ constructor(initialData = {}) {
+ super(initialData);
+ }
+
+ toggleAdding = toggleBool(this, "adding");
+ toggleLoading = toggleBool(this, "loading");
+ toggleEditing = toggleBool(this, "editing");
+ toggleRemoving = toggleBool(this, "removing");
+ toggleShow = toggleBool(this, "showing");
+ toggleLoading = toggleBool(this, "loading");
+}
+
+export {
+ RetrievableArray,
+ RetrievableMap,
+}
diff --git a/pool/shard000/JavaScript/0002594_main.js b/pool/shard000/JavaScript/0002594_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..31eb3c589e3344ea48238bfd403efde212401acf
--- /dev/null
+++ b/pool/shard000/JavaScript/0002594_main.js
@@ -0,0 +1,50 @@
+/* Calculator Omniplet */
+
+function search(expr,a,b) {
+ var i = 0
+ while (i != -1) {
+ i = expr.indexOf(a,i);
+ if (i>=0) {
+ if (i==0) {
+ expr = expr.substring(0,i)+b+expr.substring(i+a.length);
+ i += b.length
+ } else {
+ if (expr.substring(i-1,i) != "a") {
+ expr = expr.substring(0,i)+b+expr.substring(i+a.length);
+ i += b.length
+ } else {i++}
+ }
+
+ }
+ }
+ return expr
+}
+
+function calculate(f) {
+ var expr = f;
+ expr = search(expr,'cos','Math.cos');
+ expr = search(expr,'sin','Math.sin');
+ expr = search(expr,'tan','Math.tan');
+ expr = search(expr,'acos','Math.acos');
+ expr = search(expr,'asin','Math.asin');
+ expr = search(expr,'atan','Math.atan');
+ expr = search(expr,'ln','Math.log');
+ expr = search(expr,'exp','Math.exp');
+ expr = search(expr,'pow','Math.pow');
+ expr = search(expr,'sqrt','Math.sqrt');
+ expr = search(expr,'pi','Math.PI');
+ return eval(expr);
+}
+
+function onOmniBoxSearch(text){
+ if(text.substring(0,1) === "=") {
+ liri.appendSearchSuggestion("Result : " + calculate(text.substring(1,text.length)), "action/code", "start");
+ }
+}
+
+function onLoad(){
+ liri.print("Calculator Omniplet loaded");
+}
+
+liri.on("load", onLoad);
+liri.on("omnibox.search", onOmniBoxSearch);
diff --git a/pool/shard000/JavaScript/0002599_pixidemo2.js b/pool/shard000/JavaScript/0002599_pixidemo2.js
new file mode 100644
index 0000000000000000000000000000000000000000..ab677389c3e0e75ec202ec19f2d7b9b07f749733
--- /dev/null
+++ b/pool/shard000/JavaScript/0002599_pixidemo2.js
@@ -0,0 +1,175 @@
+$(document).ready(function() {
+
+ // pixi/display stuff
+ var screen = {};
+ function initScreen() {
+ screen.width = window.innerWidth;
+ screen.height = window.innerHeight;
+ }
+ initScreen();
+
+ var stage = new PIXI.Stage(0x777777, false); // interactive
+ var renderer = PIXI.autoDetectRenderer(
+ screen.width, screen.height, null, true // transparency
+ );
+
+ $(window).resize(function() {
+ initScreen();
+ renderer.resize(screen.width, screen.height);
+ });
+
+ $("body").append(renderer.view);
+
+ function isChance(p, max) {
+ if (typeof max == "undefined") max = 32767;
+ var r = Math.random() * max;
+ return r < (max * p)
+ }
+
+ var lastHeroSpawnTryTime = 0, currentTime = 0;
+ function animate() {
+ renderer.render(stage);
+ TWEEN.update();
+
+ currentTime = new Date().getTime();
+ if (currentTime - lastHeroSpawnTryTime > 100) {
+ lastHeroSpawnTryTime = currentTime;
+ heroSpawnTry();
+ }
+ moveHeroes();
+ requestAnimFrame(function() { animate(); });
+ }
+ requestAnimFrame(function() { animate(); });
+
+ // grid stuff
+ var gridSize = { width: 20, height: 20 };
+ var gridFieldSize = { width: Math.round(screen.height/gridSize.width), height: Math.round(screen.height/gridSize.height) };
+ var pathfindingGrid = new PF.Grid(gridSize.width, gridSize.height);
+ var grid = [];
+ for (var y = 0; y < gridSize.height; y++) {
+ grid[y] = [];
+ for (var x = 0; x < gridSize.width; x++) {
+ pathfindingGrid.setWalkableAt(x, y, true);
+ grid[y][x] = 0;
+ }
+ }
+ // special map positions
+ var spawnPoints = [
+ { x: 0, y: 0 },
+ { x: gridSize.width - 1, y: 0 },
+ { x: gridSize.width - 1, y: gridSize.height - 1 },
+ { x: 0, y: gridSize.height - 1 }
+ ];
+ var middlePoint = {x: Math.round(gridSize.width/2), y: Math.round(gridSize.height/2)};
+
+ // heroes stuff
+ var heroes = [], maxHeroes = 10;
+ function heroSpawnTry() {
+ if (isChance(0.3 - (0.3 / maxHeroes * heroes.length))) {
+ var position = spawnPoints[Math.round(Math.random() * (spawnPoints.length-1))];
+ heroes.push({ position: position });
+
+ var sprite = new PIXI.Sprite(PIXI.Texture.fromImage("hero.png"));
+ sprite.width = gridFieldSize.width;
+ sprite.height = gridFieldSize.height;
+ sprite.position = {
+ x: position.x * gridFieldSize.width,
+ y: position.y * gridFieldSize.height
+ };
+ stage.addChild(sprite);
+ heroes[heroes.length-1].sprite = sprite;
+ heroes[heroes.length-1].movement = false;
+ }
+ }
+
+ function moveHeroes() {
+ for (var i = 0; i < heroes.length; i++) {
+ if (heroes[i].movement == false) {
+ var behaviour = Math.round(Math.random() * 1);
+ if (behaviour == 0) {
+ // first behaviour, follow path to middle point
+ moveHero(heroes[i], middlePoint);
+ } else {
+ // second behaviour, follow path to random point
+ var distance = 10, angle = Math.round(Math.random() * 360),
+ cosAlpha = Math.cos(angle), sinAlpha = Math.sin(angle);
+ var targetPoint = {
+ x: Math.round(heroes[i].position.x - cosAlpha * distance),
+ y: Math.round(heroes[i].position.y - sinAlpha * distance)
+ };
+ targetPoint.x = (targetPoint.x < 0) ? 0 : (targetPoint.x > gridSize.width-1) ? gridSize.width-1 : targetPoint.x;
+ targetPoint.y = (targetPoint.y < 0) ? 0 : (targetPoint.y > gridSize.height-1) ? gridSize.height-1 : targetPoint.y;
+ moveHero(heroes[i], targetPoint);
+ }
+ }
+ }
+ }
+
+ function moveHero(hero, targetPosition) {
+ var path = getWalkablePath(hero.position, targetPosition);
+
+ if (isChance(0.5)) {
+ // behaviour to reduce path length
+ var pathLength = Math.round(Math.random() * path.length-1)+1;
+ var newPath = [];
+ for (var i = 0; i < pathLength; i++) {
+ newPath.push(path[i]);
+ }
+ path = newPath;
+ }
+
+ if (path.length > 0) {
+ var tweens = [], nextPosX = 0, nextPosY = 0,
+ lastPosX = hero.position.x * gridFieldSize.width,
+ lastPosY = hero.position.y * gridFieldSize.height;
+
+ for (var j = 0; j < path.length; j++) {
+ nextPosX = path[j][0] * gridFieldSize.width;
+ nextPosY = path[j][1] * gridFieldSize.height;
+ var scope = this;
+
+ tweens[j] = function(iJ, sourceX, sourceY, targetX, targetY, iFieldX, iFieldY, isLastField) {
+ var distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2));
+ return new TWEEN.Tween( { x: sourceX, y: sourceY } )
+ .to(
+ { x: targetX, y: targetY }, 1000 * distance / 10
+ )
+ .onUpdate( function () {
+ hero.sprite.position.x = this.x;
+ hero.sprite.position.y = this.y;
+ })
+ .onComplete( function () {
+ hero.position.x = iFieldX;
+ hero.position.y = iFieldY;
+ if (isLastField) hero.movement = false;
+ });
+ }(
+ j, lastPosX, lastPosY, nextPosX, nextPosY, path[j][0], path[j][1], (j == path.length - 1) ? true : false
+ );
+
+ lastPosX = nextPosX;
+ lastPosY = nextPosY;
+
+ if (j > 0) {
+ tweens[j-1].chain(tweens[j]);
+ }
+ }
+
+ tweens[0].start();
+ hero.movement = true;
+ }
+ }
+
+ function getWalkablePath(position, targetPosition) {
+ var gridBackup = pathfindingGrid.clone();
+ var finder = new PF.BestFirstFinder({
+ allowDiagonal: true,
+ dontCrossCorners: true
+ });
+ var path = finder.findPath(position.x, position.y, targetPosition.x, targetPosition.y, pathfindingGrid);
+ path.splice(0, 1);
+ pathfindingGrid = gridBackup;
+ return path;
+ }
+
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002602_wysihtml5.js b/pool/shard000/JavaScript/0002602_wysihtml5.js
new file mode 100644
index 0000000000000000000000000000000000000000..5475b72eb25ce3a192b73d9707ea59a8064af65e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002602_wysihtml5.js
@@ -0,0 +1,141 @@
+/**
+Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5).
+You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`:
+
+
+
+
+
+And also include `wysihtml5.js` from `inputs-ext` directory of x-editable:
+
+
+
+**Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion.
+
+@class wysihtml5
+@extends abstractinput
+@final
+@since 1.4.0
+@example
+
+
+**/
+import jQuery from 'jquery'
+
+(function ($) {
+ "use strict";
+
+ var Wysihtml5 = function (options) {
+ this.init('wysihtml5', options, Wysihtml5.defaults);
+
+ //extend wysihtml5 manually as $.extend not recursive
+ this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5);
+ };
+
+ debugger
+ $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput);
+
+ $.extend(Wysihtml5.prototype, {
+ render: function () {
+ var deferred = $.Deferred(),
+ msieOld;
+
+ //generate unique id as it required for wysihtml5
+ this.$input.attr('id', 'textarea_'+(new Date()).getTime());
+
+ this.setClass();
+ this.setAttr('placeholder');
+
+ //resolve deffered when widget loaded
+ $.extend(this.options.wysihtml5, {
+ events: {
+ load: function() {
+ deferred.resolve();
+ }
+ }
+ });
+
+ this.$input.wysihtml5(this.options.wysihtml5);
+
+ /*
+ In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover).
+ The only solution I found is to add . If you fine better way, please send PR.
+ */
+ msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase());
+ if(msieOld) {
+ this.$input.before(' ');
+ }
+
+ return deferred.promise();
+ },
+
+ value2html: function(value, element) {
+ $(element).html(value);
+ },
+
+ html2value: function(html) {
+ return html;
+ },
+
+ value2input: function(value) {
+ this.$input.data("wysihtml5").editor.setValue(value, true);
+ },
+
+ activate: function() {
+ this.$input.data("wysihtml5").editor.focus();
+ },
+
+ isEmpty: function($element) {
+ if($.trim($element.html()) === '') {
+ return true;
+ } else if($.trim($element.text()) !== '') {
+ return false;
+ } else {
+ //e.g. ' ', ' ', '
'
+ return !$element.height() || !$element.width();
+ }
+ }
+ });
+
+ Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
+ /**
+ @property tpl
+ @default
+ **/
+ tpl:'',
+ /**
+ @property inputclass
+ @default editable-wysihtml5
+ **/
+ inputclass: 'editable-wysihtml5',
+ /**
+ Placeholder attribute of input. Shown when input is empty.
+
+ @property placeholder
+ @type string
+ @default null
+ **/
+ placeholder: null,
+ /**
+ Wysihtml5 default options.
+ See https://github.com/jhollingworth/bootstrap-wysihtml5#options
+
+ @property wysihtml5
+ @type object
+ @default {stylesheets: false}
+ **/
+ wysihtml5: {
+ stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183
+ }
+ });
+
+ $.fn.editabletypes.wysihtml5 = Wysihtml5;
+
+}(jQuery));
diff --git a/pool/shard000/JavaScript/0002603_regularization.js b/pool/shard000/JavaScript/0002603_regularization.js
new file mode 100644
index 0000000000000000000000000000000000000000..33bfdf30b72068e2915062ebb13a72ece77c1ca8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002603_regularization.js
@@ -0,0 +1,50 @@
+var _ = require('lodash')
+ , AspectAnalysis = require('./aspect');
+
+var RegularizationAnalysis = function (analysis, options) {
+ AspectAnalysis.call(this, analysis, {
+ step : 0.02,
+ start : 0,
+ stop : 1
+ });
+
+ this.setOptions(options);
+};
+
+RegularizationAnalysis.prototype = new AspectAnalysis();
+
+RegularizationAnalysis.prototype.getValues = function () {
+ return _.range(
+ this.options.start,
+ this.options.stop + this.options.step,
+ this.options.step
+ );
+};
+
+RegularizationAnalysis.prototype.run = function () {
+ var analyses
+ , values
+ , value
+ , i
+ , l;
+
+ analyses = [];
+ values = this.getValues();
+
+ for (i = 0, l = values.length; i < l; i++) {
+ value = values[i];
+
+ this.analysis.training.derivative.setOptions({ regularization: value });
+
+ analyses.push([value, this.analysis.run()]);
+
+ this.report('analysis', {
+ iterations : i + 1,
+ value : value
+ });
+ }
+
+ return analyses;
+};
+
+exports = module.exports = RegularizationAnalysis;
diff --git a/pool/shard000/JavaScript/0002608_blobhttp.js b/pool/shard000/JavaScript/0002608_blobhttp.js
new file mode 100644
index 0000000000000000000000000000000000000000..a4ea1614d9d591e1bb4ca745a5d961ba243032f5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002608_blobhttp.js
@@ -0,0 +1,153 @@
+/* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. */
+
+/******************************************************************************
+ *
+ * You may not use the identified files except in compliance with the Apache
+ * License, Version 2.0 (the "License.")
+ *
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * NAME
+ * blobhttp.js
+ *
+ * DESCRIPTION
+ * Listens for an HTTP request and returns an image queried from a BLOB column
+ * Also shows the connection pool's caching using a 'default' pool.
+ *
+ * Start the listener with 'node blobhttp.js' and then use a browser
+ * to load http://localhost:7000/getimage
+ *
+ * This example uses Node 8's async/await syntax.
+ *
+ *****************************************************************************/
+
+const url = require('url');
+const http = require('http');
+const oracledb = require('oracledb');
+const dbConfig = require('./dbconfig.js');
+const demoSetup = require('./demosetup.js');
+
+const httpPort = 7000;
+
+// Main entry point. Creates a connection pool which becomes the
+// 'default' pool, and then creates an HTTP server.
+async function init() {
+ try {
+ await oracledb.createPool(dbConfig);
+ console.log('Connection pool started');
+
+ // create the demo table
+ const connection = await oracledb.getConnection();
+ await demoSetup.setupLobs(connection, true);
+ await connection.close();
+
+ // Create HTTP server and listen on port httpPort
+ const server = http.createServer();
+ server.on('error', (err) => {
+ throw err;
+ });
+ server.on('request', (request, response) => {
+ handleRequest(request, response);
+ });
+ await server.listen(httpPort);
+ console.log("Server is running. Try loading http://localhost:" + httpPort + "/getimage");
+
+ } catch (err) {
+ console.error('init() error: ' + err.message);
+ }
+}
+
+// Handles each web request
+async function handleRequest(request, response) {
+
+ const requrl = url.parse(request.url, true);
+ const action = requrl.pathname;
+
+ if (action == '/getimage') {
+
+ let connection;
+
+ try {
+ connection = await oracledb.getConnection(); // gets a connection from the 'default' connection pool
+
+ const result = await connection.execute(
+ "SELECT b FROM no_lobs WHERE id = :id", // get the image
+ { id: 2 }
+ );
+ if (result.rows.length === 0) {
+ throw new Error("No data selected from table.");
+ }
+
+ const lob = result.rows[0][0];
+ if (lob === null) {
+ throw new Error("BLOB was NULL");
+ }
+
+ const doStream = new Promise((resolve, reject) => {
+ lob.on('end', () => {
+ // console.log("lob.on 'end' event");
+ response.end();
+ });
+ lob.on('close', () => {
+ // console.log("lob.on 'close' event");
+ resolve();
+ });
+ lob.on('error', (err) => {
+ // console.log("lob.on 'error' event");
+ reject(err);
+ });
+ response.writeHead(200, {'Content-Type': 'image/jpeg' });
+ lob.pipe(response); // write the image out
+ });
+
+ await doStream;
+
+ } catch (err) {
+ console.error(err);
+ await closePoolAndExit();
+ } finally {
+ if (connection) {
+ try {
+ await connection.close();
+ } catch (err) {
+ console.error(err);
+ }
+ }
+ }
+
+ } else {
+ response.writeHead(200, {'Content-Type': 'text/plain' });
+ response.end("Try requesting: http://localhost:" + httpPort + "/getimage\n");
+ }
+}
+
+async function closePoolAndExit() {
+ console.log('\nTerminating');
+ try {
+ // Get the pool from the pool cache and close it when no
+ // connections are in use, or force it closed after 2 seconds.
+ // If this hangs, you may need DISABLE_OOB=ON in a sqlnet.ora file.
+ // This setting should not be needed if both Oracle Client and Oracle
+ // Database are 19c (or later).
+ await oracledb.getPool().close(2);
+ console.log('Pool closed');
+ process.exit(0);
+ } catch(err) {
+ console.error(err.message);
+ process.exit(1);
+ }
+}
+
+process
+ .once('SIGTERM', closePoolAndExit)
+ .once('SIGINT', closePoolAndExit);
+
+init();
diff --git a/pool/shard000/JavaScript/0002610_score-test.js b/pool/shard000/JavaScript/0002610_score-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..7b0ef4a3c709bab79158d881d893b31f931d9894
--- /dev/null
+++ b/pool/shard000/JavaScript/0002610_score-test.js
@@ -0,0 +1,38 @@
+const chai = require('chai');
+const assert = chai.assert;
+
+const Board = require('../lib/board');
+const Meteor = require('../lib/meteor');
+const Score = require('../lib/score');
+
+describe('Score', function() {
+ beforeEach(function() {
+ this.board = new Board();
+ });
+
+ describe('Total score and meteors destroyed', function() {
+ it('should return a totalScore and meteorsDestroyed count of zero', function() {
+ let score = new Score(this.board);
+ assert.equal(score.results().totalScore, 0);
+ assert.equal(score.results().meteorsDestroyed, 0);
+ });
+
+ it('should return a totalScore of the meteor\'s pointValue and meteorsDestroyed count of one', function() {
+ let score = new Score(this.board);
+ let meteor = this.board.addMeteor();
+ this.board.meteorsDestroyed.push(meteor);
+ assert.equal(score.results().totalScore, meteor.pointValue);
+ assert.equal(score.results().meteorsDestroyed, 1);
+ });
+
+ it('should return a totalScore summing two meteor\'s pointValues and meteorsDestroyed count of two', function() {
+ let score = new Score(this.board);
+ let meteor1 = this.board.addMeteor();
+ let meteor2 = this.board.addMeteor();
+ this.board.meteorsDestroyed.push(meteor1);
+ this.board.meteorsDestroyed.push(meteor2);
+ assert.equal(score.results().totalScore, meteor1.pointValue + meteor2.pointValue);
+ assert.equal(score.results().meteorsDestroyed, 2);
+ });
+ });
+});
diff --git a/pool/shard000/JavaScript/0002612_svgreindeer.js b/pool/shard000/JavaScript/0002612_svgreindeer.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb65b8f40c91e7d76d48d76e84165b7d0ebd386d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002612_svgreindeer.js
@@ -0,0 +1,51 @@
+/*
+ * grunt-svgreindeer
+ * https://github.com/bennyschudel/grunt-svgreindeer
+ *
+ * Copyright (c) 2014 Benny Schudel
+ * Licensed under the MIT license.
+ */
+
+"use strict";
+
+var Q = require('q');
+
+var SvgReindeer = require('svgreindeer');
+
+var log = console.log;
+
+module.exports = function(grunt) {
+
+ grunt.registerMultiTask(
+ 'svgreindeer',
+ 'Renders SVG\'s to PNG\'s for a fallback in older IE\'s and email clients.',
+ function() {
+
+ var _this = this;
+ var p = Q();
+ var done = this.async();
+
+ this.files.forEach(function(item) {
+
+ var options = _this.options({
+ verbose : false,
+ scale : 1,
+ style : null,
+ input_src : item.src,
+ output_dir : item.dest,
+ base_dir : item.base || '',
+ });
+
+ p = p.then(function(data) {
+ return (new SvgReindeer(options)).run();
+ });
+
+ });
+
+ p.done(function() {
+ done();
+ });
+
+ });
+
+};
diff --git a/pool/shard000/JavaScript/0002614_post.js b/pool/shard000/JavaScript/0002614_post.js
new file mode 100644
index 0000000000000000000000000000000000000000..05b9cb07f83cac6505d1fc93245936f1ae015939
--- /dev/null
+++ b/pool/shard000/JavaScript/0002614_post.js
@@ -0,0 +1,55 @@
+var Tistory = require('../lib/tistory'),
+ logger = require('hbn-logger').tracer({level: 'all'}),
+ options = require('./example-options');
+
+var tistory = new Tistory(options);
+
+var callback = function (err, body) {
+ if (err) {
+ logger.error(err);
+ } else {
+// logger.debug(body);
+ var json = JSON.parse(body);
+ logger.info(json.tistory);
+ }
+};
+
+//tistory.post.list({
+// page: 1, //default:1
+// count: 10, //default:10, max:30
+//// categoryId: //default all categories
+// sort: 'id' //default:id(글번호) , date(날짜)
+//}, callback);
+//tistory.post.list({page: 1, targetUrl: "blog.saltfactory.net"}, callback);
+//tistory.post.read({postId: 12}, callback);
+//
+
+//tistory.post.write({
+//// visibility: 0, //default: 0(비공개), 1(보호), 2(공개), 3(발행), 생략시 비공개
+////// published: //UNIX_TIMESTAMP() 값을 넣을 경우, 예약발행
+//// categoryId: 0, //default:0 (생략시 분류없음)
+// tag: 'nodejs, node-tistory',
+// title: 'test',
+// content: '본문'
+//}, callback);
+//
+//tistory.post.update({
+// postId: 11,
+// visibility: 0, //default: 0(비공개), 1(보호), 2(공개), 3(발행), 생략시 비공개
+// categoryId: 0, //default:0 (생략시 분류없음)
+// tag: 'nodejs, node-tistory',
+// title: 'test',
+// content: '본문 수정'
+//}, callback);
+//
+tistory.post.attach({uploadedfile: '/Users/saltfactory/Downloads/square.png'}, callback);
+//
+//tistory.post.delete({postId: 11}, callback);
+
+//tistory.writeFromFile('/Users/saltfactory/Dropbox/Blog/output/2014-07-16-using-passport-tistory-in-express/2014-07-16-using-passport-tistory-in-express.md.html',
+// {
+// title:''
+// },
+// callback
+//);
+
diff --git a/pool/shard000/JavaScript/0002620_admin-login.js b/pool/shard000/JavaScript/0002620_admin-login.js
new file mode 100644
index 0000000000000000000000000000000000000000..30c1f3aa465eaf05f6d3a242bd233111fb103bf0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002620_admin-login.js
@@ -0,0 +1,42 @@
+
+$(document).ready(function() {
+ var submit_form = $("#loginSubmit");
+ var login_form = $("#loginForm")
+ var email_error = $("#emailError");
+ var password_error = $("#passwordError");
+ var login_loading = $("#loginLoading");
+
+ login_loading.hide();
+
+ submit_form.click(function() {
+ email_error.text("");
+ password_error.text("");
+
+ login_loading.show();
+ $.ajax({
+ type: "POST",
+ url: window.base_url + "AuthController/loginExec",
+ dataType: "json",
+ data: login_form.serialize(),
+ success: function(data){
+ if (data.error == true) {
+ if (data.type == "required") {
+ email_error.text(data.message.email);
+ password_error.text(data.message.password);
+ } else if (data.type == "common") {
+ email_error.text(data.message);
+ } else {
+ console.log("[ERROR] : error type not set!");
+ }
+ } else {
+ window.location.href = window.base_url + "DashboardController/index";
+ }
+ login_loading.hide();
+ },
+ error: function(error){
+ console.log(error);
+ }
+ });
+ });
+
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002621_carts-security.js b/pool/shard000/JavaScript/0002621_carts-security.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e4536f3af308091f8b8f12eb792bf8018d0062b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002621_carts-security.js
@@ -0,0 +1,27 @@
+Security.defineMethod("inShoppingState", {
+ fetch: [],
+ transform: null,
+ deny: function (type, arg, userId, doc, fields, modifier) {
+ // console.log("inShoppingState " + doc.state + " " + userId + " " + doc.userId)
+ return doc.state !== Mart.Cart.STATES.SHOPPING || userId !== doc.userId
+ }
+});
+
+Security.defineMethod("ownsCreditCard", {
+ fetch: [],
+ transform: null,
+ deny: function (type, arg, userId, doc, fields, modifier) {
+ if(type === "update") {
+ var cardId = modifier.$set.cardId
+ var card = Mart.Cards.findOne(cardId)
+ }
+
+ return card === undefined || (card.userId !== userId)
+ }
+});
+
+Mart.Carts.permit(['update'])
+ .inShoppingState()
+ .ownsCreditCard()
+ .onlyProps(['cardId', 'contactName', 'contactEmail', 'contactPhone', 'contactEntity', 'referer'])
+ .apply()
diff --git a/pool/shard000/JavaScript/0002622_variadic.js b/pool/shard000/JavaScript/0002622_variadic.js
new file mode 100644
index 0000000000000000000000000000000000000000..7b3c9aa53a37f0cc6abe6174ba4b30a5a0a17073
--- /dev/null
+++ b/pool/shard000/JavaScript/0002622_variadic.js
@@ -0,0 +1,40 @@
+import flatten from './internal/flatten'
+
+const slice = Array.prototype.slice
+
+/**
+ * Converts a function to a variadic function.
+ *
+ * The last named parameter will be given an array of arguments.
+ *
+ * @param {Function} f The function.
+ * @returns {Function} A function that wraps the function `f` to accept any
+ * number of arguments.
+ * @example
+ *
+ * import { variadic } from 'fkit'
+ * function f (head, tail) { ... }
+ * variadic(f)(1, 2, 3) // f(1, [2, 3])
+ */
+export default function variadic (f) {
+ const arity = f.length
+
+ if (arity < 1) {
+ return f
+ } else if (arity === 1) {
+ return (...args) => {
+ const newArgs = (args.length === 1) ? flatten(args) : args
+
+ return f.call(this, newArgs)
+ }
+ } else {
+ return (...args) => {
+ const numMissingArgs = Math.max(arity - args.length - 1, 0)
+ const missingArgs = new Array(numMissingArgs)
+ const namedArgs = slice.call(args, 0, arity - 1)
+ const variadicArgs = slice.call(args, f.length - 1)
+
+ return f.apply(this, namedArgs.concat(missingArgs).concat([variadicArgs]))
+ }
+ }
+}
diff --git a/pool/shard000/JavaScript/0002624_index.js b/pool/shard000/JavaScript/0002624_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..dc3caa5c919d18e38a99aa02da0b1b6fb54c97e9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002624_index.js
@@ -0,0 +1,22 @@
+import React, {Component} from 'react';
+import PropTypes from 'prop-types';
+import {connect} from 'react-redux';
+import cn from 'classnames';
+
+@connect(({api}) => api)
+export default class Loading extends Component {
+ render() {
+ const {requests} = this.props;
+ return (
+ 0})}>
+ {Object.keys(requests).map(id => {
+ const progress = requests[id].loaded / requests[id].total;
+ return
;
+ })}
+
+ );
+ }
+ static propTypes = {
+ requests: PropTypes.object.isRequired,
+ }
+}
diff --git a/pool/shard000/JavaScript/0002626_router.js b/pool/shard000/JavaScript/0002626_router.js
new file mode 100644
index 0000000000000000000000000000000000000000..6b6ccf5f09ce4351ec806642d3d41ca2d8efa01d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002626_router.js
@@ -0,0 +1,73 @@
+// (c) Bantyev Alexander aka balsoft , 2017. This work is licensed under GPLv3, which can be found in the license file.
+/*
+/* This program routes requests from users to either
+/* -- file system
+/* -- requestHandlers.js
+/* This program should not be modified.
+*/
+var _response = {
+ 'code': 500,
+ 'content': '500 Internal server error ',
+ args: {}
+}
+const requestHandlers = require('./requestHandlers.js')
+ .requestHandlers
+const fs = require('fs')
+const auth = require('./auth.js')
+const f = require('./f.js')
+exports.route = (pathname, request, response, cookies, fields, files) => {
+ if (requestHandlers[pathname] !== undefined) {
+ try {
+ requestHandlers[pathname](response, request, fields, cookies, files)
+ } catch (err) {
+ response.writeHead(500, {
+ 'Content-Type': 'text/html'
+ })
+ response.end(`Internal server error ${err}`)
+ f.log(err)
+ }
+ } else {
+ _response.args['Content-Type'] = f.getMIME(pathname)
+ auth.check(cookies.id, cookies.password, (result) => {
+ try {
+ try {
+ var content = fs.readFileSync('./loggedin' + pathname)
+ if (result) {
+ _response.code = 200
+ _response.content = content
+ } else {
+ var error = {
+ code: 403
+ }
+ throw error
+ }
+ } catch (e) {
+ try {
+ content = fs.readFileSync('./all' + pathname)
+ _response.code = 200
+ _response.content = content
+ } catch (e) {
+ _response.code = 404
+ _response.content = '404 Not Found '
+ _response.args = {
+ 'Content-Type': 'text/html'
+ }
+ }
+ }
+ } catch (err) {
+ _response = {
+ 'code': 404,
+ 'content': '404 File not found ',
+ args: {
+ 'Content-Type': 'text/html'
+ }
+ }
+ f.log(err)
+ }
+ response.writeHead(_response.code, _response.args)
+ response.write((_response.args['Content-Type'] === 'text/html' ? ((result ? fs.readFileSync('./loggedin/header', 'utf8') : fs.readFileSync('./all/header', 'utf8')).toString() + _response.content.toString()) : (_response.content)))
+ response.end()
+ })
+
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002627_draggable.client.controller.js b/pool/shard000/JavaScript/0002627_draggable.client.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..15633d03c592ab007d76469b48d90d48daef6310
--- /dev/null
+++ b/pool/shard000/JavaScript/0002627_draggable.client.controller.js
@@ -0,0 +1,76 @@
+'use strict';
+
+angular.module('template').controller('DraggableController', ['$scope','$element',
+ function($scope, $element) {
+
+ var snap = angular.element(document.querySelector('#snap')),
+ liveSnap = angular.element(document.querySelector("#liveSnap")),
+ container = angular.element(document.querySelector("#container")),
+ gridWidth = 196,
+ gridHeight = 100,
+ gridRows = 6,
+ gridColumns = 5,
+ i, x, y;
+
+ //loop through and create the grid (a div for each cell). Feel free to tweak the variables above
+ for (i = 0; i < gridRows * gridColumns; i++) {
+ y = Math.floor(i / gridColumns) * gridHeight;
+ x = (i * gridWidth) % (gridColumns * gridWidth);
+ /*
+ var changeDiv= $element.find("div")
+ .css({
+ position:"absolute",
+ border:"1px solid #454545",
+ width:gridWidth-1,
+ height:gridHeight-1,
+ top:y, left:x});
+ container.prepend(changeDiv);*/
+ //$("
").css({position:"absolute", border:"1px solid #454545", width:gridWidth-1, height:gridHeight-1, top:y, left:x}).prependTo($container);
+ }
+
+ //set the container's size to match the grid, and ensure that the box widths/heights reflect the variables above
+ TweenLite.set(container, {height: gridRows * gridHeight + 1, width: gridColumns * gridWidth + 1});
+ TweenLite.set(".box", {width:gridWidth, height:gridHeight, lineHeight:gridHeight + "px"});
+
+ //the update() function is what creates the Draggable according to the options selected (snapping).
+ function update() {
+ //var snap = snap.prop("checked"), liveSnap = $liveSnap.prop("checked");
+ Draggable.create(".box", {
+ bounds:container,
+ edgeResistance:0.65,
+ type:"x,y",
+ throwProps:true,
+ liveSnap:liveSnap,
+ snap:{
+ x: function(endValue) {
+ return (snap || liveSnap) ? Math.round(endValue / gridWidth) * gridWidth : endValue;
+ },
+ y: function(endValue) {
+ return (snap || liveSnap) ? Math.round(endValue / gridHeight) * gridHeight : endValue;
+ }
+ }
+ });
+ }
+ /*
+ //when the user toggles one of the "snap" modes, make the necessary updates...
+ snap.on("change", applySnap);
+ liveSnap.on("change", applySnap);
+
+ function applySnap() {
+ if (snap.prop("checked") || liveSnap.prop("checked")) {
+ angular.element(document.querySelector('.box')).each(function(index, element) {
+ TweenLite.to(element, 0.5, {
+ x:Math.round(element._gsTransform.x / gridWidth) * gridWidth,
+ y:Math.round(element._gsTransform.y / gridHeight) * gridHeight,
+ delay:0.1,
+ ease:Power2.easeInOut
+ });
+ });
+ }
+ update();
+ }
+ */
+
+ update();
+ }
+]);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002628_feed.js b/pool/shard000/JavaScript/0002628_feed.js
new file mode 100644
index 0000000000000000000000000000000000000000..00f6966dc67ba3c05b99439714141d4911bb5384
--- /dev/null
+++ b/pool/shard000/JavaScript/0002628_feed.js
@@ -0,0 +1,26 @@
+import uniqBy from 'lodash.uniqby'
+import {request} from 'common/request'
+import {clone, toSelector} from 'common/utils'
+
+export const loadFeed = (dao, {filter, limiter, loadFrom, selector}) => {
+ const cursor = dao.tree.select(toSelector(selector))
+ cursor.set('isLoading', true)
+
+ return request(dao, {
+ query: {limiter, period: filter},
+ url: `/ycm/${loadFrom}`
+ }).then(({data, ids, items}) => data || ids || items)
+ .finally((res) => cursor.set('isLoading', false))
+}
+
+export const mergeFeed = (dao, {filter, items, selector}) => {
+ const cursor = dao.tree.select(toSelector(`${selector}.items.${filter}`))
+ const _items = clone(cursor.get()).concat(items)
+ return cursor.set(uniqBy(_items, ({id}) => id))
+}
+
+export const setFeed = (dao, {filter, items, selector}) =>
+ dao.tree.set(toSelector(`${selector}.items.${filter}`), items)
+
+export const setFilter = (dao, {id, selector}) =>
+ dao.tree.set(toSelector(`${selector}.filter`), id)
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js b/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js
new file mode 100644
index 0000000000000000000000000000000000000000..a783ee27ccfccf8c1d46d409b394acef444a76c8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js
@@ -0,0 +1,77 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ** This file is automatically generated by gapic-generator-typescript. **
+// ** https://github.com/googleapis/gapic-generator-typescript **
+// ** All changes to this file may be overwritten. **
+
+
+
+'use strict';
+
+function main(parent) {
+ // [START dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async]
+ /**
+ * TODO(developer): Uncomment these variables before running the sample.
+ */
+ /**
+ * Required. The name of the participant to fetch suggestion for.
+ * Format: `projects//locations//conversations//participants/`.
+ */
+ // const parent = 'abc123'
+ /**
+ * Optional. The name of the latest conversation message to compile suggestion
+ * for. If empty, it will be the latest message of the conversation.
+ * Format: `projects//locations//conversations//messages/`.
+ */
+ // const latestMessage = 'abc123'
+ /**
+ * Optional. Max number of messages prior to and including
+ * latest_message to use as context when compiling the
+ * suggestion. By default 20 and at most 50.
+ */
+ // const contextSize = 1234
+ /**
+ * Optional. Parameters for a human assist query.
+ */
+ // const assistQueryParams = {}
+
+ // Imports the Dialogflow library
+ const {ParticipantsClient} = require('@google-cloud/dialogflow').v2beta1;
+
+ // Instantiates a client
+ const dialogflowClient = new ParticipantsClient();
+
+ async function callSuggestFaqAnswers() {
+ // Construct request
+ const request = {
+ parent,
+ };
+
+ // Run request
+ const response = await dialogflowClient.suggestFaqAnswers(request);
+ console.log(response);
+ }
+
+ callSuggestFaqAnswers();
+ // [END dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async]
+}
+
+process.on('unhandledRejection', err => {
+ console.error(err.message);
+ process.exitCode = 1;
+});
+main(...process.argv.slice(2));
diff --git a/pool/shard000/JavaScript/0002635_applyEnv.js b/pool/shard000/JavaScript/0002635_applyEnv.js
new file mode 100644
index 0000000000000000000000000000000000000000..32a87df32777916169ad5c588e0f6925167da4f0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002635_applyEnv.js
@@ -0,0 +1,47 @@
+'use strict'
+const composeSections = require('./composeSections')
+const coerce = require('coercer')
+
+/**
+ * Returns a new object where the environment
+ * values have been applied the given values.
+ *
+ * Additionally, composes sections as described by the wanted section's `compose`
+ * attribute.
+ *
+ * @param {Object} parsed
+ * The parsed object from the YAML-file.
+ *
+ * @param {String} opts.env
+ * The environment section we want to return.
+ *
+ * @param {Object} opts.envObject
+ * The environment object.
+ * @param {Object} opts.raw
+ * If `true`, formats values as strings, if `false`, uses `coercer`.
+ *
+ * @return {Object}
+ * The merged object
+ *
+ * @api private
+ */
+module.exports = function applyEnv(parsed, opts) {
+ const wantedSection = composeSections(parsed, [opts.env])
+
+ const result = Object.assign({}, wantedSection, opts.envObject)
+ return opts.raw ? raw(result) : coerce(result)
+}
+
+/**
+ * Serializes env values as strings.
+ */
+function raw(obj) {
+ const result = {}
+ for (const key in obj) {
+ const value = obj[key]
+ if (value !== null && value !== undefined) {
+ result[key] = value.toString()
+ }
+ }
+ return result
+}
diff --git a/pool/shard000/JavaScript/0002636_index.js b/pool/shard000/JavaScript/0002636_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..4b396d9e5eeaf10e0f1f1cb8f4bb52db14bdd2fc
--- /dev/null
+++ b/pool/shard000/JavaScript/0002636_index.js
@@ -0,0 +1,34 @@
+'use strict';
+
+
+exports.blank = function($, _, gulp, mkdirp, rename){
+ var _this = this;
+
+ _.forEach(this.folders, function (f) {
+ mkdirp('./client/app/core/'+f);
+ mkdirp('./client/app/modules/messages/'+ f);
+ })
+
+ this.start('core', function(){
+ gulp.src(_this.local.dirs())
+ .pipe( $.template( _this._config.all() ) )
+ .pipe( $.rename( rename ))
+ .pipe( gulp.dest( _this.cwd.root() ) )
+ })
+
+}
+exports.skeleton = function($, _, gulp, mkdirp, rename){
+ var _this = this;
+ _.forEach(this.folders, function (f) {
+ mkdirp('./client/app/core/'+f);
+ mkdirp('./client/app/modules/messages/'+ f);
+ });
+
+ this.start('core', function(){
+ gulp.src(_this.local.use('./**/.*', './**/*'))
+ .pipe( $.template( _this._config.all() ) )
+ .pipe( $.rename( rename ))
+ .pipe( gulp.dest( _this.cwd.root() ) )
+ });
+
+}
diff --git a/pool/shard000/JavaScript/0002637_BitReader.js b/pool/shard000/JavaScript/0002637_BitReader.js
new file mode 100644
index 0000000000000000000000000000000000000000..0331c3d4543f6e691e24135c75391aca3de7dd94
--- /dev/null
+++ b/pool/shard000/JavaScript/0002637_BitReader.js
@@ -0,0 +1,49 @@
+
+/**
+ * Reads unsigned integers encoded in a variable amount of bits from the buffer.
+ * Bits are aligned into 32bit unsigned integers.
+ * for example, given 3 integers:
+ * x: 123 encoded in 11 bits, binary: 00001111011
+ * y: 7945 encoded in 17 bits, binary: 00001111100001001
+ * z: 12 encoded in 6 bits, binary: 001100
+ *
+ * | --- 32 bits --- || --- 32 bits --- |
+ * |................................||................................|
+ * |00001111011000011111000010010011||00
+ * | x || y || z |
+ *
+ * z does not fit fully into the first 32 bit integer.
+ * The first 4 bits of z are stored at the end of the first 32 bit integer
+ * and the remaining 2 bits at the next 32 bit integer.
+ *
+ */
+BitReader = function(buf){
+
+ var buffer = new Uint32Array(buf);
+ var bitOffset = 0;
+
+ this.read = function(bits){
+ var result;
+
+ if((bitOffset % 32) + bits <= 32){
+ var val = buffer[Math.floor(bitOffset / 32)];
+ var leftGap = bitOffset % 32;
+ var rightGap = 32 - (leftGap + bits);
+
+ result = (val << leftGap) >>> (leftGap + rightGap);
+ }else{
+ var val = buffer[Math.floor(bitOffset / 32)];
+ var leftGap = bitOffset % 32;
+ var rightGap = (leftGap + bits) - 32;
+
+ result = (val << leftGap) >>> (leftGap - rightGap)
+
+ val = buffer[Math.floor(bitOffset / 32)+1];
+ result = result | val >>> (32 - rightGap);
+ }
+
+ bitOffset += bits;
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002639_models.js b/pool/shard000/JavaScript/0002639_models.js
new file mode 100644
index 0000000000000000000000000000000000000000..ec7f8017ad1018a96901998fc5f33b108826d0c6
--- /dev/null
+++ b/pool/shard000/JavaScript/0002639_models.js
@@ -0,0 +1,131 @@
+sap.ui.define([
+ "sap/ui/model/json/JSONModel",
+ "sap/ui/Device",
+ "sap/ui/model/odata/v2/ODataModel",
+ "sap/ui/model/resource/ResourceModel"
+], function(JSONModel, Device, ODataModel, ResourceModel) {
+ "use strict";
+
+ function extendMetadataUrlParameters(aUrlParametersToAdd, oMetadataUrlParams, sServiceUrl) {
+ var oExtensionObject = {},
+ oServiceUri = new URI(sServiceUrl);
+
+ aUrlParametersToAdd.forEach(function(sUrlParam) {
+ var sLanguage,
+ oUrlParameters,
+ sParameterValue;
+ var fnGetuser = jQuery.sap.getObject("sap.ushell.Container.getUser");
+
+ // for sap-language we check if the launchpad can provide it.
+ if (sUrlParam === "sap-language") {
+ sLanguage = fnGetuser ? fnGetuser().getLanguage() : false;
+// sLanguage = fnGetuser().getLanguage();
+
+ if (sLanguage) {
+ oMetadataUrlParams["sap-language"] = sLanguage;
+ return;
+ }
+ // Continue searching in the url
+ }
+
+ oUrlParameters = jQuery.sap.getUriParameters();
+ sParameterValue = oUrlParameters.get(sUrlParam);
+ if (sParameterValue) {
+ oMetadataUrlParams[sUrlParam] = sParameterValue;
+ oServiceUri.addSearch(sUrlParam, sParameterValue);
+ }
+ });
+
+ jQuery.extend(oMetadataUrlParams, oExtensionObject);
+ return oServiceUri.toString();
+ }
+
+ return {
+ /**
+ *
+ * @param {object} oOptions a map which contains the following parameter properties
+ * @param {string} oOptions.url see {@link sap.ui.model.odata.v2.ODataModel#constructor.sServiceUrl}.
+ * @param {object} [oOptions.urlParametersForEveryRequest] If the parameter is present in the URL or in case of language the UShell can provide it,
+ * it is added to the odata models metadataUrlParams {@link sap.ui.model.odata.v2.ODataModel#constructor.mParameters.metadataUrlParams}, and to the service url.
+ * If you provided a value in the config.metadataUrlParams this value will be overwritten by the value in the url.
+ *
+ * Example: the app is started with the url query, and the user has an us language set in the launchpad:
+ *
+ * ?sap-server=serverValue&sap-host=hostValue
+ *
+ * The createODataModel looks like this.
+ *
+ * models.createODataModel({
+ * urlParametersToPassOn: [
+ * "sap-server",
+ * "sap-language",
+ * "anotherValue"
+ * ],
+ * url : "my/Url"
+ * });
+ *
+ * then the config will have the following metadataUrlParams:
+ *
+ * metadataUrlParams: {
+ * // retrieved from the url
+ * "sap-server" : "serverValue"
+ * // language is added from the launchpad
+ * "sap-language" : "us"
+ * // anotherValue is not present in the url and will not be added
+ * }
+ *
+ * @param {object} [oOptions.config] see {@link sap.ui.model.odata.v2.ODataModel#constructor.mParameters} it is the exact same object, the metadataUrlParams are enriched by the oOptions.urlParametersToPassOn
+ * @returns {sap.ui.model.odata.v2.ODataModel}
+ */
+ createODataModel: function(oOptions) {
+ var aUrlParametersForEveryRequest,
+ oConfig,
+ sUrl;
+
+ oOptions = oOptions || {};
+
+ if (!oOptions.url) {
+ jQuery.sap.log.error("Please provide a url when you want to create an ODataModel", "myDevRequests.model.models.createODataModel");
+ return null;
+ }
+
+ // create a copied instance since we modify the config
+ oConfig = jQuery.extend(true, {}, oOptions.config);
+
+ aUrlParametersForEveryRequest = oOptions.urlParametersForEveryRequest || [];
+ oConfig.metadataUrlParams = oConfig.metadataUrlParams || {};
+
+ sUrl = extendMetadataUrlParameters(aUrlParametersForEveryRequest, oConfig.metadataUrlParams, oOptions.url);
+
+ return this._createODataModel(sUrl, oConfig);
+ },
+
+ _createODataModel: function(sUrl, oConfig) {
+ return new ODataModel(sUrl, oConfig);
+ },
+
+ createDeviceModel: function() {
+ var oModel = new JSONModel(Device);
+ oModel.setDefaultBindingMode("OneWay");
+ return oModel;
+ },
+
+ createFLPModel: function() {
+ var fnGetuser = jQuery.sap.getObject("sap.ushell.Container.getUser"),
+ bIsShareInJamActive = fnGetuser ? fnGetuser().isJamActive() : false,
+ oModel = new JSONModel({
+ isShareInJamActive: bIsShareInJamActive
+ });
+ oModel.setDefaultBindingMode("OneWay");
+ return oModel;
+ },
+
+ createResourceModel: function(sBundleName) {
+ var oResourceModel = new ResourceModel({
+ "bundleName": sBundleName
+ });
+ return oResourceModel;
+ }
+ };
+
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002640_audioMixers.js b/pool/shard000/JavaScript/0002640_audioMixers.js
new file mode 100644
index 0000000000000000000000000000000000000000..369268552d1bcad34aeadcf1aaa57a57409b6cc7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002640_audioMixers.js
@@ -0,0 +1,68 @@
+var _ = require('lodash');
+var native = require('../../build/Release/native.node');
+
+module.exports = function(app) {
+ // Define the audio mixer type.
+ app.store.onCreate('audio-mixer', function(obj) {
+ obj._sources = [];
+
+ obj.setSources = function(list) {
+ _.each(obj._sources, function(source) {
+ source._obj.unref(obj);
+ });
+
+ obj._sources = list || [];
+
+ _.each(obj._sources, function(source) {
+ source._obj.ref(obj);
+ });
+
+ obj.emit('sourcesChanged', obj._sources);
+ };
+
+ obj.on('destroy', function() {
+ _.each(obj._sources, function(source) {
+ source._obj.unref(obj);
+ });
+ });
+
+ obj.activation('native audio mixer', {
+ start: function(lg) {
+ obj._instance = new native.AudioMixer({
+ onEvent: onEvent
+ });
+ app.mark();
+
+ updateSources(obj._sources);
+ lg.listen(obj, 'sourcesChanged', updateSources);
+ function updateSources(list) {
+ obj._instance.setSources(list);
+ }
+ },
+ stop: function() {
+ obj._instance.destroy();
+ obj._instance = null;
+ app.mark();
+ }
+ });
+
+ function onEvent(id, arg) {
+ switch (id) {
+ case native.EV_AUDIO_HEADERS:
+ obj._headers = arg;
+ app.mark();
+
+ obj.emit('headers', arg);
+ break;
+
+ case native.EV_AUDIO_FRAME:
+ obj.emit('frame', arg);
+ break;
+
+ default:
+ obj.handleNativeEvent(id, arg);
+ break;
+ }
+ }
+ });
+};
diff --git a/pool/shard000/JavaScript/0002641_gdcon.js b/pool/shard000/JavaScript/0002641_gdcon.js
new file mode 100644
index 0000000000000000000000000000000000000000..ce88eff6d4ebbfe47acfd94163376409bea3b9e0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002641_gdcon.js
@@ -0,0 +1,159 @@
+/**
+ * connect to Google Drive
+ * (c) 2013, Cybozu.
+ */
+goog.provide('main.gdcon');
+
+
+main.gdcon.startRealtime = function() {
+ realtimeLoader = new rtclient.RealtimeLoader(realtimeOptions);
+ realtimeLoader.start();
+ setInterval(function() {
+ console.log('re-authorizing' + new Date());
+ realtimeLoader.authorizer.authorize();
+ console.log('re-authorized' + new Date());
+ }, 1000 * 60 * 5); // do auth each 5 minute
+};
+
+
+
+/**
+ * This function is called the first time that the Realtime model is created
+ * for a file. This function should be used to initialize any values of the
+ * model.
+ * @param {gapi.drive.realtime.Model} model the Realtime root model object.
+ */
+main.gdcon.initializeModel = function(model) {
+ var field = model.createList();
+ model.getRoot().set('my_list', field);
+};
+
+
+/**
+ * This function is called when the Realtime file has been loaded. It should
+ * be used to initialize any user interface components and event handlers
+ * depending on the Realtime model.
+ * @param {gapi.drive.realtime.Document} doc the Realtime document.
+ */
+main.gdcon.onFileLoaded = function onFileLoaded(doc) {
+ /**
+ * @type {gapi.drive.realtime.CollaborativeList}
+ */
+ main.gdcon._list = doc.getModel().getRoot().get('my_list');
+ console.log('doc');
+ console.log(doc);
+ $('#docid').text('OK');
+ $('#docid').attr(
+ 'href',
+ '../grouping/' +
+ '#fileIds=' + rtclient.params['fileIds'] +
+ '&userId=' + realtimeLoader.authorizer.userId);
+
+ // push local items into _list
+ console.log('merge');
+ var _arr = main.gdcon._list.asArray();
+ var saved_items = _arr.map(JSON.parse);
+ items.forEach(function(item){
+ var s = JSON.stringify(item);
+ var found = false;
+ for(var i=0; i < saved_items.length; i++){
+ if(saved_items[i].when == item.when){
+ found = true;
+ console.log('found');
+ break;
+ }
+ }
+ if(!found){
+ // not saved yet
+ main.gdcon._list.push(s);
+ saved_items.push(item);
+ console.log('pushed');
+ }
+ });
+ items = saved_items;
+ updateJSON();
+ updateUI();
+ //main.gdcon.updateUI();
+};
+
+main.gdcon.push = function(item){
+ if(main.gdcon._list){
+ main.gdcon._list.push(JSON.stringify(item));
+ }
+}
+
+
+/**
+ * @this {rtclient.Authorizer}
+ */
+main.gdcon.onNeedAuth = function() {
+ var authorizer = this;
+ var b = $('#authButton');
+ b.click(function(){
+ authorizer.authorizeWithPopup();
+ b.hide();
+ });
+ b.show();
+};
+
+
+/**
+ * Options for the Realtime loader.
+ */
+var realtimeOptions = {
+ appId: '240613571940',
+ /**
+ * Client ID from the APIs Console.
+ */
+ clientId: '240613571940.apps.googleusercontent.com',
+
+ /**
+ * The ID of the button to click to authorize. Must be a DOM element ID.
+ */
+ authButtonElementId: 'authorizeButton',
+
+ onNeedAuth: main.gdcon.onNeedAuth,
+ onNoNeedAuth: function() {
+ console.log('no need to auth');
+ },
+
+ /**
+ * Function to be called when a Realtime model is first created.
+ */
+ initializeModel: main.gdcon.initializeModel,
+
+ /**
+ * Autocreate files right after auth automatically.
+ */
+ autoCreate: true,
+
+ /**
+ * The name of newly created Drive files.
+ */
+ defaultTitle: 'My Idea',
+
+ /**
+ * The MIME type of newly created Drive Files. By default the application
+ * specific MIME type will be used:
+ * application/vnd.google-apps.drive-sdk.
+ */
+ newFileMimeType: null, // Using default.
+
+ /**
+ * Function to be called every time a Realtime file is loaded.
+ */
+ onFileLoaded: main.gdcon.onFileLoaded,
+
+ /**
+ * Function to be called to inityalize custom Collaborative Objects types.
+ */
+ registerTypes: null, // No action.
+
+ /**
+ * Function to be called after authorization and before loading files.
+ */
+ afterAuth: function(){
+ console.log('after auth');
+ console.log(realtimeLoader);
+ }
+};
diff --git a/pool/shard000/JavaScript/0002643_subnav.js b/pool/shard000/JavaScript/0002643_subnav.js
new file mode 100644
index 0000000000000000000000000000000000000000..0755340a8d0d898b51d313fd24dae866c95f01f5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002643_subnav.js
@@ -0,0 +1,89 @@
+/**
+ * Subnavigation. Handles tab highlighting.
+ * Replaces most of the rowMark.js functionality.
+ *
+ * @author dirk.eschler
+ */
+var sub = {
+
+ /**
+ * Highlights the first tab by default (div#navcontainer li#c_0 a)
+ * by setting the class to 'current'. Is called in subnavigation template.
+ */
+ 'init': function() {
+ //console.log("init");
+ if(document.getElementById('c_0') != null && document.getElementById('c_0').getElementsByTagName('a'))
+ {
+ document.getElementById('c_0').getElementsByTagName('a')[0].className = 'current';
+
+ if(top.frames[0].document.getElementById('help') != null) {
+ var sElClass = document.getElementById('c_0').getAttribute('class');
+ var aElClass = sElClass.split(" ");
+ top.frames[0].document.getElementById('help').setAttribute('data', aElClass[1]);
+ }
+ }
+ },
+
+ /**
+ * Highlights the active tab.
+ *
+ * @param {Object} cElm Clicked a-element, resp. the tab to highlight.
+ * @todo Consider new name ("highlight"?) and rename remaining instances.
+ */
+ 'clicked': function(cElm) {
+ //console.log("clicked");
+ // first unhighlight all tabs
+ var ul = document.getElementById('navlist');
+ var as = ul.getElementsByTagName('a');
+ for (var i=0; i<=as.length; i++) {
+ if (as[i]) {
+ as[i].className = '';
+ }
+ }
+ // then highlight the active tab
+ cElm.className = 'current';
+ },
+
+ /**
+ * Highlights a tab by its element id. Useful for highlighting from an outer frame.
+ *
+ * @param {String} id Element id of tab to highlight
+ * @param {Object} frame Reference to frame hodling the subnavigation:
+ * top.content.right.right_top (when there is a left/right frameset)
+ * top.content.right_top (when there is no left/right frameset)
+ */
+ 'highlightById': function(id, frame) {
+ var ul = frame.document.getElementById('navlist');
+ var as = ul.getElementsByTagName('a');
+ for (var i=0; i<=as.length; i++) {
+ if (as[i]) {
+ as[i].className = '';
+ }
+ }
+ frame.document.getElementById(id).getElementsByTagName('a')[0].className = 'current';
+ },
+
+ /**
+ * Unhighlights all tabs.
+ */
+ /*
+ 'unhighlight': function() {
+ var ul = this.frame.document.getElementById('navlist');
+ var as = ul.getElementsByTagName('a');
+ for (var i=0; i<=as.length; i++) {
+ if (as[i]) {
+ as[i].className = '';
+ }
+ }
+ },*/
+
+ /**
+ * Dummy method to avoid breakage.
+ *
+ * @todo Locate remaining inline calls to sub.click() and remove them
+ */
+ 'click': function() {
+ //console.log("remove me");
+ return;
+ }
+};
diff --git a/pool/shard000/JavaScript/0002644_cpal.js b/pool/shard000/JavaScript/0002644_cpal.js
new file mode 100644
index 0000000000000000000000000000000000000000..326b719e9188c4f2bd952adcebe04dd2daff09a7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002644_cpal.js
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+
+/***********************
+ * Wire up requirejs *
+ ***********************/
+
+var requirejs = require('requirejs');
+
+requirejs.config({
+ baseUrl : __dirname + '/includes',
+ nodeRequire : require
+});
+
+/*************
+ * Imports *
+ *************/
+
+var fs = require('fs');
+var Canvas = require('canvas');
+var rgb = requirejs('imgdata2rgb');
+var mcut = requirejs('mcut')();
+var formats = requirejs('formats');
+
+var canvas_width = 128;
+var canvas_height = 128;
+var canvas = new Canvas(canvas_height, canvas_width);
+var ctx = canvas.getContext('2d');
+var Image = Canvas.Image;
+
+var format;
+var formats_string = Object.keys(formats);
+formats_string = formats_string.join(', ');
+
+/****************************************
+ * command line options with optimism! *
+ ****************************************/
+
+var argv = require('optimist')
+
+ .usage('Generate a color palette from an image! :)\nUSAGE: node cpal.js IMAGE')
+
+ // -f or --fixed
+ .options('s', {
+ alias: 'size',
+ describe: 'Generate a fixed size palette; you specify the number of colors you want.'
+ })
+
+ // -d or --dynamic
+ .options('d', {
+ alias: 'dynamic',
+ describe: 'Generate a palette, sized dynamically based on the color diversity of the image; you can optionally specify a number from 0.0 to 1.0, where larger numbers increase the number of colors.'
+ })
+
+ // -d or --dynamic
+ .options('f', {
+ default: "json",
+ alias: 'format',
+ describe: 'Specify the output format. Available formats are: ' + formats_string
+ })
+
+ .demand(1) // at least 1 image must be specified
+
+ .check(function (args) {
+ var d_num = args.d && typeof args.d === "number",
+ s_num = args.s && typeof args.s === "number";
+ if (args.f && Object.keys(formats).indexOf(args.f) !== -1) {
+ format = formats[args.f];
+ }
+ return d_num && s_num;
+ })
+
+ .argv;
+
+var palette_types = {
+ fixed: 'get_fixed_size_palette',
+ dynamic: 'get_dynamic_size_palette'
+};
+
+var images = argv._;
+var src;
+var num;
+var i;
+var type;
+
+if (argv.s) {
+ type = palette_types.fixed;
+ num = argv.s;
+} else {
+ type = palette_types.dynamic;
+ num = argv.d || 0.4; // default dynamic scale 0.4
+}
+
+function get_colors (img) {
+ var data = rgb(img),
+ palette,
+ output;
+ mcut.init(data);
+ palette = mcut[type](num);
+ output = format(palette);
+ console.log(output);
+}
+
+for (i = 0; i < images.length; i += 1) {
+ (function (image_name) {
+ fs.readFile(images[i], function(err, image_file){
+ if (err) {
+ throw err;
+ }
+
+ if (images.length > 1) {
+ console.log('\n' + image_name + '\n');
+ }
+
+ var img = new Image();
+ var pixels;
+ img.src = image_file;
+ ctx.drawImage(img, 0, 0, canvas_height, canvas_width);
+ pixels = ctx.getImageData(0, 0, canvas_height, canvas_width);
+ get_colors(pixels.data);
+ });
+ }(images[i]));
+}
diff --git a/pool/shard000/JavaScript/0002646_verpontos.js b/pool/shard000/JavaScript/0002646_verpontos.js
new file mode 100644
index 0000000000000000000000000000000000000000..5cdb2c537f6e6a34c7663de3152c5071ebbf7060
--- /dev/null
+++ b/pool/shard000/JavaScript/0002646_verpontos.js
@@ -0,0 +1,57 @@
+//Throw this in your console tab, F12 at browser then console tab. Refresh your page to unload the script.
+//commands = /uid @:name:, example: /uid @Isly | chat reply 'User @Isly statistics: djPoints: 10691 | listenerPoints: 11415 | fans: 289 | grabPoints: 513'
+API.on(API.CHAT_COMMAND, command);
+function command(value) {
+
+ if(value.indexOf("/ver @") >=0)
+ {
+ userIdCommand(value);
+ }
+}
+
+ function userIdCommand(data)
+ {
+ var name = data.substr(6).trim();
+ var pos = checkUsername(name);
+ if(pos != null){
+ var id = getUserId(name);
+ var points = API.getUser(id).djPoints;
+ var listenerPoints = API.getUser(id).listenerPoints;
+ var fans = API.getUser(id).fans;
+ var curatorPoints = API.getUser(id).curatorPoints;
+ API.chatLog(" O Id do usuario " + name + " é : " + id);
+ API.chatLog("Usuario @" + name + " Pontos Tocando: " + points + " / Pontos Avaliando: " + listenerPoints + " / Fans: " + fans + " / Pontos de Grab: " + curatorPoints);
+ }
+ }
+
+ function checkUsername(name)
+ {
+ var userlist = API.getUsers();
+
+ for(var i=0; i < userlist.length; i++)
+ {
+ if(userlist[i].username == name)
+ {
+ var pos = i;
+ break;
+ }else{
+ var pos = null;
+ }
+ }
+ return pos;
+ }
+
+ function getUserId(name)
+ {
+ var userlist = API.getUsers();
+
+ for(var i=0; i < userlist.length; i++)
+ {
+ if(userlist[i].username == name)
+ {
+ var userid = userlist[i].id;
+ break;
+ }
+ }
+ return userid;
+ }
diff --git a/pool/shard000/JavaScript/0002650_redeyed-smoke.js b/pool/shard000/JavaScript/0002650_redeyed-smoke.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf6c81b38a36898b639b92ef53212f26098cfd72
--- /dev/null
+++ b/pool/shard000/JavaScript/0002650_redeyed-smoke.js
@@ -0,0 +1,57 @@
+'use strict';
+/*jshint asi: true*/
+
+// applying redeyed to a bunch of files of contained libraries as a smoke test
+var test = require('tap').test
+ , path = require('path')
+ , fs = require('fs')
+ , readdirp = require('readdirp')
+ , redeyed = require('..')
+ , node_modules = path.join(__dirname, '..', 'node_modules')
+ , tapdir = path.join(node_modules, 'tap')
+ , esprimadir = path.join(node_modules, 'esprima')
+
+test('tap', function (t) {
+ var invalidTapFiles = [
+ 'async-map-ordered.js'
+ , 'prof.js'
+ ]
+
+ readdirp({ root: tapdir, fileFilter: '*.js' })
+ .on('data', function (entry) {
+
+ if (~invalidTapFiles.indexOf(entry.name)) return
+
+ var code = fs.readFileSync(entry.fullPath, 'utf-8')
+ , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code
+
+ t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path)
+ })
+ .on('end', t.end.bind(t))
+})
+
+test('esprima', function (t) {
+
+ readdirp({ root: esprimadir, fileFilter: '*.js' })
+ .on('data', function (entry) {
+
+ var code = fs.readFileSync(entry.fullPath, 'utf-8')
+ , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code
+
+ t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path)
+ })
+ .on('end', t.end.bind(t))
+})
+
+test('redeyed', function (t) {
+
+ readdirp({ root: path.join(__dirname, '..'), fileFilter: '*.js', directoryFilter: ['!.git', '!node_modules' ] })
+ .on('data', function (entry) {
+
+ var code = fs.readFileSync(entry.fullPath, 'utf-8')
+ , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code
+
+ t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path)
+ })
+ .on('end', t.end.bind(t))
+})
diff --git a/pool/shard000/JavaScript/0002654_iscroll.js b/pool/shard000/JavaScript/0002654_iscroll.js
new file mode 100644
index 0000000000000000000000000000000000000000..4b0fc71ac21f05c5925382e20171539dd0630daa
--- /dev/null
+++ b/pool/shard000/JavaScript/0002654_iscroll.js
@@ -0,0 +1,10 @@
+
+function infiniteLoad(callback) {
+ $(window).on('scroll', function () {
+ var h1 = $(document).height() - $(window).height();
+ var h2 = $(window).scrollTop() + 350; // start loading before user can see the change
+ if (h2 >= h1) {
+ callback();
+ }
+ });
+}
diff --git a/pool/shard000/JavaScript/0002659_index.js b/pool/shard000/JavaScript/0002659_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..1a77d53bfd47aae6d4897a31ef23c9d93233db89
--- /dev/null
+++ b/pool/shard000/JavaScript/0002659_index.js
@@ -0,0 +1,206 @@
+var is = require('matthewp-is');
+
+module.exports = Map;
+
+/**
+ * @param {any} element
+ * @return {Number}
+**/
+function indexOf (element) {
+ for (var i = this.length; i-- && !is(this[i], element);) {}
+ return i;
+}
+
+
+
+
+/**
+ * @class Map
+ * @constructor
+ * @param {Array} iterable
+**/
+function Map (iterable) {
+ this._keys = [];
+ this._values = [];
+
+ if (iterable) {
+ for (var i = -1, l = iterable.length; ++i < l;) {
+ this.set(iterable[i][0], iterable[i][1]);
+ }
+ }
+}
+
+/**
+ * get entry value associated with `key`
+ * @method get
+ * @param {any} key
+ * @return {any}
+**/
+Map.prototype.get = function (key) {
+ return this._values[indexOf.call(this._keys, key)];
+};
+
+/**
+ * set entry value associated with `key`
+ * @method set
+ * @chainable
+ * @param {any} key
+ * @param {any} value
+ * @return {Hash}
+**/
+Map.prototype.set = function (key, value) {
+ var index = indexOf.call(this._keys, key);
+
+ if (index > -1) {
+ this._values[index] = value;
+ } else {
+ this._keys.push(key);
+ this._values.push(value);
+ }
+
+ return this;
+};
+
+/**
+ * remove entry key and value with `key`
+ * @method delete
+ * @param {any} key
+ * @return {Boolean}
+**/
+Map.prototype.delete = function (key) {
+ var index = indexOf.call(this._keys, key);
+
+ if (index > -1) {
+ this._keys.splice(index, 1);
+ this._values.splice(index, 1);
+ return true;
+ }
+
+ return false;
+};
+
+/**
+ * entry existence
+ * @method has
+ * @param {any} key
+ * @return {Boolean}
+**/
+Map.prototype.has = function (key) {
+ return indexOf.call(this._keys, key) > -1 ? true : false;
+};
+
+
+/**
+ * remove all entries
+ * @method clear
+**/
+Map.prototype.clear = function () {
+ this._keys.splice(0);
+ this._values.splice(0);
+};
+
+/**
+ * numbers of entries
+ * @readonly
+ * @property size
+ * @type {Number}
+ * @default 0
+**/
+Object.defineProperty(Map.prototype, 'size', {
+ configurable: true,
+ get: function () {
+ return this._keys.length;
+ }
+});
+
+/**
+ * call `callback` with `context` as this for all entries with (value, key, hash)
+ * @method forEach
+ * @param {Function} callback
+ * @param {Object} context
+**/
+Map.prototype.forEach = function (callback, context) {
+ for (var i = -1, l = this._keys.length; ++i < l;) {
+ callback.call(context, this._values[i], this._keys[i], this);
+ }
+};
+
+/**
+ * iterator over `kind`
+ * @method iterator
+ * @param {String} kind
+ * @return {MapIterator}
+**/
+Map.prototype.iterator = function (kind) {
+ return new MapIterator(this, kind);
+};
+
+/**
+ * iterator over keys
+ * @method keys
+ * @return {MapIterator}
+**/
+Map.prototype.keys = function () {
+ return this.iterator('key');
+};
+
+/**
+ * iterator over values
+ * @method values
+ * @return {MapIterator}
+**/
+Map.prototype.values = function () {
+ return this.iterator('value');
+};
+
+/**
+ * iterator over entries
+ * @method entries
+ * @return {MapIterator}
+**/
+Map.prototype.entries = Map.prototype.__iterator__ = function () {
+ return this.iterator('key+value');
+};
+
+
+
+
+/**
+ * @class MapIterator
+ * @constructor
+ * @param {Map} map
+ * @param {String} kind
+ * @return {MapIterator}
+**/
+function MapIterator (map, kind) {
+ this._index = 0;
+ this._keys = map._keys;
+ this._values = map._values;
+ this._kind = kind;
+}
+
+/**
+ * iterate over key/value/entry
+ * @method next
+ * @return {any}
+**/
+MapIterator.prototype.next = function () {
+ var key = this._keys[this._index] !== undefined ? this._keys[this._index] : null;
+ var value = this._values[this._index] !== undefined ? this._values[this._index] : null;
+
+ this._index++;
+
+ switch (this._kind) {
+ case 'key':
+ return key;
+ break;
+
+ case 'value':
+ return value;
+ break;
+
+ case 'key+value':
+ return key != null || value != null ? [key, value] : null;
+ break;
+ }
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002662_travel-manager.js b/pool/shard000/JavaScript/0002662_travel-manager.js
new file mode 100644
index 0000000000000000000000000000000000000000..3e4e12f861304ccc1a2d4da04b7099612dfa074c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002662_travel-manager.js
@@ -0,0 +1,43 @@
+System.register(['./travel'], function(exports_1, context_1) {
+ "use strict";
+ var __moduleName = context_1 && context_1.id;
+ var __extends = (this && this.__extends) || function (d, b) {
+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+ var travel_1;
+ var TravelManager, SampleTravelManager;
+ return {
+ setters:[
+ function (travel_1_1) {
+ travel_1 = travel_1_1;
+ }],
+ execute: function() {
+ TravelManager = (function () {
+ function TravelManager() {
+ this.list = [];
+ }
+ TravelManager.prototype.find = function (id) {
+ return this.list.filter(function (c) { return c.id == id; })[0];
+ };
+ TravelManager.prototype.remove = function (travel) {
+ var index = this.list.indexOf(travel);
+ this.list.splice(index, 1);
+ };
+ return TravelManager;
+ }());
+ exports_1("TravelManager", TravelManager);
+ SampleTravelManager = (function (_super) {
+ __extends(SampleTravelManager, _super);
+ function SampleTravelManager() {
+ _super.call(this);
+ this.list.push(new travel_1.Travel("SF2015", "San Francisco", "USA", 2015, "sanfrancisco.jpg"), new travel_1.Travel("NA2014", "Nantes", "France", 2014, "nantes.jpg"), new travel_1.Travel("BX2014", "Bruxelles", "Belgique", 2014, "bruxelles.jpg"), new travel_1.Travel("YO2014", "Yosemite", "USA", 2014, "yosemite.jpg"), new travel_1.Travel("BT2013", "Bretagne", "France", 2013, "bretagne.jpg"));
+ }
+ return SampleTravelManager;
+ }(TravelManager));
+ exports_1("SampleTravelManager", SampleTravelManager);
+ }
+ }
+});
+//# sourceMappingURL=travel-manager.js.map
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002663_autosave.js b/pool/shard000/JavaScript/0002663_autosave.js
new file mode 100644
index 0000000000000000000000000000000000000000..f61b59da933b5824d96a2275244ba481fb5114a0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002663_autosave.js
@@ -0,0 +1,259 @@
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see .
+/* global NOTIFY_WARNING, NOTIFY_INFO */
+/* eslint-disable no-unused-vars */
+
+/**
+ * A autosave function for the Atto editor.
+ *
+ * @module moodle-editor_atto-autosave
+ * @submodule autosave-base
+ * @package editor_atto
+ * @copyright 2014 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+var SUCCESS_MESSAGE_TIMEOUT = 5000,
+ RECOVER_MESSAGE_TIMEOUT = 60000,
+ LOGNAME_AUTOSAVE = 'moodle-editor_atto-editor-autosave';
+
+function EditorAutosave() {}
+
+EditorAutosave.ATTRS= {
+ /**
+ * Enable/Disable auto save for this instance.
+ *
+ * @attribute autosaveEnabled
+ * @type Boolean
+ * @writeOnce
+ */
+ autosaveEnabled: {
+ value: true,
+ writeOnce: true
+ },
+
+ /**
+ * The time between autosaves (in seconds).
+ *
+ * @attribute autosaveFrequency
+ * @type Number
+ * @default 60
+ * @writeOnce
+ */
+ autosaveFrequency: {
+ value: 60,
+ writeOnce: true
+ },
+
+ /**
+ * Unique hash for this page instance. Calculated from $PAGE->url in php.
+ *
+ * @attribute pageHash
+ * @type String
+ * @writeOnce
+ */
+ pageHash: {
+ value: '',
+ writeOnce: true
+ }
+};
+
+EditorAutosave.prototype = {
+
+ /**
+ * The text that was auto saved in the last request.
+ *
+ * @property lastText
+ * @type string
+ */
+ lastText: "",
+
+ /**
+ * Autosave instance.
+ *
+ * @property autosaveInstance
+ * @type string
+ */
+ autosaveInstance: null,
+
+ /**
+ * Initialize the autosave process
+ *
+ * @method setupAutosave
+ * @chainable
+ */
+ setupAutosave: function() {
+ var draftid = -1,
+ form,
+ optiontype = null,
+ options = this.get('filepickeroptions'),
+ params;
+
+ if (!this.get('autosaveEnabled')) {
+ // Autosave disabled for this instance.
+ return;
+ }
+
+ this.autosaveInstance = Y.stamp(this);
+ for (optiontype in options) {
+ if (typeof options[optiontype].itemid !== "undefined") {
+ draftid = options[optiontype].itemid;
+ }
+ }
+
+ // First see if there are any saved drafts.
+ // Make an ajax request.
+ params = {
+ contextid: this.get('contextid'),
+ action: 'resume',
+ draftid: draftid,
+ elementid: this.get('elementid'),
+ pageinstance: this.autosaveInstance,
+ pagehash: this.get('pageHash')
+ };
+
+ this.autosaveIo(params, this, {
+ success: function(response) {
+ if (response === null) {
+ // This can happen when there is nothing to resume from.
+ return;
+ } else if (!response) {
+ Y.log('Invalid response received.', 'debug', LOGNAME_AUTOSAVE);
+ return;
+ }
+
+ // Revert untouched editor contents to an empty string.
+ // Check for FF and Chrome.
+ if (response.result === '
' || response.result === '
' ||
+ response.result === ' ') {
+ response.result = '';
+ }
+
+ // Check for IE 9 and 10.
+ if (response.result === '
' || response.result === '
') {
+ response.result = '';
+ }
+
+ if (response.error || typeof response.result === 'undefined') {
+ Y.log('Error occurred recovering draft text: ' + response.error, 'debug', LOGNAME_AUTOSAVE);
+ this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
+ NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
+ } else if (response.result !== this.textarea.get('value') &&
+ response.result !== '') {
+ Y.log('Autosave text found - recover it.', 'debug', LOGNAME_AUTOSAVE);
+ this.recoverText(response.result);
+ }
+ this._fireSelectionChanged();
+
+ },
+ failure: function() {
+ this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
+ NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
+ }
+ });
+
+ // Now setup the timer for periodic saves.
+ var delay = parseInt(this.get('autosaveFrequency'), 10) * 1000;
+ Y.later(delay, this, this.saveDraft, false, true);
+
+ // Now setup the listener for form submission.
+ form = this.textarea.ancestor('form');
+ if (form) {
+ this.autosaveIoOnSubmit(form, {
+ action: 'reset',
+ contextid: this.get('contextid'),
+ elementid: this.get('elementid'),
+ pageinstance: this.autosaveInstance,
+ pagehash: this.get('pageHash')
+ });
+ }
+ return this;
+ },
+
+ /**
+ * Recover a previous version of this text and show a message.
+ *
+ * @method recoverText
+ * @param {String} text
+ * @chainable
+ */
+ recoverText: function(text) {
+ this.editor.setHTML(text);
+ this.saveSelection();
+ this.updateOriginal();
+ this.lastText = text;
+
+ this.showMessage(M.util.get_string('textrecovered', 'editor_atto'),
+ NOTIFY_INFO, RECOVER_MESSAGE_TIMEOUT);
+
+ return this;
+ },
+
+ /**
+ * Save a single draft via ajax.
+ *
+ * @method saveDraft
+ * @chainable
+ */
+ saveDraft: function() {
+ var url, params;
+ // Only copy the text from the div to the textarea if the textarea is not currently visible.
+ if (!this.editor.get('hidden')) {
+ this.updateOriginal();
+ }
+ var newText = this.textarea.get('value');
+
+ if (newText !== this.lastText) {
+ Y.log('Autosave text', 'debug', LOGNAME_AUTOSAVE);
+
+ // Make an ajax request.
+ url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
+ params = {
+ sesskey: M.cfg.sesskey,
+ contextid: this.get('contextid'),
+ action: 'save',
+ drafttext: newText,
+ elementid: this.get('elementid'),
+ pagehash: this.get('pageHash'),
+ pageinstance: this.autosaveInstance
+ };
+
+ // Reusable error handler - must be passed the correct context.
+ var ajaxErrorFunction = function(response) {
+ var errorDuration = parseInt(this.get('autosaveFrequency'), 10) * 1000;
+ Y.log('Error while autosaving text', 'warn', LOGNAME_AUTOSAVE);
+ Y.log(response, 'warn', LOGNAME_AUTOSAVE);
+ this.showMessage(M.util.get_string('autosavefailed', 'editor_atto'), NOTIFY_WARNING, errorDuration);
+ };
+
+ this.autosaveIo(params, this, {
+ failure: ajaxErrorFunction,
+ success: function(response) {
+ if (response && response.error) {
+ Y.soon(Y.bind(ajaxErrorFunction, this, [response]));
+ } else {
+ // All working.
+ this.lastText = newText;
+ this.showMessage(M.util.get_string('autosavesucceeded', 'editor_atto'),
+ NOTIFY_INFO, SUCCESS_MESSAGE_TIMEOUT);
+ }
+ }
+ });
+ }
+ return this;
+ }
+};
+
+Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosave]);
diff --git a/pool/shard000/JavaScript/0002664_Shader.js b/pool/shard000/JavaScript/0002664_Shader.js
new file mode 100644
index 0000000000000000000000000000000000000000..99343122db1d3640e9c3839605a1740a2cdcfe98
--- /dev/null
+++ b/pool/shard000/JavaScript/0002664_Shader.js
@@ -0,0 +1,63 @@
+module.exports = (function() {
+ ///
+ /// Pulls a shader script from the specified DOM element (script_id), and attempts to compile it as either a vertex or fragment shader.
+ ///
+ function buildShaderScript(gl, script_id) {
+ var script = document.getElementById(script_id);
+
+ if (!script) {
+ throw("ERROR: Invalid shader script_id (" + script_id + ")");
+ }
+ else {
+ if (script.type == "x-shader/x-vertex") {
+ //Compiles and returns a vertex shader from script.
+ return compile(gl, script.text, gl.VERTEX_SHADER);
+ }
+ else if (script.type == "x-shader/x-fragment") {
+ //Compiles and returns a fragment shader from script.
+ return compile(gl, script.text, gl.FRAGMENT_SHADER);
+ }
+ else {
+ throw("ERROR: Invalid shader type (" + script.type +")");
+ }
+ }
+ }
+
+ ///
+ /// Attempts to compile the supplied shader script into a WebGL shader object.
+ ///
+ function compile(gl, src, type) {
+ var shader = gl.createShader(type);
+
+ gl.shaderSource(shader, src);
+ gl.compileShader(shader);
+
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+ throw("ERROR: Unable to compile shader (" + gl.getShaderInfoLog(shader) + ")");
+ }
+ return shader;
+ }
+
+ ///
+ /// Attempts to attach both a vertex and fragment shader to a newly created WebGL program
+ ///
+ function newProgram(gl, vert, frag) {
+ var prog = gl.createProgram();
+
+ gl.attachShader(prog, vert);
+ gl.attachShader(prog, frag);
+ gl.linkProgram(prog);
+
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
+ throw("ERROR: Shader Program failed to link (" + gl.getProgramInfoLog(prog) + ")");
+ }
+
+ return prog;
+ }
+
+ return {
+ buildShaderScript: buildShaderScript,
+ compile: compile,
+ newProgram: newProgram
+ };
+})();
diff --git a/pool/shard000/JavaScript/0002665_compiler.js b/pool/shard000/JavaScript/0002665_compiler.js
new file mode 100644
index 0000000000000000000000000000000000000000..93371191aab6ca3b493367a6b2e183ead9f8473a
--- /dev/null
+++ b/pool/shard000/JavaScript/0002665_compiler.js
@@ -0,0 +1,60 @@
+// MySQL Schema Compiler
+// -------
+const inherits = require('inherits');
+const SchemaCompiler = require('../../../schema/compiler');
+
+const some = require('lodash/some');
+
+function SchemaCompiler_MySQL(client, builder) {
+ SchemaCompiler.call(this, client, builder);
+}
+inherits(SchemaCompiler_MySQL, SchemaCompiler);
+
+Object.assign(SchemaCompiler_MySQL.prototype, {
+ // Rename a table on the schema.
+ renameTable(tableName, to) {
+ this.pushQuery(
+ `rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap(
+ to
+ )}`
+ );
+ },
+
+ // Check whether a table exists on the query.
+ hasTable(tableName) {
+ let sql = 'select * from information_schema.tables where table_name = ?';
+ const bindings = [tableName];
+
+ if (this.schema) {
+ sql += ' and table_schema = ?';
+ bindings.push(this.schema);
+ } else {
+ sql += ' and table_schema = database()';
+ }
+
+ this.pushQuery({
+ sql,
+ bindings,
+ output: function output(resp) {
+ return resp.length > 0;
+ },
+ });
+ },
+
+ // Check whether a column exists on the schema.
+ hasColumn(tableName, column) {
+ this.pushQuery({
+ sql: `show columns from ${this.formatter.wrap(tableName)}`,
+ output(resp) {
+ return some(resp, (row) => {
+ return (
+ this.client.wrapIdentifier(row.Field) ===
+ this.client.wrapIdentifier(column)
+ );
+ });
+ },
+ });
+ },
+});
+
+module.exports = SchemaCompiler_MySQL;
diff --git a/pool/shard000/JavaScript/0002667_exercisesLib.js b/pool/shard000/JavaScript/0002667_exercisesLib.js
new file mode 100644
index 0000000000000000000000000000000000000000..78ce0fdd6f804dc638878f3ff9bc1e5d05609273
--- /dev/null
+++ b/pool/shard000/JavaScript/0002667_exercisesLib.js
@@ -0,0 +1,100 @@
+/**
+ * Created by wizard on 11/14/16.
+ */
+const Promise = require('bluebird').Promise,
+ Punching = require('../models/punchingRecord'),
+ logger = require('../libs/ironmanLogger');
+
+module.exports.punchingHomeworkForParent = function (user) {
+ if (user.linkedUserMails == undefined || user.linkedUserMails.length == 0) {
+ return new Promise(function (resolve) {
+ resolve([]);
+ });
+ }
+
+ const mails = user.linkedUserMails;
+
+ let promises = mails.map((mail)=> {
+ let type = Punching.PunchingType.homework;
+ return Punching.PunchingRecordModel.find({mail, type}).exec();
+ });
+
+ let datas = [];
+
+ return Promise.all(promises)
+ .then((arrayOfRecords)=> {
+
+ arrayOfRecords.map((records, index) => {
+ datas[index] = {mail: mails[index], count: records.length}
+ });
+
+ let ps = mails.map((mail)=> {
+ let type = Punching.PunchingType.homework;
+ return Punching.isPunchedToday(mail, type);
+ });
+
+ return Promise.all(ps);
+ })
+
+ .then((arrayOfIsPunched)=> {
+ arrayOfIsPunched.map((isPunched, index) => {
+ datas[index]["today"] = isPunched;
+ });
+
+ return new Promise(function (resolve) {
+ resolve(datas);
+ });
+ })
+
+ .catch((e)=> {
+ logger.error(e.message);
+ throw e;
+ })
+};
+
+function punchingRecords(user, type) {
+ if (user.isStudent) {
+ let mail = user.mail;
+ const promise = Punching.PunchingRecordModel.find({mail, type}).exec();
+ return Promise.all([promise]);
+ }
+
+ if (user.linkedUserMails == undefined || user.linkedUserMails.length == 0) {
+ return new Promise(function (resolve) {
+ resolve([]);
+ });
+ }
+
+ const mails = user.linkedUserMails;
+
+ let promises = mails.map((mail)=> {
+ return Punching.PunchingRecordModel.find({mail, type}).exec();
+ });
+
+ return Promise.all(promises)
+ .catch((e)=> {
+ logger.error(e.message);
+ throw e;
+ })
+}
+
+module.exports.homeworkPunchingRecords = function (user) {
+ return punchingRecords(user, Punching.PunchingType.homework);
+};
+
+
+module.exports.wordPunchingRecords = function (user) {
+ return punchingRecords(user, Punching.PunchingType.word);
+};
+
+module.exports.punchForChild = function (user, childMail, type) {
+ return Punching.isPunchedToday(childMail, type)
+ .then((succeed)=> {
+ if (succeed) {
+ return Promise.resolve(succeed);
+ }
+ else {
+ return Punching.punchToday(childMail, type);
+ }
+ });
+};
diff --git a/pool/shard000/JavaScript/0002668_ArabicNumberMap.js b/pool/shard000/JavaScript/0002668_ArabicNumberMap.js
new file mode 100644
index 0000000000000000000000000000000000000000..0d59c637d506d791f5d1c202e595bc329c70ddb4
--- /dev/null
+++ b/pool/shard000/JavaScript/0002668_ArabicNumberMap.js
@@ -0,0 +1,43 @@
+'use strict';
+
+let should = require('chai').should(),
+ describe = require('mocha').describe,
+ it = require('mocha').it;
+
+describe('ArabicNumberMap class', function () {
+
+ let ArabicNumberMap = require('../roman-numerals').ArabicNumberMap;
+
+ it('should be an object', function () {
+
+ ArabicNumberMap.should.be.a('object');
+
+ });
+
+ describe('should return the correct roman numeral values for given arabic number values', function () {
+
+ function checkRomanValueForArabicNumber(arabicNumber, expectedRomanValue) {
+ let romanValue = ArabicNumberMap[arabicNumber];
+
+ romanValue.should.be.a('string');
+ romanValue.should.equal(expectedRomanValue);
+ }
+
+ it('should contain all necessary roman numerals for arabic numbers 1 through 1000', function () {
+ checkRomanValueForArabicNumber(1000,'M');
+ checkRomanValueForArabicNumber(900,'CM');
+ checkRomanValueForArabicNumber(500,'D');
+ checkRomanValueForArabicNumber(400,'CD');
+ checkRomanValueForArabicNumber(100,'C');
+ checkRomanValueForArabicNumber(90,'XC');
+ checkRomanValueForArabicNumber(50,'L');
+ checkRomanValueForArabicNumber(40,'XL');
+ checkRomanValueForArabicNumber(10,'X');
+ checkRomanValueForArabicNumber(9,'IX');
+ checkRomanValueForArabicNumber(5,'V');
+ checkRomanValueForArabicNumber(4,'IV');
+ });
+
+ });
+
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002669_equation.js b/pool/shard000/JavaScript/0002669_equation.js
new file mode 100644
index 0000000000000000000000000000000000000000..99fbe392f410a546569908f26d7c698baa26aec7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002669_equation.js
@@ -0,0 +1,202 @@
+import assert from 'assert';
+import sinon from 'sinon';
+import Matrix from '../../src/recurrent/matrix';
+import OnesMatrix from '../../src/recurrent/matrix/ones-matrix';
+import Equation from '../../src/recurrent/matrix/equation';
+
+function fourSquareMatrix(value) {
+ var result = new Matrix(4, 4);
+ result.weights.forEach((_, i) => {
+ result.weights[i] = value;
+ });
+ return result;
+}
+
+describe('equation', () => {
+ describe('run', () => {
+ it('calls all forwardFn properties', () => {
+ var equation = new Equation();
+ for (var i = 0; i < 10; i++) {
+ equation.states.push({
+ forwardFn: sinon.spy()
+ })
+ }
+ equation.runIndex();
+ equation.states.forEach((state) => {
+ assert(state.forwardFn.called);
+ });
+ });
+ });
+ describe('runBack', () => {
+ it('calls all forwardFn properties', () => {
+ var equation = new Equation();
+ for (var i = 0; i < 10; i++) {
+ equation.states.push({
+ backpropagationFn: sinon.spy()
+ })
+ }
+ equation.backpropagate();
+ equation.states.forEach((state) => {
+ assert(state.backpropagationFn.called);
+ });
+ });
+ });
+ describe('add', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('multiply', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.multiply(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('multiplyElement', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('relu', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('inputMatrixToRow', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('sigmoid', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('tanh', () => {
+ it('calls forwardFn', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(1);
+ equation.add(input, fourSquareMatrix(1));
+ assert.equal(equation.states.length, 1);
+ sinon.spy(equation.states[0], 'forwardFn');
+ equation.runIndex();
+ assert(equation.states[0].forwardFn.called);
+ });
+ });
+ describe('nesting', () => {
+ it('can nest 3 deep and run forward', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(2);
+ equation.multiply(equation.multiply(equation.multiply(input, fourSquareMatrix(2)), fourSquareMatrix(2)), fourSquareMatrix(2));
+ assert.equal(equation.states.length, 3);
+ sinon.spy(equation.states[0], 'forwardFn');
+ sinon.spy(equation.states[1], 'forwardFn');
+ sinon.spy(equation.states[2], 'forwardFn');
+ equation.runIndex();
+ equation.states.forEach((state) => {
+ assert(state.forwardFn.called);
+ });
+ });
+ it('can nest 3 deep and run backward', () => {
+ var equation = new Equation();
+ var input = fourSquareMatrix(2);
+ equation.tanh(equation.multiply(equation.add(input, fourSquareMatrix(2)), fourSquareMatrix(2)), fourSquareMatrix(2));
+ assert.equal(equation.states.length, 3);
+ sinon.spy(equation.states[0], 'backpropagationFn');
+ sinon.spy(equation.states[1], 'backpropagationFn');
+ sinon.spy(equation.states[2], 'backpropagationFn');
+ equation.backpropagate();
+ equation.states.forEach((state) => {
+ assert(state.backpropagationFn.called);
+ });
+ });
+ });
+ describe('inputMatrixToRow', () => {
+ context('runIndex', () => {
+ it('can properly split up a matrix', () => {
+ var input = new Matrix(2, 2);
+ /**
+ * Matrix like:
+ * 1 1
+ * 2 2
+ */
+ input.weights.forEach((w, i) => {
+ if (i < 2) {
+ input.weights[i] = 1;
+ } else {
+ input.weights[i] = 2;
+ }
+ });
+ var equation = new Equation();
+ equation.add(new OnesMatrix(1, 2), equation.inputMatrixToRow(input));
+ var output = equation.runIndex();
+ assert.equal(output.weights.length, 2);
+ assert.equal(output.weights[0], 2);
+ assert.equal(output.weights[1], 2);
+
+ output = equation.runIndex(1);
+ assert.equal(output.weights.length, 2);
+ assert.equal(output.weights[0], 3);
+ assert.equal(output.weights[1], 3);
+ });
+ });
+ context('.backpropagate()', () => {
+ it('can properly split up a matrix', () => {
+ var input = new Matrix(2, 2);
+ /**
+ * Matrix like:
+ * 1 1
+ * 2 2
+ */
+ input.weights.forEach((w, i) => {
+ if (i < 2) {
+ input.weights[i] = 1;
+ } else {
+ input.weights[i] = 2;
+ }
+ });
+ var equation = new Equation();
+ equation.add(new OnesMatrix(1, 2), equation.inputMatrixToRow(input));
+ var output = equation.runIndex();
+ assert.equal(output.weights.length, 2);
+ output = equation.runIndex(1);
+ assert.equal(output.weights.length, 2);
+ });
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002671_view-omic-overview-national.js b/pool/shard000/JavaScript/0002671_view-omic-overview-national.js
new file mode 100644
index 0000000000000000000000000000000000000000..188f9277e0558abd65abae11d26e91b8c995f461
--- /dev/null
+++ b/pool/shard000/JavaScript/0002671_view-omic-overview-national.js
@@ -0,0 +1,119 @@
+const expect = require('chai').expect
+const authenticationHelper = require('../helpers/routes/authentication-helper')
+const workloadTypes = require('../../app/constants/workload-type')
+
+const nationalDefaultUrl = '/' + workloadTypes.OMIC + '/hmpps/0'
+
+describe('National Omic Overview', function () {
+ describe('Staff', function () {
+ before(async function () {
+ await authenticationHelper.login(authenticationHelper.users.Staff)
+ await browser.url(nationalDefaultUrl)
+ })
+
+ it('should show regional breakdown table', async function () {
+ const element = await $('.sln-table-org-level')
+ const text = await element.getText()
+ expect(text).to.equal('Region')
+ })
+
+ it('should allow the user to navigate down the org hierarchy from the national page', async function () {
+ await browser.url(nationalDefaultUrl + '/overview')
+ let pageTitle = await $('.govuk-caption-xl')
+ let text = await pageTitle.getText()
+ expect(text).to.equal('National')
+
+ const activeRegion = await browser.findElements('xpath', '//*[@id="example"]/tbody/tr[position()=1]/td[position()=1]/a')
+ const viewRegionLink = await $(activeRegion[0])
+ await viewRegionLink.click()
+
+ pageTitle = await $('.govuk-caption-xl')
+ text = await pageTitle.getText()
+ expect(text).to.equal('Region')
+
+ const activeLdu = await browser.findElements('xpath', '//*[@id="example"]/tbody/tr[position()=1]/td[position()=1]/a')
+ const viewLduLink = await $(activeLdu[0])
+
+ await viewLduLink.click()
+
+ pageTitle = await $('.govuk-caption-xl')
+ text = await pageTitle.getText()
+ expect(text).to.equal('Probation Delivery Unit')
+ })
+
+ it('should contain breadcrumbs which allow the user to navigate up the org hierarchy', async function () {
+ const breadcrumbRegion = await browser.findElements('xpath', '//*[@class="govuk-breadcrumbs__list"]/li[position()=2]/a')
+ const breadcrumbRegionLink = await $(breadcrumbRegion[0])
+
+ await breadcrumbRegionLink.click()
+
+ let pageTitle = await $('.govuk-caption-xl')
+ let text = await pageTitle.getText()
+ expect(text).to.equal('Region')
+
+ const breadcrumbNational = await browser.findElements('xpath', '//*[@class="govuk-breadcrumbs__list"]/li[position()=1]/a')
+ const breadcrumbNationalLink = await $(breadcrumbNational[0])
+
+ await breadcrumbNationalLink.click()
+
+ pageTitle = await $('.govuk-caption-xl')
+ text = await pageTitle.getText()
+ expect(text).to.equal('National')
+ })
+
+ after(function () {
+ authenticationHelper.logout()
+ })
+ })
+
+ describe('Managers', function () {
+ before(async function () {
+ await authenticationHelper.login(authenticationHelper.users.Manager)
+ await browser.url(nationalDefaultUrl)
+ })
+
+ it('should show regional breakdown table', async function () {
+ const element = await $('.sln-table-org-level')
+ const text = await element.getText()
+ expect(text).to.equal('Region')
+ })
+
+ after(function () {
+ authenticationHelper.logout()
+ })
+ })
+
+ describe('Application Support', function () {
+ before(async function () {
+ await authenticationHelper.login(authenticationHelper.users.ApplicationSupport)
+ await browser.url(nationalDefaultUrl)
+ })
+
+ it('should show regional breakdown table', async function () {
+ const element = await $('.sln-table-org-level')
+ const text = await element.getText()
+ expect(text).to.equal('Region')
+ })
+
+ after(function () {
+ authenticationHelper.logout()
+ })
+ })
+
+ describe('Super User', function () {
+ before(async function () {
+ await authenticationHelper.login(authenticationHelper.users.SuperUser)
+ await browser.url(nationalDefaultUrl)
+ })
+
+ it('should show regional breakdown table', async function () {
+ const element = await $('.sln-table-org-level')
+ const text = await element.getText()
+ expect(text).to.equal('Region')
+ })
+
+ after(function () {
+ authenticationHelper.logout()
+ })
+ })
+})
diff --git a/pool/shard000/JavaScript/0002672_index.modern.js b/pool/shard000/JavaScript/0002672_index.modern.js
new file mode 100644
index 0000000000000000000000000000000000000000..d74edc08a5ae1456934771d7af4cc05b7399588d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002672_index.modern.js
@@ -0,0 +1,234 @@
+import React, { forwardRef, useRef, useMemo, useState, useImperativeHandle, useEffect } from 'react';
+import Chart$1 from 'chart.js/auto';
+import merge from 'lodash/merge';
+import assign from 'lodash/assign';
+import find from 'lodash/find';
+import { defaults as defaults$1, Chart as Chart$2 } from 'chart.js';
+
+function _extends() {
+ _extends = Object.assign || function (target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i];
+
+ for (var key in source) {
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
+ target[key] = source[key];
+ }
+ }
+ }
+
+ return target;
+ };
+
+ return _extends.apply(this, arguments);
+}
+
+function _objectWithoutPropertiesLoose(source, excluded) {
+ if (source == null) return {};
+ var target = {};
+ var sourceKeys = Object.keys(source);
+ var key, i;
+
+ for (i = 0; i < sourceKeys.length; i++) {
+ key = sourceKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ target[key] = source[key];
+ }
+
+ return target;
+}
+
+var ChartComponent = forwardRef(function (props, ref) {
+ var id = props.id,
+ className = props.className,
+ _props$height = props.height,
+ height = _props$height === void 0 ? 150 : _props$height,
+ _props$width = props.width,
+ width = _props$width === void 0 ? 300 : _props$width,
+ _props$redraw = props.redraw,
+ redraw = _props$redraw === void 0 ? false : _props$redraw,
+ type = props.type,
+ data = props.data,
+ _props$options = props.options,
+ options = _props$options === void 0 ? {} : _props$options,
+ _props$plugins = props.plugins,
+ plugins = _props$plugins === void 0 ? [] : _props$plugins,
+ getDatasetAtEvent = props.getDatasetAtEvent,
+ getElementAtEvent = props.getElementAtEvent,
+ getElementsAtEvent = props.getElementsAtEvent,
+ fallbackContent = props.fallbackContent,
+ rest = _objectWithoutPropertiesLoose(props, ["id", "className", "height", "width", "redraw", "type", "data", "options", "plugins", "getDatasetAtEvent", "getElementAtEvent", "getElementsAtEvent", "fallbackContent"]);
+
+ var canvas = useRef(null);
+ var computedData = useMemo(function () {
+ if (typeof data === 'function') {
+ return canvas.current ? data(canvas.current) : {};
+ } else return merge({}, data);
+ }, [data, canvas.current]);
+
+ var _useState = useState(),
+ chart = _useState[0],
+ setChart = _useState[1];
+
+ useImperativeHandle(ref, function () {
+ return chart;
+ }, [chart]);
+
+ var renderChart = function renderChart() {
+ if (!canvas.current) return;
+ setChart(new Chart$1(canvas.current, {
+ type: type,
+ data: computedData,
+ options: options,
+ plugins: plugins
+ }));
+ };
+
+ var onClick = function onClick(e) {
+ if (!chart) return;
+ getDatasetAtEvent && getDatasetAtEvent(chart.getElementsAtEventForMode(e, 'dataset', {
+ intersect: true
+ }, false), e);
+ getElementAtEvent && getElementAtEvent(chart.getElementsAtEventForMode(e, 'nearest', {
+ intersect: true
+ }, false), e);
+ getElementsAtEvent && getElementsAtEvent(chart.getElementsAtEventForMode(e, 'index', {
+ intersect: true
+ }, false), e);
+ };
+
+ var updateChart = function updateChart() {
+ if (!chart) return;
+
+ if (options) {
+ chart.options = _extends({}, options);
+ }
+
+ if (!chart.config.data) {
+ chart.config.data = computedData;
+ chart.update();
+ return;
+ }
+
+ var _computedData$dataset = computedData.datasets,
+ newDataSets = _computedData$dataset === void 0 ? [] : _computedData$dataset,
+ newChartData = _objectWithoutPropertiesLoose(computedData, ["datasets"]);
+
+ var _chart$config$data$da = chart.config.data.datasets,
+ currentDataSets = _chart$config$data$da === void 0 ? [] : _chart$config$data$da;
+ assign(chart.config.data, newChartData);
+ chart.config.data.datasets = newDataSets.map(function (newDataSet) {
+ var currentDataSet = find(currentDataSets, function (d) {
+ return d.label === newDataSet.label && d.type === newDataSet.type;
+ });
+ if (!currentDataSet || !newDataSet.data) return _extends({}, newDataSet);
+
+ if (!currentDataSet.data) {
+ currentDataSet.data = [];
+ } else {
+ currentDataSet.data.length = newDataSet.data.length;
+ }
+
+ assign(currentDataSet.data, newDataSet.data);
+ assign(currentDataSet, _extends({}, newDataSet, {
+ data: currentDataSet.data
+ }));
+ return currentDataSet;
+ });
+ chart.update();
+ };
+
+ var destroyChart = function destroyChart() {
+ if (chart) chart.destroy();
+ };
+
+ useEffect(function () {
+ renderChart();
+ return function () {
+ return destroyChart();
+ };
+ }, []);
+ useEffect(function () {
+ if (redraw) {
+ destroyChart();
+ setTimeout(function () {
+ renderChart();
+ }, 0);
+ } else {
+ updateChart();
+ }
+ }, [props, computedData]);
+ return React.createElement("canvas", Object.assign({}, rest, {
+ height: height,
+ width: width,
+ ref: canvas,
+ id: id,
+ className: className,
+ onClick: onClick,
+ "data-testid": 'canvas',
+ role: 'img'
+ }), fallbackContent);
+});
+
+var Line = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'line',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Bar = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'bar',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Radar = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'radar',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Doughnut = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'doughnut',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var PolarArea = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'polarArea',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Bubble = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'bubble',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Pie = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'pie',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var Scatter = forwardRef(function (props, ref) {
+ return React.createElement(ChartComponent, Object.assign({}, props, {
+ type: 'scatter',
+ ref: ref,
+ options: props.options || {}
+ }));
+});
+var defaults = defaults$1;
+var Chart = Chart$2;
+
+export default ChartComponent;
+export { Bar, Bubble, Chart, Doughnut, Line, Pie, PolarArea, Radar, Scatter, defaults };
+//# sourceMappingURL=index.modern.js.map
diff --git a/pool/shard000/JavaScript/0002673_config.js b/pool/shard000/JavaScript/0002673_config.js
new file mode 100644
index 0000000000000000000000000000000000000000..882f94f29d84aa207eaef7dcdd1913773d3c70d8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002673_config.js
@@ -0,0 +1,23 @@
+'use strict';
+
+// Init the application configuration module for AngularJS application
+var ApplicationConfiguration = (function () {
+ // Init module configuration options
+ var applicationModuleName = 'muncci';
+ var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
+
+ // Add a new vertical module
+ var registerModule = function (moduleName, dependencies) {
+ // Create angular module
+ angular.module(moduleName, dependencies || []);
+
+ // Add the module to the AngularJS configuration file
+ angular.module(applicationModuleName).requires.push(moduleName);
+ };
+
+ return {
+ applicationModuleName: applicationModuleName,
+ applicationModuleVendorDependencies: applicationModuleVendorDependencies,
+ registerModule: registerModule
+ };
+})();
diff --git a/pool/shard000/JavaScript/0002676_uamdatatables.js b/pool/shard000/JavaScript/0002676_uamdatatables.js
new file mode 100644
index 0000000000000000000000000000000000000000..cef1501546a8f666df713d34630e1fd8075f9417
--- /dev/null
+++ b/pool/shard000/JavaScript/0002676_uamdatatables.js
@@ -0,0 +1,117 @@
+!function( $ ) {
+ $.fn.uamdatatables = function( method ) {
+
+ var settings,
+ table;
+
+ // Public methods
+ var methods = {
+ init: function( options ) {
+ settings = $.extend( true, {}, $.fn.uamdatatables.defaults, options );
+
+ return this.each(function() {
+ var $this = $( this );
+
+ $( ".filters input" ).keyup(function( event ) {
+ event.stopPropagation();
+ table.api().draw();
+ });
+
+ $( ".filters :checkbox" ).change(function( event ) {
+ event.stopPropagation();
+ table.api().draw();
+ });
+
+ $( ".filters input[type='date']" ).change(function( event ) {
+ console.log( this.value );
+ event.stopPropagation();
+ table.api().draw();
+ });
+
+ $(".filters select").change(function( event ) {
+ event.stopPropagation();
+ table.api().draw();
+ });
+
+ table = $( "table.table", this ).dataTable( $.extend(
+ true,
+ {
+ ajax: {
+ data: function( data ) {
+ $( ".filters input, .filters select" ).each(function() {
+ var name = $( this ).attr( "name" ),
+ value = $( this ).val();
+
+ if ( "checkbox" == $( this ).attr( "type" ) ) {
+ value = $( this ).is( ":checked" ) ? $( this ).val() : 0;
+ }
+
+ if ("date" == $( this ).attr( "type" ) ) {
+ value = $( this ).val();
+ }
+
+ data[name] = value;
+ } );
+ }
+ },
+ initComplete: function( settings, json ) {
+ $( this ).show();
+ },
+ language: {
+ url: "/bundles/uamdatatables/vendor/datatables-plugins/i18n/" + settings.locale + ".json"
+ },
+ stateLoadParams: function( settings, data ) {
+ $( ".filters input, .filters select", $this ).each(function() {
+ var value = data[ $( this ).attr( "name" ) ];
+
+ if ( $( this ).attr( "type" ) == "checkbox" ) {
+ $( this ).attr( "checked", value );
+ } else {
+ $( this ).val( value );
+ }
+ });
+ },
+ stateSaveParams: function( settings, data ) {
+ $( ".filters input, .filters select", $this ).each(function() {
+ var name = $( this ).attr( "name" ),
+ value = $( this ).attr( "type" ) == "checkbox"
+ ? ($( this ).is( ":checked" ) ? $( this ).val() : 0)
+ : $( this ).val();
+
+ data[ name ] = value;
+ });
+ }
+ },
+ settings
+ ) );
+ });
+ }
+ };
+
+ if ( methods[ method ] ) {
+ return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
+ }
+ else if ( typeof method === "object" || !method ) {
+ return methods.init.apply( this, arguments );
+ }
+ else {
+ $.error( "Method " + method + " does not exist in $.uamdatatables." );
+ }
+ };
+
+ $.fn.uamdatatables.defaults = {
+ autoWidth: false,
+ locale: "en",
+ ordering: true,
+ orderCellsTop: true,
+ paging: true,
+ processing: true,
+ searching: true,
+ serverSide: true,
+ stripeClasses: []
+ };
+} ( window.jQuery );
+
+$( document ).ready(function() {
+ $( ".uamdatatables" ).uamdatatables( "undefined" === typeof uamdatatables ? {} : uamdatatables );
+});
diff --git a/pool/shard000/JavaScript/0002680_clidriver.js b/pool/shard000/JavaScript/0002680_clidriver.js
new file mode 100644
index 0000000000000000000000000000000000000000..31dcc767b25f3a47b35071611d45fc591622f23d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002680_clidriver.js
@@ -0,0 +1,32 @@
+import fs from 'fs'
+import path from 'path'
+import {processFile} from './lib/payrollcsv'
+
+const outFilepath = (outDir, inFilepath) => {
+ const filename = path.basename(inFilepath)
+ return path.join(outDir, filename)
+}
+
+export const main = ({input: inFiles, outDir, force}) => {
+ outDir = path.resolve(outDir)
+
+ if (!fs.existsSync(outDir)) {
+ if(force) {
+ fs.mkdirSync(outDir)
+ } else {
+ console.error(`Error: no such directory ${outDir}`)
+ process.exit(1)
+ }
+ }
+
+ inFiles
+ .map(inFile => path.resolve(inFile))
+ .map(inFile => {
+ try {
+ processFile(inFile, outFilepath(outDir, inFile))
+ } catch(err) {
+ console.error(err)
+ process.exit(1)
+ }
+ })
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002682_admin.js b/pool/shard000/JavaScript/0002682_admin.js
new file mode 100644
index 0000000000000000000000000000000000000000..ba6c560a3d52a62aa501c869b14c46f634b583fd
--- /dev/null
+++ b/pool/shard000/JavaScript/0002682_admin.js
@@ -0,0 +1,89 @@
+/*
+ addAdmin
+ - makeAdmin 56b7b29b9b4ef7e0289ca293
+ */
+
+
+
+'use strict'
+
+const _ = require('lodash')
+const set = require('setthings').set
+const settings = require('setthings').settings
+const MongoClient = require('mongodb').MongoClient
+var ObjectId = require('mongodb').ObjectId
+const DA = require(__dirname + '/data_access/DA')
+
+// settings
+set('mongo.uri', 'mongodb://localhost:27017/restinpieces')
+set('jwt.secret', 'doubledoubletoilandtrouble')
+
+// connect to database, create entity objects
+let database = null
+MongoClient.connect(settings.mongo.uri)
+ .then(db => {
+ database = db
+ console.log("successfully connected to mongo db")
+ // initialize data access objects
+ console.log("initializing data access objects")
+ DA.init(db)
+ // parse
+ return parse()
+ })
+ .then(cmd => {
+ return cmd.run(cmd.value)
+ })
+ .then((message) => {
+ console.log("message:", message)
+ database.close()
+ })
+ .catch(err => {
+ console.error(err.message)
+ database.close()
+ })
+
+function parse() {
+ return new Promise((resolve, reject) => {
+ let args = process.argv.slice(2)
+ if(args.length < 2) {
+ reject(new Error("not enough parameters"))
+ }
+ else {
+
+ let funcs = {'makeAdmin': makeAdmin}
+ if(funcs.hasOwnProperty(args[0])) {
+ let command = { run: funcs[args[0]], value: args[1]}
+ resolve(command)
+ }
+ else {
+ reject(new Error(`unknown command '${args[0]}'`))
+ }
+ }
+ })
+}
+
+function makeAdmin(user_id) {
+
+ return new Promise((resolve, reject) => {
+ database.collection('users').find({'_id':ObjectId(user_id)}).limit(1).toArray()
+ .then(users => {
+ if(users.length > 0) {
+ if(new Set(users[0].roles).has("admin") === false ) {
+ users[0].roles.push("admin")
+ }
+ return database.collection('users').updateOne({'_id': ObjectId(user_id)}, {'$set': {roles:users[0].roles}})
+ }
+ else {
+ reject(new Error("user not found"))
+ }
+ })
+ .then(result => {
+ resolve("admin role added to user")
+ })
+ .catch(err => {
+ reject(new Error(err.message))
+ })
+ })
+
+ //return DA.O.users.makeAdmin(user_id)
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002686_secret.js b/pool/shard000/JavaScript/0002686_secret.js
new file mode 100644
index 0000000000000000000000000000000000000000..59b2fb96eac1390c9242b0707ed01d7c13f98bde
--- /dev/null
+++ b/pool/shard000/JavaScript/0002686_secret.js
@@ -0,0 +1,14 @@
+var
+ assign = require('lodash.assign')
+;
+
+var Secret = module.exports = function Secret(data)
+{
+ assign(this, data);
+};
+
+Secret.prototype.lease_id = null;
+Secret.prototype.renewable = null;
+Secret.prototype.lease_duration = false;
+Secret.prototype.auth = null;
+Secret.prototype.data = null;
diff --git a/pool/shard000/JavaScript/0002688_profiles.js b/pool/shard000/JavaScript/0002688_profiles.js
new file mode 100644
index 0000000000000000000000000000000000000000..0ee0271688ca6876f35a7bac8ffe989c1bab484c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002688_profiles.js
@@ -0,0 +1,29 @@
+var profiles = [{
+ id: 1,
+ name: 'Denise',
+ phone: '+54 11 7894-1591',
+ gender: 'm',
+ locationId: 6
+}, {
+ id: 2,
+ name: 'Jessica',
+ phone: '+54 11 9879-4564',
+ gender: 'f',
+ locationId: 5
+}, {
+ id: 3,
+ name: 'Tatiana',
+ phone: '+54 11 1234-4789',
+ gender: 't',
+ locationId: 4
+}].map(profile => {
+ profile.avatar = '/assets/profiles/:id/avatar.png'.replace(':id', profile.id)
+ return profile
+})
+
+for (var i = 0; i < 4; i++) {
+ profiles.map(p => {
+ profiles.push(p)
+ })
+}
+module.exports = profiles
diff --git a/pool/shard000/JavaScript/0002692_js_basics.js b/pool/shard000/JavaScript/0002692_js_basics.js
new file mode 100644
index 0000000000000000000000000000000000000000..6e8ca14969c849c903de3ef320b65c3c5813b71c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002692_js_basics.js
@@ -0,0 +1,50 @@
+//Write a function called squareNumber
+function squareNumber(squnum) {
+ var squaredNumber = squnum * squnum;
+ //console output
+ console.log('The result of squaring the number ' + squnum + ' is ' + squaredNumber +".");
+
+ //user output
+ document.write("The result of squaring the number " + squnum + " is " + squaredNumber + ". ");
+return squaredNumber;
+}
+//Write a function called halfNumber
+function halfOf(halfnum) {
+ var half = halfnum / 2;
+ //console output
+ console.log('Half of ' + halfnum + ' is ' + half +".");
+
+ //user output
+ document.write("Half of " + halfnum + " is " + half + ". ");
+ return half;
+}
+//Write a function called percentOf, round numbers to 2 decimals
+function percentOf(num1, num2) {
+ var percent = Math.round((num1/num2) * 100) ;
+ //console output
+ console.log(num1 + ' is ' + percent + '% of ' + num2 +".");
+
+ //user output
+ document.write(num1 + " is " + percent + "% of " + num2 + ". ");
+ return percent;
+}
+//Write a function called areaOfCircle, round numbers to 2 decimals
+function areaOfCircle(radius) {
+ var area = Math.round(Math.PI * radius*radius *100) /100;
+ //console output
+ console.log('The area of circle with radius ' + radius + ' is ' + area +".");
+
+ //user output
+ document.write("The area of circle with radius " + radius + " is " + area + ". ");
+ return area;
+
+}
+//console
+console.log("All functions ");
+
+function all(num) {
+halfOf(num);
+ squareNumber(num);
+ areaOfCircle(num);
+ percentOf(num, num);
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002695_shows.client.controller.js b/pool/shard000/JavaScript/0002695_shows.client.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..15472c4778d3d6a0148f1069b91bfc3dd07a1315
--- /dev/null
+++ b/pool/shard000/JavaScript/0002695_shows.client.controller.js
@@ -0,0 +1,113 @@
+'use strict';
+
+// Shows controller
+angular.module('shows').controller('ShowsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Shows',
+ function ($scope, $stateParams, $location, Authentication, Shows) {
+ $scope.authentication = Authentication;
+
+ // Create new Show
+ $scope.create = function (isValid) {
+ $scope.error = null;
+
+ if (!isValid) {
+ $scope.$broadcast('show-errors-check-validity', 'showForm');
+
+ return false;
+ }
+
+ // Create new Show object
+ var show = new Shows({
+ title: this.title,
+ profileImageURL: this.profileImageURL,
+ mixcloud: this.mixcloud,
+ categories: this.categories,
+ description: this.description,
+ hostID: this.hostID,
+ programID: this.programID,
+ dateTime: this.dateTime,
+ length: this.length
+ });
+
+ // Redirect after save
+ show.$save(function (response) {
+
+ $location.path('shows/' + response._id);
+
+ // Clear form fields
+ $scope.title = '';
+ $scope.profileImageURL = '';
+ $scope.mixcloud = '';
+ $scope.categories = [];
+ $scope.description = {};
+ $scope.hostID = {};
+ $scope.programID = '';
+ $scope.dateTime = '';
+ $scope.length = '';
+
+ }, function (errorResponse) {
+ $scope.error = errorResponse.data.message;
+ });
+ };
+
+ // Remove existing Show
+ $scope.remove = function (show) {
+ if (show) {
+ show.$remove();
+
+ for (var i in $scope.shows) {
+ if ($scope.shows[i] === show) {
+ $scope.shows.splice(i, 1);
+ }
+ }
+ } else {
+ $scope.show.$remove(function () {
+ $location.path('shows');
+ });
+ }
+ };
+
+ // Update existing Show
+ $scope.update = function (isValid) {
+ $scope.error = null;
+
+ if (!isValid) {
+ $scope.$broadcast('show-errors-check-validity', 'showForm');
+
+ return false;
+ }
+
+ var show = $scope.show;
+
+ show.$update(function () {
+
+ $location.path('shows/' + show._id);
+
+ // Clear form fields
+ $scope.title = '';
+ $scope.profileImageURL = '';
+ $scope.mixcloud = '';
+ $scope.categories = [];
+ $scope.description = {};
+ $scope.hostID = {};
+ $scope.programID = '';
+ $scope.dateTime = '';
+ $scope.length = '';
+
+ }, function (errorResponse) {
+ $scope.error = errorResponse.data.message;
+ });
+ };
+
+ // Find a list of Shows
+ $scope.find = function () {
+ $scope.shows = Shows.query();
+ };
+
+ // Find existing Show
+ $scope.findOne = function () {
+ $scope.show = Shows.get({
+ showId: $stateParams.showId
+ });
+ };
+ }
+]);
diff --git a/pool/shard000/JavaScript/0002698_legendChart.test.js b/pool/shard000/JavaScript/0002698_legendChart.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..cbaeba2da9995e00bfc7a35ebb77b51d2288f075
--- /dev/null
+++ b/pool/shard000/JavaScript/0002698_legendChart.test.js
@@ -0,0 +1,159 @@
+import legendData from './legendChart.fixtures';
+import legendChart from './legendChart';
+
+describe('legend Chart', () => {
+ let anchor;
+
+ beforeEach(() => {
+ anchor = document.createElement('div');
+ });
+
+ describe('create', () => {
+
+ describe('when incorrect arguments are used', () => {
+
+ describe('when the DOM element is not passed', () => {
+ it('should throw an error', () => {
+ expect(() => {
+ legendChart.create(
+ undefined,
+ legendData.with6Points(),
+ {}
+ );
+ }).toThrow('A root container is required');
+ });
+ });
+
+ describe('when a non-supported method is passed', () => {
+ it('should throw an error', () => {
+ expect(() => {
+ legendChart.create(
+ anchor,
+ legendData.with6Points(),
+ { test: 'test' }
+ );
+ }).toThrow('Method not supported by Britechart: test');
+ });
+ });
+ });
+
+ describe('when proper arguments are passed', () => {
+
+ it('should set data as a DOM property', () => {
+ const expected = legendData.with6Points().length;
+
+ legendChart.create(anchor, legendData.with6Points());
+
+ const actual = anchor.__data__.length;
+
+ expect(actual).toEqual(expected);
+ });
+
+ it('should set the width', () => {
+ const expected = 500;
+
+ const chart = legendChart.create(
+ anchor,
+ legendData.with6Points(),
+ { width: expected }
+ );
+
+ const actual = chart.width();
+
+ expect(actual).toEqual(expected);
+ });
+
+ it('should set the height', () => {
+ const expected = 600;
+
+ const chart = legendChart.create(
+ anchor,
+ legendData.with6Points(),
+ { height: expected }
+ );
+
+ const actual = chart.height();
+
+ expect(actual).toEqual(expected);
+ });
+
+ it('should set the margin', () => {
+ const expected = {
+ top: 0,
+ bottom: 1,
+ left: 2,
+ right: 3,
+ };
+
+ const chart = legendChart.create(
+ anchor,
+ legendData.with6Points(),
+ { margin: expected }
+ );
+
+ const actual = chart.margin();
+
+ expect(actual).toEqual(expected);
+ });
+ });
+ });
+
+ describe('update', () => {
+
+ describe('when updating data', () => {
+
+ describe('when new data is passed', () => {
+ it('should update the data in the container', () => {
+ const firstDataSet = legendData.with6Points();
+ const secondDataSet = legendData.with6Points();
+
+ const chart = legendChart.create(anchor, firstDataSet, {});
+
+ legendChart.update(anchor, secondDataSet, {}, chart);
+
+ const expected = secondDataSet.length;
+ const actual = anchor.__data__.length;
+
+ expect(actual).toEqual(expected);
+ });
+ });
+
+ describe('when new data is not passed', () => {
+ it('should keep the data in the container', () => {
+ const dataSet = legendData.with6Points();
+
+ const chart = legendChart.create(anchor, dataSet, {});
+
+ legendChart.update(anchor, [], {}, chart);
+
+ const expected = dataSet.length;
+ const actual = anchor.__data__.length;
+
+ expect(actual).toEqual(expected);
+ });
+ });
+ });
+
+ describe('when updating configuration', () => {
+
+ describe('when new configuration is passed', () => {
+ it('should update the configuration in the chart', () => {
+ const expected = 500;
+ const firstWidth = 200;
+ const chart = legendChart.create(
+ anchor,
+ legendData.with6Points(),
+ { width: firstWidth }
+ );
+
+ legendChart.update(anchor, [], { width: expected }, chart);
+
+ const actual = chart.width();
+
+ expect(actual).toEqual(expected);
+ });
+ });
+ });
+ });
+});
+
diff --git a/pool/shard000/JavaScript/0002699_HeroIcon.js b/pool/shard000/JavaScript/0002699_HeroIcon.js
new file mode 100644
index 0000000000000000000000000000000000000000..556ee3e67d83c917199a41f07d58fecf477b8da4
--- /dev/null
+++ b/pool/shard000/JavaScript/0002699_HeroIcon.js
@@ -0,0 +1,158 @@
+/*eslint max-len: ["error", { "code": 800 }]*/
+
+import React from 'react';
+import {
+ View,
+ asset,
+ VrButton,
+ NativeModules,
+ StyleSheet
+} from 'react-360';
+import { ImageBackground } from 'react-native';
+import { connect } from 'react-redux';
+import LoadingBar from './../LoadingBar/LoadingBar';
+import { fetchHeroHover, fetchLoadingContent } from './../../../actions';
+
+class HeroIcon extends React.Component {
+
+ componentDidUpdate() {
+ const { webMode, heroHover, fetchLoadingContent, iconName } = this.props;
+ if (webMode === 'mobile-webvr') {
+ if (heroHover === iconName) fetchLoadingContent(heroHover);
+ else if (heroHover === '') fetchLoadingContent('');
+ }
+ }
+
+ iconStyle() {
+ if (this.props.iconName === 'centerLeftIcon') return styles.leftIcon;
+ return styles.rightIcon;
+ }
+
+ iconHoverStyle() {
+ if (this.props.iconName === 'centerLeftIcon') return styles.leftIconHover;
+ return styles.rightIconHover;
+ }
+
+ iconHitBoxStyle() {
+ if (this.props.iconName === 'centerLeftIcon') return styles.leftIconHitBox;
+ return styles.rightIconHitBox;
+ }
+
+ iconImgStyle() {
+ if (this.props.iconName === 'centerLeftIcon') return styles.leftIconImage;
+ return styles.rightIconImage;
+ }
+
+ modeCheck(webMode) {
+ if (webMode === 'web' || webMode === 'webvr') this.openLink();
+ }
+
+ openLink() {
+ const { iconUrl } = this.props;
+ NativeModules.LinkingManager.openURL(iconUrl);
+ }
+
+ setLeftMargin() {
+ if (this.props.heroHover === 'centerRightIcon') return -50;
+ return -55;
+ }
+
+ render() {
+ const { heroHover, iconName, iconUrl, webMode } = this.props;
+ return (
+
+
+
+
+
+ this.props.fetchHeroHover(iconName)}
+ onExit={() => this.props.fetchHeroHover('')}
+ onClick={() => this.modeCheck(webMode)}
+ style={this.iconHitBoxStyle()}
+ />
+
+ );
+ }
+}
+
+const mapStateToProps = ({ heroHover, webMode }) => ({ heroHover, webMode });
+
+export default connect(mapStateToProps, { fetchHeroHover, fetchLoadingContent })(HeroIcon);
+
+const styles = StyleSheet.create({
+ leftIcon: {
+ width: 100,
+ height: 100,
+ backgroundColor: '#7d7d7d',
+ position: 'absolute',
+ marginTop: 110,
+ marginLeft: 60,
+ borderRadius: 100 / 2
+ },
+ leftIconHover: {
+ width: 100,
+ height: 100,
+ backgroundColor: '#269a18',
+ position: 'absolute',
+ marginTop: 110,
+ borderRadius: 100 / 2,
+ },
+ leftIconHitBox: {
+ width: 150,
+ height: 150,
+ marginLeft: 35,
+ // backgroundColor: '#ff0006',
+ marginTop: 90,
+ position: 'absolute',
+ borderRadius: 150 / 2
+ },
+ leftIconImage: {
+ height: 33,
+ width: 70,
+ marginTop: 33,
+ marginLeft: '15%'
+ },
+ rightIcon: {
+ width: 100,
+ height: 100,
+ backgroundColor: '#7d7d7d',
+ position: 'absolute',
+ marginTop: 110,
+ marginLeft: 538,
+ borderRadius: 100 / 2,
+ },
+ rightIconHover: {
+ width: 100,
+ height: 100,
+ backgroundColor: '#e3bb2a',
+ position: 'absolute',
+ marginTop: 110,
+ borderRadius: 100 / 2
+ },
+ rightIconImage: {
+ width: 70,
+ height: 33,
+ marginTop: 33,
+ marginLeft: '15%'
+ },
+ rightIconHitBox: {
+ width: 150,
+ height: 150,
+ // backgroundColor: '#ff0006',
+ marginTop: 90,
+ position: 'absolute',
+ borderRadius: 150 / 2,
+ marginLeft: 515
+ }
+});
diff --git a/pool/shard000/JavaScript/0002701_mock-module.test.js b/pool/shard000/JavaScript/0002701_mock-module.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..f033b2573258368b28c310925903904aef0fbf1e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002701_mock-module.test.js
@@ -0,0 +1,83 @@
+suite("mock module", function () {
+ "use strict";
+
+ var assert = require("assert");
+ var MockModule = require("./mock-module");
+
+ test("tear does not fail when nothing mocked", function () {
+ var safe = MockModule.create();
+ safe.teardown();
+ });
+
+ test("replaces module property with noop", function () {
+ var Module = {
+ f: function () {
+ assert(false);
+ }
+ };
+
+ var safe = MockModule.create();
+ safe.mock(Module, "f");
+
+ Module.f();
+ });
+
+ test("replaces module property with mock", function (done) {
+ var Module = {
+ f: function () {
+ assert(false);
+ }
+ };
+
+ var safe = MockModule.create();
+ safe.mock(Module, "f", done);
+
+ Module.f();
+ });
+
+ test("restores module", function (done) {
+ var Module = {f: done};
+ var safe = MockModule.create();
+
+ safe.mock(Module, "f", function () {
+ assert(false);
+ });
+
+ safe.teardown();
+ Module.f();
+ });
+
+ test("uses latest mock", function (done) {
+ var Module = {
+ f: function () {
+ assert(false);
+ }
+ };
+
+ var safe = MockModule.create();
+
+ safe.mock(Module, "f", function () {
+ assert(false);
+ });
+
+ safe.mock(Module, "f", done);
+
+ Module.f();
+ });
+
+ test("restores module after multiple mocks", function (done) {
+ var Module = {f: done};
+ var safe = MockModule.create();
+
+ safe.mock(Module, "f", function () {
+ assert(false);
+ });
+
+ safe.mock(Module, "f", function () {
+ assert(false);
+ });
+
+ safe.teardown();
+ Module.f();
+ });
+});
diff --git a/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js b/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js
new file mode 100644
index 0000000000000000000000000000000000000000..8d4b7d4702a54386e70c0a368e4c7ed856443c61
--- /dev/null
+++ b/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js
@@ -0,0 +1,54 @@
+if (this.importScripts) {
+ importScripts('../../../resources/js-test.js');
+ importScripts('shared.js');
+}
+
+description("Test that an abort in the initial upgradeneeded sets version back to 0");
+
+function test()
+{
+ setDBNameFromPath();
+
+ request = evalAndLog("indexedDB.deleteDatabase(dbname)");
+ request.onsuccess = deleteSuccess;
+ request.onerror = unexpectedErrorCallback;
+}
+
+function deleteSuccess() {
+ request = evalAndLog("indexedDB.open(dbname, 2)");
+ request.onsuccess = unexpectedSuccessCallback;
+ evalAndLog("request.onupgradeneeded = upgradeNeeded");
+ evalAndLog("request.onerror = onError");
+ request.onblocked = unexpectedBlockedCallback;
+}
+
+function upgradeNeeded(evt)
+{
+ preamble(evt);
+ db = event.target.result;
+ shouldBe("db.version", "2");
+ transaction = event.target.transaction;
+ transaction.oncomplete = unexpectedCompleteCallback;
+ transaction.onabort = onAbort;
+ evalAndLog("transaction.abort()");
+}
+
+function onAbort(evt)
+{
+ preamble(evt);
+ shouldBe("event.target.db.version", "0");
+ shouldBeNonNull("request.transaction");
+}
+
+function onError(evt)
+{
+ preamble(evt);
+ shouldBe("request", "event.target");
+ shouldBeUndefined("event.target.result");
+ shouldBeNonNull("event.target.error");
+ shouldBeEqualToString("event.target.error.name", "AbortError");
+ shouldBeNull("request.transaction");
+ finishJSTest();
+}
+
+test();
diff --git a/pool/shard000/JavaScript/0002703_roles.test.js b/pool/shard000/JavaScript/0002703_roles.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..f5965914f34c242d9f0f790c741c9697c36ac3d9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002703_roles.test.js
@@ -0,0 +1,151 @@
+import supertest from 'supertest';
+import chai from 'chai';
+import app from '../../../server';
+import { Role } from '../../models';
+import helper from '../test-helper';
+
+const request = supertest.agent(app);
+const expect = chai.expect;
+
+const userParams = helper.firstUser;
+
+let role, token;
+
+describe('Roles API', () => {
+ before((done) => {
+ Role.create(helper.adminRole)
+ .then((newRole) => {
+ userParams.roleId = newRole.id;
+ request.post('/users')
+ .send(userParams)
+ .end((err, res) => {
+ token = res.body.token;
+ done();
+ });
+ });
+ });
+
+ after(() => Role.sequelize.sync({ force: true }));
+
+ describe('CONTEXT: With existing role', () => {
+ beforeEach(() =>
+ Role.create(helper.regularRole)
+ .then((newRole) => {
+ role = newRole;
+ }));
+
+ afterEach(() => Role.destroy({ where: { id: role.id } }));
+
+ describe('Get all GET: /roles', () => {
+ it('should return unauthorised for no token', (done) => {
+ request.get('/roles')
+ .end((err, res) => {
+ expect(res.status).to.equal(401);
+ done();
+ });
+ });
+
+ it('should return all roles', (done) => {
+ request.get('/roles')
+ .set({ Authorization: token })
+ .end((err, res) => {
+ expect(res.status).to.equal(200);
+ expect(Array.isArray(res.body)).to.be.true;
+ expect(res.body.length).to.not.equal(0);
+ done();
+ });
+ });
+ });
+
+ describe('Get role GET: /roles/:id', () => {
+ it('should get correct role', (done) => {
+ request.get(`/roles/${role.id}`)
+ .set({ Authorization: token })
+ .end((err, res) => {
+ expect(res.status).to.equal(200);
+ expect(res.body.title).to.equal(role.title);
+ done();
+ });
+ });
+
+ it('should return NOT FOUND for invalid id', (done) => {
+ request.get('/roles/100')
+ .set({ Authorization: token })
+ .expect(404, done);
+ });
+ });
+
+ describe('Edit role PUT: /roles/:id', () => {
+ it('updates the role attributes', (done) => {
+ const newAttributes = { title: 'role' };
+
+ request.put(`/roles/${role.id}`)
+ .set({ Authorization: token })
+ .send(newAttributes)
+ .end((err, res) => {
+ expect(res.status).to.equal(200);
+ expect(res.body.title).to.equal(newAttributes.title);
+ done();
+ });
+ });
+
+ it('should return NOT FOUND for invalid id', (done) => {
+ request.put('/roles/100')
+ .set({ Authorization: token })
+ .expect(404, done);
+ });
+ });
+
+ describe('Delete role DELETE: /roles/:id', () => {
+ it('deletes the role', (done) => {
+ request.delete(`/roles/${role.id}`)
+ .set({ Authorization: token })
+ .end((err, res) => {
+ expect(res.status).to.equal(200);
+ Role.count().then((count) => {
+ expect(count).to.equal(1);
+ done();
+ });
+ });
+ });
+
+ it('should return NOT FOUND for invalid id', (done) => {
+ request.delete('/roles/100')
+ .set({ Authorization: token })
+ .expect(404, done);
+ });
+ });
+ });
+
+ describe('CONTEXT: without existing role', () => {
+ afterEach(() => Role.sequelize.sync({ force: true }));
+
+ describe('Create role POST: /roles', () => {
+ it('creates a new role', (done) => {
+ request.post('/roles')
+ .set({ Authorization: token })
+ .send({ title: 'authors' })
+ .end((err, res) => {
+ expect(res.status).to.equal(201);
+ expect(res.body.title).to.equal('authors');
+ done();
+ });
+ });
+
+ it('fails if user is not an admin', (done) => {
+ Role.create(helper.regularRole)
+ .then((newRole) => {
+ helper.secondUser.roleId = newRole.id;
+ request.post('/users')
+ .send(helper.secondUser)
+ .end((err, res) => {
+ request.post('/roles')
+ .set({ Authorization: res.body.token })
+ .send({ title: 'other' })
+ .expect(403, done);
+ });
+ });
+ });
+ });
+ });
+});
diff --git a/pool/shard000/JavaScript/0002706_musicBox.js b/pool/shard000/JavaScript/0002706_musicBox.js
new file mode 100644
index 0000000000000000000000000000000000000000..871d0b3023986bce3cfc2ff93ed52ba0144d395c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002706_musicBox.js
@@ -0,0 +1,105 @@
+import api from '../../axios'
+import wyApi from '../../wyApi'
+const state = {
+ show: false,
+ el: '',
+ url:'',
+ musicData: '',
+ autoPlay: true,
+ playlist: false,
+ songlist:[]
+}
+const mutations = {
+ deletePlaylist(state, payload) {
+ if (payload != undefined) {
+ if (state.playlist.length == 1) {
+ state.playlist = false
+ localStorage.removeItem('playlist')
+ } else {
+ state.playlist.splice(payload, 1)
+ localStorage.setItem('playlist', JSON.stringify(state.playlist))
+ }
+ } else {
+ state.playlist = false
+ localStorage.removeItem('playlist')
+ }
+ },
+ loadPlaylist(state, payload) {
+ state.playlist = payload
+ },
+ addPlaylist(state,payload) {
+ if (state.playlist) {
+ let addFlag = true
+ state.playlist.forEach((item) => {
+ if (item.music.wyID == payload.music.wyID) {
+ addFlag = false
+ }
+ })
+ if (addFlag) {
+ state.playlist.push(payload)
+ localStorage.setItem('playlist', JSON.stringify(state.playlist))
+ }
+ } else {
+ state.playlist = []
+ state.playlist.push(payload)
+ }
+ },
+ playMusic(state, payload) {
+ state.musicData = payload
+ state.onPlay = false
+ state.currTime = 0
+ state.totalTime = 0
+ state.playProgress = 0
+ if (payload.hasOwnProperty('local')) {
+ state.autoPlay = false
+ } else {
+ state.autoPlay = true
+ if (state.playlist) {
+ let addFlag = true
+ state.playlist.forEach((item) => {
+ if (item.music.wyID == payload.music.wyID) {
+ addFlag = false
+ }
+ })
+ if (addFlag) {
+ state.playlist.push(payload)
+ }
+ } else {
+ state.playlist = []
+ state.playlist.push(payload)
+ }
+ }
+ localStorage.setItem('playlist', JSON.stringify(state.playlist))
+ localStorage.setItem('musicData', JSON.stringify(payload))
+ state.show = true
+ },
+ setEl(state, payload) {
+ state.el = payload
+ },
+ hideMusicBox(state) {
+ state.show = false
+ }
+}
+
+const actions = {
+ playMusic({
+ commit
+ }, payload) {
+ // if(payload.url){
+ // commit('playMusic', payload)
+ // }else{
+ return wyApi.getMusicUrl(payload.music.wyID).then((result) => {
+ if (result.code == 200) {
+ payload.url = result.data[0].url
+ commit('playMusic', payload)
+ }
+ })
+ // }
+ }
+}
+
+export default {
+ state,
+ mutations,
+ actions
+}
diff --git a/pool/shard000/JavaScript/0002707_InputLabel.js b/pool/shard000/JavaScript/0002707_InputLabel.js
new file mode 100644
index 0000000000000000000000000000000000000000..71231ba2b2cb924fb6cb375a7cac031393a47016
--- /dev/null
+++ b/pool/shard000/JavaScript/0002707_InputLabel.js
@@ -0,0 +1,229 @@
+"use strict";
+
+var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
+
+var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.default = void 0;
+
+var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
+
+var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
+
+var React = _interopRequireWildcard(require("react"));
+
+var _propTypes = _interopRequireDefault(require("prop-types"));
+
+var _unstyled = require("@material-ui/unstyled");
+
+var _formControlState = _interopRequireDefault(require("../FormControl/formControlState"));
+
+var _useFormControl = _interopRequireDefault(require("../FormControl/useFormControl"));
+
+var _FormLabel = _interopRequireWildcard(require("../FormLabel"));
+
+var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
+
+var _experimentalStyled = _interopRequireWildcard(require("../styles/experimentalStyled"));
+
+var _inputLabelClasses = require("./inputLabelClasses");
+
+var _jsxRuntime = require("react/jsx-runtime");
+
+const useUtilityClasses = styleProps => {
+ const {
+ classes,
+ formControl,
+ size,
+ shrink,
+ disableAnimation,
+ variant
+ } = styleProps;
+ const slots = {
+ root: ['root', formControl && 'formControl', !disableAnimation && 'animated', shrink && 'shrink', size === 'small' && 'sizeSmall', variant]
+ };
+ const composedClasses = (0, _unstyled.unstable_composeClasses)(slots, _inputLabelClasses.getInputLabelUtilityClasses, classes);
+ return (0, _extends2.default)({}, classes, composedClasses);
+};
+
+const InputLabelRoot = (0, _experimentalStyled.default)(_FormLabel.default, {
+ shouldForwardProp: prop => (0, _experimentalStyled.rootShouldForwardProp)(prop) || prop === 'classes',
+ name: 'MuiInputLabel',
+ slot: 'Root',
+ overridesResolver: (props, styles) => {
+ const {
+ styleProps
+ } = props;
+ return (0, _extends2.default)({
+ [`& .${_FormLabel.formLabelClasses.asterisk}`]: styles.asterisk
+ }, styles.root, !styleProps.formControl && styles.formControl, styleProps.size === 'small' && styles.sizeSmall, styleProps.shrink && styles.shrink, !styleProps.disableAnimation && styles.animated, styles[styleProps.variant]);
+ }
+})(({
+ theme,
+ styleProps
+}) => (0, _extends2.default)({
+ display: 'block',
+ transformOrigin: 'top left',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ maxWidth: '100%'
+}, styleProps.formControl && {
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ // slight alteration to spec spacing to match visual spec result
+ transform: 'translate(0, 20px) scale(1)'
+}, styleProps.size === 'small' && {
+ // Compensation for the `Input.inputSizeSmall` style.
+ transform: 'translate(0, 17px) scale(1)'
+}, styleProps.shrink && {
+ transform: 'translate(0, -1.5px) scale(0.75)',
+ transformOrigin: 'top left',
+ maxWidth: '133%'
+}, !styleProps.disableAnimation && {
+ transition: theme.transitions.create(['color', 'transform', 'max-width'], {
+ duration: theme.transitions.duration.shorter,
+ easing: theme.transitions.easing.easeOut
+ })
+}, styleProps.variant === 'filled' && (0, _extends2.default)({
+ // Chrome's autofill feature gives the input field a yellow background.
+ // Since the input field is behind the label in the HTML tree,
+ // the input field is drawn last and hides the label with an opaque background color.
+ // zIndex: 1 will raise the label above opaque background-colors of input.
+ zIndex: 1,
+ pointerEvents: 'none',
+ transform: 'translate(12px, 16px) scale(1)',
+ maxWidth: 'calc(100% - 24px)'
+}, styleProps.size === 'small' && {
+ transform: 'translate(12px, 13px) scale(1)'
+}, styleProps.shrink && (0, _extends2.default)({
+ transform: 'translate(12px, 7px) scale(0.75)',
+ maxWidth: 'calc(133% - 24px)'
+}, styleProps.size === 'small' && {
+ transform: 'translate(12px, 4px) scale(0.75)'
+})), styleProps.variant === 'outlined' && (0, _extends2.default)({
+ // see comment above on filled.zIndex
+ zIndex: 1,
+ pointerEvents: 'none',
+ transform: 'translate(14px, 16px) scale(1)',
+ maxWidth: 'calc(100% - 24px)'
+}, styleProps.size === 'small' && {
+ transform: 'translate(14px, 9px) scale(1)'
+}, styleProps.shrink && {
+ maxWidth: 'calc(133% - 24px)',
+ transform: 'translate(14px, -9px) scale(0.75)'
+})));
+const InputLabel = /*#__PURE__*/React.forwardRef(function InputLabel(inProps, ref) {
+ const props = (0, _useThemeProps.default)({
+ name: 'MuiInputLabel',
+ props: inProps
+ });
+ const {
+ disableAnimation = false,
+ shrink: shrinkProp
+ } = props,
+ other = (0, _objectWithoutPropertiesLoose2.default)(props, ["disableAnimation", "margin", "shrink", "variant"]);
+ const muiFormControl = (0, _useFormControl.default)();
+ let shrink = shrinkProp;
+
+ if (typeof shrink === 'undefined' && muiFormControl) {
+ shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart;
+ }
+
+ const fcs = (0, _formControlState.default)({
+ props,
+ muiFormControl,
+ states: ['size', 'variant']
+ });
+ const styleProps = (0, _extends2.default)({}, props, {
+ disableAnimation,
+ formControl: muiFormControl,
+ shrink,
+ size: fcs.size,
+ variant: fcs.variant
+ });
+ const classes = useUtilityClasses(styleProps);
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(InputLabelRoot, (0, _extends2.default)({
+ "data-shrink": shrink,
+ styleProps: styleProps,
+ ref: ref
+ }, other, {
+ classes: classes
+ }));
+});
+process.env.NODE_ENV !== "production" ? InputLabel.propTypes
+/* remove-proptypes */
+= {
+ // ----------------------------- Warning --------------------------------
+ // | These PropTypes are generated from the TypeScript type definitions |
+ // | To update them edit the d.ts file and run "yarn proptypes" |
+ // ----------------------------------------------------------------------
+
+ /**
+ * The content of the component.
+ */
+ children: _propTypes.default.node,
+
+ /**
+ * Override or extend the styles applied to the component.
+ */
+ classes: _propTypes.default.object,
+
+ /**
+ * The color of the component. It supports those theme colors that make sense for this component.
+ */
+ color: _propTypes.default.oneOf(['primary', 'secondary']),
+
+ /**
+ * If `true`, the transition animation is disabled.
+ * @default false
+ */
+ disableAnimation: _propTypes.default.bool,
+
+ /**
+ * If `true`, the component is disabled.
+ */
+ disabled: _propTypes.default.bool,
+
+ /**
+ * If `true`, the label is displayed in an error state.
+ */
+ error: _propTypes.default.bool,
+
+ /**
+ * If `true`, the `input` of this label is focused.
+ */
+ focused: _propTypes.default.bool,
+
+ /**
+ * If `dense`, will adjust vertical spacing. This is normally obtained via context from
+ * FormControl.
+ */
+ margin: _propTypes.default.oneOf(['dense']),
+
+ /**
+ * if `true`, the label will indicate that the `input` is required.
+ */
+ required: _propTypes.default.bool,
+
+ /**
+ * If `true`, the label is shrunk.
+ */
+ shrink: _propTypes.default.bool,
+
+ /**
+ * The system prop that allows defining system overrides as well as additional CSS styles.
+ */
+ sx: _propTypes.default.object,
+
+ /**
+ * The variant to use.
+ */
+ variant: _propTypes.default.oneOf(['filled', 'outlined', 'standard'])
+} : void 0;
+var _default = InputLabel;
+exports.default = _default;
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002710_connectFunctions.js b/pool/shard000/JavaScript/0002710_connectFunctions.js
new file mode 100644
index 0000000000000000000000000000000000000000..8769053e8c40b4973f5b1fa7b83c6f8e786d9876
--- /dev/null
+++ b/pool/shard000/JavaScript/0002710_connectFunctions.js
@@ -0,0 +1,36 @@
+(function(){var __modFun = function(__require, promiseland){ __modFun = undefined;
+
+if (promiseland._hasModule({ hashStr: "68b329da9893e34099c7d8ad5cb9c940" })){ return promiseland._getModule("68b329da9893e34099c7d8ad5cb9c940"); };
+var PL$1 = (function(){
+"use strict";
+
+ ;
+ ;})();
+;return PL$1;
+};
+
+ if (typeof exports == "object" && typeof module == "object"){ // CommonJS
+ module.exports = __modFun(function(modulesAr, callback, errBack){
+ // the require function for CommonJs
+ var args = [];
+ try{
+ var i = 0;
+ var l = modulesAr.length;
+ for (i; i < l; ++i){
+ args.push(require(modulesAr[i]));
+ };
+ }catch(e){
+ errBack(e);
+ return;
+ };
+ callback.apply(callback, args);
+ }, require("promiseland"));
+
+ }else if (typeof define == "function" && define.amd){ // AMD
+ define(["require", "promiseland"], __modFun);
+
+ }else{ // Plain browser env
+ __modFun(function(){ throw { msg: "require not possible in non loader mode" }; });
+
+ };
+})();
diff --git a/pool/shard000/JavaScript/0002712_threejsboilerplate.js b/pool/shard000/JavaScript/0002712_threejsboilerplate.js
new file mode 100644
index 0000000000000000000000000000000000000000..b3fc9c7a37cd51fcc648ec648dbc6b958f36dc59
--- /dev/null
+++ b/pool/shard000/JavaScript/0002712_threejsboilerplate.js
@@ -0,0 +1,15 @@
+var express = require('express');
+var chalk = require('chalk');
+var fs = require('fs');
+var app = express();
+var port = 8080;
+
+app.use(express.static(__dirname + '/public'));
+
+
+app.listen(port);
+console.log("listening port " + port);
+
+app.get('/', function(req, res) {
+ res.sendfile(__dirname + '/public/index.html');
+});
diff --git a/pool/shard000/JavaScript/0002713_store-component.js b/pool/shard000/JavaScript/0002713_store-component.js
new file mode 100644
index 0000000000000000000000000000000000000000..1380a46a2aee2f0567b676693b37137877d767e0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002713_store-component.js
@@ -0,0 +1,63 @@
+'use babel'
+/** @jsx etch.dom */
+
+import etch from 'etch'
+import { CompositeDisposable } from 'atom'
+
+import UiComponent from './component'
+import { shallowEqual } from '../helpers'
+
+export default class UiStoreComponent extends UiComponent {
+ constructor (props, children) {
+ // all props except the "Component" will be passed through to the component
+ props.passThrough = Object.keys(props).filter((key) => key !== 'Component')
+
+ super(props, children)
+ }
+
+ init () {
+ this._subscriptions = new CompositeDisposable(
+ { dispose: this.props.store.subscribe(this.handleStoreChange.bind(this)) }
+ )
+
+ this.updateComponentProps()
+
+ super.init()
+ }
+
+ dispose () {
+ this._subscriptions.dispose()
+ this._subscriptions = null
+
+ super.dispose()
+ }
+
+ render () {
+ const props = {}
+ this.props.passThrough.forEach((key) => { props[key] = this.props[key] })
+ Object.assign(props, this.props.storeProps)
+ return
+ }
+
+ handleStoreChange () {
+ this.updateComponentProps()
+ }
+
+ updateComponentProps () {
+ const storeProps = this.storeToProps(this.props.store.getState())
+ if (this.props.storeProps && shallowEqual(this.props.storeProps, storeProps)) {
+ return
+ }
+ this.update({ storeProps: storeProps })
+ }
+
+ static create (Component, storeToProps) {
+ return class UiContainer extends UiStoreComponent {
+ init () {
+ this.Component = Component
+ this.storeToProps = storeToProps
+ super.init()
+ }
+ }
+ }
+}
diff --git a/pool/shard000/JavaScript/0002719_find-key.js b/pool/shard000/JavaScript/0002719_find-key.js
new file mode 100644
index 0000000000000000000000000000000000000000..682c62c6607dc978f0cfe1908966ec8b4a45835e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002719_find-key.js
@@ -0,0 +1,22 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.default = findKey;
+function findKey(object, predicate) {
+ var resultKey = void 0;
+
+ Object.keys(object).some(function (key) {
+ var isKey = predicate(object[key], key, object);
+
+ if (isKey) {
+ resultKey = key;
+ return true;
+ }
+
+ return false;
+ });
+
+ return resultKey;
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002724_http.js b/pool/shard000/JavaScript/0002724_http.js
new file mode 100644
index 0000000000000000000000000000000000000000..c44c2146380d12c23af89938bd5b0338b331df90
--- /dev/null
+++ b/pool/shard000/JavaScript/0002724_http.js
@@ -0,0 +1,16 @@
+/**
+ * jsonp request.
+ * Copied from http://stackoverflow.com/a/22780569/3408818
+ */
+function jsonp(url, callback) {
+ var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
+ window[callbackName] = function(data) {
+ delete window[callbackName];
+ document.body.removeChild(script);
+ callback(data);
+ };
+
+ var script = document.createElement('script');
+ script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
+ document.body.appendChild(script);
+}
diff --git a/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js b/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..d7ffa769ef1a7904dc8fe5eb004f46dcbd0fa7fa
--- /dev/null
+++ b/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js
@@ -0,0 +1,95 @@
+/* globals $ */
+(function() {
+ 'use strict';
+
+ angular
+ .module('helloJhipsterApp')
+ .directive('passwordStrengthBar', passwordStrengthBar);
+
+ function passwordStrengthBar () {
+ var directive = {
+ replace: true,
+ restrict: 'E',
+ template: '' +
+ '
Password strength: ' +
+ '
' +
+ '
',
+ scope: {
+ passwordToCheck: '='
+ },
+ link: linkFunc
+ };
+
+ return directive;
+
+ /* private helper methods*/
+
+ function linkFunc(scope, iElement) {
+ var strength = {
+ colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'],
+ mesureStrength: function (p) {
+
+ var _force = 0;
+ var _regex = /[$-/:-?{-~!"^_`\[\]]/g; // "
+
+ var _lowerLetters = /[a-z]+/.test(p);
+ var _upperLetters = /[A-Z]+/.test(p);
+ var _numbers = /[0-9]+/.test(p);
+ var _symbols = _regex.test(p);
+
+ var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols];
+ var _passedMatches = $.grep(_flags, function (el) {
+ return el === true;
+ }).length;
+
+ _force += 2 * p.length + ((p.length >= 10) ? 1 : 0);
+ _force += _passedMatches * 10;
+
+ // penalty (short password)
+ _force = (p.length <= 6) ? Math.min(_force, 10) : _force;
+
+ // penalty (poor variety of characters)
+ _force = (_passedMatches === 1) ? Math.min(_force, 10) : _force;
+ _force = (_passedMatches === 2) ? Math.min(_force, 20) : _force;
+ _force = (_passedMatches === 3) ? Math.min(_force, 40) : _force;
+
+ return _force;
+
+ },
+ getColor: function (s) {
+
+ var idx;
+ if (s <= 10) {
+ idx = 0;
+ }
+ else if (s <= 20) {
+ idx = 1;
+ }
+ else if (s <= 30) {
+ idx = 2;
+ }
+ else if (s <= 40) {
+ idx = 3;
+ }
+ else {
+ idx = 4;
+ }
+
+ return { idx: idx + 1, col: this.colors[idx] };
+ }
+ };
+ scope.$watch('passwordToCheck', function (password) {
+ if (password) {
+ var c = strength.getColor(strength.mesureStrength(password));
+ iElement.removeClass('ng-hide');
+ iElement.find('ul').children('li')
+ .css({ 'background-color': '#DDD' })
+ .slice(0, c.idx)
+ .css({ 'background-color': c.col });
+ }
+ });
+ }
+ }
+})();
diff --git a/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js b/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..5f07bccfc329fa5972b1e419f63d7e946da4a5d8
--- /dev/null
+++ b/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js
@@ -0,0 +1,53 @@
+describe('Enlightened Warrior', function() {
+ integration(function() {
+ describe('Enlightened Warrior\'s ability', function() {
+ beforeEach(function() {
+ this.setupTest({
+ phase: 'conflict',
+ player1: {
+ inPlay: ['doji-whisperer']
+ },
+ player2: {
+ inPlay: ['enlightened-warrior']
+ }
+ });
+
+ this.dojiWhisperer = this.player1.findCardByName('doji-whisperer');
+ this.enlightenedWarrior = this.player2.findCardByName('enlightened-warrior');
+
+ this.game.rings.water.fate = 1;
+ });
+
+ it('should trigger when your opponent selects a ring with fate on it (during conflict declaration)', function() {
+ this.noMoreActions();
+ this.initiateConflict({
+ attackers: [this.dojiWhisperer],
+ ring: 'water'
+ });
+ expect(this.player2).toHavePrompt('Triggered Abilities');
+ expect(this.player2).toBeAbleToSelect(this.enlightenedWarrior);
+ });
+
+ it('should not trigger when your opponent selects a ring with no fate on it (during conflict declaration)', function() {
+ this.noMoreActions();
+ this.initiateConflict({
+ attackers: [this.dojiWhisperer],
+ ring: 'fire'
+ });
+ expect(this.player2).not.toHavePrompt('Triggered Abilities');
+ expect(this.player2).toHavePrompt('Choose defenders');
+ });
+
+ it('should place 1 fate on Enlightened Warrior', function() {
+ let fate = this.enlightenedWarrior.fate;
+ this.noMoreActions();
+ this.initiateConflict({
+ attackers: [this.dojiWhisperer],
+ ring: 'water'
+ });
+ this.player2.clickCard(this.enlightenedWarrior);
+ expect(this.enlightenedWarrior.fate).toBe(fate + 1);
+ });
+ });
+ });
+});
diff --git a/pool/shard000/JavaScript/0002728_okshadowSpec.js b/pool/shard000/JavaScript/0002728_okshadowSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..df4f3fa0f3516795e24c2073c68ab49a70f79120
--- /dev/null
+++ b/pool/shard000/JavaScript/0002728_okshadowSpec.js
@@ -0,0 +1,61 @@
+ describe('okshadow', function() {
+ var testDiv;
+
+ beforeEach(function(){
+
+ this.addMatchers({
+ toHaveBoxShadow: function() {
+ if (this.actual.css('boxShadow') && this.actual.css('boxShadow') !== 'none') return true;
+ },
+ toHaveTextShadow: function() {
+ if (this.actual.css('text-shadow') && this.actual.css('textShadow') !== 'none') return true;
+ }
+ });
+ });
+
+ describe('with default options', function () {
+ beforeEach(function(){
+ jasmine.getFixtures().set('
');
+ testDiv = $('#test').okshadow();
+ });
+
+ it('adds box-shadow', function () {
+ expect(testDiv).toHaveBoxShadow();
+ });
+
+ });
+
+ describe('allows developers to control options', function() {
+ beforeEach(function(){
+ jasmine.getFixtures().set('');
+ });
+
+ it('text shadow', function() {
+ testDiv = $('#test p').okshadow({
+ textShadow: true
+ });
+ expect(testDiv).toHaveTextShadow();
+ });
+
+
+ it('color', function(){
+ testText = $('#test p').okshadow({
+ color: 'rgb(4,2,0)'
+ });
+ expect(/4, 2, 0/.test(testText.css('box-shadow'))).toBe(true);
+ });
+
+ it('transparency', function(){
+ testText = $('#test p').okshadow({
+ transparent: true
+ });
+
+ expect(/0, 0, 0, 0/.test(testText.css('color'))).toBe(true);
+
+ });
+
+
+
+ });
+
+ });
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002731_app_module.js b/pool/shard000/JavaScript/0002731_app_module.js
new file mode 100644
index 0000000000000000000000000000000000000000..c47556821722f6fb635145cab4437eed24e742c5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002731_app_module.js
@@ -0,0 +1,141 @@
+var app_module = function(){
+ var TimeSlot = function(){
+ this.agenda = null;
+ this.unparsedString = null;
+ }
+
+ TimeSlot.prototype.isDefined = function(){
+ return this.unparsedString!=null && this.unparsedString.trim().length>0;
+ }
+
+ var timeSlotArg = null;
+ var apptDetails = null;
+
+ var redirectWindow = function(path){
+ window.location.replace(path);
+ }
+
+ var openDialog = function(){
+ //this will force creation of new object
+ timeSlotArg = null;
+ $("#listing-add-new").show();
+
+ }
+
+ var onDateTimeChange = function(e){
+ if(timeSlotArg == null){
+ timeSlotArg = new TimeSlot();
+ }
+ timeSlotArg.unparsedString = e.detail.target.value;
+ }
+
+ var onAgendaChange = function(e){
+ if(timeSlotArg == null){
+ timeSlotArg = new TimeSlot();
+ }
+ timeSlotArg.agenda = e.detail.target.value;
+ }
+
+
+ var onSubmit = function(){
+ if(timeSlotArg!=null && timeSlotArg.isDefined()){
+ dataOut = JSON.stringify(timeSlotArg);
+ $.ajax({
+ url: "/group/"+getCurrentGroupId()+"/schedule/new.json",
+ data: {timeslot: dataOut},
+ type: "POST",
+ dataType: "json",
+ success: onSucess,
+ error: onError
+ });
+ }
+ }
+
+ var getCurrentGroupId = function(){
+ // get this as data attribute from the page
+ var id = $("#listing-header").attr("data-group-id");
+ return id;
+ }
+
+ var addAvialability = function(){
+
+ if (!$("#listing-add-new").is(':visible')){
+ $("#add_button").text("Hide Availability Form");
+ openDialog();
+ }else{
+ $("#listing-add-new").hide();
+ $("#add_button").text("Add Your Availabilty");
+ }
+
+
+ }
+
+ var onError = function(response){
+ console.log(response);
+ if (response.error){
+ alert("Your operation HAS FAILED. Error: " + response.error);
+ }else{
+ alert("Your operation HAS FAILED. Contact DBC for help.");
+ }
+
+ }
+
+ var onSucess = function(response){
+ if (response.error){
+ onError(response);
+ }else{
+ if(apptDetails!=null){
+ alert("You have accepted the following appointment:\n" + apptDetails);
+ apptDetails = null;
+ }
+
+ redirectWindow(response.path);
+ }
+
+ }
+
+ var getScheduleIfFromEvent = function(e){
+ var target = $(e.detail.currentTarget).closest(".calendar-listing");
+ return target.attr("data-id");
+ }
+
+ var getDetailsForId = function(id){
+ return $("#calendar-listing-"+id).attr("data-details");
+ }
+
+ //TODO move this into a helper delete/accept module
+ var acceptSchedule = function(e){
+ var id = getScheduleIfFromEvent(e);
+ apptDetails = getDetailsForId(id);
+ $.ajax({
+ url: "/group/"+getCurrentGroupId()+"/schedule/accept.json/" +id,
+ type: "POST",
+ dataType: "json",
+ success: onSucess,
+ error: onError
+ });
+ }
+
+ var deleteSchedule = function(e){
+ var id = getScheduleIfFromEvent(e);
+ $.ajax({
+ url: "/group/"+getCurrentGroupId()+"/schedule/delete.json/" +id,
+ type: "POST",
+ dataType: "json",
+ success: onSucess,
+ error: onError
+ });
+ }
+
+
+ addEventListener("add_button_clicked", addAvialability);
+ addEventListener("accept_schedule_clicked", acceptSchedule);
+ addEventListener("delete_schedule_clicked", deleteSchedule);
+ addEventListener("submit_clicked", onSubmit);
+ addEventListener("datetime_changed", onDateTimeChange);
+ addEventListener("agenda_changed", onAgendaChange);
+ //no public API - event bus architecture
+ return {
+
+ }
+}();
diff --git a/pool/shard000/JavaScript/0002732_common.js b/pool/shard000/JavaScript/0002732_common.js
new file mode 100644
index 0000000000000000000000000000000000000000..d30c4964eb18a4598cc0182055322ff4345c92f0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002732_common.js
@@ -0,0 +1,61 @@
+window.onload = function() {
+ window.scrollTo(0,document.body.scrollHeight);
+};
+
+function docHeight() {
+ var body = document.body.scrollHeight;
+ return body;
+}
+
+function scrollHeight() {
+ var top = document.body.scrollTop;
+ var viewport = window.innerHeight;
+ return top + viewport;
+}
+
+function imageLoad(ev, img) {
+ img.style.display = "none";
+ var scrollBefore = scrollHeight();
+ var heightBefore = docHeight();
+ img.style.display = "initial";
+
+ scroll(scrollBefore, heightBefore, docHeight());
+}
+
+function scroll(scrollBefore, heightBefore, heightAfter) {
+ if(scrollBefore >= heightBefore)
+ { //scroll to bot
+ window.scrollTo(0, heightAfter);
+ }
+}
+
+var n = 0;
+function addPost(post, nick) {
+ var scrollBefore = scrollHeight();
+ var heightBefore = docHeight();
+
+ var elemPost = document.createElement("div");
+ elemPost.className = "app-post"+(n%2);
+ elemPost.innerHTML = post;
+ var images = elemPost.getElementsByTagName("img");
+ for(var i = 0; i < images.length; i++)
+ images[i].onload = function(ev) { imageLoad(ev, this); };
+ document.getElementById("app-contents").appendChild(elemPost);
+
+ scroll(scrollBefore, heightBefore, docHeight());
+
+ n++;
+ onNewPost(elemPost);
+}
+
+function clearPosts(max) {
+ var posts = document.getElementsByClassName("app-post");
+ if(posts.length > max && posts.length > 2) //Minimum post limit
+ { //Clear second post
+ document.getElementById("app-contents").removeChild(posts[1]);
+ //To get this function working, app-post classes MUST be children of
+ //app-contents div. Do not ever put app-contents in another parent
+
+ clearPosts(max);
+ }
+}
diff --git a/pool/shard000/JavaScript/0002733_vat.js b/pool/shard000/JavaScript/0002733_vat.js
new file mode 100644
index 0000000000000000000000000000000000000000..ef84a3d31ed7032993d73a0c0ed6cfc748dcc464
--- /dev/null
+++ b/pool/shard000/JavaScript/0002733_vat.js
@@ -0,0 +1,40 @@
+/**
+ * Created by Daniel Dimmick on 24/03/15.
+ */
+function VAT(successbox,errorbox){
+ this.vatNumber=null;
+ this.message=null;
+
+ var parent = this;
+
+ this.getVatNumber=function(){
+ return this.vatNumber;
+ }
+ this.setVatNumber=function(vatNumber){
+ this.vatNumber=vatNumber;
+ }
+
+ this.save= function (){
+ $.when(this.ajaxCall()).then(function(data){
+ if(data.status=='success'){
+ errorbox.stop().hide();
+ successbox.find('#message').html(data.message);
+ successbox.stop().fadeOut('fast').fadeIn('fast');
+ }
+ else{
+ successbox.stop().hide();
+ errorbox.find('#message').html(data.message);
+ errorbox.stop().fadeOut('fast').fadeIn('fast');
+ }
+ })
+ }
+
+ this.ajaxCall= function(){
+ return $.ajax({
+ url: "/payment/vat/",
+ type: 'post',
+ dataType: 'json',
+ data: {"vatnumber":this.getVatNumber(),'CSRF_SESSION_TOKEN': CSRF_SESSION_TOKEN}
+ });
+ }
+}
diff --git a/pool/shard000/JavaScript/0002735_PrivateMessage.js b/pool/shard000/JavaScript/0002735_PrivateMessage.js
new file mode 100644
index 0000000000000000000000000000000000000000..3006ac4a9b48cb67e4c7467dcafbc8eeef0e1f65
--- /dev/null
+++ b/pool/shard000/JavaScript/0002735_PrivateMessage.js
@@ -0,0 +1,50 @@
+var {
+ mongoose,
+ defaultOptions,
+ modifySchema,
+ defaultSchema
+} = require('../index.js');
+
+// Define the document Schema
+var schema = new mongoose.Schema(
+ Object.assign({}, defaultSchema, {
+ creator: {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: 'User',
+ required: true
+ },
+ members: [
+ {
+ user: {
+ type: mongoose.Schema.Types.ObjectId,
+ ref: 'User',
+ required: true
+ },
+ muted: {
+ type: Boolean,
+ default: false
+ },
+ notifications_enabled: {
+ type: Boolean,
+ default: true
+ }
+ }
+ ]
+ }),
+ defaultOptions
+);
+
+schema.query.byMember = function(user) {
+ return this.find({ 'members.user': user });
+};
+
+schema.query.byCreator = function(user) {
+ return this.find({ creator: user });
+};
+
+modifySchema(schema);
+
+// Initialize the model with the schema, and export it
+var model = mongoose.model('PrivateMessages', schema);
+
+module.exports = model;
diff --git a/pool/shard000/JavaScript/0002736_mostrar_lei.js b/pool/shard000/JavaScript/0002736_mostrar_lei.js
new file mode 100644
index 0000000000000000000000000000000000000000..9bb1c2115d81ac80386f55eaed487744b4870b08
--- /dev/null
+++ b/pool/shard000/JavaScript/0002736_mostrar_lei.js
@@ -0,0 +1,22 @@
+'use strict';
+
+describe('Controller: MostrarLeiCtrl', function () {
+
+ // load the controller's module
+ beforeEach(module('vigiaPoliticoApp'));
+
+ var MostrarLeiCtrl,
+ scope;
+
+ // Initialize the controller and a mock scope
+ beforeEach(inject(function ($controller, $rootScope) {
+ scope = $rootScope.$new();
+ MostrarLeiCtrl = $controller('MostrarLeiCtrl', {
+ $scope: scope
+ });
+ }));
+
+ it('should attach a list of awesomeThings to the scope', function () {
+ expect(scope.awesomeThings.length).toBe(3);
+ });
+});
diff --git a/pool/shard000/JavaScript/0002737_gulpfile.js b/pool/shard000/JavaScript/0002737_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..834e350b851950de31eb677beeaa8d4d2ecde636
--- /dev/null
+++ b/pool/shard000/JavaScript/0002737_gulpfile.js
@@ -0,0 +1,178 @@
+// generated on 2017-03-18 using generator-webapp 2.4.1
+const gulp = require('gulp');
+const gulpLoadPlugins = require('gulp-load-plugins');
+const browserSync = require('browser-sync').create();
+const del = require('del');
+const wiredep = require('wiredep').stream;
+const runSequence = require('run-sequence');
+
+const $ = gulpLoadPlugins();
+const reload = browserSync.reload;
+
+var dev = true;
+
+gulp.task('styles', () => {
+ return gulp.src('app/styles/*.scss')
+ .pipe($.plumber())
+ .pipe($.if(dev, $.sourcemaps.init()))
+ .pipe($.sass.sync({
+ outputStyle: 'expanded',
+ precision: 10,
+ includePaths: ['.']
+ }).on('error', $.sass.logError))
+ .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
+ .pipe($.if(dev, $.sourcemaps.write()))
+ .pipe(gulp.dest('.tmp/styles'))
+ .pipe(reload({stream: true}));
+});
+
+gulp.task('scripts', () => {
+ return gulp.src('app/scripts/**/*.js')
+ .pipe($.plumber())
+ .pipe($.if(dev, $.sourcemaps.init()))
+ .pipe($.babel())
+ .pipe($.if(dev, $.sourcemaps.write('.')))
+ .pipe(gulp.dest('.tmp/scripts'))
+ .pipe(reload({stream: true}));
+});
+
+function lint(files) {
+ return gulp.src(files)
+ .pipe($.eslint({ fix: true }))
+ .pipe(reload({stream: true, once: true}))
+ .pipe($.eslint.format())
+ .pipe($.if(!browserSync.active, $.eslint.failAfterError()));
+}
+
+gulp.task('lint', () => {
+ return lint('app/scripts/**/*.js')
+ .pipe(gulp.dest('app/scripts'));
+});
+gulp.task('lint:test', () => {
+ return lint('test/spec/**/*.js')
+ .pipe(gulp.dest('test/spec'));
+});
+
+gulp.task('html', ['styles', 'scripts'], () => {
+ return gulp.src('app/*.html')
+ .pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
+ .pipe($.if(/\.js$/, $.uglify({compress: {drop_console: true}})))
+ .pipe($.if(/\.css$/, $.cssnano({safe: true, autoprefixer: false})))
+ .pipe($.if(/\.html$/, $.htmlmin({
+ collapseWhitespace: true,
+ minifyCSS: true,
+ minifyJS: {compress: {drop_console: true}},
+ processConditionalComments: true,
+ removeComments: true,
+ removeEmptyAttributes: true,
+ removeScriptTypeAttributes: true,
+ removeStyleLinkTypeAttributes: true
+ })))
+ .pipe(gulp.dest('dist'));
+});
+
+gulp.task('images', () => {
+ return gulp.src('app/images/**/*')
+ .pipe($.cache($.imagemin()))
+ .pipe(gulp.dest('dist/images'));
+});
+
+gulp.task('fonts', () => {
+ return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
+ .concat('app/fonts/**/*'))
+ .pipe($.if(dev, gulp.dest('.tmp/fonts'), gulp.dest('dist/fonts')));
+});
+
+gulp.task('extras', () => {
+ return gulp.src([
+ 'app/*',
+ '!app/*.html'
+ ], {
+ dot: true
+ }).pipe(gulp.dest('dist'));
+});
+
+gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
+
+gulp.task('serve', () => {
+ runSequence(['clean', 'wiredep'], ['styles', 'scripts', 'fonts'], () => {
+ browserSync.init({
+ notify: false,
+ port: 9000,
+ server: {
+ baseDir: ['.tmp', 'app'],
+ routes: {
+ '/bower_components': 'bower_components'
+ }
+ }
+ });
+
+ gulp.watch([
+ 'app/*.html',
+ 'app/images/**/*',
+ '.tmp/fonts/**/*'
+ ]).on('change', reload);
+
+ gulp.watch('app/styles/**/*.scss', ['styles']);
+ gulp.watch('app/scripts/**/*.js', ['scripts']);
+ gulp.watch('app/fonts/**/*', ['fonts']);
+ gulp.watch('bower.json', ['wiredep', 'fonts']);
+ });
+});
+
+gulp.task('serve:dist', ['default'], () => {
+ browserSync.init({
+ notify: false,
+ port: 9000,
+ server: {
+ baseDir: ['dist']
+ }
+ });
+});
+
+gulp.task('serve:test', ['scripts'], () => {
+ browserSync.init({
+ notify: false,
+ port: 9000,
+ ui: false,
+ server: {
+ baseDir: 'test',
+ routes: {
+ '/scripts': '.tmp/scripts',
+ '/bower_components': 'bower_components'
+ }
+ }
+ });
+
+ gulp.watch('app/scripts/**/*.js', ['scripts']);
+ gulp.watch(['test/spec/**/*.js', 'test/index.html']).on('change', reload);
+ gulp.watch('test/spec/**/*.js', ['lint:test']);
+});
+
+// inject bower components
+gulp.task('wiredep', () => {
+ gulp.src('app/styles/*.scss')
+ .pipe($.filter(file => file.stat && file.stat.size))
+ .pipe(wiredep({
+ ignorePath: /^(\.\.\/)+/
+ }))
+ .pipe(gulp.dest('app/styles'));
+
+ gulp.src('app/*.html')
+ .pipe(wiredep({
+ exclude: ['bootstrap-sass'],
+ ignorePath: /^(\.\.\/)*\.\./
+ }))
+ .pipe(gulp.dest('app'));
+});
+
+gulp.task('build', ['lint', 'html', 'images', 'fonts', 'extras'], () => {
+ return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
+});
+
+gulp.task('default', () => {
+ return new Promise(resolve => {
+ dev = false;
+ runSequence(['clean', 'wiredep'], 'build', resolve);
+ });
+});
diff --git a/pool/shard000/JavaScript/0002739_role.js b/pool/shard000/JavaScript/0002739_role.js
new file mode 100644
index 0000000000000000000000000000000000000000..053d3c1c162dc039cd8393907543259e07823323
--- /dev/null
+++ b/pool/shard000/JavaScript/0002739_role.js
@@ -0,0 +1,35 @@
+var express = require('express');
+var router = express.Router();
+var core = require('../../libs/core');
+var role = require('../../controllers/server/role');
+
+//权限判断
+router.use(function(req, res, next) {
+ console.log('角色页: ' + Date.now());
+ res.locals.Path = 'role';
+ if(!req.session.user) {
+ var path = core.translateAdminDir('/user/login');
+ return res.redirect(path);
+ }
+ if(!req.Roles || (req.Roles.indexOf('admin') < 0 && req.Actions && req.Actions.indexOf('role') < 0)) {
+ var path = core.translateAdminDir('/');
+ return res.redirect(path);
+ }
+ next();
+});
+//内容列表
+router.route('/').get(role.list);
+//添加内容
+router.route('/add').all(role.add);
+//单条信息
+router.route('/:id').get(role.one);
+//更新信息
+router.route('/:id/edit').all(role.edit);
+//删除信息
+router.route('/:id/del').all(role.del);
+
+
+module.exports = function(app) {
+ var path = core.translateAdminDir('/role');
+ app.use(path, router);
+};
diff --git a/pool/shard000/JavaScript/0002740_Callback.js b/pool/shard000/JavaScript/0002740_Callback.js
new file mode 100644
index 0000000000000000000000000000000000000000..5deaacf18f3e102e16b1619ca16348540351c696
--- /dev/null
+++ b/pool/shard000/JavaScript/0002740_Callback.js
@@ -0,0 +1,124 @@
+/**
+ * Created by kgrube on 4/3/2019
+ * @private
+ */
+const request = require('request');
+const crypto = require('crypto');
+
+/**
+ * @typedef {Object} CallbackPayload
+ * @property Action
+ * @property CompanyId
+ * @property Entity json string
+ * @property FromUrl
+ * @property ID
+ * @property MemberId
+ * @property {object} Metadata
+ * @property Metadata.key_url
+ * @property Type
+ */
+
+/**
+ * @typedef {object} CWCallback
+ * @property verifyCallback
+ * @property verifyMessage
+ * @property middleware
+ *
+ */
+
+/**
+ * Load signing key and verify the message
+ * @param {CallbackPayload} callbackBody
+ * @param {string} contentSignature base64 content signature req.headers[x-content-signature]
+ * @return {Promise}
+ */
+function verifyCallback(callbackBody, contentSignature) {
+ return new Promise((resolve, reject) => {
+ if (!callbackBody || !contentSignature) {
+ throw new Error('callbackBody and contentSignature must be defined.');
+ }
+
+ const key_url = callbackBody.Metadata && callbackBody.Metadata.key_url;
+
+ request(key_url, (err, res, body) => {
+ if (err) throw err;
+ try {
+ const parsed = JSON.parse(body);
+ const signingKey = parsed.signing_key;
+
+ return resolve(verifyMessage(callbackBody, contentSignature, signingKey));
+ } catch (parseErr) {
+ throw parseErr;
+ }
+ });
+ });
+}
+
+/**
+ * Validate a callback body against signed key
+ * @param {CallbackPayload} callbackBody
+ * @param {string} contentSignature
+ * @param {string} signingKey
+ * @returns {boolean}
+ */
+function verifyMessage(callbackBody, contentSignature, signingKey) {
+ const hash = crypto.createHash('sha256').update(signingKey).digest();
+ const hmac = crypto.createHmac('sha256', hash);
+
+ return contentSignature === hmac.update(JSON.stringify(callbackBody)).digest('base64');
+}
+
+/**
+ * Express style middleware
+ * @example
+ * app.post('/your/api', cw.utils.middleware((err, req, res, verified, payload) => {
+ * if (err) {
+ * //handle error
+ * res.status(500).end();
+ * } else if (!verified) {
+ * // send 403 on verification failure
+ * res.status(403).end();
+ * } else {
+ * res.status(200).end()
+ * }
+ * const {action, id} = req.query;
+ * // do something with the payload
+ * }));
+ *
+ * @param {function} cb callback(err, req, res, verified, payload)
+ */
+function middleware(cb) {
+ if (!cb || typeof cb !== 'function') {
+ throw new Error('callback must be a function.');
+ }
+
+ return (req, res) => {
+ if (!req || !req.body || !req.body.Metadata) {
+ return cb(new Error('callback payload is invalid.'), req, res, false);
+ }
+
+ const contentSignature = req.headers['x-content-signature'];
+ const callbackBody = req.body;
+
+ let parsedEntity;
+ try {
+ parsedEntity = JSON.parse(callbackBody.Entity);
+ } catch (parseErr) {
+ return cb(parseErr, req, res, false);
+ }
+
+ verifyCallback(callbackBody, contentSignature)
+ .then(verified => {
+ return cb(null, req, res, verified, Object.assign(callbackBody, {Entity: parsedEntity}));
+ })
+ .catch(err => {
+ return cb(err, req, res, false);
+ });
+ };
+}
+
+module.exports = {
+ verifyMessage,
+ verifyCallback,
+ middleware,
+};
diff --git a/pool/shard000/JavaScript/0002742_sv.js b/pool/shard000/JavaScript/0002742_sv.js
new file mode 100644
index 0000000000000000000000000000000000000000..bde95daa653b5cd5852a319b6089442160c51c0c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002742_sv.js
@@ -0,0 +1,54 @@
+(function () {
+ var lang = {
+ months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),
+ monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),
+ weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),
+ weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"),
+ longDateFormat : {
+ LT : "HH:mm",
+ L : "YYYY-MM-DD",
+ LL : "D MMMM YYYY",
+ LLL : "D MMMM YYYY LT",
+ LLLL : "dddd D MMMM YYYY LT"
+ },
+ calendar : {
+ sameDay: '[Idag klockan] LT',
+ nextDay: '[Imorgon klockan] LT',
+ lastDay: '[Igår klockan] LT',
+ nextWeek: 'dddd [klockan] LT',
+ lastWeek: '[Förra] dddd [en klockan] LT',
+ sameElse: 'L'
+ },
+ relativeTime : {
+ future : "om %s",
+ past : "för %s sen",
+ s : "några sekunder",
+ m : "en minut",
+ mm : "%d minuter",
+ h : "en timme",
+ hh : "%d timmar",
+ d : "en dag",
+ dd : "%d dagar",
+ M : "en månad",
+ MM : "%d månader",
+ y : "ett år",
+ yy : "%d år"
+ },
+ ordinal : function (number) {
+ var b = number % 10;
+ return (~~ (number % 100 / 10) === 1) ? 'e' :
+ (b === 1) ? 'a' :
+ (b === 2) ? 'a' :
+ (b === 3) ? 'e' : 'e';
+ }
+ };
+
+ // Node
+ if (typeof module !== 'undefined') {
+ module.exports = lang;
+ }
+ // Browser
+ if (typeof window !== 'undefined' && this.moment && this.moment.lang) {
+ this.moment.lang('sv', lang);
+ }
+}());
diff --git a/pool/shard000/JavaScript/0002743_autoprefixer-test.js b/pool/shard000/JavaScript/0002743_autoprefixer-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..716bdad46c9ec5bf4d19b2106c74d1b4839dada5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002743_autoprefixer-test.js
@@ -0,0 +1,55 @@
+var vows = require('vows'),
+ assert = require('assert'),
+ AssetGraph = require('../lib/AssetGraph');
+
+vows.describe('transforms.autoprefixer').addBatch({
+ 'After loading an unprefixed test case': {
+ topic: function () {
+ new AssetGraph({root: __dirname + '/autoprefixer/'})
+ .loadAssets('index.html')
+ .populate()
+ .run(this.callback);
+ },
+ 'the graph should contain 2 HtmlStyle relations': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 2);
+ },
+ 'the graph should contain 1 CssImage relation': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'CssImage'}).length, 1);
+ },
+ 'then running the autoprefixer transform': {
+ topic: function (assetGraph) {
+ assetGraph
+ .autoprefixer()
+ .run(this.callback);
+ },
+ 'the graph should contain 2 HtmlStyle relations': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 2);
+ },
+ 'the graph should contain 3 CssImage relation': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'CssImage'}).length, 3);
+ }
+ }
+ },
+ 'After loading an test case using prefixfree.js': {
+ topic: function () {
+ new AssetGraph({root: __dirname + '/autoprefixer/'})
+ .loadAssets('prefixfree.html')
+ .populate()
+ .run(this.callback);
+ },
+ 'the graph should contain 2 HtmlScript relations': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'HtmlScript'}).length, 2);
+ },
+ 'then running the autoprefixer transform': {
+ topic: function (assetGraph) {
+ assetGraph
+ .autoprefixer()
+ .run(this.callback);
+ },
+ 'the graph should contain 0 HtmlScript relations': function (assetGraph) {
+ assert.equal(assetGraph.findRelations({type: 'HtmlScript'}).length, 0);
+ }
+ }
+ }
+
+})['export'](module);
diff --git a/pool/shard000/JavaScript/0002748_nativeBridge.js b/pool/shard000/JavaScript/0002748_nativeBridge.js
new file mode 100644
index 0000000000000000000000000000000000000000..cacda30e861544d0ae88bfe62e736b7548b9595f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002748_nativeBridge.js
@@ -0,0 +1,214 @@
+(function (mw, $) {
+ "use strict";
+ var NativeBridge = {
+ callbacksCount: 1,
+ callbacks: {},
+
+ // Automatically called by native layer when a result is available
+ resultForCallback: function resultForCallback(callbackId, resultArray) {
+ try {
+ var callback = NativeBridge.callbacks[callbackId];
+ if (!callback) {
+ return;
+ }
+
+ callback.apply(null, resultArray);
+ } catch (e) {
+ alert(e);
+ }
+ },
+
+ // Use this in javascript to request native objective-c code
+ // functionName : string (I think the name is explicit :p)
+ // args : array of arguments
+ // callback : function with n-arguments that is going to be called when the native code returned
+ call: function call(functionName, args, callback) {
+
+ var hasCallback = callback && typeof callback == "function";
+ var callbackId = hasCallback ? NativeBridge.callbacksCount++ : 0;
+
+ if (hasCallback) {
+ NativeBridge.callbacks[callbackId] = callback;
+ }
+
+ var iframe = document.createElement("IFRAME");
+ iframe.setAttribute("src", "js-frame:" + functionName + ":" + callbackId + ":" + encodeURIComponent(JSON.stringify(args)));
+ document.documentElement.appendChild(iframe);
+ iframe.parentNode.removeChild(iframe);
+ iframe = null;
+ }
+ };
+
+ NativeBridge.videoPlayer = NativeBridge.videoPlayer || {
+ proxyElement: null,
+ embedPlayer: null,
+ isJsCallbackReady: false,
+ bindPostfix: ".nativeBridge",
+ subscribed: [],
+ playerMethods: [
+ 'stop', 'play', 'pause', 'replay', 'setPlayerSource', 'bindPlayerEvents', 'showNativePlayer', 'hideNativePlayer', 'toggleFullscreen', 'notifyKPlayerEvent', 'notifyKPlayerEvaluated', 'notifyJsReady', 'showChromecastDeviceList', 'notifyLayoutReady',
+ 'doneFSBtnPressed', 'addNativeAirPlayButton', 'showNativeAirPlayButton', 'hideNativeAirPlayButton', 'doNativeAction', 'textTracksReceived', 'loadEmbeddedCaptions', 'flavorsListChanged', 'switchFlavor' ],
+
+ registePlayer: function (proxyElement) {
+ var _this = this;
+ this.proxyElement = proxyElement;
+
+ this.proxyElement.attr = function (attributeName, attributeValue) {
+ if (attributeName && attributeValue === undefined) {
+ return _this.proxyElement[ attributeName ];
+ } else if (attributeName && attributeValue) {
+ _this.proxyElement[attributeName] = attributeValue;
+ _this.execute('setAttribute', [ attributeName, attributeValue ]);
+ _this.proxyElement['language'] = mw.getConfig('localizationCode');
+ _this.execute('setAttribute', [ 'language', mw.getConfig('localizationCode') ]);
+ }
+ }
+
+ for (var i = 0; i < this.playerMethods.length; i++) {
+ (function (method) {
+ _this.proxyElement[method] = function (arg) {
+ _this.execute(method, arg);
+ }
+ })(this.playerMethods[i]);
+ }
+
+
+ //TODO support more than 1 subscribe?
+ this.proxyElement.subscribe = function (callback, eventName) {
+ _this.subscribed[eventName] = callback;
+ }
+
+ this.proxyElement.unsubscribe = function (eventName) {
+ _this.subscribed[eventName] = undefined;
+ }
+
+ this.bindNativeEvents();
+ },
+
+ notifyJsReadyFunc: function () {
+ if (this.isJsCallbackReady && this.proxyElement) {
+ this.proxyElement.notifyJsReady([]);
+ }
+ },
+
+ registerEmbedPlayer: function (embedPlayer) {
+ this.embedPlayer = embedPlayer;
+ this.notifyJsReadyFunc();
+ },
+ sendNotification: function (eventName, eventValue) {
+ this.embedPlayer.sendNotification(eventName, JSON.parse(eventValue));
+ },
+ /**
+ *
+ * @param object
+ * @returns String rerpesantation of given object
+ */
+ getObjectString: function (object) {
+ var stringValue = object;
+ if (typeof object === "object") {
+ stringValue = JSON.stringify(object);
+ }
+ return stringValue;
+ },
+ addJsListener: function (eventName) {
+ var _this = this;
+ this.embedPlayer.addJsListener(eventName + this.bindPostfix, function (val) {
+ _this.embedPlayer.getPlayerElement().notifyKPlayerEvent([ eventName, _this.getObjectString(val) ]);
+ });
+ },
+ removeJsListener: function (eventName) {
+ this.embedPlayer.removeJsListener(eventName + this.bindPostfix);
+ },
+ setKDPAttribute: function (host, prop, value) {
+ this.embedPlayer.setKDPAttribute(host, prop, value);
+ },
+ /**
+ * will evaluate given expression and send the resulted value back to native code with the given callbackName
+ * @param expression
+ * @param callbackName
+ */
+ asyncEvaluate: function (expression, callbackName) {
+ var result = this.embedPlayer.evaluate(expression);
+ this.embedPlayer.getPlayerElement().notifyKPlayerEvaluated([ callbackName, this.getObjectString(result) ]);
+ },
+ //this function should be called from IOS/Andorid
+ trigger: function (eventName, eventValue) {
+ // mw.log('nativeBridge.js --> trigger:' + eventName + ' ' + eventValue);
+
+ if (eventValue === "(null)") {
+ //set undefined
+ eventValue = void(0);
+ }
+
+ if (eventValue != undefined) {
+ var jsEventValue = this.stringConvertion(eventValue);
+ }
+
+ if (eventName == 'timeupdate') {
+ this.proxyElement['currentTime'] = jsEventValue;
+ } else if (eventName == 'progress') {
+ this.proxyElement['progress'] = jsEventValue;
+ } else if (eventName == 'visible') {
+ this.proxyElement['visible'] = jsEventValue;
+ } else if (eventName == 'durationchange') {
+ this.proxyElement['duration'] = jsEventValue;
+ } else if (eventName == 'nativeAction') {
+ this.proxyElement['nativeAction'] = jsEventValue;
+ } else if (eventName == 'play') {
+ this.proxyElement['paused'] = false;
+ } else if (eventName == 'pause') {
+ this.proxyElement['paused'] = true;
+ }
+
+ $(this.proxyElement).trigger(eventName, [jsEventValue]);
+
+ if (this.subscribed[eventName]) {
+ this.subscribed[eventName](jsEventValue);
+ }
+ },
+ execute: function (command, args) {
+ args = args || [];
+ console.log(command);
+ console.log(args);
+ NativeBridge.call(command, args);
+ },
+ bindNativeEvents: function () {
+ console.log('bindNativeEvents');
+ this.proxyElement.bindPlayerEvents([]);
+ },
+ log: function (message, arg) {
+ console.log(message, arg);
+ },
+ getVideoHolderHeight: function () {
+ return this.embedPlayer.getVideoHolder().height();
+ },
+ getControlBarHeight: function () {
+ return this.embedPlayer.getControlBarContainer().height();
+ },
+ stringConvertion: function (str) {
+ var value = parseFloat(str);
+
+ if (isNaN(value)) {
+ if (value == 'true') {
+ return true;
+ } else if (value == 'false') {
+ return false;
+ } else {
+ return str;
+ }
+ }
+
+ return value;
+ }
+ };
+
+
+ if (mw.getConfig('EmbedPlayer.ForceNativeComponent') === true) {
+ window["NativeBridge"] = NativeBridge;
+ kWidget.addReadyCallback(function () {
+ NativeBridge.videoPlayer.isJsCallbackReady = true;
+ NativeBridge.videoPlayer.notifyJsReadyFunc();
+ });
+ }
+
+})(window.mw, window.jQuery);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002749_filter.js b/pool/shard000/JavaScript/0002749_filter.js
new file mode 100644
index 0000000000000000000000000000000000000000..d8e8e9234df3a5bf5ce0e9d814e71d512e31e3a0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002749_filter.js
@@ -0,0 +1,41 @@
+const symbols = require('../../../symbols');
+const createToken = require('../../../create-token');
+const callFunction = require('./call-function');
+
+const lelPromise = require('../../../util/lel-promise');
+const lelSeries = require('../../../util/lel-series');
+
+const getFilteringFunction =
+ (resolve, reject, evaluateExpr, scope, expr) =>
+ (list) => {
+ if (list.type !== symbols.LIST) {
+ reject(new Error(`Invalid list passed to filter. Got ${expr}`));
+ }
+
+ evaluateExpr(scope, expr[2])
+ .then(performFiltering(resolve, reject, evaluateExpr, scope, expr, list));
+ };
+
+const performFiltering =
+ (resolve, reject, evaluateExpr, scope, expr, list) =>
+ (filteringFunction) => {
+ if (filteringFunction.type !== symbols.FUNCTION_REFERENCE) {
+ reject(new Error(`Invalid function passed to filter. Got ${expr}`));
+ }
+
+ const mapCalls = list.value.map(
+ (listElement, i) =>
+ () => callFunction(evaluateExpr, scope, [listElement, createToken(symbols.NUMBER, i)], filteringFunction.value)
+ );
+ lelSeries(mapCalls)
+ .then(values => {
+ const newList = list.value.filter((element, index) => values[index].value);
+ resolve(createToken(symbols.LIST, newList))
+ });
+ };
+
+module.exports = (evaluateExpr, scope, expr) =>
+ lelPromise((resolve, reject) =>
+ evaluateExpr(scope, expr[1])
+ .then(getFilteringFunction(resolve, reject, evaluateExpr, scope, expr))
+ );
diff --git a/pool/shard000/JavaScript/0002750_listener.js b/pool/shard000/JavaScript/0002750_listener.js
new file mode 100644
index 0000000000000000000000000000000000000000..7d39d81b924dd0d0eeacf95e1b8af32717a4a5c5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002750_listener.js
@@ -0,0 +1,173 @@
+// Copyright 2005 The Closure Library Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS-IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @fileoverview Listener object.
+ * @see ../demos/events.html
+ */
+
+goog.provide('goog.events.Listener');
+
+goog.require('goog.events.ListenableKey');
+
+
+
+/**
+ * Simple class that stores information about a listener
+ * @implements {goog.events.ListenableKey}
+ * @constructor
+ */
+goog.events.Listener = function() {
+ if (goog.events.Listener.ENABLE_MONITORING) {
+ this.creationStack = new Error().stack;
+ }
+};
+
+
+/**
+ * @define {boolean} Whether to enable the monitoring of the
+ * goog.events.Listener instances. Switching on the monitoring is only
+ * recommended for debugging because it has a significant impact on
+ * performance and memory usage. If switched off, the monitoring code
+ * compiles down to 0 bytes.
+ */
+goog.events.Listener.ENABLE_MONITORING = false;
+
+
+/**
+ * Whether the listener is a function or an object that implements handleEvent.
+ * @type {boolean}
+ * @private
+ */
+goog.events.Listener.prototype.isFunctionListener_;
+
+
+/**
+ * Call back function or an object with a handleEvent function.
+ * @type {Function|Object|null}
+ */
+goog.events.Listener.prototype.listener;
+
+
+/**
+ * Proxy for callback that passes through {@link goog.events#HandleEvent_}
+ * @type {Function}
+ */
+goog.events.Listener.prototype.proxy;
+
+
+/**
+ * Object or node that callback is listening to
+ * @type {Object|goog.events.EventTarget}
+ */
+goog.events.Listener.prototype.src;
+
+
+/**
+ * Type of event
+ * @type {string}
+ */
+goog.events.Listener.prototype.type;
+
+
+/**
+ * Whether the listener is being called in the capture or bubble phase
+ * @type {boolean}
+ */
+goog.events.Listener.prototype.capture;
+
+
+/**
+ * Optional object whose context to execute the listener in
+ * @type {Object|undefined}
+ */
+goog.events.Listener.prototype.handler;
+
+
+/**
+ * The key of the listener.
+ * @type {number}
+ * @override
+ */
+goog.events.Listener.prototype.key = 0;
+
+
+/**
+ * Whether the listener has been removed.
+ * @type {boolean}
+ */
+goog.events.Listener.prototype.removed = false;
+
+
+/**
+ * Whether to remove the listener after it has been called.
+ * @type {boolean}
+ */
+goog.events.Listener.prototype.callOnce = false;
+
+
+/**
+ * If monitoring the goog.events.Listener instances is enabled, stores the
+ * creation stack trace of the Disposable instance.
+ * @type {string}
+ */
+goog.events.Listener.prototype.creationStack;
+
+
+/**
+ * Initializes the listener.
+ * @param {Function|Object} listener Callback function, or an object with a
+ * handleEvent function.
+ * @param {Function} proxy Wrapper for the listener that patches the event.
+ * @param {Object} src Source object for the event.
+ * @param {string} type Event type.
+ * @param {boolean} capture Whether in capture or bubble phase.
+ * @param {Object=} opt_handler Object in whose context to execute the callback.
+ */
+goog.events.Listener.prototype.init = function(listener, proxy, src, type,
+ capture, opt_handler) {
+ // we do the test of the listener here so that we do not need to
+ // continiously do this inside handleEvent
+ if (goog.isFunction(listener)) {
+ this.isFunctionListener_ = true;
+ } else if (listener && listener.handleEvent &&
+ goog.isFunction(listener.handleEvent)) {
+ this.isFunctionListener_ = false;
+ } else {
+ throw Error('Invalid listener argument');
+ }
+
+ this.listener = listener;
+ this.proxy = proxy;
+ this.src = src;
+ this.type = type;
+ this.capture = !!capture;
+ this.handler = opt_handler;
+ this.callOnce = false;
+ this.key = goog.events.ListenableKey.reserveKey();
+ this.removed = false;
+};
+
+
+/**
+ * Calls the internal listener
+ * @param {Object} eventObject Event object to be passed to listener.
+ * @return {boolean} The result of the internal listener call.
+ */
+goog.events.Listener.prototype.handleEvent = function(eventObject) {
+ if (this.isFunctionListener_) {
+ return this.listener.call(this.handler || this.src, eventObject);
+ }
+ return this.listener.handleEvent.call(this.listener, eventObject);
+};
diff --git a/pool/shard000/JavaScript/0002753_release.js b/pool/shard000/JavaScript/0002753_release.js
new file mode 100644
index 0000000000000000000000000000000000000000..7fa79b847b94929e796f82d49a6754990f0a674a
--- /dev/null
+++ b/pool/shard000/JavaScript/0002753_release.js
@@ -0,0 +1,35 @@
+'use strict';
+
+const Command = require('cmnd').Command;
+const UpCommand = require('./up.js');
+
+const fs = require('fs');
+const inquirer = require('inquirer');
+
+class ReleaseCommand extends Command {
+
+ constructor() {
+
+ super('release');
+
+ }
+
+ help() {
+
+ return {
+ description: 'Pushes release of Autocode package to registry and cloud (Alias of `lib up -r`)'
+ };
+
+ }
+
+ run(params, callback) {
+
+ params.flags.r = [];
+ params.args = [];
+ UpCommand.prototype.run.call(this, params, callback);
+
+ }
+
+}
+
+module.exports = ReleaseCommand;
diff --git a/pool/shard000/JavaScript/0002754_index.js b/pool/shard000/JavaScript/0002754_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..3221131c6380653a2204b5f423de3fa4f55ad9ff
--- /dev/null
+++ b/pool/shard000/JavaScript/0002754_index.js
@@ -0,0 +1,71 @@
+#!/usr/bin/env node
+
+// # node rename.js
+// node shell scripting
+
+// Ensure that files are able to be modified
+// Possible chmod needs to happen too
+
+const colors = require('colors');
+const program = require('commander');
+const fs = require('fs');
+const path = require('path');
+let folder = 'Path/to/directory'; // Folder the script reads to replace text
+let regex = /\(.+\) |\(.+\)|[^a-zA-Z0-9.\s\&\,]/gi; // rename.js finds `regex` to replace with `replaceWith`, which replaces with whatever
+let replace = '';
+
+let massRename;
+
+program
+ .version('0.0.1')
+ .usage('[options] ')
+ .option('-c --copy ', 'Makes a copy')
+ .parse(process.argv);
+
+massRename = (folder, regex, replace) => {
+ let files = fs.readdirSync(folder);
+ console.dir(files);
+ for (let i = 0; i < files.length; i++) {
+ let check = fs.readdirSync(folder); // Updates per cycle
+ let prev = path.join(folder, files[i]);
+ let stat = fs.statSync(prev);
+ // console.log(prev)
+ if (stat.isFile()) {
+ if (files[i].match(regex) && files[i].charAt(0) != '.') {
+
+ let ext = path.extname(files[i]); // Extension
+ let basename = path.basename(files[i], ext)
+ .replace(/\&/, 'and')
+ .replace(/_/g, ' ') // Replaces _ with ' '
+ .replace(regex, replace) // basename with regex applied
+ .replace(/\s\s+/g, ' '); // Condenses double spaces
+ if (basename.charAt(basename.length - 1) == ' ') {
+ basename = basename.slice(0, -1) + ext; // Removes ' '
+ } else {
+ basename = basename + ext;
+ };
+ let next = path.join(folder, basename);
+ if (check.indexOf(basename) > -1) {
+ console.log(`:: Err! Program would overwrite existing file.\n:: File: ${prev}\n:: Dir: ${folder}`.red);
+ break;
+ } else {
+ // fs.renameSync(prev, next);
+ console.log(`${files[i]} => ${basename}`);
+ }
+ }
+ } else if (stat.isDirectory() && files[i] != '.yacreaderlibrary') {
+ let newPath = path.join(folder, files[i]);
+ // console.log(`: Switching to folder ${newPath}`.green);
+ massRename(newPath, regex, replace);
+ // console.log(`: Returning to ${folder}`.green)
+ } else {
+ console.log(`No valid target file for ${files[i]}.`);
+ }
+ };
+};
+
+massRename(folder, regex, replace);
+
+exports.module = (folder, regex, replace) => {
+ massRename(folder, regex, replace);
+};
diff --git a/pool/shard000/JavaScript/0002758_actions.js b/pool/shard000/JavaScript/0002758_actions.js
new file mode 100644
index 0000000000000000000000000000000000000000..7bcd7a0aae8173796bc975cf0065dc4163251803
--- /dev/null
+++ b/pool/shard000/JavaScript/0002758_actions.js
@@ -0,0 +1,29 @@
+const playbackStates = require("../../../backend/player/Player").playbackStates;
+const actions = require("../../../actions");
+const SearchPanel = require("../SearchPanel");
+const errors = require("./errors");
+const QueuePanel = require("../QueuePanel");
+const UserPlaylistsPanel = require("../UserPlaylistsPanel");
+const AppConfiguration = require("../../../backend/Configuration/App");
+const appConfiguration = new AppConfiguration().getConfig();
+
+module.exports = {
+ loginRequired: {
+ [appConfiguration["INPUT_BAR_ACTIONS"]["PAUSE"]]: store => store.dispatch(actions.player.setPlaybackState(playbackStates.PAUSED)),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["RESUME"]]: store => store.dispatch(actions.player.setPlaybackState(playbackStates.PLAYING)),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["SEARCH"]]: (store, searchValue) => {
+ if (!searchValue) {
+ return errors.undefinedSearchValue;
+ }
+ store.dispatch(actions.ui.setCurrentActivity(SearchPanel, {searchValue}));
+ },
+ [appConfiguration["INPUT_BAR_ACTIONS"]["PLAYLISTS"]]: store => store.dispatch(actions.ui.setCurrentActivity(UserPlaylistsPanel, {})),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["QUEUE"]]: store => store.dispatch(actions.ui.setCurrentActivity(QueuePanel, {})),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["NEXT"]]: store => store.dispatch(actions.player.skipTracks(1)),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["SKIP"]]: (store, amount = 1) => store.dispatch(actions.player.skipTracks(amount)),
+ [appConfiguration["INPUT_BAR_ACTIONS"]["SHUFFLE"]]: store => store.dispatch(actions.player.shuffleTracksQueue()),
+ },
+ loginNotRequired: {
+ [appConfiguration["INPUT_BAR_ACTIONS"]["QUIT"]]: store => store.dispatch(actions.basic.exit())
+ }
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002760_main.js b/pool/shard000/JavaScript/0002760_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..c5c60eb5c08984d5ec9b49f81e247d56e68bef97
--- /dev/null
+++ b/pool/shard000/JavaScript/0002760_main.js
@@ -0,0 +1,254 @@
+/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE
+ Author: Jean Frank Arias Sanchez
+ Description: Site Form Scripts
+*/
+
+$(document).ready(function() {
+ slider();
+ scroller();
+ dropDownMenu();
+ Menu();
+ fixedMenu();
+ menuSlider();
+});
+
+$(window).resize(function() {
+ scroller();
+ Menu();
+});
+
+/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE
+ Author: Jean Frank Arias Sanchez
+ Description: Simple Fade Gallery
+*/
+
+function slider(){
+
+ // Variables
+
+ var gallery = $('.slider');
+ var slides = $('.slider li');
+ var activeSlide = 1; // Set to 1 since the slides animation must start in the second slide
+
+ // Function to remove the .active class from all the slides
+
+ function resetGallery() {
+ for (var slide = 0; slide < slides.length; slide++){
+ $(slides[slide]).removeClass('active');
+ }
+ }
+
+ // Function to add the .active class to the current slide
+
+ function setActiveSlide() {
+ $(slides[activeSlide]).addClass('active');
+ activeSlide++;
+ if (activeSlide >= slides.length){
+ activeSlide = 0;
+ };
+ }
+
+ // Running the gallery
+
+ setInterval(function(){
+ resetGallery();
+ setActiveSlide();
+ },
+ 4000); // Slides time in mili seconds. 4000 = 4 seconds
+
+}
+
+/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE
+ Author: Jean Frank Arias Sanchez
+ Description: Paralax Fixed Menu
+*/
+
+function fixedMenu(){
+
+ $(document).scroll(function(){
+
+ var menuItems = $('.main-menu li');
+ var homePos = $('#Home').offset().top;
+ var aboutPos = $('#About').offset().top;
+ var menuPos = $('#Menu').offset().top;
+ var reservationPos = $('#Reservation').offset().top;
+ var contactPos = $('#Contact').offset().top;
+
+ var docWidth = $(document).width();
+ var scrollPos = $(document).scrollTop();
+ var contentOffset = 0;
+
+ if (docWidth >= 623){
+ contentOffset = 50;
+ }else{
+ contentOffset = 100;
+ }
+
+ if (scrollPos >= ( aboutPos - contentOffset)){
+ activeReset();
+ menuItems.eq(1).addClass('active');
+ }else{
+ activeReset();
+ menuItems.eq(0).addClass('active');
+ }
+ if (scrollPos >= ( menuPos - contentOffset)){
+ activeReset();
+ menuItems.eq(2).addClass('active');
+ }
+ if (scrollPos >= ( reservationPos - contentOffset)){
+ activeReset();
+ menuItems.eq(3).addClass('active');
+ }
+ if (scrollPos >= ( contactPos - contentOffset)){
+ activeReset();
+ menuItems.eq(4).addClass('active');
+ }
+
+ function activeReset(){
+ menuItems.each(function(){
+ $(this).removeClass('active');
+ });
+ }
+
+ var docOffsetTop = $(document).scrollTop();
+ var menuHeight = 0;
+
+ if (docWidth >= 975){
+ menuHeight = 155;
+ }else {
+ menuHeight = 50;
+ }
+
+ if (docOffsetTop >= menuHeight ) {
+
+ $('.logo').addClass('fixed');
+ $('.main-menu').addClass('fixed');
+ $('.social-menu').addClass('fixed');
+
+ }else{
+
+ $('.logo').removeClass('fixed');
+ $('.main-menu').removeClass('fixed');
+ $('.social-menu').removeClass('fixed');
+
+ }
+
+ });
+
+}
+
+
+function collapseReset(){
+ $('.collapse-btn i').removeClass('fa-angle-up');
+ $('.collapse-btn i').addClass('fa-angle-down');
+}
+
+function Menu() {
+
+ var screenWidth = $(document).width();
+
+ if (screenWidth >= 975){
+
+ showMenu();
+
+ }else{
+
+ hideMenu();
+ collapseReset();
+
+ $('.main-menu li').not('.active').click(function(){
+ hideMenu();
+ });
+ $('.main-menu li').click(function(){
+ collapseReset();
+ });
+ }
+
+}
+
+function dropDownMenu() {
+
+ $('.collapse-btn').click(function(e){
+ e.preventDefault();
+ var isCollapsed = $('.main-menu li').not('.active').hasClass('collapsed');
+ if ( isCollapsed == true ){
+ showMenu();
+ $('.collapse-btn i').removeClass('fa-angle-down');
+ $('.collapse-btn i').addClass('fa-angle-up');
+ }else{
+ hideMenu();
+ $('.collapse-btn i').removeClass('fa-angle-up');
+ $('.collapse-btn i').addClass('fa-angle-down');
+ }
+ });
+
+}
+
+function showMenu(){
+ $('.main-menu li').not('.active').removeClass('collapsed').addClass('visible');
+}
+
+function hideMenu(){
+ $('.main-menu li').not('.active').removeClass('visible').addClass('collapsed');
+}
+
+/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE
+ Author: Jean Frank Arias Sanchez
+ Description: Manu Slider Fixed Menu
+*/
+
+function menuSlider(){
+
+ $('.slider-Item a').click(function(e){
+ e.preventDefault();
+ imgSrc = $(this).attr("href");
+ imgCaption = $(this).attr("title");
+ sliderItem = $(this).parent();
+ sliderSelectors = sliderItem.parent();
+ sliderContainer = sliderSelectors.parent();
+
+ $(sliderSelectors).find('.slider-Item').each(function(){
+ $(this).removeClass('active');
+ });
+
+ $(sliderItem).addClass('active');
+
+ $(sliderContainer).find('.slider-activeItem img').attr('src', imgSrc);
+ $(sliderContainer).find('.slider-activeItem .slider-caption').text(imgCaption);
+
+ });
+
+}
+
+/* scroll.js v1.0.0 | GNU GENERAL PUBLIC LICENSE
+ Author: Jean Frank Arias Sanchez
+ Description: Section Scroller
+*/
+
+function scroller(){
+
+ var menuItems = $('.main-menu li');
+ var contentOffset;
+ var documentWidth = $(document).width();
+
+ if (documentWidth >= 623){
+ contentOffset = 48;
+ }else{
+ contentOffset = 100;
+ }
+
+ $(menuItems).find('a').click(function(e) {
+ e.preventDefault();
+ var section = $(this).attr("href");
+ var scrollTo = ($(section).offset().top) - contentOffset;
+ $("html, body").animate({
+ scrollTop: scrollTo
+ });
+ });
+
+ $('.logo a').click(function(e) {
+ e.preventDefault();
+ $("html, body").animate({scrollTop: 0});
+ });
+
+}
diff --git a/pool/shard000/JavaScript/0002762_controller.js b/pool/shard000/JavaScript/0002762_controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..265f7bd76835459b9345917e6a9271a200de63ad
--- /dev/null
+++ b/pool/shard000/JavaScript/0002762_controller.js
@@ -0,0 +1,111 @@
+/**
+ * Copyright (c) 2014 brian@bevey.org
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+/**
+ * @author brian@bevey.org
+ * @fileoverview Unit test for devices/geiger/controller.js
+ */
+
+exports.geigerControllerTest = {
+ fragments : function (test) {
+ 'use strict';
+
+ var geigerController = require(__dirname + '/../../../../devices/geiger/controller'),
+ fragments = geigerController.fragments();
+
+ test.strictEqual(typeof fragments.report, 'string', 'Fragment verified');
+ test.strictEqual(typeof fragments.graph, 'string', 'Fragment verified');
+
+ test.done();
+ },
+
+ postPrepare : function (test) {
+ 'use strict';
+
+ var geigerController = require(__dirname + '/../../../../devices/geiger/controller'),
+ config = { host : 'example.com',
+ port : '80',
+ path : '/test/',
+ method : 'POST',
+ badData : 'FAILURE',
+ postRequest : 'hello :)'},
+ testPost = geigerController.postPrepare(config);
+
+ test.deepEqual(testPost, { host : 'example.com',
+ port : '80',
+ path : '/test/',
+ method : 'POST',
+ headers : {
+ 'Accept' : 'application/json',
+ 'Accept-Charset' : 'utf-8',
+ 'User-Agent' : 'node-switchBoard',
+ 'Content-Type' : 'application/x-www-form-urlencoded',
+ 'Content-Length' : 8
+ }
+ }, 'Additional params are filtered out.');
+
+ test.done();
+ },
+
+ postData : function (test) {
+ 'use strict';
+
+ var geigerController = require(__dirname + '/../../../../devices/geiger/controller'),
+ geigerData = { username: 'bar', password: 'baz', maxCount: 5 },
+ postData = geigerController.postData(geigerData);
+
+ test.equal(postData, 'type=geiger&user=bar&pass=baz&count=5');
+
+ test.done();
+ },
+
+ getReadings : function (test) {
+ 'use strict';
+
+ var geigerController = require(__dirname + '/../../../../devices/geiger/controller'),
+ geigerData = [ {
+ aid : "123456",
+ gid : "2",
+ cpm : "21.0123",
+ acpm : "20.1234",
+ usv : "0.075",
+ name : "Ghandi",
+ time : 1234567890
+ },
+ {
+ aid : "123457",
+ gid : "2",
+ cpm : "21.0126",
+ acpm : "20.1237",
+ usv : "0.077",
+ name : "Ghandi",
+ time : 1234569890
+ } ],
+ testGeigerData = geigerController.getReadings(geigerData, 1),
+ testBadData = geigerController.getReadings({}, 10);
+
+ test.equal(testGeigerData.report.length, 1, 'One reading should be found for data feeds');
+ test.deepEqual(testBadData, { report : [] }, 'Nothing should be returned for bad data');
+
+ test.done();
+ }
+};
diff --git a/pool/shard000/JavaScript/0002764_wrap.js b/pool/shard000/JavaScript/0002764_wrap.js
new file mode 100644
index 0000000000000000000000000000000000000000..9c82d4ed647220528db17938a36150ac9dbbedf0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002764_wrap.js
@@ -0,0 +1,328 @@
+/*
+ * @Author: cungen
+ * @Date: 2017-09-25 15:32:29
+ * @Last Modified by: cungen
+ * @Last Modified time: 2017-05-22 11:16:44
+ * updating time 2017-9-25
+*/
+
+'use strict';
+(function (global){
+
+typeof defaults === 'undefined' ? false : defaults;
+
+
+var defaults = {
+ g: global,
+ step: 0,
+ stamp: 0,
+ wrap: global.wrap || {}
+};
+
+
+global.wrap = defaults.wrap;
+
+
+// init wrap lib
+defaults.wrap = function (){
+ this.absoluteObject = [];
+ this.relativeObject = [];
+}
+
+
+// 一、AJAX封装
+// 1、封裝AJAX函數
+defaults.wrap.prototype.nativeAjax = function (success, error) {
+
+ // 定义domain,方便环境切换
+ var domain = 'https://' + global.location.host + '/';
+
+ var url = domain + this.relativeObject.URL;
+ var type = this.relativeObject.TYPE;
+ var data = this.relativeObject.data;
+ var xhrRequest = null;
+ var _this = this;
+ var str = '';
+
+ if (global.XMLHttpRequest) xhrRequest = new XMLHttpRequest();
+ else xhrRequest = new ActiveXObject('Microsoft.XMLHTTP');
+
+ xhrRequest.open(type, url, true);
+
+ if (type === "POST" && data != null) {
+ xhrRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
+ for (var key in data) {
+ str += '&'+key+'='+data[key];
+ str = str.slice(1);
+ }
+ }
+
+ xhrRequest.onreadystatechange = function() {
+
+ if (xhrRequest.readyState == 4) {
+
+ if (xhrRequest.status == 200) {
+
+ var obj = {
+ statu: xhrRequest.status,
+ textData: xhrRequest.responseText
+ }
+
+ var responseData = _this.resolveData(obj);
+
+ _this.validateSuccess(success,[responseData],true)
+
+ } else error(xhrRequest.status);
+
+ }
+
+ }
+
+ xhrRequest.send(str);
+ ++defaults.step
+}
+
+
+defaults.wrap.prototype.resolveData = function (options){
+ var responseTextData = options.textData;
+
+ (options.statu === 200) && !0;
+
+ var text;
+ if(typeof responseTextData === 'string'){
+ var _search = responseTextData.search(' ');
+ if(_search >= 0){
+ text = this.trim(responseTextData)
+ }
+ else text = responseTextData;
+ }
+
+ return this.compileParse(text);
+}
+
+
+
+defaults.wrap.prototype.validateSuccess = function (isComplate,options,bool){
+ var turn = [{
+ bool: bool,
+ msg:'查询成功',
+ count: options.length,
+ result: options
+ }];
+
+ isComplate(turn)
+}
+
+
+
+defaults.wrap.prototype.compileStringify = function (options){
+ return typeof options === 'object' ? JSON.stringify(options) : false;
+}
+
+
+defaults.wrap.prototype.compileParse = function (options){
+ return typeof options === 'string' ? JSON.parse(options) : false;
+}
+
+
+// call fallback method
+defaults.wrap.prototype.resolveComplexFallback = function resolveComplexFallback(options){
+ var bindCall = [options];
+ var _this = this;
+ return {
+ custom : function (){
+ var callAjaxMehtod = bindCall;
+
+ for(;;){
+ if( callAjaxMehtod instanceof Array ){
+ callAjaxMehtod = callAjaxMehtod.pop();
+ continue;
+ }
+ break;
+ }
+
+ _this.absoluteObject = callAjaxMehtod;
+
+ return this
+ },
+ bind : function (){
+ console.log([bindCall?bindCall:false])
+ }
+ }
+}
+
+
+defaults.wrap.prototype.trim = function(options){
+ return options.replace(/^\s+|\S|\n$/,'');
+}
+
+
+defaults.wrap.prototype.toUppCase = function(options){
+ return options.toUpperCase();
+}
+
+
+defaults.wrap.prototype.toLowCase = function(options){
+ return options.toLowerCase();
+}
+
+
+defaults.wrap.prototype.setType = function(options){
+ this.relativeObject[this.toUppCase(options)] = this.toUppCase(this.absoluteObject[options]);
+}
+
+
+defaults.wrap.prototype.getType = function(options){
+ // please return a debug log
+ var takeUpper = this.relativeObject[this.toUppCase(options)];
+ if(takeUpper === 'GET' || takeUpper === 'POST') return takeUpper;
+ return false
+}
+
+
+defaults.wrap.prototype.setUrl = function(options){
+ // please return a debug log
+ this.relativeObject[this.toUppCase(options)] = this.toLowCase(this.absoluteObject[options]);
+}
+
+
+defaults.wrap.prototype.getUrl = function(options){
+ return this.relativeObject[this.toUppCase(options)];
+}
+
+
+defaults.wrap.prototype.setData = function(options){
+ // please return a debug log
+ if(options in this.absoluteObject) this.relativeObject[this.toUppCase(options)] = this.toLowCase(this.absoluteObject[options]);
+ else this.relativeObject[this.toUppCase(options)] = null;
+}
+
+
+defaults.wrap.prototype.getData = function(options){
+ return this.relativeObject[this.toUppCase(options)];
+}
+
+
+defaults.wrap.prototype.setSuccess = function(options){
+ this.relativeObject[this.toUppCase(options)] = [this.absoluteObject[options]];
+}
+
+
+defaults.wrap.prototype.getSuccess = function(options){
+ return this.relativeObject[this.toUppCase(options)];
+}
+
+
+defaults.wrap.prototype.setError = function(options){
+ this.relativeObject[this.toUppCase(options)] = [this.absoluteObject[options]];
+}
+
+
+defaults.wrap.prototype.getError = function(options){
+ return this.relativeObject[this.toUppCase(options)];
+}
+
+
+defaults.wrap.prototype.validateKeyForLowerCase = function (){
+ var lower;
+
+ for(var k in this.absoluteObject){
+ lower = this.toLowCase(k);
+
+ if(lower !== k){
+ this.absoluteObject[lower] = this.absoluteObject[k];
+ delete this.absoluteObject[k];
+ }
+
+ }
+ return 1
+}
+
+
+// return procssing ajax
+defaults.wrap.fn = function bindObjectGroup(opt,fallback){
+ var bindCall = new defaults.wrap(true);
+ var empty = [];
+
+ if(typeof opt === 'string'){
+
+ if(opt === 'ajax'){
+ empty.length = 0;
+ defaults.wrap.chain;
+ defaults.wrap.module = opt;
+ }
+ else return false;
+ }
+
+
+ if(typeof fallback === 'function'){
+
+ if(empty.length) empty.length = 0;
+ else empty.push(fallback);
+
+ defaults.wrap.chain = function (options){
+ return [(new empty[0])]
+ }
+
+ }
+
+
+ var resolveComplexFallback = bindCall.resolveComplexFallback(defaults.wrap.chain());
+ var _customMethod = resolveComplexFallback.custom();
+
+
+
+ if(typeof _customMethod === 'object'){
+ // return boolean true
+ var isTruth = bindCall.validateKeyForLowerCase();
+
+ bindCall.setType('type');
+ bindCall.setUrl('url');
+ bindCall.setData('data');
+ bindCall.getType('type');
+ bindCall.getUrl('url');
+ bindCall.getData('data');
+ bindCall.setSuccess('success');
+ bindCall.setError('error');
+ }
+
+ var getSuccess = bindCall.getSuccess('success');
+ var getError = bindCall.getError('error');
+
+ // dist property bound to this pointer
+ var print = bindCall.nativeAjax(getSuccess.pop(), getError.pop());
+
+ return print ? 'request json data success' : false
+}
+
+
+global.wrap['service'] = defaults.wrap.fn;
+
+})(this);
+
+
+
+
+
+
+
+
+/*
+合并其他分支上指定的文件或者文件夹到当前分支
+
+git checkout branchName folderName
+git checkout branchName path
+
+注:一下都是在主分支master上执行的命令
+1 把dev1 分支上app下所有的文件合并到主分支master上.
+git checkout dev app
+
+2 部分更新,如单独合并app/css/index.css到master主分支上.
+git checkout dev app/css/index.css
+
+3 部分文件夹dev分支上app的js文件夹下有多个JS文件都更新了.
+git checkout dev app/js
+
+合并过来的文件或者文件夹在主分支master上都是默认add过的,
+然后需要在master分支上commit,再push即可完成合并更新!
+*/
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002765_video-js.jquery.js b/pool/shard000/JavaScript/0002765_video-js.jquery.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb43320b6a68adcdff8d6a40975577074527ffd1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002765_video-js.jquery.js
@@ -0,0 +1,24 @@
+/* jQuery Plugin
+================================================================================ */
+if (window.jQuery) {
+ (function($) {
+
+ $.fn.setupPlayer = function(options) {
+ return VideoJS.setup(this[0], options);
+ };
+
+ // Deprecated
+ $.fn.VideoJS = function(options) {
+ this.each(function() {
+ VideoJS.setup(this, options);
+ });
+ return this;
+ };
+
+ $.fn.player = function() {
+ return this[0].player;
+ };
+
+ })(jQuery);
+}
+
diff --git a/pool/shard000/JavaScript/0002766_index.js b/pool/shard000/JavaScript/0002766_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..3b60782bffa4c567568d4550ed1545f0b6635faa
--- /dev/null
+++ b/pool/shard000/JavaScript/0002766_index.js
@@ -0,0 +1,38 @@
+import { select } from "d3-selection";
+
+const svg = select("svg");
+
+function render(data){
+ const circles = svg.selectAll("circle").data(data);
+ circles.exit().remove();
+ circles
+ .enter().append("circle")
+ .attr("fill", "rgba(255, 0, 0, 0.3)")
+ .attr("stroke", "black")
+ .merge(circles)
+ .attr("cx", d => d.x)
+ .attr("cy", d => d.y)
+ .attr("r", d => d.r);
+}
+
+render([
+ { x: 300, y:150, r: 44 },
+ { x: 500, y:350, r: 51 },
+ { x: 700, y:200, r: 33 },
+ { x: 583, y:114, r: 77 },
+ { x: 844, y:218, r: 74 },
+ { x: 257, y:316, r: 44 },
+ { x: 466, y:200, r: 31 },
+ { x: 179, y:414, r: 50 },
+ { x: 179, y:231, r: 36 },
+ { x: 376, y:326, r: 26 },
+ { x: 676, y:118, r: 68 },
+ { x: 626, y:199, r: 68 },
+ { x: 510, y:269, r: 15 },
+ { x: 510, y:419, r: 15 },
+ { x: 311, y:388, r: 15 },
+ { x: 50, y:388, r: 6 },
+ { x: 90, y:431, r: 6 },
+ { x: 90, y:287, r: 11 },
+ { x: 630, y:145, r: 11 }
+]);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002768_prettify.js b/pool/shard000/JavaScript/0002768_prettify.js
new file mode 100644
index 0000000000000000000000000000000000000000..50a3385ba800367b3383947851ee09d5181a73b1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002768_prettify.js
@@ -0,0 +1,27 @@
+//
+// Google Prettify
+// A showdown extension to add Google Prettify (http://code.google.com/p/google-code-prettify/)
+// hints to showdown's HTML output.
+//
+
+(function(){
+
+ var prettify = function(converter) {
+ return [{
+ type: 'output',
+ filter: function(source) {
+ return source
+ .replace(//mig, function (match, pre) {
+ return '';
+ })
+ .replace(/<\/p>/mig, '
');
+ }
+ }];
+ };
+
+ // Client-side export
+ if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.prettify = prettify; }
+ // Server-side export
+ if (typeof module !== 'undefined') module.exports = prettify;
+
+}());
diff --git a/pool/shard000/JavaScript/0002769_EventWithin.js b/pool/shard000/JavaScript/0002769_EventWithin.js
new file mode 100644
index 0000000000000000000000000000000000000000..a09681c0445b94edb17e71a2a8dcd164010a80d1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002769_EventWithin.js
@@ -0,0 +1,26 @@
+var _ = require("lodash");
+
+var time_period_in_ms = {
+ second: 1000,
+ minute: 1000 * 60,
+ hour : 1000 * 60 * 60,
+ day : 1000 * 60 * 60 * 24,
+ week : 1000 * 60 * 60 * 24 * 7,
+ month : 1000 * 60 * 60 * 24 * 30,
+ year : 1000 * 60 * 60 * 24 * 365,
+};
+
+module.exports = function(ast, comp, e){
+ var multiplier = 1;
+ if(_.has(time_period_in_ms, ast.time_period)){
+ multiplier = time_period_in_ms[ast.time_period];
+ }else{
+ var key = ast.time_period.replace(/s$/i, "");
+ if(_.has(time_period_in_ms, key)){
+ multiplier = time_period_in_ms[key];
+ }
+ }
+ return e("genfn", ["ctx"], [
+ e("return", e("*", comp(ast.expression), e("num", multiplier)))
+ ]);
+};
diff --git a/pool/shard000/JavaScript/0002770_raf-debounce.js b/pool/shard000/JavaScript/0002770_raf-debounce.js
new file mode 100644
index 0000000000000000000000000000000000000000..59431b21b37f95592de732215b48187e464fd154
--- /dev/null
+++ b/pool/shard000/JavaScript/0002770_raf-debounce.js
@@ -0,0 +1,25 @@
+export function rafDebounce (fn) {
+ let args, context, requestID;
+
+ function later () {
+ fn.apply(context, args);
+ args = context = requestID = null;
+ }
+
+ function debounced () {
+ if (fn == null) {
+ throw new Error('raf debounced function is already disposed.');
+ }
+ args = arguments;
+ context = this;
+ window.cancelAnimationFrame(requestID);
+ requestID = window.requestAnimationFrame(later);
+ }
+
+ debounced.dispose = () => {
+ window.cancelAnimationFrame(requestID);
+ fn = args = context = requestID = null;
+ };
+
+ return debounced;
+}
diff --git a/pool/shard000/JavaScript/0002773_secureScriptTestController.js b/pool/shard000/JavaScript/0002773_secureScriptTestController.js
new file mode 100644
index 0000000000000000000000000000000000000000..8562c9a4c61b85255af7123915c9bf61348aff29
--- /dev/null
+++ b/pool/shard000/JavaScript/0002773_secureScriptTestController.js
@@ -0,0 +1,30 @@
+({
+ testScriptSrcExposed: function(cmp) {
+ var testUtils = cmp.get("v.testUtils");
+ var script = document.createElement("script");
+
+ script.src = "foo.js";
+ testUtils.assertEquals("foo.js", script.src, "Unexpected script source");
+ testUtils.assertEquals("foo.js", script.getAttribute("src"), "Unexpected script source");
+
+ script.setAttribute("src", "foo2.js");
+ testUtils.assertEquals("foo2.js", script.src, "Unexpected script source");
+ testUtils.assertEquals("foo2.js", script.getAttribute("src"), "Unexpected script source");
+ },
+
+ testGetSetAttribute: function(cmp, event, helper) {
+ var testUtils = cmp.get("v.testUtils");
+
+ var script = document.createElement("script");
+
+ testUtils.assertUndefined(script.getAttribute("data-foo"), "Unexpected unset attribute value");
+ script.setAttribute("data-foo", "bar");
+ testUtils.assertEquals("bar", script.getAttribute("data-foo"), "Unexpected attribute value");
+
+ script.setAttribute("data-foo", null);
+ testUtils.assertEquals(null, script.getAttribute("data-foo"), "Unexpected attribute value, should be null");
+
+ script.setAttribute("data-foo", undefined);
+ testUtils.assertUndefined(script.getAttribute("data-foo"), "Unexpected attribute value, should be undefined");
+ }
+})
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002774_mongo-connection.js b/pool/shard000/JavaScript/0002774_mongo-connection.js
new file mode 100644
index 0000000000000000000000000000000000000000..b811909357365fe91cd7874598074d41e7acd741
--- /dev/null
+++ b/pool/shard000/JavaScript/0002774_mongo-connection.js
@@ -0,0 +1,231 @@
+/**
+ * Interface for abstracting over a database connection
+ */
+var Connection = require('../connection');
+var mongoose = require('mongoose');
+var Promise = require('bluebird');
+
+var Version = require('./mongo/version');
+var Application = require('./mongo/application');
+
+function MongoConnection() {
+ this.connected = false;
+ this.client = null;
+}
+
+MongoConnection.prototype = Object.create(Connection.prototype);
+
+MongoConnection.prototype.connect = function(env, callback) {
+ Connection.prototype.connect.apply(this, arguments);
+ var connectionString =
+ "mongodb://" +
+ this.env.get('stores:mongo:host') +
+ ':' +
+ this.env.get('stores:mongo:port') +
+ '/' +
+ this.env.get('stores:mongo:collection')
+ ;
+
+ this.client = mongoose.connection;
+ this.client.on('error', function() {
+ if (typeof callback === 'function') {
+ callback({
+ message: 'unable to connect to mongo',
+ store: 'mongo',
+ connectionString: connectionString
+ }, null);
+ }
+ });
+ this.client.on('open', function() {
+ if (typeof callback === 'function') {
+ callback(null, {
+ store: 'mongo',
+ connectionString: connectionString
+ });
+ }
+ });
+ mongoose.connect(connectionString, {
+ user: this.env.get('stores:mongo:username'),
+ pass: this.env.get('stores:mongo:password')
+ });
+ return this;
+};
+
+MongoConnection.prototype.disconnect = function(callback) {
+ Connection.prototype.disconnect.apply(this, arguments);
+ this.connected = false;
+ return this;
+};
+
+MongoConnection.prototype.getLatestContent = function(urlSlug, callback) {
+ var _findOneApplication = Promise.promisify(Application.findOne).bind(Application);
+ var _findOneVersion = Promise.promisify(Version.findOne).bind(Version);
+ _findOneApplication({urlSlug: urlSlug}, 'applicationId')
+ .then(function(data) {
+ if (!data) {
+ callback(null, null);
+ return;
+ }
+ return _findOneVersion({applicationId: data.applicationId, isLatest: true}, 'contents');
+ })
+ .then(function(data) {
+ callback(null, data.contents);
+ })
+ .catch(function(err) {
+ callback(err);
+ })
+ ;
+};
+
+MongoConnection.prototype.getLatestVersion = function(appId, callback) {
+ Version.findOne({
+ applicationId: appId,
+ isLatest: true
+ }, callback);
+};
+
+MongoConnection.prototype.updateLatestContent = function(appId, versionId, callback) {
+ var _findOneAndUpdate = Promise.promisify(Version.findOneAndUpdate).bind(Version);
+ var _getLatestVersion = Promise.promisify(this.getLatestVersion).bind(this);
+
+ // Order of operations, in sequence:
+ // - Get the previous `latest` version so we know which one it was
+ // - Set the desired one as the `latest`
+ // - Unset the previous `latest` version
+ // This way, we briefly have dual versions released, but there is never a
+ // moment when there is no `latest` version to serve.
+
+ var previousLatestQuery = {
+ applicationId: appId
+ };
+
+ var hadPreviousLatest = false;
+ var versionAlreadyDeployed = false;
+
+ var newLatestQuery = {
+ applicationId: appId,
+ versionId: versionId
+ };
+
+ var setLatest = { isLatest: true };
+ var unsetLatest = { isLatest: false };
+
+ _getLatestVersion(appId)
+ .then(function(previousLatestData) {
+ if (previousLatestData) {
+ hadPreviousLatest = true;
+ previousLatestQuery.versionId = previousLatestData.versionId;
+
+ // Version being deployed is already deployed!
+ if (previousLatestData.versionId === versionId) {
+ versionAlreadyDeployed = true;
+ return previousLatestData;
+ }
+ }
+ return _findOneAndUpdate(newLatestQuery, setLatest);
+ })
+ .then(function(data) {
+ if (hadPreviousLatest && !versionAlreadyDeployed) {
+ return _findOneAndUpdate(previousLatestQuery, unsetLatest);
+ } else {
+ return data;
+ }
+ })
+ .then(function(data) {
+ callback(null, data);
+ })
+ .catch(function(err) {
+ callback(err);
+ })
+ ;
+};
+
+MongoConnection.prototype.getContent = function(urlSlug, versionId, callback) {
+ var _findOneApplication = Promise.promisify(Application.findOne).bind(Application);
+ var _findOneVersion = Promise.promisify(Version.findOne).bind(Version);
+ _findOneApplication({urlSlug: urlSlug}, 'applicationId')
+ .then(function(data) {
+ if (!data) {
+ callback(null, null);
+ return;
+ }
+ return _findOneVersion({applicationId: data.applicationId, versionId: versionId}, 'contents');
+ })
+ .then(function(data) {
+ callback(null, data.contents);
+ })
+ .catch(function(err) {
+ callback(err);
+ })
+ ;
+};
+
+MongoConnection.prototype.getVersion = function(appId, versionId, callback) {
+ Version.findOne({
+ applicationId: appId,
+ versionId: versionId
+ }, callback);
+};
+
+MongoConnection.prototype.getVersions = function(appId, limit, offset, callback) {
+ if (offset == null) {
+ offset = 0;
+ }
+
+ if (limit <= 0) {
+ limit = 20;
+ }
+
+ Version
+ .find({
+ applicationId: appId
+ })
+ .limit(limit)
+ .skip(offset)
+ .exec(callback)
+ ;
+};
+
+MongoConnection.prototype.updateVersion = function(appId, versionId, params, callback) {
+ Version.findOneAndUpdate({
+ applicationId: appId,
+ versionId: versionId
+ },
+ params, {
+ upsert: true
+ }, callback);
+};
+
+MongoConnection.prototype.getApplications = function(limit, offset, callback) {
+ if (offset == null) {
+ offset = 0;
+ }
+
+ if (limit <= 0) {
+ limit = 20;
+ }
+
+ Application
+ .find({})
+ .limit(limit)
+ .skip(offset)
+ .exec(callback)
+ ;
+};
+
+MongoConnection.prototype.getApplication = function(appId, callback) {
+ Application.findOne({
+ applicationId: appId
+ }, callback);
+};
+
+MongoConnection.prototype.updateApplication = function(appId, params, callback) {
+ Application.findOneAndUpdate({
+ applicationId: appId
+ },
+ params, {
+ upsert: true
+ }, callback);
+};
+
+module.exports = MongoConnection;
diff --git a/pool/shard000/JavaScript/0002776_local.js b/pool/shard000/JavaScript/0002776_local.js
new file mode 100644
index 0000000000000000000000000000000000000000..3e69f36084e56305917f8206ccdecfd843ae32d7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002776_local.js
@@ -0,0 +1,436 @@
+'use strict';
+
+var Q = require('q'); /* jshint ignore:line */
+var _ = require('lodash'); /* jshint ignore:line */
+var Page = require('../../../../../base/Page'); /* jshint ignore:line */
+var deserialize = require(
+ '../../../../../base/deserialize'); /* jshint ignore:line */
+var values = require('../../../../../base/values'); /* jshint ignore:line */
+
+var LocalList;
+var LocalPage;
+var LocalInstance;
+
+/* jshint ignore:start */
+/**
+ * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList
+ * @description Initialize the LocalList
+ *
+ * @param {Twilio.Api.V2010} version - Version of the resource
+ * @param {string} accountSid -
+ * The 34 character string that uniquely identifies your account.
+ * @param {string} countryCode - The ISO Country code to lookup phone numbers for.
+ */
+/* jshint ignore:end */
+LocalList = function LocalList(version, accountSid, countryCode) {
+ /* jshint ignore:start */
+ /**
+ * @function local
+ * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext
+ * @instance
+ *
+ * @param {string} sid - sid of instance
+ *
+ * @returns {Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalContext}
+ */
+ /* jshint ignore:end */
+ function LocalListInstance(sid) {
+ return LocalListInstance.get(sid);
+ }
+
+ LocalListInstance._version = version;
+ // Path Solution
+ LocalListInstance._solution = {
+ accountSid: accountSid,
+ countryCode: countryCode
+ };
+ LocalListInstance._uri = _.template(
+ '/Accounts/<%= accountSid %>/AvailablePhoneNumbers/<%= countryCode %>/Local.json' // jshint ignore:line
+ )(LocalListInstance._solution);
+ /* jshint ignore:start */
+ /**
+ * Streams LocalInstance records from the API.
+ *
+ * This operation lazily loads records as efficiently as possible until the limit
+ * is reached.
+ *
+ * The results are passed into the callback function, so this operation is memory efficient.
+ *
+ * If a function is passed as the first argument, it will be used as the callback function.
+ *
+ * @function each
+ * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList
+ * @instance
+ *
+ * @param {object|function} opts - ...
+ * @param {number} [opts.areaCode] - The area_code
+ * @param {string} [opts.contains] - The contains
+ * @param {string} [opts.smsEnabled] - The sms_enabled
+ * @param {string} [opts.mmsEnabled] - The mms_enabled
+ * @param {string} [opts.voiceEnabled] - The voice_enabled
+ * @param {string} [opts.excludeAllAddressRequired] -
+ * The exclude_all_address_required
+ * @param {string} [opts.excludeLocalAddressRequired] -
+ * The exclude_local_address_required
+ * @param {string} [opts.excludeForeignAddressRequired] -
+ * The exclude_foreign_address_required
+ * @param {string} [opts.beta] - The beta
+ * @param {string} [opts.nearNumber] - The near_number
+ * @param {string} [opts.nearLatLong] - The near_lat_long
+ * @param {number} [opts.distance] - The distance
+ * @param {string} [opts.inPostalCode] - The in_postal_code
+ * @param {string} [opts.inRegion] - The in_region
+ * @param {string} [opts.inRateCenter] - The in_rate_center
+ * @param {string} [opts.inLata] - The in_lata
+ * @param {number} [opts.limit] -
+ * Upper limit for the number of records to return.
+ * each() guarantees never to return more than limit.
+ * Default is no limit
+ * @param {number} [opts.pageSize=50] -
+ * Number of records to fetch per request,
+ * when not set will use the default value of 50 records.
+ * If no pageSize is defined but a limit is defined,
+ * each() will attempt to read the limit with the most efficient
+ * page size, i.e. min(limit, 1000)
+ * @param {Function} [opts.callback] -
+ * Function to process each record. If this and a positional
+ * callback are passed, this one will be used
+ * @param {Function} [opts.done] -
+ * Function to be called upon completion of streaming
+ * @param {Function} [callback] - Function to process each record
+ */
+ /* jshint ignore:end */
+ LocalListInstance.each = function each(opts, callback) {
+ opts = opts || {};
+ if (_.isFunction(opts)) {
+ opts = { callback: opts };
+ } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) {
+ opts.callback = callback;
+ }
+
+ if (_.isUndefined(opts.callback)) {
+ throw new Error('Callback function must be provided');
+ }
+
+ var done = false;
+ var currentPage = 1;
+ var currentResource = 0;
+ var limits = this._version.readLimits({
+ limit: opts.limit,
+ pageSize: opts.pageSize
+ });
+
+ function onComplete(error) {
+ done = true;
+ if (_.isFunction(opts.done)) {
+ opts.done(error);
+ }
+ }
+
+ function fetchNextPage(fn) {
+ var promise = fn();
+ if (_.isUndefined(promise)) {
+ onComplete();
+ return;
+ }
+
+ promise.then(function(page) {
+ _.each(page.instances, function(instance) {
+ if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
+ done = true;
+ return false;
+ }
+
+ currentResource++;
+ opts.callback(instance, onComplete);
+ });
+
+ if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
+ onComplete();
+ } else if (!done) {
+ currentPage++;
+ fetchNextPage(_.bind(page.nextPage, page));
+ }
+ });
+
+ promise.catch(onComplete);
+ }
+
+ fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
+ };
+
+ /* jshint ignore:start */
+ /**
+ * @description Lists LocalInstance records from the API as a list.
+ *
+ * If a function is passed as the first argument, it will be used as the callback function.
+ *
+ * @function list
+ * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList
+ * @instance
+ *
+ * @param {object|function} opts - ...
+ * @param {number} [opts.areaCode] - The area_code
+ * @param {string} [opts.contains] - The contains
+ * @param {string} [opts.smsEnabled] - The sms_enabled
+ * @param {string} [opts.mmsEnabled] - The mms_enabled
+ * @param {string} [opts.voiceEnabled] - The voice_enabled
+ * @param {string} [opts.excludeAllAddressRequired] -
+ * The exclude_all_address_required
+ * @param {string} [opts.excludeLocalAddressRequired] -
+ * The exclude_local_address_required
+ * @param {string} [opts.excludeForeignAddressRequired] -
+ * The exclude_foreign_address_required
+ * @param {string} [opts.beta] - The beta
+ * @param {string} [opts.nearNumber] - The near_number
+ * @param {string} [opts.nearLatLong] - The near_lat_long
+ * @param {number} [opts.distance] - The distance
+ * @param {string} [opts.inPostalCode] - The in_postal_code
+ * @param {string} [opts.inRegion] - The in_region
+ * @param {string} [opts.inRateCenter] - The in_rate_center
+ * @param {string} [opts.inLata] - The in_lata
+ * @param {number} [opts.limit] -
+ * Upper limit for the number of records to return.
+ * list() guarantees never to return more than limit.
+ * Default is no limit
+ * @param {number} [opts.pageSize] -
+ * Number of records to fetch per request,
+ * when not set will use the default value of 50 records.
+ * If no page_size is defined but a limit is defined,
+ * list() will attempt to read the limit with the most
+ * efficient page size, i.e. min(limit, 1000)
+ * @param {function} [callback] - Callback to handle list of records
+ *
+ * @returns {Promise} Resolves to a list of records
+ */
+ /* jshint ignore:end */
+ LocalListInstance.list = function list(opts, callback) {
+ if (_.isFunction(opts)) {
+ callback = opts;
+ opts = {};
+ }
+ opts = opts || {};
+ var deferred = Q.defer();
+ var allResources = [];
+ opts.callback = function(resource, done) {
+ allResources.push(resource);
+
+ if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
+ done();
+ }
+ };
+
+ opts.done = function(error) {
+ if (_.isUndefined(error)) {
+ deferred.resolve(allResources);
+ } else {
+ deferred.reject(error);
+ }
+ };
+
+ if (_.isFunction(callback)) {
+ deferred.promise.nodeify(callback);
+ }
+
+ this.each(opts);
+ return deferred.promise;
+ };
+
+ /* jshint ignore:start */
+ /**
+ * Retrieve a single page of LocalInstance records from the API.
+ * Request is executed immediately
+ *
+ * If a function is passed as the first argument, it will be used as the callback function.
+ *
+ * @function page
+ * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList
+ * @instance
+ *
+ * @param {object|function} opts - ...
+ * @param {number} [opts.areaCode] - The area_code
+ * @param {string} [opts.contains] - The contains
+ * @param {string} [opts.smsEnabled] - The sms_enabled
+ * @param {string} [opts.mmsEnabled] - The mms_enabled
+ * @param {string} [opts.voiceEnabled] - The voice_enabled
+ * @param {string} [opts.excludeAllAddressRequired] -
+ * The exclude_all_address_required
+ * @param {string} [opts.excludeLocalAddressRequired] -
+ * The exclude_local_address_required
+ * @param {string} [opts.excludeForeignAddressRequired] -
+ * The exclude_foreign_address_required
+ * @param {string} [opts.beta] - The beta
+ * @param {string} [opts.nearNumber] - The near_number
+ * @param {string} [opts.nearLatLong] - The near_lat_long
+ * @param {number} [opts.distance] - The distance
+ * @param {string} [opts.inPostalCode] - The in_postal_code
+ * @param {string} [opts.inRegion] - The in_region
+ * @param {string} [opts.inRateCenter] - The in_rate_center
+ * @param {string} [opts.inLata] - The in_lata
+ * @param {string} [opts.pageToken] - PageToken provided by the API
+ * @param {number} [opts.pageNumber] -
+ * Page Number, this value is simply for client state
+ * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
+ * @param {function} [callback] - Callback to handle list of records
+ *
+ * @returns {Promise} Resolves to a list of records
+ */
+ /* jshint ignore:end */
+ LocalListInstance.page = function page(opts, callback) {
+ if (_.isFunction(opts)) {
+ callback = opts;
+ opts = {};
+ }
+ opts = opts || {};
+
+ var deferred = Q.defer();
+ var data = values.of({
+ 'AreaCode': _.get(opts, 'areaCode'),
+ 'Contains': _.get(opts, 'contains'),
+ 'SmsEnabled': _.get(opts, 'smsEnabled'),
+ 'MmsEnabled': _.get(opts, 'mmsEnabled'),
+ 'VoiceEnabled': _.get(opts, 'voiceEnabled'),
+ 'ExcludeAllAddressRequired': _.get(opts, 'excludeAllAddressRequired'),
+ 'ExcludeLocalAddressRequired': _.get(opts, 'excludeLocalAddressRequired'),
+ 'ExcludeForeignAddressRequired': _.get(opts, 'excludeForeignAddressRequired'),
+ 'Beta': _.get(opts, 'beta'),
+ 'NearNumber': _.get(opts, 'nearNumber'),
+ 'NearLatLong': _.get(opts, 'nearLatLong'),
+ 'Distance': _.get(opts, 'distance'),
+ 'InPostalCode': _.get(opts, 'inPostalCode'),
+ 'InRegion': _.get(opts, 'inRegion'),
+ 'InRateCenter': _.get(opts, 'inRateCenter'),
+ 'InLata': _.get(opts, 'inLata'),
+ 'PageToken': opts.pageToken,
+ 'Page': opts.pageNumber,
+ 'PageSize': opts.pageSize
+ });
+
+ var promise = this._version.page({
+ uri: this._uri,
+ method: 'GET',
+ params: data
+ });
+
+ promise = promise.then(function(payload) {
+ deferred.resolve(new LocalPage(
+ this._version,
+ payload,
+ this._solution
+ ));
+ }.bind(this));
+
+ promise.catch(function(error) {
+ deferred.reject(error);
+ });
+
+ if (_.isFunction(callback)) {
+ deferred.promise.nodeify(callback);
+ }
+
+ return deferred.promise;
+ };
+
+ return LocalListInstance;
+};
+
+
+/* jshint ignore:start */
+/**
+ * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalPage
+ * @augments Page
+ * @description Initialize the LocalPage
+ *
+ * @param {Twilio.Api.V2010} version - Version of the resource
+ * @param {object} response - Response from the API
+ * @param {object} solution - Path solution
+ *
+ * @returns LocalPage
+ */
+/* jshint ignore:end */
+LocalPage = function LocalPage(version, response, solution) {
+ // Path Solution
+ this._solution = solution;
+
+ Page.prototype.constructor.call(this, version, response, this._solution);
+};
+
+_.extend(LocalPage.prototype, Page.prototype);
+LocalPage.prototype.constructor = LocalPage;
+
+/* jshint ignore:start */
+/**
+ * Build an instance of LocalInstance
+ *
+ * @function getInstance
+ * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalPage
+ * @instance
+ *
+ * @param {object} payload - Payload response from the API
+ *
+ * @returns LocalInstance
+ */
+/* jshint ignore:end */
+LocalPage.prototype.getInstance = function getInstance(payload) {
+ return new LocalInstance(
+ this._version,
+ payload,
+ this._solution.accountSid,
+ this._solution.countryCode
+ );
+};
+
+
+/* jshint ignore:start */
+/**
+ * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalInstance
+ * @description Initialize the LocalContext
+ *
+ * @property {string} friendlyName - The friendly_name
+ * @property {string} phoneNumber - The phone_number
+ * @property {string} lata - The lata
+ * @property {string} rateCenter - The rate_center
+ * @property {number} latitude - The latitude
+ * @property {number} longitude - The longitude
+ * @property {string} region - The region
+ * @property {string} postalCode - The postal_code
+ * @property {string} isoCountry - The iso_country
+ * @property {string} addressRequirements - The address_requirements
+ * @property {string} beta - The beta
+ * @property {string} capabilities - The capabilities
+ *
+ * @param {Twilio.Api.V2010} version - Version of the resource
+ * @param {object} payload - The instance payload
+ */
+/* jshint ignore:end */
+LocalInstance = function LocalInstance(version, payload, accountSid,
+ countryCode) {
+ this._version = version;
+
+ // Marshaled Properties
+ this.friendlyName = payload.friendly_name; // jshint ignore:line
+ this.phoneNumber = payload.phone_number; // jshint ignore:line
+ this.lata = payload.lata; // jshint ignore:line
+ this.rateCenter = payload.rate_center; // jshint ignore:line
+ this.latitude = deserialize.decimal(payload.latitude); // jshint ignore:line
+ this.longitude = deserialize.decimal(payload.longitude); // jshint ignore:line
+ this.region = payload.region; // jshint ignore:line
+ this.postalCode = payload.postal_code; // jshint ignore:line
+ this.isoCountry = payload.iso_country; // jshint ignore:line
+ this.addressRequirements = payload.address_requirements; // jshint ignore:line
+ this.beta = payload.beta; // jshint ignore:line
+ this.capabilities = payload.capabilities; // jshint ignore:line
+
+ // Context
+ this._context = undefined;
+ this._solution = {
+ accountSid: accountSid,
+ countryCode: countryCode,
+ };
+};
+
+module.exports = {
+ LocalList: LocalList,
+ LocalPage: LocalPage,
+ LocalInstance: LocalInstance
+};
diff --git a/pool/shard000/JavaScript/0002779_transactions.js b/pool/shard000/JavaScript/0002779_transactions.js
new file mode 100644
index 0000000000000000000000000000000000000000..29996d7f6732cc5c96bef2325f1b929850ef7783
--- /dev/null
+++ b/pool/shard000/JavaScript/0002779_transactions.js
@@ -0,0 +1,28 @@
+import * as types from '../constants/ActionTypes';
+import checkStatus from '../utils/checkStatus';
+
+export function fetchTransactions(accessToken, accountId) {
+ return dispatch => {
+ fetch(`https://api.getmondo.co.uk/transactions?expand[]=merchant&account_id=${accountId}`, {
+ headers: { 'Authorization': `Bearer ${accessToken}` }
+ })
+ .then(checkStatus)
+ .then(response => response.json())
+ .then(json => {
+ const transactions = json.transactions
+ .map(transaction => {
+ transaction.created = new Date(transaction.created);
+ transaction.updated = new Date(transaction.updated);
+ if (transaction.settled) {
+ transaction.settled = new Date(transaction.settled);
+ }
+ return transaction;
+ });
+ dispatch(receiveTransactions(transactions));
+ });
+ };
+}
+
+function receiveTransactions(transactions) {
+ return { type: types.RECEIVE_TRANSACTIONS, transactions };
+}
diff --git a/pool/shard000/JavaScript/0002783_treeDataCreator.js b/pool/shard000/JavaScript/0002783_treeDataCreator.js
new file mode 100644
index 0000000000000000000000000000000000000000..17246a405776453dcf5c95fd7167e5022d999c86
--- /dev/null
+++ b/pool/shard000/JavaScript/0002783_treeDataCreator.js
@@ -0,0 +1,94 @@
+/* scenarioo-client
+ * Copyright (C) 2014, scenarioo.org Development Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * Transforms any nested object and array structure into a tree structure that can be used by our tree directive.
+ */
+angular.module('scenarioo.filters').filter('scTreeDataCreator', function () {
+
+ function createTreeData(data) {
+ if (angular.isUndefined(data)) {
+ return undefined;
+ }
+
+ if (angular.isString(data)) {
+ return {nodeLabel: data};
+ }
+
+ return transformNode(data, '');
+ }
+
+ function transformNode(node, nodeTitle) {
+ var transformedNode = {
+ nodeLabel: nodeTitle
+ };
+
+ if (angular.isArray(node)) {
+ transformedNode.childNodes = createArrayChildNodes(node);
+ } else if (angular.isObject(node)) {
+ transformedNode.childNodes = createObjectChildNodes(node);
+ } else if (angular.isString(node)) {
+ transformedNode = node;
+ }
+
+ return transformedNode;
+ }
+
+ function createObjectChildNodes(node) {
+ var childNodes = [];
+ angular.forEach(node, function (value, key) {
+ if (angular.isArray(value)) {
+ childNodes.push({
+ nodeLabel: key,
+ childNodes: createArrayChildNodes(value)
+ });
+ } else if (angular.isObject(value)) {
+ childNodes.push({
+ nodeLabel: key,
+ childNodes: createObjectChildNodes(value)
+ });
+ } else {
+ childNodes.push({
+ nodeLabel: key,
+ nodeValue: value
+ });
+ }
+ });
+
+ return childNodes;
+ }
+
+ function createArrayChildNodes(array) {
+ var childNodes = [];
+ angular.forEach(array, function (element) {
+ if (angular.isString(element)) {
+ childNodes.push({
+ nodeLabel: element
+ });
+ } else {
+ childNodes.push({
+ nodeLabel: '',
+ childNodes: createObjectChildNodes(element)
+ });
+ }
+ });
+
+ return childNodes;
+ }
+
+ return createTreeData;
+});
diff --git a/pool/shard000/JavaScript/0002784_runtimeshow.js b/pool/shard000/JavaScript/0002784_runtimeshow.js
new file mode 100644
index 0000000000000000000000000000000000000000..4a41983f3f30cbc04d3eff086ca896db3c90c62b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002784_runtimeshow.js
@@ -0,0 +1,16 @@
+// get user config
+var start_date = document.getElementById("runtionshow").getAttribute("start_date")
+
+function show_date_time() {
+ window.setTimeout("show_date_time()", 1000);
+ BirthDay=new Date(start_date);
+ today=new Date();
+ timeold=(today.getTime()-BirthDay.getTime());
+ msPerDay=24*60*60*1000
+ e_daysold=timeold/msPerDay
+ daysold=Math.floor(e_daysold);
+ webinfo_runtime_count.innerHTML= daysold + " " + GLOBAL_CONFIG.runtime_unit
+}
+
+show_date_time()
+
diff --git a/pool/shard000/JavaScript/0002787_fs_test.js b/pool/shard000/JavaScript/0002787_fs_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..ef496f01a3fbf00b10c7d51f0bbc4c0e03ea3d0d
--- /dev/null
+++ b/pool/shard000/JavaScript/0002787_fs_test.js
@@ -0,0 +1,55 @@
+// Copyright 2011 The Closure Library Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS-IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+goog.provide('goog.testing.fsTest');
+goog.setTestOnly('goog.testing.fsTest');
+
+goog.require('goog.testing.AsyncTestCase');
+goog.require('goog.testing.fs');
+goog.require('goog.testing.fs.Blob');
+goog.require('goog.testing.jsunit');
+
+var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
+
+function testObjectUrls() {
+ var blob = goog.testing.fs.getBlob('foo');
+ var url = goog.testing.fs.createObjectUrl(blob);
+ assertTrue(goog.testing.fs.isObjectUrlGranted(blob));
+ goog.testing.fs.revokeObjectUrl(url);
+ assertFalse(goog.testing.fs.isObjectUrlGranted(blob));
+}
+
+function testGetBlob() {
+ assertEquals(
+ new goog.testing.fs.Blob('foobarbaz').toString(),
+ goog.testing.fs.getBlob('foo', 'bar', 'baz').toString());
+ assertEquals(
+ new goog.testing.fs.Blob('foobarbaz').toString(),
+ goog.testing.fs.getBlob('foo', new goog.testing.fs.Blob('bar'), 'baz').
+ toString());
+}
+
+function testBlobToString() {
+ goog.testing.fs.blobToString(new goog.testing.fs.Blob('foobarbaz')).
+ addCallback(goog.partial(assertEquals, 'foobarbaz')).
+ addCallback(goog.bind(asyncTestCase.continueTesting, asyncTestCase));
+ asyncTestCase.waitForAsync('testBlobToString');
+}
+
+function testGetBlobWithProperties() {
+ assertEquals(
+ 'data:spam/eggs;base64,Zm9vYmFy',
+ new goog.testing.fs.getBlobWithProperties(
+ ['foo', new goog.testing.fs.Blob('bar')], 'spam/eggs').toDataUrl());
+}
diff --git a/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js b/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js
new file mode 100644
index 0000000000000000000000000000000000000000..3788d0f43359119ce8cbdfbec7061066e578c4fc
--- /dev/null
+++ b/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js
@@ -0,0 +1,72 @@
+/*!
+ * UI development toolkit for HTML5 (OpenUI5)
+ * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
+ * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
+ */
+
+// Provides default renderer for the sap.ui.ux3.OverlayContainer
+sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', './OverlayRenderer'],
+ function(jQuery, Renderer, OverlayRenderer) {
+ "use strict";
+
+/**
+ * OverlayContainer renderer.
+ * @namespace
+ */
+ var OverlayContainerRenderer = Renderer.extend(OverlayRenderer);
+
+ /**
+ * Renders the Overlay content
+ *
+ * @param {sap.ui.core.RenderManager}
+ * oRenderManager the RenderManager that can be used for writing to
+ * the Render-Output-Buffer
+ * @param {sap.ui.core.Control}
+ * oControl an object representation of the control that should be
+ * rendered
+ */
+ OverlayContainerRenderer.renderContent = function(oRenderManager, oControl) {
+ var rm = oRenderManager;
+ rm.write("");
+ var content = oControl.getContent();
+ for (var i = 0; i < content.length; i++) {
+ var control = content[i];
+ rm.renderControl(control);
+ }
+ rm.write("
");
+ };
+
+ /**
+ * Add root class to Overlay
+ *
+ * @param {sap.ui.core.RenderManager}
+ * oRenderManager the RenderManager that can be used for writing to
+ * the Render-Output-Buffer
+ * @param {sap.ui.core.Control}
+ * oControl an object representation of the control that should be
+ * rendered
+ */
+ OverlayContainerRenderer.addRootClasses = function(oRenderManager, oControl) {
+ var rm = oRenderManager;
+ rm.addClass("sapUiUx3OC");
+ };
+
+ /**
+ * Add class to Overlay
+ *
+ * @param {sap.ui.core.RenderManager}
+ * oRenderManager the RenderManager that can be used for writing to
+ * the Render-Output-Buffer
+ * @param {sap.ui.core.Control}
+ * oControl an object representation of the control that should be
+ * rendered
+ */
+ OverlayContainerRenderer.addOverlayClasses = function(oRenderManager, oControl) {
+ var rm = oRenderManager;
+ rm.addClass("sapUiUx3OCOverlay");
+ };
+
+
+ return OverlayContainerRenderer;
+
+}, /* bExport= */ true);
diff --git a/pool/shard000/JavaScript/0002803_index.js b/pool/shard000/JavaScript/0002803_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..de9d51dfa261dd1a57da7cbf55b092fdd63855a4
--- /dev/null
+++ b/pool/shard000/JavaScript/0002803_index.js
@@ -0,0 +1,101 @@
+"use strict";
+var fs = require("fs");
+var insert = require("insert-css");
+
+var Ractive = require("ractive");
+
+var getSize = require("bounding-client-rect");
+var getScrollbarWidth = require("scrollbar-width");
+var hasScrollbar = require("has-scrollbar");
+var debounce = require("debounce");
+
+var template = fs.readFileSync(__dirname + "/template.html", "utf8");
+var style = fs.readFileSync(__dirname + "/style.css", "utf8");
+
+insert(style);
+
+module.exports = Ractive.extend({
+ isolated: false,
+ template: template,
+ data: {
+ gridClass: "",
+ gridItems: [],
+ gridRows: 1,
+ gridColumns: 1,
+
+ gridSize: "0px",
+ gridMarginX: "0px",
+ gridMarginY: "0px",
+ },
+ oncomplete: oncomplete,
+
+ recalculate: recalculate,
+});
+
+function recalculate() {
+ // Get raw information about the state
+ var container = this.find(".rm-grid-container");
+ var size = getSize(container);
+ var gridRows = this.get("gridRows");
+ var gridColumns = this.get("gridColumns");
+ var isScrolling = gridRows === "scroll";
+
+ // Get certain dimensions
+ var containerWidth = size.width;
+ var containerHeight = size.height;
+ var itemWidth = containerWidth / +(gridColumns);
+ var itemHeight = containerHeight / +(gridRows);
+
+ if (isScrolling) {
+ // Calculate for vertical scrolling
+ var gridSize = itemWidth;
+ if (hasScrollbar(container))
+ gridSize = itemWidth - (getScrollbarWidth() / gridColumns);
+
+ this.set({
+ gridSize: gridSize + "px",
+ gridMarginX: "0px",
+ gridMarginY: "0px"
+ });
+ } else {
+ // Calculate for fitting perfectly
+ var padding = "0px";
+ if (gridRows === "scroll") {} else if (itemWidth > itemHeight) {
+ // Will pad on the sides
+ padding = (itemWidth - itemHeight) / 2;
+ this.set({
+ gridSize: itemHeight + "px",
+ gridMarginY: "0px",
+ gridMarginX: padding + "px"
+ });
+ } else {
+ // Will pad on top/bottom
+ padding = (itemHeight - itemWidth) / 2;
+ this.set({
+ gridSize: itemWidth + "px",
+ gridMarginY: padding + "px",
+ gridMarginX: "0px"
+ });
+ }
+ }
+}
+
+function oncomplete() {
+ listenResize(this);
+ this.on("teardown", unlistenResize.bind(null, this));
+
+ this.recalculate();
+}
+
+function unlistenResize(component) {
+ window.removeEventListener("resize", component._recalculate);
+}
+
+function listenResize(component) {
+ var listener = component._recalculate = debounce(recalculate.bind(component), 50);
+ window.addEventListener("resize", listener);
+ component.observe("gridRows", listener);
+ component.observe("gridColumns", listener);
+ component.observe("gridClass", listener);
+ component.observe("gridItems", listener);
+}
diff --git a/pool/shard000/JavaScript/0002806_cv-controller.js b/pool/shard000/JavaScript/0002806_cv-controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..91f37c6f8956f13d6e63c09e1a917a58ca1db92f
--- /dev/null
+++ b/pool/shard000/JavaScript/0002806_cv-controller.js
@@ -0,0 +1,25 @@
+angular.module('bitvagas.users.controllers')
+.controller('FreelancerController', FreelancerController)
+.controller('CVController', CVController);
+
+FreelancerController.$inject = ['$scope', 'FreelancerService'];
+CVController.$inject = ['$scope', '$state', '$stateParams', 'FreelancerService'];
+function CVController($scope, $state, $stateParams, FreelancerService){
+
+ var id = $stateParams.id || $scope.currentUser.id;
+ FreelancerService.findById(id).then(function(user){
+ $scope.user = user.data;
+ var linkedIn = user.data.LINKEDIN_TOKEN;
+ if(linkedIn) {
+ FreelancerService.getCV({ token : linkedIn}).then(function(data){
+ $scope.user.cv = data.data;
+ });
+ }
+ });
+}
+
+function FreelancerController ($scope, FreelancerService) {
+ FreelancerService.findAll().then(function(data){
+ $scope.freelancers = data.data;
+ });
+}
diff --git a/pool/shard000/JavaScript/0002811_friendlyDates.js b/pool/shard000/JavaScript/0002811_friendlyDates.js
new file mode 100644
index 0000000000000000000000000000000000000000..7d5ca24d39414dff47063483a7f76227916db1be
--- /dev/null
+++ b/pool/shard000/JavaScript/0002811_friendlyDates.js
@@ -0,0 +1,87 @@
+function makeFriendlyDates(arr) {
+ const months = [
+ 'January',
+ 'February',
+ 'March',
+ 'April',
+ 'May',
+ 'June',
+ 'July',
+ 'August',
+ 'September',
+ 'October',
+ 'November',
+ 'December'
+ ];
+
+ let date1 = arr[0].split('-'),
+ date2 = arr[1].split('-'),
+ year1 = parseInt(date1[0]),
+ year2 = parseInt(date2[0]),
+ month1 = parseInt(date1[1]),
+ month2 = parseInt(date2[1]),
+ day1 = parseInt(date1[2]),
+ day2 = parseInt(date2[2]),
+ curYear = 2016;
+
+ // eliminate redundancy
+ if(JSON.stringify(date1) === JSON.stringify(date2)) {
+ return [buildString(date1)];
+ } else if(year1 === curYear && year2 === curYear) {
+ if(month1 === month2) {
+ return [buildString(date1, true, false), buildString(date2, false, false)];
+ }
+ return [buildString(date1, true, false), buildString(date2, true, false)];
+ } else if (year2 - year1 < 1) {
+ if(month1 === month2) {
+ return [buildString(date1, true, false), buildString(date2, false, false)];
+ }
+ return [buildString(date1), buildString(date2, true, false)];
+ } else {
+ if(year1 === curYear && year2 === curYear + 1) {
+ if(month2 < month1) {
+ return [buildString(date1, true, false), buildString(date2, true, false)];
+ }
+ }
+ if(year2 - year1 === 1) {
+ if(month1 === month2 && day2 < day1) {
+ return [buildString(date1), buildString(date2, true, false)];
+ }
+ }
+ }
+
+ // default
+ return [buildString(date1), buildString(date2)];
+
+ function buildString(date, showMonth = true, showYear = true) {
+ let year = date[0],
+ month = months[parseInt(date[1]) - 1],
+ day = parseInt(date[2]),
+ ending = '',
+ lastDigit = parseInt(date[2][date[2].length - 1]);
+
+ switch(lastDigit) { //generate appropriate date ending
+ case 1:
+ ending += 'st';
+ break;
+ case 2:
+ if(day === 12) ending += 'th';
+ else ending += 'nd';
+ break;
+ case 3:
+ if(day === 13) ending += 'th';
+ else ending += 'rd';
+ break;
+ default:
+ ending += 'th';
+ }
+
+ if (!showMonth) {
+ return `${day}${ending}`;
+ } else if (!showYear) {
+ return `${month} ${day}${ending}`;
+ } else {
+ return `${month} ${day}${ending}, ${year}`;
+ }
+ }
+}
diff --git a/pool/shard000/JavaScript/0002813_hashchange.js b/pool/shard000/JavaScript/0002813_hashchange.js
new file mode 100644
index 0000000000000000000000000000000000000000..d3ed1adfe3faba4524d17ffcff62d24648f99a42
--- /dev/null
+++ b/pool/shard000/JavaScript/0002813_hashchange.js
@@ -0,0 +1,247 @@
+/*!
+ * jQuery hashchange event - v1.2 - 2/11/2010
+ * http://benalman.com/projects/jquery-hashchange-plugin/
+ *
+ * Copyright (c) 2010 "Cowboy" Ben Alman
+ * Dual licensed under the MIT and GPL licenses.
+ * http://benalman.com/about/license/
+ */
+
+// Script: jQuery hashchange event
+//
+// *Version: 1.2, Last updated: 2/11/2010*
+//
+// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
+// GitHub - http://github.com/cowboy/jquery-hashchange/
+// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
+// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (1.1kb)
+//
+// About: License
+//
+// Copyright (c) 2010 "Cowboy" Ben Alman,
+// Dual licensed under the MIT and GPL licenses.
+// http://benalman.com/about/license/
+//
+// About: Examples
+//
+// This working example, complete with fully commented code, illustrate one way
+// in which this plugin can be used.
+//
+// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
+//
+// About: Support and Testing
+//
+// Information about what version or versions of jQuery this plugin has been
+// tested with, what browsers it has been tested in, and where the unit tests
+// reside (so you can test it yourself).
+//
+// jQuery Versions - 1.3.2, 1.4.1, 1.4.2pre
+// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.1.
+// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
+//
+// About: Known issues
+//
+// While this jQuery hashchange event implementation is quite stable and robust,
+// there are a few unfortunate browser bugs surrounding expected hashchange
+// event-based behaviors, independent of any JavaScript window.onhashchange
+// abstraction. See the following examples for more information:
+//
+// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
+// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
+// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
+// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
+//
+// About: Release History
+//
+// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
+// from a page on another domain would cause an error in Safari 4. Also,
+// IE6/7 Iframe is now inserted after the body (this actually works),
+// which prevents the page from scrolling when the event is first bound.
+// Event can also now be bound before DOM ready, but it won't be usable
+// before then in IE6/7.
+// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
+// where browser version is incorrectly reported as 8.0, despite
+// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
+// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
+// window.onhashchange functionality into a separate plugin for users
+// who want just the basic event & back button support, without all the
+// extra awesomeness that BBQ provides. This plugin will be included as
+// part of jQuery BBQ, but also be available separately.
+
+(function($,window,undefined){
+ '$:nomunge'; // Used by YUI compressor.
+
+
+
+var is_old_ie = (function(){
+ if(!jQuery.support.leadingWhitespace){
+ oldIE = true;
+ }
+ })();
+
+ // Method / object references.
+ var fake_onhashchange,
+ jq_event_special = $.event.special,
+
+ // Reused strings.
+ str_location = 'location',
+ str_hashchange = 'hashchange',
+ str_href = 'href',
+
+
+ // Does the browser support window.onhashchange? Test for IE version, since
+ // IE8 incorrectly reports this when in "IE7" or "IE8 Compatibility View"!
+ supports_onhashchange = 'on' + str_hashchange in window && !is_old_ie;
+
+ // Get location.hash (or what you'd expect location.hash to be) sans any
+ // leading #. Thanks for making this necessary, Firefox!
+ function get_fragment( url ) {
+ url = url || window[ str_location ][ str_href ];
+ return url.replace( /^[^#]*#?(.*)$/, '$1' );
+ };
+
+ // Property: jQuery.hashchangeDelay
+ //
+ // The numeric interval (in milliseconds) at which the
+ // polling loop executes. Defaults to 100.
+
+ $[ str_hashchange + 'Delay' ] = 100;
+
+ // Event: hashchange event
+ //
+ // Fired when location.hash changes. In browsers that support it, the native
+ // window.onhashchange event is used (IE8, FF3.6), otherwise a polling loop is
+ // initialized, running every milliseconds to see if
+ // the hash has changed. In IE 6 and 7, a hidden Iframe is created to allow
+ // the back button and hash-based history to work.
+ //
+ // Usage:
+ //
+ // > $(window).bind( 'hashchange', function(e) {
+ // > var hash = location.hash;
+ // > ...
+ // > });
+ //
+ // Additional Notes:
+ //
+ // * The polling loop and Iframe are not created until at least one callback
+ // is actually bound to 'hashchange'.
+ // * If you need the bound callback(s) to execute immediately, in cases where
+ // the page 'state' exists on page load (via bookmark or page refresh, for
+ // example) use $(window).trigger( 'hashchange' );
+ // * The event can be bound before DOM ready, but since it won't be usable
+ // before then in IE6/7 (due to the necessary Iframe), recommended usage is
+ // to bind it inside a $(document).ready() callback.
+
+ jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], {
+
+ // Called only when the first 'hashchange' event is bound to window.
+ setup: function() {
+ // If window.onhashchange is supported natively, there's nothing to do..
+ if ( supports_onhashchange ) { return false; }
+
+ // Otherwise, we need to create our own. And we don't want to call this
+ // until the user binds to the event, just in case they never do, since it
+ // will create a polling loop and possibly even a hidden Iframe.
+ $( fake_onhashchange.start );
+ },
+
+ // Called only when the last 'hashchange' event is unbound from window.
+ teardown: function() {
+ // If window.onhashchange is supported natively, there's nothing to do..
+ if ( supports_onhashchange ) { return false; }
+
+ // Otherwise, we need to stop ours (if possible).
+ $( fake_onhashchange.stop );
+ }
+
+ });
+
+ // fake_onhashchange does all the work of triggering the window.onhashchange
+ // event for browsers that don't natively support it, including creating a
+ // polling loop to watch for hash changes and in IE 6/7 creating a hidden
+ // Iframe to enable back and forward.
+ fake_onhashchange = (function(){
+ var self = {},
+ timeout_id,
+ iframe,
+ set_history,
+ get_history;
+
+ // Initialize. In IE 6/7, creates a hidden Iframe for history handling.
+ function init(){
+ // Most browsers don't need special methods here..
+ set_history = get_history = function(val){ return val; };
+
+ // But IE6/7 do!
+ if ( is_old_ie ) {
+
+ // Create hidden Iframe after the end of the body to prevent initial
+ // page load from scrolling unnecessarily.
+ iframe = $('').hide().insertAfter( 'body' )[0].contentWindow;
+
+ // Get history by looking at the hidden Iframe's location.hash.
+ get_history = function() {
+ return get_fragment( iframe.document[ str_location ][ str_href ] );
+ };
+
+ // Set a new history item by opening and then closing the Iframe
+ // document, *then* setting its location.hash.
+ set_history = function( hash, history_hash ) {
+ if ( hash !== history_hash ) {
+ var doc = iframe.document;
+ doc.open().close();
+ doc[ str_location ].hash = '#' + hash;
+ }
+ };
+
+ // Set initial history.
+ set_history( get_fragment() );
+ }
+ };
+
+ // Start the polling loop.
+ self.start = function() {
+ // Polling loop is already running!
+ if ( timeout_id ) { return; }
+
+ // Remember the initial hash so it doesn't get triggered immediately.
+ var last_hash = get_fragment();
+
+ // Initialize if not yet initialized.
+ set_history || init();
+
+ // This polling loop checks every $.hashchangeDelay milliseconds to see if
+ // location.hash has changed, and triggers the 'hashchange' event on
+ // window when necessary.
+ (function loopy(){
+ var hash = get_fragment(),
+ history_hash = get_history( last_hash );
+
+ if ( hash !== last_hash ) {
+ set_history( last_hash = hash, history_hash );
+
+ $(window).trigger( str_hashchange );
+
+ } else if ( history_hash !== last_hash ) {
+ window[ str_location ][ str_href ] = window[ str_location ][ str_href ].replace( /#.*/, '' ) + '#' + history_hash;
+ }
+
+ timeout_id = setTimeout( loopy, $[ str_hashchange + 'Delay' ] );
+ })();
+ };
+
+ // Stop the polling loop, but only if an IE6/7 Iframe wasn't created. In
+ // that case, even if there are no longer any bound event handlers, the
+ // polling loop is still necessary for back/next to work at all!
+ self.stop = function() {
+ if ( !iframe ) {
+ timeout_id && clearTimeout( timeout_id );
+ timeout_id = 0;
+ }
+ };
+
+ return self;
+ })();
+
+})(jQuery,this);
diff --git a/pool/shard000/JavaScript/0002816_Firework.js b/pool/shard000/JavaScript/0002816_Firework.js
new file mode 100644
index 0000000000000000000000000000000000000000..3cc75e45e104a688c8d7875f15f456ef8806e4ff
--- /dev/null
+++ b/pool/shard000/JavaScript/0002816_Firework.js
@@ -0,0 +1,188 @@
+import {
+ Mesh,
+ MeshNormalMaterial,
+ Object3D,
+ Texture,
+ Points,
+ Vector3,
+ AdditiveBlending,
+ Color,
+ BufferGeometry,
+ BufferAttribute
+} from "three";
+
+import THREEShaderMaterial from "dlib/three/THREEShaderMaterial.js";
+import Particle from "dlib/physics/Particle.js";
+
+const PARTICLES_NUMBER = 1000;
+
+let TEXTURE;
+
+(function() {
+ let canvas = document.createElement("canvas");
+ canvas.width = 64;
+ canvas.height = 64;
+ let ctx = canvas.getContext("2d");
+ let gradient = ctx.createRadialGradient(32, 32, 32, 32, 32, 0);
+ gradient.addColorStop(0, "rgba(255, 255, 255, 0)");
+ gradient.addColorStop(.25, "rgba(255, 255, 255, 1)");
+ ctx.fillStyle = gradient;
+ ctx.fillRect(0, 0, 64, 64);
+
+ TEXTURE = new Texture(canvas);
+ TEXTURE.needsUpdate = true;
+})();
+
+export default class Firework extends Object3D {
+ constructor({color}) {
+ super();
+
+ this.particle = new Particle();
+ this.particle.dead = true;
+
+ let vertices = new Float32Array(PARTICLES_NUMBER * 3);
+ let opacities = new Float32Array(PARTICLES_NUMBER * 3);
+
+ let vector3 = new Vector3();
+ for (let i = 0; i < PARTICLES_NUMBER; i++) {
+ vector3.set(
+ Math.random() * 20 - 10,
+ Math.random() * 20 - 10,
+ Math.random() * 20 - 10
+ );
+ vector3.normalize();
+ vector3.multiplyScalar(.5 + Math.random() * .5);
+
+ vertices[i * 3] = vector3.x;
+ vertices[i * 3 + 1] = vector3.y;
+ vertices[i * 3 + 2] = vector3.z;
+
+ opacities[i] = .5 + .5 * Math.random();
+ }
+
+ let geometry = new BufferGeometry();
+ geometry.addAttribute("position", new BufferAttribute(vertices, 3));
+ geometry.addAttribute("vertexOpacity", new BufferAttribute(opacities, 1));
+ this.points = new Points(geometry, new THREEShaderMaterial({
+ type: "points",
+ transparent: true,
+ blending: AdditiveBlending,
+ depthTest: false,
+ depthWrite: false,
+ uniforms: {
+ diffuse: new Color(color),
+ size: 30,
+ opacity: 1,
+ map: TEXTURE
+ },
+ vertexShaderChunks: new Map([
+ ["start", `
+ #define USE_SIZEATTENUATION
+
+ varying vec3 vPosition;
+ varying vec3 vInitialPosition;
+ varying float vVertexOpacity;
+
+ uniform vec3 head;
+ uniform vec3 tail;
+ uniform float explosion;
+
+ attribute float vertexOpacity;
+ `],
+ [
+ "main", `
+ vec3 position = position;
+ vInitialPosition = position;
+ vVertexOpacity = vertexOpacity;
+
+ vec3 trailPosition = tail + (head - tail) * length(position) + position * .01;
+ trailPosition.x += cos(trailPosition.y * 10.) * .01;
+ trailPosition.z += sin(trailPosition.y * 10.) * .01;
+
+ vec3 explosionPosition = tail + distance(head, tail) * position * .5;
+
+ position = mix(trailPosition, explosionPosition, explosion);
+
+ vPosition = position;
+ `
+ ]
+ ]),
+ fragmentShaderChunks: new Map([
+ ["start", `
+ varying vec3 vPosition;
+ varying vec3 vInitialPosition;
+ varying float vVertexOpacity;
+
+ uniform vec3 head;
+ uniform vec3 tail;
+ uniform float explosion;
+ `],
+ [
+ "main", `
+ vec3 position = vPosition;
+
+ float opacity = opacity;
+ opacity *= smoothstep(0., mix(4., .5, explosion), distance(head, tail));
+ opacity *= vVertexOpacity;
+ opacity *= mix(1., .8 + ((cos((vPosition.y + length(vInitialPosition)) * 200.) + 1.) * .5) * .2, explosion);
+
+ vec3 diffuse = diffuse;
+ diffuse += .5 * mix(0., 1. - smoothstep(0., 4., distance(head, tail)), explosion);
+ diffuse += mix(0., ((cos((vPosition.y + length(vInitialPosition)) * 100.) + 1.) * .5) * .5, explosion);
+ `
+ ]
+ ])
+ }));
+ this.points.frustumCulled = false;
+ this.add(this.points);
+ }
+
+ reset() {
+ this.points.material.explosion = 0;
+ this.particle.dead = true;
+ this.particle.position.set({
+ x: 0,
+ y: 0,
+ z: 0
+ });
+ this.particle.velocity.set(0, 0, 0);
+ this.points.material.head.set(0, 0, 0);
+ this.points.material.tail.set(0, 0, 0);
+ }
+
+ launch() {
+ this.reset();
+ this.points.material.explosion = 0;
+ this.particle.position.set(0, 0 ,0);
+ this.particle.velocity.set((Math.random() - .5) * .05, .07 + Math.random() * .03, (Math.random() - .5) * .05);
+ this.particle.dead = false;
+ }
+
+ explode() {
+ this.points.material.explosion = 1;
+ this.particle.velocity.set(0, 0, .05 + Math.random() * .1);
+ this.particle.dead = false;
+ }
+
+ update() {
+ if(!this.particle.dead) {
+ this.particle.velocity.y -= this.points.material.explosion ? .0001 : .001;
+ }
+ this.particle.update();
+
+ if(!this.points.material.explosion && this.particle.velocity.y < 0) {
+ this.particle.dead = true;
+ if(this.points.material.tail.distanceTo(this.particle) < .01) {
+ this.explode();
+ }
+ }
+
+ this.points.material.head.copy(this.particle);
+
+ if(!this.points.material.explosion) {
+ this.points.material.tail.lerp(this.particle, (1. - this.particle.velocity.y / .1) * .2);
+ } else {
+ this.points.material.tail.y += (this.particle.y - this.points.material.tail.y) * .01;
+ }
+ }
+}
diff --git a/pool/shard000/JavaScript/0002818_custom-renderer.js b/pool/shard000/JavaScript/0002818_custom-renderer.js
new file mode 100644
index 0000000000000000000000000000000000000000..4d9e9efbddd956d3cd406b0ff8c3718c7f5937dd
--- /dev/null
+++ b/pool/shard000/JavaScript/0002818_custom-renderer.js
@@ -0,0 +1,66 @@
+import Ember from 'ember'
+const {RSVP} = Ember
+import {AbstractInput} from 'ember-frost-bunsen'
+import computed, {readOnly} from 'ember-computed-decorators'
+
+export default AbstractInput.extend({
+ classNames: ['frost-field'],
+ invalidNames: ['Donald Trump'],
+
+ fullName: '', // local cache used for validation later
+
+ init () {
+ this._super(...arguments)
+ // this component would like to validate it's own values
+ this.registerValidator(this)
+ },
+
+ // this method must be implemented in order to support validation on custom-renderers
+ validate () {
+ const result = {
+ value: {}
+ }
+
+ if (this.invalidNames.indexOf(this.get('fullName')) !== -1) {
+ result.value = {
+ errors: [
+ {message: 'Invalid name', path: '#/name'}
+ ],
+ warnings: []
+ }
+ }
+
+ return RSVP.resolve(result)
+ },
+
+ /* eslint-disable complexity */
+ @readOnly
+ @computed('transformedValue')
+ renderValue (name) {
+ if (!name) {
+ return ''
+ }
+
+ const first = name.first || ''
+ const last = name.last || ''
+ const space = this.get('trailingSpace') || name.last ? ' ' : ''
+
+ return `${first}${space}${last}`
+ },
+ /* eslint-enable complexity */
+
+ parseValue (target) {
+ // this saves the name to use for local validation because you can't rely on
+ // formValue to do validation against since it only updates after validation
+ this.set('fullName', target.value)
+ const parts = target.value.split(' ')
+ const trailingSpace = / $/.test(target.value)
+
+ this.set('trailingSpace', trailingSpace)
+
+ return {
+ first: parts[0],
+ last: (parts.length > 1) ? parts.slice(1).join(' ') : undefined
+ }
+ }
+})
diff --git a/pool/shard000/JavaScript/0002819_search.js b/pool/shard000/JavaScript/0002819_search.js
new file mode 100644
index 0000000000000000000000000000000000000000..ae7039493c660dbe8a35c49c29dde4a5077161b6
--- /dev/null
+++ b/pool/shard000/JavaScript/0002819_search.js
@@ -0,0 +1,139 @@
+/**
+ * Search controller.
+ *
+ * @desc This controller is the search controller.
+ * @param {!angular.Scope} $scope
+ * @constructor
+ */
+angular.module('app')
+ .controller('Search', ['$scope', '$interval', '$routeParams', '$location', 'Connection',
+ function($scope, $interval, $routeParams, $location, Connection) {
+
+ //alert('test');
+ $scope.searchPanel = true;
+ $scope.path = $location.path();
+ $scope.$emit('sidebar', false);
+
+ /**
+ * Establish message handlers
+ * @msg - message from websocket to pass on to handler
+ */
+
+ var listeners = Connection.$$listeners;
+
+ listeners.load_page = [];
+ Connection.$on('load_page', function(e, msg){ $scope.load_page(msg); });
+ Connection.$on('global_search_result', function(e, msg){ $scope.parse_search_result(msg); });
+ listeners.query_listing_result = [];
+ Connection.$on('query_listing_result', function(e, msg){ $scope.parse_query_listing_result(msg); });
+
+ $scope.searchNetwork = function() {
+
+ var query = {
+ 'type': 'search',
+ 'key': $scope.search
+ };
+ $scope.searching = $scope.search;
+
+ $scope.search_results = {};
+ $scope.awaitingQuery = $scope.search;
+ Connection.send('search', query);
+ $scope.search = "";
+ $scope.showDashboardPanel('search');
+
+ };
+
+ $scope.load_page = function(msg) {
+ console.log($location.search());
+ $('#dashboard-container').removeClass('col-sm-8').addClass('col-sm-12');
+ $scope.searchNetwork();
+ };
+
+ var getJsonFromUrl = function() {
+
+ console.log($routeParams);
+ return $routeParams.search;
+ //var query = location.search.substr(1);
+ //var result = {};
+ //query.split("&").forEach(function(part) {
+ // var item = part.split("=");
+ // result[item[0]] = decodeURIComponent(item[1]);
+ //});
+ //return result;
+ };
+
+ //var url_json = getJsonFromUrl();
+ $scope.search = $routeParams.search;
+ $scope.searchlabel = $routeParams.search;
+ $scope.searchNetwork();
+
+ //$scope.search = $scope.search.replace("+", " ");
+ console.log('Search term: ', $scope.search);
+
+ $scope.isEmpty = function(obj) {
+ for(var prop in obj) {
+ if(obj.hasOwnProperty(prop)) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+
+
+ $scope.parse_query_listing_result = function(msg) {
+
+ var contract_data = msg.listing[0];
+ var key = contract_data.key;
+ var contract_body = JSON.parse(contract_data.contract_body);
+ console.log(contract_body.Seller);
+
+ if(!(key in $scope.search_results)) {
+ $scope.search_results[key] = contract_body;
+ }
+
+ //$scope.search_results.push(contract_body);
+ console.log('Search Results', $scope.search_results);
+
+ };
+
+ $scope.search_results = {};
+ $scope.parse_search_result = function(msg) {
+ console.log('Global Search Result', msg);
+ var contract_data = msg.data;
+ contract_data.key = msg.key;
+ contract_data.rawContract = msg.rawContract;
+ contract_data.nickname = msg.nickname;
+
+ var contract_dupe = false;
+ $.each($scope.search_results, function(index, contract) {
+ if(contract.key == msg.key) {
+ contract_dupe = true;
+ }
+ });
+
+ if(!contract_dupe) {
+ $scope.search_results.push(contract_data);
+ }
+
+ $.each($scope.search_results, function(index, contract) {
+
+ if (jQuery.isEmptyObject(contract.Contract.item_images)) {
+ console.log('empty object');
+ contract.Contract.item_images = "img/no-photo.png";
+ }
+ });
+
+ console.log('Search Results', $scope.search_results);
+
+ if (!$scope.$$phase) {
+ $scope.$apply();
+ }
+ };
+
+ if (Connection.websocket.readyState == 1) {
+ $scope.load_page({});
+ }
+
+ }
+ ]);
diff --git a/pool/shard000/JavaScript/0002821_ActionFile.connect.js b/pool/shard000/JavaScript/0002821_ActionFile.connect.js
new file mode 100644
index 0000000000000000000000000000000000000000..4404b965d17d16cdd1786b56084c0c703c0f8658
--- /dev/null
+++ b/pool/shard000/JavaScript/0002821_ActionFile.connect.js
@@ -0,0 +1,65 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import cmf, { cmfConnect } from '@talend/react-cmf';
+import { ActionFile } from '@talend/react-components/lib/Actions';
+
+export function mapStateToProps(state, ownProps) {
+ if (!ownProps.actionId) {
+ return {};
+ }
+ return cmf.action.getActionInfo(
+ {
+ registry: cmf.registry.getRegistry(),
+ store: {
+ getState: () => state,
+ },
+ },
+ ownProps.actionId,
+ );
+}
+
+export function mergeProps(stateProps, dispatchProps, ownProps) {
+ const props = { ...ownProps, ...stateProps, ...dispatchProps };
+ delete props.actionId;
+ props.name = stateProps.name;
+ return props;
+}
+
+export function ContainerActionFile({ onChange, ...props }) {
+ const newProps = { ...props };
+ if (!onChange) {
+ newProps.onChange = (event, data) => {
+ if (props.actionCreator) {
+ props.dispatchActionCreator(props.actionCreator, event, data);
+ } else {
+ props.dispatch({
+ model: props.model,
+ ...props.payload,
+ file: data,
+ });
+ }
+ };
+ }
+ return ;
+}
+
+ContainerActionFile.displayName = 'ContainerActionFile';
+
+ContainerActionFile.propTypes = {
+ onChange: PropTypes.func,
+ actionCreator: PropTypes.string,
+ dispatch: PropTypes.func,
+ dispatchActionCreator: PropTypes.func,
+ model: PropTypes.object,
+ payload: PropTypes.object,
+};
+
+export default cmfConnect({
+ mapStateToProps,
+ mergeProps,
+ omitCMFProps: true,
+ withComponentRegistry: true,
+ withDispatch: true,
+ withDispatchActionCreator: true,
+ withComponentId: true,
+})(ContainerActionFile);
diff --git a/pool/shard000/JavaScript/0002823_amp-web-push-permission-dialog.js b/pool/shard000/JavaScript/0002823_amp-web-push-permission-dialog.js
new file mode 100644
index 0000000000000000000000000000000000000000..7a7670952adf60a7eac08ec5ad0cfd59a79d2063
--- /dev/null
+++ b/pool/shard000/JavaScript/0002823_amp-web-push-permission-dialog.js
@@ -0,0 +1,280 @@
+/**
+ * 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 {escapeCssSelectorIdent} from '#core/dom/css-selectors';
+import {parseQueryString, tryDecodeUriComponent} from '#core/types/string/url';
+
+import {NotificationPermission, StorageKeys} from './vars';
+import {WindowMessenger} from './window-messenger';
+
+import {getMode} from '../../../src/mode';
+import {parseUrlDeprecated} from '../../../src/url';
+
+/** @typedef {{
+ * debug: boolean,
+ * windowContext: (?Window|undefined),
+ * }}
+ */
+export let PermissionDialogOptions;
+
+/**
+ * @fileoverview
+ * The script for the web push notification permission dialog. This script will
+ * eventually live on the publisher's origin. It shows the notification prompt
+ * and forwards results to the AMP page.
+ */
+export class AmpWebPushPermissionDialog {
+ /** @param {PermissionDialogOptions} options */
+ constructor(options) {
+ /**
+ * Debug enables verbose logging for this page and the window and worker
+ * messengers
+ * @private {boolean}
+ */
+ this.debug_ = options && options.debug;
+
+ /**
+ * @private {!Window}
+ */
+ this.window_ = options.windowContext || window;
+
+ /**
+ * For communication between the AMP page and this helper iframe
+ * @private {./window-messenger.WindowMessenger}
+ */
+ this.ampMessenger_ = new WindowMessenger({
+ debug: this.debug_,
+ windowContext: this.window_,
+ });
+ }
+
+ /**
+ * Returns true if this permission dialog is loaded as a popup; returns false
+ * if the permission dialog was redirected to its current location.
+ * @return {boolean}
+ */
+ isCurrentDialogPopup() {
+ return !!this.window_.opener && this.window_.opener !== this.window_;
+ }
+
+ /**
+ * Wraps the browser Notification API requestPermission() in a promise.
+ * @return {!Promise}
+ */
+ requestNotificationPermission() {
+ return new Promise((resolve, reject) => {
+ try {
+ this.window_.Notification.requestPermission((permission) =>
+ resolve(permission)
+ );
+ } catch (e) {
+ reject(e);
+ }
+ });
+ }
+
+ /**
+ * Requests notification permissions and reports the result back to the AMP
+ *
+ * page.
+ *
+ * If this dialog was redirected instead of opened as a pop up, the page is
+ * redirected back.
+ *
+ * A DOM section with ID preload is visible (defaults to a spinning circle)
+ * while this script is downloading and running. The preload section is then
+ * hidden and the postload section is unhidden.
+ */
+ run() {
+ this.onCloseIconClick_();
+ this.storeNotificationPermission_();
+ this.showTargetPermissionSection_();
+ this.showPostloadSection_();
+ if (
+ this.window_.Notification.permission !== NotificationPermission.DENIED
+ ) {
+ this.onPermissionDefaultOrGranted_();
+ } else {
+ this.onPermissionDenied_();
+ }
+ }
+
+ /** @private */
+ onCloseIconClick_() {
+ const closeIcon = this.window_.document.querySelector('#close');
+
+ if (closeIcon) {
+ closeIcon.addEventListener('click', () => {
+ this.closeDialog();
+ });
+ }
+ }
+
+ /**
+ * Closes the popup or redirects the dialog back to the AMP page.
+ *
+ * @public
+ */
+ closeDialog() {
+ if (this.isCurrentDialogPopup()) {
+ this.window_.close();
+ } else {
+ const winLocation = this.window_.fakeLocation || this.window_.location;
+ const queryParams = parseQueryString(winLocation.search);
+ if (!queryParams['return']) {
+ throw new Error('Missing required parameter.');
+ }
+ const redirectLocation = tryDecodeUriComponent(queryParams['return']);
+ this.redirectToUrl(redirectLocation);
+ }
+ }
+
+ /** @private */
+ onPermissionDenied_() {
+ navigator.permissions
+ .query({name: 'notifications'})
+ .then((permissionStatus) => {
+ permissionStatus.onchange = () => {
+ this.storeNotificationPermission_();
+ switch (this.window_.Notification.permission) {
+ case NotificationPermission.DEFAULT:
+ case NotificationPermission.GRANTED:
+ this.onPermissionDefaultOrGranted_();
+ break;
+ }
+ };
+ });
+ }
+
+ /**
+ * Stores the notification permission in local storage for the helper frame to
+ * access later.
+ * @private
+ */
+ storeNotificationPermission_() {
+ this.window_.localStorage.setItem(
+ StorageKeys.NOTIFICATION_PERMISSION,
+ this.window_.Notification.permission
+ );
+ }
+
+ /** @private */
+ showTargetPermissionSection_() {
+ // Hide all permission sections first
+ const allSections = this.window_.document.querySelectorAll('[permission]');
+ for (let i = 0; i < allSections.length; i++) {
+ const section = allSections[i];
+ this.setDomElementVisibility_(section, false);
+ }
+
+ // Show the section that matches the current permission
+ const section = this.window_.document.querySelector(
+ `[permission=${escapeCssSelectorIdent(
+ this.window_.Notification.permission
+ )}]`
+ );
+
+ if (section) {
+ this.setDomElementVisibility_(section, true);
+ }
+ }
+
+ /** @private */
+ showPostloadSection_() {
+ // Hide all permission sections first
+ const preloadSection = this.window_.document.querySelector('#preload');
+ const postloadSection = this.window_.document.querySelector('#postload');
+
+ if (preloadSection && postloadSection) {
+ this.setDomElementVisibility_(preloadSection, false);
+ this.setDomElementVisibility_(postloadSection, true);
+ }
+ }
+
+ /**
+ * Toggles a predefined visiblity class name on the specified DOM element.
+ *
+ * @param {HtmlElement} domElement
+ * @param {boolean} isVisible
+ * @private
+ *
+ */
+ setDomElementVisibility_(domElement, isVisible) {
+ if (!domElement) {
+ return;
+ }
+
+ const invisibilityCssClassName = 'invisible';
+
+ if (isVisible) {
+ domElement.classList.remove(invisibilityCssClassName);
+ } else {
+ domElement.classList.add(invisibilityCssClassName);
+ }
+ }
+
+ /**
+ * @private
+ * @return {*} TODO(#23582): Specify return type
+ */
+ onPermissionDefaultOrGranted_() {
+ // Prompt for permissions
+ return this.requestNotificationPermission().then((permission) => {
+ this.storeNotificationPermission_();
+ if (this.isCurrentDialogPopup()) {
+ this.ampMessenger_.connect(opener, '*');
+
+ return this.ampMessenger_
+ .send(
+ WindowMessenger.Topics.NOTIFICATION_PERMISSION_STATE,
+ permission
+ )
+ .then((result) => {
+ const message = result[0];
+ if (message && message.closeFrame) {
+ this.closeDialog();
+ }
+ });
+ } else {
+ this.closeDialog();
+ }
+ });
+ }
+
+ /**
+ * Redirects the top-level frame to another URL.
+ *
+ * This is wrapped as a method for testing purposes, because window.location
+ * cannot be mocked.
+ * @param {string} url
+ */
+ redirectToUrl(url) {
+ const parsedUrl = parseUrlDeprecated(url);
+ if (
+ parsedUrl &&
+ (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:')
+ ) {
+ this.window_.location.href = url;
+ }
+ }
+}
+
+if (!getMode().test) {
+ window._ampWebPushPermissionDialog = new AmpWebPushPermissionDialog({
+ debug: false,
+ });
+ window._ampWebPushPermissionDialog.run();
+}
diff --git a/pool/shard000/JavaScript/0002824_helpers.js b/pool/shard000/JavaScript/0002824_helpers.js
new file mode 100644
index 0000000000000000000000000000000000000000..00a5b332a104b9c8aa554ed57dbfe9cd52d437b1
--- /dev/null
+++ b/pool/shard000/JavaScript/0002824_helpers.js
@@ -0,0 +1,140 @@
+/**
+ * Copyright (c) 2012 Andreas Madsen
+ * MIT License
+ */
+
+(function () {
+ "use strict";
+
+ var fs = require('fs');
+ var path = require('path');
+ var util = require('util');
+ var events = require('events');
+
+ // exists path (path.exists was moved to fs.exists in node 0.7)
+ exports.exists = fs.exists || path.exists;
+
+ // common directorys
+ exports.root = path.join(path.dirname(module.filename), '../');
+ exports.lib = path.join(exports.root, 'lib');
+
+ // get a core module
+ exports.core = function (name) {
+ return require(path.join(exports.lib, 'core', name + '.js'));
+ };
+
+ // get a executable path
+ exports.executable = function (name) {
+ return path.join(exports.lib, 'executables', name);
+ };
+
+ // parse the node version
+ var version = exports.version = process.version.split(/[^0-9]+/)
+ .filter(function (val) { return (val !== ''); })
+ .map(function (val) { return parseInt(val, 10); });
+
+ // support detection using version
+ exports.support = {
+ detached: version[0] >= 1 || version[1] >= 8,
+ disconnect: version[0] >= 1 || version[1] >= 8,
+ close: version[0] >= 1 || version[1] >= 8,
+ pipeFork: version[0] >= 1 || version[1] >= 8
+ };
+
+ // Simple progress tracker, will execute callback when .list is empty
+ function ProgressTracker(callback) {
+ this.list = [];
+ this.callback = callback;
+ }
+ ProgressTracker.prototype.add = function(track) {
+ this.list = this.list.concat(track);
+ };
+ ProgressTracker.prototype.set = function(what) {
+ var index = this.list.indexOf(what);
+ if (index === -1) return;
+ this.list.splice(index, 1);
+ this.check();
+ };
+ ProgressTracker.prototype.check = function() {
+ if (this.list.length === 0 && this.callback) {
+ this.callback();
+ }
+ };
+ exports.ProgressTracker = ProgressTracker;
+
+ // convert arguments to an array
+ exports.toArray = function (args) {
+ return Array.prototype.slice.call(args);
+ };
+
+ // merge/copy objects
+ exports.mergeObject = function (to, from) {
+ for (var key in from) {
+ to[key] = from[key];
+ }
+ return to;
+ };
+
+ // check if process is alive
+ exports.alive = function(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ };
+
+ // continusely check if process alive
+ // and execute callback when the process is missing
+ function ProcessWatcher(pid, parent) {
+ var self = this;
+
+ this.dead = false;
+
+ // check first if process is alive
+ if (exports.alive(pid) === false) {
+ process.nextTick(function () {
+ self.dead = true;
+ self.emit('dead');
+ });
+ return self;
+ }
+
+ // use disconnect to detect parent death
+ if (parent && exports.support.disconnect) {
+ var listen = function() {
+ self.dead = true;
+ self.stop();
+ self.emit('dead');
+ }
+
+ parent.once('disconnect', listen);
+ this.stop = parent.removeListener.bind(null, 'disconnect', listen);
+
+ this.on('newListener', function (eventName) {
+ if (eventName !== 'cycle') return;
+
+ process.nextTick(function () {
+ self.emit('cycle');
+ });
+ });
+
+ return self;
+ }
+
+ // fallback to an setInterval try/catch check
+ var timer = setInterval(function () {
+ if (exports.alive(pid) === false) {
+ self.dead = true;
+ self.stop();
+ self.emit('dead');
+ }
+ self.emit('cycle');
+ });
+ this.stop = clearInterval.bind(null, timer);
+ }
+ util.inherits(ProcessWatcher, events.EventEmitter);
+ exports.ProcessWatcher = ProcessWatcher;
+
+})();
diff --git a/pool/shard000/JavaScript/0002829_text_2d.js b/pool/shard000/JavaScript/0002829_text_2d.js
new file mode 100644
index 0000000000000000000000000000000000000000..dcccff3e4761d156b10b2a41f18241d2f29266cf
--- /dev/null
+++ b/pool/shard000/JavaScript/0002829_text_2d.js
@@ -0,0 +1,243 @@
+$_QE.prototype.Text2D = function(args) {
+ /*this.set_dimensions(width, height);
+ let w = QE.manager_text2D.get_text_width(text, font);
+ l('The needed width is {' + w + '}');*/
+
+ this.__init__text2d(args);
+
+ if (this._arg_is_on(args, ARG_INTERACTIVE)) {
+ $_QE.prototype.FeatureTyping.call(this);
+ }
+};
+
+
+Object.assign(
+ $_QE.prototype.Text2D.prototype,
+ $_QE.prototype.FloatingElementText.prototype,
+ $_QE.prototype.DomCanvasTexture.prototype,
+ $_QE.prototype.CanvasRenderingTextLine.prototype,
+ {
+ constructor: $_QE.prototype.Text2D,
+
+ __init__text2d: function(args) {
+ args[ARG_GEOMETRY_TYPE] = FEATURE_GEOMETRY_TYPE_PLANE;
+ args[ARG_MATERIAL_TYPE] = FEATURE_MATERIAL_CANVAS_BASIC;
+ args[ARG_MESH_TYPE] = FEATURE_MESH_TYPE_DEFAULT;
+ args[ARG_COLOR_DEFAULT_FOREGROUND] = QE.COLOR_RGB_GREEN_LIGHT;
+ args[ARG_COLOR_DEFAULT_BACKGROUND] = QE.COLOR_RGBA_TRANSPARENT;
+ args[ARG_NUMBER_OF_ROWS] = -1;
+
+ this.__init__floating_element();
+ this.__init__canvas_texture(args);
+ this._parse_arguments_engine(args);
+ this._parse_arguments_color(args);
+ this._parse_arguments_text(args);
+ this._parse_arguments_floating_element(args);
+ this.set_value_post_changed_event(this._on_text_change.bind(this));
+ },
+
+ _on_text_change: function(text) {
+ this.set_row_text(text);
+ if (this.attachment_parent != null) {
+ this.attachment_parent.flag_set_on(EFLAG_IS_UPDATED_NEEDED_FOR_CHILD);
+ }
+ },
+
+ create: function() {
+ this._create_engine_objects();
+
+ this._force_refresh();
+
+ let self = this;
+ this.set_event(ELEMENT_EVENT_ON_FOREGROUND_COLOR, function() {
+ self._render_needed = true;
+ if (self.attachment_parent != null) {
+ self.attachment_parent.flag_set_on(EFLAG_IS_UPDATED_NEEDED_FOR_CHILD);
+ }
+ });
+ this.set_event(ELEMENT_EVENT_ON_BACKGROUND_COLOR, function() {
+ self._render_needed = true;
+ if (self.attachment_parent != null) {
+ self.attachment_parent.flag_set_on(EFLAG_IS_UPDATED_NEEDED_FOR_CHILD);
+ }
+ });
+ },
+
+ // Temporary solution.
+ _force_refresh: function() {
+ let t = this.text;
+ this.update_text('');
+ this.update_text(t);
+ },
+ }
+);
+
+
+/*
+$_QE.prototype.Text2DUtilities = function() {
+ this.canvas = new $_QE.prototype.CanvasAbstraction();
+ this.get_width_needed = function(text, height, bold, italic) {
+ if (is_defined(bold)) {
+ this.canvas.set_font_property_bold(bold);
+ }
+ if (is_defined(italic)) {
+ this.canvas.set_font_property_italic(italic);
+ }
+ this.canvas._set_height(height);
+ this.canvas.set_font();
+ return this.canvas.get_text_width(text);
+ };
+};
+
+const _MANAGER_TEXT_2D = new $_QE.prototype.Text2DUtilities();
+*/
+
+/*
+$_QE.prototype.Text2D = function(world, width, height, text, cacheable, cacheable_texture) {
+
+ // Inherit.
+ $_QE.prototype.FloatingElement.call(this, world);
+ $_QE.prototype.FeatureText.call(this, text);
+
+ this.cacheable = cacheable;
+ if (is_defined(cacheable_texture)) {
+ this.cacheable_texture = cacheable_texture;
+ } else {
+ this.cacheable_texture = false;
+ }
+
+ this.width = width;
+ this.height = height;
+ this.dynamic_width = false;
+
+ if (!this.cacheable_texture) {
+ this.canvas = new $_QE.prototype.CanvasTexture();
+ }
+ //this.canvas = new CanvasTexture();
+
+ this.initialized = false;
+ this.needs_hex_colors = true;
+
+ this.refresh = function() {
+ if (this.initialized) {
+ if (this.dynamic_width) {
+ if (this.text_changed) {
+ this.width = null;
+ this.process_width();
+ if (!this.cacheable_texture) {
+ this.canvas.modify_canvas(this.width, this.height);
+ }
+ this.delete_mesh();
+ this.delete_material();
+ this.create_base_material();
+ this.create_base_mesh();
+
+ // Update horizontal offset if needed.
+ if (this.is_attached()) {
+ if (this.is_left_attachment) {
+ this.set_attachment_horizontal_distance_offset(-this.width / 2);
+ } else if (this.is_right_attachment) {
+ this.set_attachment_horizontal_distance_offset(this.width / 2);
+ }
+ this.attachment_parent.refresh_position_and_look_at();
+ }
+ }
+ }
+
+ if (!this.cacheable_texture) {
+ this.canvas.update(this.get_current_background_color(), this.get_current_foreground_color(), this.get_display_text());
+ this.material.needsUpdate = true;
+ } else {
+ //this._material.needsUpdate = true;
+ }
+
+ this.text_changed = false;
+ this.color_changed = false;
+ }
+ };
+
+ // Creation
+ this.process_width = function() {
+ if (!is_defined(this.width)) {
+ this._original_text_width = _MANAGER_TEXT_2D.get_width_needed(this.get_display_text(), this.height);
+ this.width = math_get_nearest_power_of_two(this._original_text_width);
+ this.dynamic_width = true;
+ this.ratio = this._original_text_width / (QE.get_next_highest_power_of_two(this.width * 2));
+ } else {
+ this.ratio = 1;
+ }
+ };
+
+ this.initialize = function() {
+ this.process_width();
+
+ if (!this.cacheable_texture) {
+ this.canvas.set_dimensions(this.width, this.height);
+ this.canvas.initialize();
+ } else {
+ this.canvas_cache = QE.manager_heap.get_text_2D_canvas(this.width, this.height, this.get_display_text(), this.get_current_background_color(), this.get_current_foreground_color());
+ }
+
+ this.create_base_material();
+ this.create_base_mesh();
+ this.initialized = true;
+ this.refresh();
+ };
+
+ this.create_base_material = function() {
+ if (this.cacheable_texture) {
+ this._material = QE.manager_heap.get_text_2D_material(this.width, this.height, this.get_display_text());
+ } else {
+ this.material = new THREE.MeshToonMaterial({
+ map : this.canvas.texture, transparent: true, side: THREE.FrontSide
+ });
+ this.material.transparent = true;
+ this.material.side = THREE.FrontSide;
+ }
+ };
+
+ this._create_base_mesh = function(geometry) {
+ if (is_defined(geometry)) {
+ if (this.cacheable_texture) {
+ this.mesh = new THREE.Mesh(geometry, this._material);
+ } else {
+ this.mesh = new THREE.Mesh(geometry, this.material);
+ }
+ } else {
+ if (this.dynamic_width) {
+ this.geometry = new THREE.PlaneGeometry(this.width, this.height);
+
+ this.geometry.faceVertexUvs[0][0][2].x = this.ratio;
+ this.geometry.faceVertexUvs[0][1][1].x = this.ratio;
+ this.geometry.faceVertexUvs[0][1][2].x = this.ratio;
+
+ this.geometry.uvsNeedUpdate = true;
+ } else {
+ this.geometry = new THREE.PlaneGeometry(this.width, this.height);
+ }
+ if (this.cacheable_texture) {
+ this.mesh = new THREE.Mesh(this.geometry, this._material);
+ } else {
+ this.mesh = new THREE.Mesh(this.geometry, this.material);
+ }
+ }
+ this.object3D.add(this.mesh);
+ };
+
+ this.create_base_mesh = function() {
+ if (this.dynamic_width) {
+ this.width *= this.ratio;
+ }
+
+ if (is_defined(this.cacheable)) {
+ if (this.cacheable) {
+ this._create_base_mesh(MANAGER_HEAP.get_text_2D_geometry(this.width, this.height, this.ratio));
+ } else {
+ this._create_base_mesh(null);
+ }
+ } else {
+ this._create_base_mesh(null);
+ }
+ };
+};
+*/
diff --git a/pool/shard000/JavaScript/0002831_fast.js b/pool/shard000/JavaScript/0002831_fast.js
new file mode 100644
index 0000000000000000000000000000000000000000..67a7901fac2eceb6ce9d25124d1ca46fb67074ef
--- /dev/null
+++ b/pool/shard000/JavaScript/0002831_fast.js
@@ -0,0 +1,16 @@
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ define(factory);
+ } else if (typeof exports === 'object') {
+ module.exports = factory();
+ } else {
+ // Browser globals (root is window)
+ root.r_fast_r_furious = factory();
+ }
+}(this, function () {
+ var r_fast = /^((T(he)(?=.*the)|2(?=.* 2)) )?Fast (Five|(((and t\3)|\2(?=.*s$)|&(?!.*:)) Furious(( (6|7))|: Tokyo Drift)?))$/;
+
+ return function (str) {
+ return r_fast.test(str);
+ }
+}));
diff --git a/pool/shard000/JavaScript/0002832_baiduMap.js b/pool/shard000/JavaScript/0002832_baiduMap.js
new file mode 100644
index 0000000000000000000000000000000000000000..57ba8d3d74d9b7849a0ca64a4e79a5cc72d5fef9
--- /dev/null
+++ b/pool/shard000/JavaScript/0002832_baiduMap.js
@@ -0,0 +1,125 @@
+/**
+ * 百度地图JS封装
+ */
+
+var marker;
+var map = new BMap.Map("baiduMap");
+map.enableScrollWheelZoom(); //启用滚轮放大缩小,默认禁用
+map.enableContinuousZoom(true); //启用地图惯性拖拽,默认禁用
+map.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件
+map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
+map.addControl(new BMap.OverviewMapControl({ isOpen: false, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); //右下角,打开
+map.centerAndZoom("杭州市",11);
+map.panBy(305,165);
+//map.centerAndZoom("成都市",12);
+//map.setCurrentCity("成都市");// 设置地图显示的城市 此项是必须设置的
+var localSearch = new BMap.LocalSearch(map);
+//localSearch.enableAutoViewport(); //允许自动调节窗体大小
+function initMap(){
+ map.addEventListener("click",function(e){//手动标注地理信息
+ putIconIntoMap(e.point.lng, e.point.lat, "images/curlocation.png", 30, 30, null);
+ var gc = new BMap.Geocoder();
+ //获取地址的数据地址
+ gc.getLocation(e.point, function(rs){
+ var addComp = rs.addressComponents;
+ var lat=e.point.lat;
+ var lng=e.point.lng;
+ var address=addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
+ document.getElementById("address").value =address;
+ $("#lat").val(lat);
+ $("#lng").val(lng);
+ $("#locationName").val(address);
+ });
+ });
+};
+function searchByStationName() {
+ map.clearOverlays();//清空原来的标注
+ var keyword = document.getElementById("address").value;
+ if(keyword == "" || keyword == undefined){
+ keyword ="杭州市";
+ }
+ localSearch.setSearchCompleteCallback(function (searchResult) {
+ var poi = searchResult.getPoi(0);
+ $("#lat").val(poi.point.lat);
+ $("#lng").val(poi.point.lng);
+ $("#locationName").val(keyword);
+ map.centerAndZoom(poi.point, 13);
+ putIconIntoMap(poi.point.lng,poi.point.lat, "images/curlocation.png", 30, 30, null);//绘制苗点
+ });
+ localSearch.search(keyword);
+}
+
+/**
+ *
+ * @param lng 经度
+ * @param lat 维度
+ * @param pic 图标路径
+ * @param w 图标宽度
+ * @param h 图标高度
+ * @param func 点击事件
+ */
+function putIconIntoMap(lng,lat, pic, w, h, func){
+ map.removeOverlay(marker);
+ var pt = new BMap.Point(lng, lat);
+ var myIcon = new BMap.Icon(pic, new BMap.Size(w, h));
+ marker = new BMap.Marker(pt,{icon:myIcon}); // 创建标注
+ marker.addEventListener("click", func);
+ map.addOverlay(marker); // 将标注添加到地图中
+ var content = document.getElementById("address").value + " 经度:" + lng + " 纬度:" + lat;
+ var infoWindow = new BMap.InfoWindow("" + content + "
");
+ marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); });
+ marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
+}
+/*var marker2;
+ //百度地图API功能
+ var map = new BMap.Map("baiduMap"); // 创建Map实例
+
+ function init(){
+ //map.centerAndZoom(new BMap.Point(106.558099,29.569741), 12); // 初始化地图,设置中心点坐标和地图级别
+ map.centerAndZoom(new BMap.Point(104.070354,30.683673), 12); // 初始化地图,设置中心点坐标和地图级别
+ map.panBy(305,165);
+ var anchorCtrl = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT});// 右下角,添加比例尺
+ map.addControl(anchorCtrl);
+ map.addControl(new BMap.NavigationControl()); //左上角,添加默认缩放平移控件
+ map.setCurrentCity("成都"); // 设置地图显示的城市 此项是必须设置的
+
+ map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
+
+ map.addEventListener("click",function(e){
+ putIconIntoMap(e.point.lng, e.point.lat, "../images/curlocation.png", 30, 30, null);
+ var gc = new BMap.Geocoder();
+ //获取地址的数据地址
+ gc.getLocation(e.point, function(rs){
+ var addComp = rs.addressComponents;
+ var lat=e.point.lat;
+ var lng=e.point.lng;
+ var address=addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
+ //document.getElementById("address").value =address+"("+lat+","+lng+")";
+ document.getElementById("address").value =address;
+ $("#lat").val(lat);
+ $("#lng").val(lng);
+ $("#t_lat").val(lat);
+ $("#t_lng").val(lng);
+ $("#locationName").val(address);
+ });
+ });
+
+ }
+
+
+ *//**
+ *
+ * @param lng 经度
+ * @param lat 维度
+ * @param pic 图标路径
+ * @param w 图标宽度
+ * @param h 图标高度
+ * @param func 点击事件
+ */
+//function putIconIntoMap(lng,lat, pic, w, h, func){
+// var pt = new BMap.Point(lng, lat);
+// var myIcon = new BMap.Icon(pic, new BMap.Size(w, h));
+// var marker2 = new BMap.Marker(pt,{icon:myIcon}); // 创建标注
+// marker2.addEventListener("click", func);
+// map.addOverlay(marker2); // 将标注添加到地图中
+//}
diff --git a/pool/shard000/JavaScript/0002833_produce.js b/pool/shard000/JavaScript/0002833_produce.js
new file mode 100644
index 0000000000000000000000000000000000000000..b9bc1f5d8e2211822f47471c8d392b5f64864298
--- /dev/null
+++ b/pool/shard000/JavaScript/0002833_produce.js
@@ -0,0 +1,51 @@
+var Producer = require('./Producer')
+var optimist = require('optimist')
+ .usage('Consume a topic from the most recent message\nUsage: $0')
+ .options('h', {
+ alias: 'host',
+ default: 'localhost'
+ })
+ .options('p', {
+ alias: 'port',
+ default: '9092',
+ })
+ .options('t', {
+ alias: 'topic',
+ default: 'testtopic'
+ })
+ .options('m', {
+ alias: 'message',
+ default: 'hello world'
+ })
+ .options('r', {
+ alias: 'repeat-interval',
+ default: '0'
+ })
+var argv = optimist.argv
+
+if (argv.help) {
+ optimist.showHelp(console.error)
+ process.exit()
+}
+
+var producer = new Producer({
+ host: argv.host,
+ port: argv.port })
+
+var f = function() {
+ console.error("Sending to topic: " + argv.topic + " msg: " + argv.message)
+ producer.send(argv.topic, argv.message)
+}
+
+producer.on('connecting', function(address) {
+ console.error("Connecting to " + address + "...")
+})
+producer.on('connected', function(address) {
+ console.error('Connected to ' + address)
+ if (argv.r > 0) setInterval(f, argv.r)
+ f()
+})
+producer.on('disconnected', function(address) {
+ console.error('Disconnected from ' + address)
+})
+producer.connect()
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002840_create-test.js b/pool/shard000/JavaScript/0002840_create-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..ba49a9491e04fc33b5e7d0468db44b4532695e79
--- /dev/null
+++ b/pool/shard000/JavaScript/0002840_create-test.js
@@ -0,0 +1,59 @@
+import Schema from 'ember-cli-mirage/orm/schema';
+import Model from 'ember-cli-mirage/orm/model';
+import Db from 'ember-cli-mirage/db';
+import {module, test} from 'qunit';
+
+var schema;
+module('Integration | Schema | Creating an Unregistered Model', {
+ beforeEach: function() {
+ schema = new Schema(new Db());
+ }
+});
+
+test('it cannot make new models that havent been registered', function(assert) {
+ assert.throws(function() {
+ schema.user.new({name: 'Link'});
+ });
+});
+
+test('it cannot create models that havent been registered', function(assert) {
+ assert.throws(function() {
+ schema.user.create({name: 'Link'});
+ });
+});
+
+
+var db, schema, User;
+module('Integration | Schema | Creating a Model', {
+ beforeEach: function() {
+ db = new Db();
+
+ User = Model.extend();
+ schema = new Schema(db, {
+ user: User
+ });
+ }
+});
+
+test('it can make new models and then save them', function(assert) {
+ var user = schema.user.new({name: 'Link'});
+
+ assert.ok(user instanceof User);
+ assert.deepEqual(user.attrs, {name: 'Link'});
+ assert.deepEqual(db.users, []);
+
+ user.save();
+
+ assert.ok(user.id, 'user has an id getter');
+ assert.deepEqual(user.attrs, {id: '1', name: 'Link'});
+ assert.deepEqual(db.users, [{id: '1', name: 'Link'}]);
+});
+
+test('it can create new models, saved directly to the db', function(assert) {
+ var user = schema.user.create({name: 'Link'});
+
+ assert.ok(user instanceof Model);
+ assert.ok(user instanceof User);
+ assert.deepEqual(user.attrs, {id: '1', name: 'Link'});
+ assert.deepEqual(db.users, [{id: '1', name: 'Link'}]);
+});
diff --git a/pool/shard000/JavaScript/0002843_helpers.js b/pool/shard000/JavaScript/0002843_helpers.js
new file mode 100644
index 0000000000000000000000000000000000000000..4b5deaeab4ee73934dc2abcaf8ee172658aea776
--- /dev/null
+++ b/pool/shard000/JavaScript/0002843_helpers.js
@@ -0,0 +1,77 @@
+/*
+ This is a javascript library to make some of the common things
+ in SQLCL simplier.
+*/
+
+var helpers = {} ;
+
+/* for complex type a java hashmap is needed for binds */
+helpers.getBindMap = function(){
+ var HashMap = Java.type("java.util.HashMap");
+ map = new HashMap();
+ return map;
+};
+
+/* create a temp blob and load it from a local to sqlcl file */
+helpers.getBlobFromFile=function (fileName){
+ try {
+ var b = conn.createBlob();
+ var out = b.setBinaryStream(1);
+ var path = java.nio.file.FileSystems.getDefault().getPath(fileName);
+ java.nio.file.Files.copy(path, out);
+ out.flush();
+ return b;
+ } catch(e){
+ ctx.write(e);
+ }
+};
+
+/* makes getting a DBUtil instance easier */
+helpers.getDBUtil=function(){
+ var DBUtil = Java.type("oracle.dbtools.db.DBUtil");
+ return DBUtil;
+}
+
+/* This converts the results of util.executeReturnList from a java List to a JSON object. */
+helpers.resultsToJSON=function(ret){
+ var data = [] ;
+ for ( r in ret ) {
+ /* loop all the columns in the row */
+ var set = ret[r].keySet().iterator();;
+ var row = {};
+ while( set.hasNext() ) {
+ var key = set.next();
+ row[key] = ret[r][key];
+ }
+ data[data.length] = row;
+ }
+ return data;
+
+}
+
+/*
+* Runs the passed in command and returns an Object with
+* .rc - the return code
+* .stdout - STDOUT
+* .stderr - STDERR
+*
+*/
+helpers.exec=function(cmd){
+ var RunTime = Java.type("java.lang.Runtime");
+ var Scanner = Java.type("java.util.Scanner");
+ var p = RunTime.getRuntime().exec(cmd);
+
+ var ret={};
+ s = new Scanner(p.getInputStream()).useDelimiter("\\A");
+ ret.stdout = s.hasNext() ? s.next().trim() : "";
+ s = new Scanner(p.getErrorStream()).useDelimiter("\\A");
+ ret.stderr = s.hasNext() ? s.next().trim() : "";
+
+ p.waitFor();
+ ret.rc = p.exitValue();
+ p.destroy();
+ return ret;
+}
+
+
+
diff --git a/pool/shard000/JavaScript/0002846_writer.test.js b/pool/shard000/JavaScript/0002846_writer.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..6b898d7ab40c069710c0cdd6ece2fd4478ef3d11
--- /dev/null
+++ b/pool/shard000/JavaScript/0002846_writer.test.js
@@ -0,0 +1,96 @@
+var fs = require('fs')
+
+var chai = require('chai'),
+ assert = chai.assert,
+ async = require('async'),
+ GtfsRealtimeBindings = require('gtfs-realtime-bindings'),
+ nock = require('nock'),
+ realtime = require('gtfs-realtime-bindings'),
+ rimraf = require('rimraf')
+
+chai.use(require('chai-json-schema'))
+
+var writer = require('../scripts/writer.js')
+
+var util = require('./util.js')
+
+
+var BASE_URL_PATH = '/service/publicXMLFeed',
+ NOCK_HOST = 'http://webservices.nextbus.com',
+ FIXTURES_FOLDER = './test/fixtures'
+
+var clean = function(done) {
+ rimraf('./cache', function() {
+ rimraf('./outputs', done)
+ })
+}
+
+describe('writer', function() {
+
+ beforeEach(clean)
+
+ afterEach(clean)
+
+ it('should download feed, translate to gtfs-rt and write files', function(done) {
+
+ var nockScope = nock(NOCK_HOST)
+ .get(BASE_URL_PATH)
+ .query(util.makeQueryParams('messages', { t: 0 }))
+ .replyWithFile(200, FIXTURES_FOLDER + '/messages.xml')
+ .get(BASE_URL_PATH)
+ .query(util.makeQueryParams('routeList'))
+ .replyWithFile(200, FIXTURES_FOLDER + '/routeList.xml')
+ .get(BASE_URL_PATH)
+ .query(util.makeQueryParams('routeConfig'))
+ .replyWithFile(200, FIXTURES_FOLDER + '/routeConfig-all.xml')
+ .get(BASE_URL_PATH)
+ .query(util.makeQueryParams('predictionsForMultiStops', util.predictionsForMultiStopsParams))
+ .replyWithFile(200, FIXTURES_FOLDER + '/predictionsForMultiStops-ok.xml')
+ .get(BASE_URL_PATH)
+ .query(util.makeQueryParams('vehicleLocations', { t: 0, r: '' }))
+ .replyWithFile(200, FIXTURES_FOLDER + '/vehicleLocations.xml')
+
+ writer({ a: 'seattle-sc', d: './outputs' }, function(err) {
+
+ try {
+
+ assert.isNotOk(err)
+
+ nockScope.done()
+
+ // verify existance of files and conformity to gtfs-rt protobuf definition
+ async.each([
+ 'service-alerts',
+ 'trip-updates',
+ 'vehicle-positions'
+ ],
+ function(item, fileCallback) {
+ var filename = './outputs/' + item + '.proto'
+ async.auto({
+ assertFileExistance: function(cb) {
+ fs.stat(filename, cb)
+ },
+ readFileContents: ['assertFileExistance', function(results, cb) {
+ fs.readFile(filename, cb)
+ }],
+ assertIsGtfsRtProtobuf: ['readFileContents', function(results, cb) {
+ try {
+ var feed = GtfsRealtimeBindings.FeedMessage.decode(results.readFileContents)
+ assert.jsonSchema(feed, require('./fixtures/gtfs-realtime.json'))
+ } catch(e) {
+ return cb(e)
+ }
+ cb()
+ }]
+ }, fileCallback)
+ },
+ done)
+
+ } catch(e) {
+ return done(e)
+ }
+
+ })
+
+ })
+})
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002849_index.js b/pool/shard000/JavaScript/0002849_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..fde2a4e7d4f60c658a2ec181e32486a2e2f8e2d2
--- /dev/null
+++ b/pool/shard000/JavaScript/0002849_index.js
@@ -0,0 +1,116 @@
+import React from 'react';
+import { AsyncStorage, Alert, Text, View, TextInput, TouchableOpacity } from 'react-native';
+import Home from '../home';
+import Goods from '../goods';
+import DICT from '../../config/dict';
+import API from '../../config/api';
+import styles from '../../styles';
+
+class Login extends React.Component {
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ name: "",
+ password: ""
+ }
+
+ this.changeName = this.changeName.bind(this);
+ this.changePswd = this.changePswd.bind(this);
+ this.login = this.login.bind(this);
+ }
+
+ render() {
+ return (
+
+
+
+ 用户名
+
+
+
+
+
+ 密码
+
+
+
+
+
+ 登录
+
+
+
+ )
+ }
+
+ changeName(name) {
+ this.setState({
+ name: name
+ });
+ }
+
+ changePswd(password) {
+ this.setState({
+ password: password
+ });
+ }
+
+ async login() {
+ var { name, password } = this.state;
+ if (!name || !password) {
+ Alert.alert('登录失败', '用户名或密码不能为空!');
+ return;
+ }
+ try {
+ var response = await fetch(API.login, {
+ method: 'post',
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ userName: name,
+ password: password
+ })
+ })
+
+ var status = response.status;
+ var responseText = await response.text();
+ switch (status) {
+ case 200:
+ try {
+ await AsyncStorage.setItem(DICT.LOGINKEY, responseText);
+ await this.props.initUser(responseText);
+ } catch (error) {
+ Alert.alert('内部错误', '内部错误,即将退出!');
+ return;
+ }
+ this.jumpForward();
+ break;
+ default:
+ Alert.alert('登录失败', responseText || '服务器内部错误');
+ break;
+ }
+ } catch (error) {
+ Alert.alert('登录失败', '无法连接到服务器');
+ }
+ }
+
+ jumpForward() {
+ var { navigator } = this.props;
+ navigator.pop();
+ }
+
+}
+
+export default Login;
diff --git a/pool/shard000/JavaScript/0002850_entity-relationship-overview.js b/pool/shard000/JavaScript/0002850_entity-relationship-overview.js
new file mode 100644
index 0000000000000000000000000000000000000000..c05be61dc766e731a18c2c8df1e9235dc7805917
--- /dev/null
+++ b/pool/shard000/JavaScript/0002850_entity-relationship-overview.js
@@ -0,0 +1,61 @@
+import template from './entity-relationship-overview.html';
+import {initialiseData} from "../../../common";
+import {CORE_API} from "../../../common/services/core-api-utils";
+import * as _ from "lodash";
+
+
+const bindings = {
+ parentEntityRef: '<'
+};
+
+const initialState = [];
+
+
+function controller($q, serviceBroker) {
+
+ const vm = initialiseData(this, initialState);
+
+ function loadData() {
+ const relationshipKindPromise = serviceBroker
+ .loadAppData(CORE_API.RelationshipKindStore.findAll)
+ .then(r => r.data);
+
+ const relationshipPromise = serviceBroker
+ .loadViewData(CORE_API.EntityRelationshipStore.getById, [vm.parentEntityRef.id])
+ .then(r => r.data);
+
+
+ return $q
+ .all([relationshipKindPromise, relationshipPromise])
+ .then(([relKinds, relationship]) => {
+
+ const relationshipKind = _.find(relKinds,
+ k => k.code === relationship.relationship
+ && k.kindA === relationship.a.kind
+ && k.kindB === relationship.b.kind);
+
+ vm.relationship = Object.assign({}, relationship, {relationshipKind: relationshipKind})
+ })
+ }
+
+ vm.$onInit = () => {
+ loadData();
+ };
+}
+
+
+controller.$inject = [
+ "$q",
+ "ServiceBroker"
+];
+
+const component = {
+ template,
+ bindings,
+ controller
+};
+
+export default {
+ id: 'waltzEntityRelationshipOverview',
+ component
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002851_chat.js b/pool/shard000/JavaScript/0002851_chat.js
new file mode 100644
index 0000000000000000000000000000000000000000..cda9ad66da43f2fc8b10c3ca58b9a7c0e85cad6a
--- /dev/null
+++ b/pool/shard000/JavaScript/0002851_chat.js
@@ -0,0 +1,131 @@
+/*
+ * copyright (c) 2015 Susisu
+ */
+
+"use strict";
+
+function ChatScreen(chat) {
+ var chatScreen = window.document.getElementById("chat-screen");
+
+ var chatMembers = window.document.getElementById("chat-members");
+
+ var chatExit = window.document.getElementById("chat-logout");
+ chatExit.addEventListener("click", function () {
+ logout();
+ });
+
+ var chatMessageInput = window.document.getElementById("chat-message-input");
+ chatMessageInput.addEventListener("keypress", function (event) {
+ if (event.keyCode === 13) {
+ event.preventDefault();
+ var message = chatMessageInput.value;
+ if (message !== "") {
+ chat.sendMessage(message);
+ chatMessageInput.value = "";
+ }
+ }
+ });
+ var chatMessageSend = window.document.getElementById("chat-message-send");
+ chatMessageSend.addEventListener("click", function () {
+ var message = chatMessageInput.value;
+ chat.sendMessage(message);
+ chatMessageInput.value = "";
+ });
+
+ var chatMessages = window.document.getElementById("chat-messages");
+
+ function logout() {
+ chat.logout();
+ clearMembers();
+ memberElems = [];
+ clearMessages();
+ }
+
+ var memberElems = [];
+ function clearMembers() {
+ while (chatMembers.firstChild) {
+ chatMembers.removeChild(chatMembers.firstChild);
+ }
+ }
+
+ function updateMembers() {
+ clearMembers();
+ for (var i = 0; i < memberElems.length; i++) {
+ chatMembers.appendChild(memberElems[i]["elem"]);
+ }
+ }
+
+ function clearMessages() {
+ while (chatMessages.firstChild) {
+ chatMessages.removeChild(chatMessages.firstChild);
+ }
+ }
+
+ function updateMessages(data) {
+ var name = window.document.createElement("p");
+ if (data["screen_name"]) {
+ name.className = "chat-message-name";
+ name.innerText = data["screen_name"];
+ }
+ else {
+ name.className = "chat-server-message-name";
+ name.innerText = "Server"
+ }
+ var text = window.document.createElement("p");
+ text.className = "chat-message-text";
+ text.innerText = data["message"];
+ var date = window.document.createElement("p");
+ date.className = "chat-message-date";
+ date.innerText = new Date(data["date"]).toLocaleString();
+ var messageElem = window.document.createElement("li");
+ messageElem.className = "chat-message";
+ messageElem.appendChild(name);
+ messageElem.appendChild(text);
+ messageElem.appendChild(date);
+ chatMessages.appendChild(messageElem);
+ }
+
+ chat.on("welcome", function (data) {
+ for (var i = 0; i < data["users"].length; i++) {
+ var elem = window.document.createElement("li");
+ elem.innerText = data["users"][i]["screen_name"];
+ memberElems.push({
+ "user_id": data["users"][i]["user_id"],
+ "elem" : elem
+ });
+ }
+ updateMembers();
+ });
+
+ chat.on("userConnected", function (data) {
+ var elem = window.document.createElement("li");
+ elem.innerText = data["screen_name"];
+ memberElems.push({
+ "user_id": data["user_id"],
+ "elem" : elem
+ });
+ updateMembers();
+ });
+ chat.on("userDisconnected", function (data) {
+ for (var i = 0; i < memberElems.length; i++) {
+ if (memberElems[i]["user_id"] === data["user_id"]) {
+ memberElems.splice(i, 1);
+ break;
+ }
+ }
+ updateMembers();
+ });
+ chat.on("serverMessage", function (data) {
+ updateMessages(data);
+ });
+ chat.on("message", function (data) {
+ updateMessages(data);
+ });
+ chat.on("disconnect", function (data) {
+ logout();
+ });
+
+ return chatScreen;
+}
+
+module.exports = ChatScreen;
diff --git a/pool/shard000/JavaScript/0002852_note.js b/pool/shard000/JavaScript/0002852_note.js
new file mode 100644
index 0000000000000000000000000000000000000000..437ba82c0b6cdb4ae1395b29172bd1eb4ae447ba
--- /dev/null
+++ b/pool/shard000/JavaScript/0002852_note.js
@@ -0,0 +1,39 @@
+import axios from 'axios';
+
+// 장부 등록
+export const addNote = (formdata) => {
+ return axios.post('/api/note', formdata);
+};
+
+// 전체 장부 가져오기
+export const getAllNotes = () => {
+ return axios.get('/api/note');
+};
+
+// 특정 장부 가져오기
+export const getNote = (id, params={}) => {
+ return axios.get(`/api/note/${id}`, { params });
+};
+
+// 오늘의 장부자료 가져오기
+export const getTodayNotes = () => {
+ return axios.get('/api/note/today');
+};
+
+// 특정 검색어로 장부 검색하기
+export const searchNotes = (searchTxt) => {
+ return axios.get(`/api/note/search/${searchTxt}`);
+};
+
+export const getMonthNotes = (month) => {
+ return axios.get(`/api/note/month/${month}`);
+};
+
+export const getCategoryStatistics = (category, filters) => {
+ return axios.get('/api/note/stat', {
+ params: {
+ category,
+ filters
+ }
+ });
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002853_15.4.4.21-7-7.js b/pool/shard000/JavaScript/0002853_15.4.4.21-7-7.js
new file mode 100644
index 0000000000000000000000000000000000000000..72f61ea8b1bec39f42b43695493166feedfd122e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002853_15.4.4.21-7-7.js
@@ -0,0 +1,54 @@
+/// Copyright (c) 2009 Microsoft Corporation
+///
+/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
+/// that the following conditions are met:
+/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
+/// the following disclaimer.
+/// * 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.
+/// * Neither the name of Microsoft nor the names of its contributors may be used to
+/// endorse or promote products derived from this software without specific prior written permission.
+///
+/// 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.
+
+
+ES5Harness.registerTest( {
+id: "15.4.4.21-7-7",
+
+path: "TestCases/chapter15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-7.js",
+
+description: "Array.prototype.reduce returns initialValue if 'length' is 0 and initialValue is present (subclassed Array, length overridden with obj w/o valueOf (toString))",
+
+test: function testcase() {
+ foo.prototype = new Array(1, 2, 3);
+ function foo() {}
+ var f = new foo();
+
+ var o = { toString: function () { return '0';}};
+ f.length = o;
+
+ // objects inherit the default valueOf method of the Object object;
+ // that simply returns the itself. Since the default valueOf() method
+ // does not return a primitive value, ES next tries to convert the object
+ // to a number by calling its toString() method and converting the
+ // resulting string to a number.
+
+ function cb(){}
+ try {
+ if(f.reduce(cb,1) === 1)
+ return true;
+ }
+ catch (e) { }
+ },
+
+precondition: function prereq() {
+ return fnExists(Array.prototype.reduce);
+ }
+});
diff --git a/pool/shard000/JavaScript/0002854_env.js b/pool/shard000/JavaScript/0002854_env.js
new file mode 100644
index 0000000000000000000000000000000000000000..34a012c9fc08cbc147c63510999de32f98f4c77e
--- /dev/null
+++ b/pool/shard000/JavaScript/0002854_env.js
@@ -0,0 +1,65 @@
+
+import { createSelector } from 'reselect';
+const clientComponentsSelector = state => state.freestone.env.freestone.clientComponents;
+const requestedComponentsNameSelector = (state, props) => props.name;
+
+export const clientComponentInfosSelector = createSelector(
+ [clientComponentsSelector, requestedComponentsNameSelector],
+ (clientComponents, requestedComponentsName) => {
+ return (clientComponents && clientComponents.find(el => el.id === requestedComponentsName)) || {};
+ }
+);
+
+const stateTicketSelector = state => state.freestone.auth.ticket;
+const urlTicketSelector = createSelector(
+ [],
+ () => {
+ const currentURL = new URL(window.location.href);
+ const ticketInGET = currentURL.searchParams.get('ticket');
+ if (ticketInGET && ticketInGET.length > 0) {
+ return ticketInGET;
+ }
+
+ return null;
+ }
+);
+
+const redirectOnLoginURLSelector = createSelector(
+ [],
+ () => {
+ const currentURL = new URL(window.location.href);
+ const redirectURL = currentURL.searchParams.get('redirect_url');
+ if (redirectURL && redirectURL.length > 0) {
+ return redirectURL;
+ }
+
+ return null;
+ }
+);
+
+
+const isAuthenticatedSelector = state => state.freestone.auth.isAuthenticated;
+const needsReloginSelector = state => state.freestone.auth.needsRelogin;
+const jwtSelector = state => state.freestone.auth.jwt;
+const domainSelector = state => state.freestone.env.freestone.domain;
+const clientScriptsSelector = state => state.freestone.env.freestone.clientScripts;
+const isNavVisibleSelector = state => state.freestone.siteHeader.nav_visibility;
+const versionSelector = state => state.freestone.env.freestone.version;
+
+export const appRootSelector = createSelector(
+ [isAuthenticatedSelector, needsReloginSelector, jwtSelector, redirectOnLoginURLSelector, stateTicketSelector, urlTicketSelector, domainSelector, clientScriptsSelector, isNavVisibleSelector, versionSelector],
+ (isAuthenticated, needsRelogin, jwt, redirectOnLoginURL, ticket, urlTicket, domain, clientScripts, isNavVisible, version) => {
+ return {
+ needsRelogin,
+ redirectOnLoginURL,
+ jwt,
+ ticket,
+ urlTicket,
+ isAuthenticated,
+ domain,
+ clientScripts,
+ isNavVisible,
+ ...version,
+ };
+ }
+);
diff --git a/pool/shard000/JavaScript/0002855_index.js b/pool/shard000/JavaScript/0002855_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..d9934f2f8dcc69470a727160df60e38ccd7e79bf
--- /dev/null
+++ b/pool/shard000/JavaScript/0002855_index.js
@@ -0,0 +1,38 @@
+/**
+* @license Apache-2.0
+*
+* Copyright (c) 2018 The Stdlib Authors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+'use strict';
+
+var randu = require( '@stdlib/random/iter/randu' );
+var iterEveryBy = require( './../lib' );
+
+function threshold( r ) {
+ return ( r < 0.99 );
+}
+
+// Create an iterator which generates uniformly distributed pseudorandom numbers:
+var opts = {
+ 'iter': 100
+};
+var riter = randu( opts );
+
+// Determine if all values are below a threshold:
+var bool = iterEveryBy( riter, threshold );
+// returns
+
+console.log( bool );
diff --git a/pool/shard000/JavaScript/0002857_bank_account-spec.js b/pool/shard000/JavaScript/0002857_bank_account-spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..ec7b3ae6b7a06a6d2d8cde36fbfdd8141a467c63
--- /dev/null
+++ b/pool/shard000/JavaScript/0002857_bank_account-spec.js
@@ -0,0 +1,31 @@
+var Helper = require('./helper.js');
+var PagarMe = require('../libs/pagarme.js');
+var Request = require('request');
+
+describe('Bank Account',function(){
+
+ beforeEach(function(){
+ PagarMe.setApiKeys('ak_test_degoc5yK7aIZ6We84UenZicTICiSeI','ek_test_y2xsJCewfhfc9WBTB79HnCmUWQ86df');
+ });
+
+ it('should be able to create a bank_account',function(done){
+ var bank = Helper.testBankAccount();
+ bank.create(function(result){
+ expect(result.bank_code).toEqual('237');
+ done();
+ });
+ });
+
+ it('should be able to search by anything', function(done){
+ var bank = Helper.testBankAccount();
+ PagarMe.bankAccount().findBy({bank_code:'237'},function(res){
+ expect(res.length).toBeDefined();
+ for(var i=0; i ({
+ variables: { email: props.user.email },
+ fetchPolicy: 'cache-and-network'
+ })
+}
+
+@compose(
+ graphql(getUserByEmail(QueryUserParams), QueryUserOptions),
+ graphql(setUserPaidAmount('ok failureMessage'), {name: 'MutationSetUserPaidAmount'}),
+ graphql(addPermission('ok'), {name: 'MutationAddPermission'}),
+ graphql(removePermission('ok'), {name: 'MutationRemovePermission'})
+)
+@autobind
+@HotkeysTarget
+class UserProfile extends React.Component {
+ static propTypes = {
+ user: PropTypes.object.isRequired,
+ closeProfile: PropTypes.func.isRequired,
+ paymentAmount: PropTypes.number.isRequired,
+ }
+
+ state = {
+ paidAmount: null,
+ paidAmountModified: false,
+ saving: false
+ }
+
+ componentDidMount() {
+ this._mounted = true;
+ }
+
+ componentWillUnmount() {
+ this._mounted = false;
+ }
+
+ closeProfile() {
+ this.props.closeProfile();
+ }
+
+ editPaid(value) {
+ this.setState({ paidAmount: value, paidAmountModified: true });
+ }
+
+ confirmPaid(value) {
+ if (value.length > 0 && this.state.paidAmountModified) {
+ const regex = /^[0-9]+(\.|)[0-9]{0,2}$/;
+ if (regex.exec(value)) {
+ this.savePaid();
+ return;
+ }
+ }
+ this.setState({ paidAmount: this.props.QueryUser.getUserByEmail.paidAmount, paidAmountModified: false });
+ }
+
+ async savePaid() {
+ this.setState({ saving: true, paidAmountModified: false });
+
+ const variables = {
+ username: this.props.QueryUser.getUserByEmail.username,
+ amount: this.state.paidAmount
+ };
+
+ try {
+ const result = await this.props.MutationSetUserPaidAmount({ variables });
+ await this.props.QueryUser.refetch();
+ }
+ catch (err) {
+ NotificationToaster.show({
+ intent: Intent.DANGER,
+ message: err.toString()
+ });
+ }
+
+ if (this._mounted) this.setState({ saving: false });
+ }
+
+ renderHotkeys() {
+ return (
+
+
+
+ );
+ }
+
+ render() {
+ const { firstname, lastname, email, university } = this.props.user;
+ const { loading, getUserByEmail } = this.props.QueryUser;
+ let content;
+
+ if (getUserByEmail) {
+ const {
+ username, mobileNumber, studentID, isAdmin,
+ registerDate, paidAmount, permissions,
+ raceDetails: {
+ PTProficiency, hasSmartphone,
+ friends, dietaryRequirements
+ }
+ } = getUserByEmail;
+
+ if (this.state.paidAmount === null) {
+ setTimeout(() => {
+ this.setState({paidAmount});
+ }, 0);
+ }
+
+ let paidIcon = ;
+ if (parseFloat(this.state.paidAmount) >= this.props.paymentAmount) {
+ paidIcon = ;
+ }
+
+ content = (
+
+
+
+
+ Username
+ {username}
+
+
+ Email
+ {email}
+
+
+ Mobile
+ {mobileNumber}
+
+
+ Paid {paidIcon}
+
+ $
+
+
+
+ Student ID
+ {studentID}
+
+
+ Register date
+ {DateFormat(new Date(registerDate), 'mmm dd yyyy hh:MM TT')}
+
+
+ PT Proficiency
+ {PTProficiency}
+
+
+ Has smartphone
+ {hasSmartphone ? 'Yes' : 'No' }
+
+
+ Friends
+ {friends ? friends : 'None'}
+
+
+ Dietary Requirements
+ {dietaryRequirements ? dietaryRequirements : 'None'}
+
+
+ Admin
+ {isAdmin ? 'true':'false'}
+
+
+ Password
+
+
+
+
+ Account Permissions
+
+
+
+
+ { permissions.map((permission, index) => {
+ return ;
+ }) }
+
+
+
+
+
+
+ );
+ }
+ else if (loading) {
+ content = ;
+ }
+
+ return (
+
+
+ {this.state.saving ?
+
+
+
+ : null }
+ {firstname + ' ' + lastname}
+ {university}
+ {content}
+
+ );
+ }
+}
+
+
+export default UserProfile;
diff --git a/pool/shard000/JavaScript/0002865_wrapper.js b/pool/shard000/JavaScript/0002865_wrapper.js
new file mode 100644
index 0000000000000000000000000000000000000000..9e6a122c521cea1e24f7ab8df46419f6f9fe76e0
--- /dev/null
+++ b/pool/shard000/JavaScript/0002865_wrapper.js
@@ -0,0 +1,19 @@
+//::LICENSE:://
+;(function () {
+var factory = function(signals){
+
+//::HASHER:://
+
+ return hasher;
+};
+
+if (typeof define === 'function' && define.amd) {
+ define(['signals'], factory);
+} else if (typeof exports === 'object') {
+ module.exports = factory(require('signals'));
+} else {
+ /*jshint sub:true */
+ window['hasher'] = factory(window['signals']);
+}
+
+}());
diff --git a/pool/shard000/JavaScript/0002868_Report-Movements.js b/pool/shard000/JavaScript/0002868_Report-Movements.js
new file mode 100644
index 0000000000000000000000000000000000000000..83d4dd56303a86e9fb9cfb9b4f237a6b317ae9ee
--- /dev/null
+++ b/pool/shard000/JavaScript/0002868_Report-Movements.js
@@ -0,0 +1,28 @@
+//Genera las filas que contienen los datos del reporte
+myApp.onPageBeforeAnimation('Movements-Report', function(page) {
+ render();
+
+ function render() {
+ var listado = almacenamientoMovements.get();
+ var myMovementsReportController = new movementsReportController(listado);
+ var listadoItemReports = myMovementsReportController.calcularItemsReports();
+
+ var listadoView = $$('#listadoItemsReporte');
+
+ listadoView.find('li').remove();
+
+ for (var i in listadoItemReports) {
+ var item = listadoItemReports[i];
+ var html = Template7.templates.reporteItemTemplate(item.toJSON());
+
+ listadoView.append(html);
+ }
+
+ //Comienza el proceso de borrado de un movimiento cuando se preciona el boton "deleted"
+ $$('.swipeout-movement').on('deleted', function(e) {
+ var id = $$(this).data('id');
+ myMovementsReportController.eliminarMovimiento(id);
+ render();
+ });
+ }
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002877_DeletionRequest.js b/pool/shard000/JavaScript/0002877_DeletionRequest.js
new file mode 100644
index 0000000000000000000000000000000000000000..75a092cbe249cdb99fcb2024af58151ba94fda53
--- /dev/null
+++ b/pool/shard000/JavaScript/0002877_DeletionRequest.js
@@ -0,0 +1,76 @@
+/*!
+ * This file is part of {@link https://github.com/MovLib MovLib}.
+ *
+ * Copyright © 2013-present {@link https://movlib.org/ MovLib}.
+ *
+ * MovLib 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.
+ *
+ * MovLib 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 MovLib.
+ * If not, see {@link http://www.gnu.org/licenses/ gnu.org/licenses}.
+ */
+
+/* jshint browser:true */
+
+/**
+ * @module MovLib
+ * @namespace modules
+ * @submodule InputImage
+ * @author Richard Fussenegger
+ * @copyright © 2013 MovLib
+ * @license http://www.gnu.org/licenses/agpl.html AGPL-3.0
+ * @link https://movlib.org/
+ * @since 0.0.1-dev
+ * @param {MovLib} MovLib
+ */
+(function (MovLib) {
+ "use strict";
+
+ /**
+ * The name of this JavaScript module.
+ *
+ * @type String
+ */
+ var moduleName = "DeletionRequest";
+
+ /**
+ * Attach InputImage to the MovLib modules.
+ *
+ * @param {HTMLCollection} context
+ * The context we are currently working with.
+ * @returns {MovLib}
+ */
+ MovLib.modules[moduleName] = function (context) {
+ // The select element containing the deletion types.
+ var reason = context.getElementById("reason");
+
+ // The additional input elements for some deletion types.
+ var infos = reason.form.getElementsByClassName("info");
+
+ // Listen for the change event on the deletion type select element.
+ reason.addEventListener("change", function () {
+ // Try to get the info element for the selected deletion type.
+ var info = context.getElementById("info-" + this.value);
+
+ // Hide all other info elements and remove the required attribute.
+ var c = infos.length;
+ for (var i = 0; i < c; ++i) {
+ infos[i].removeAttribute("required");
+ infos[i].classList.add("hidden");
+ }
+
+ // Show the info element associated with this deletion type and make it required.
+ if (info) {
+ info.setAttribute("required", "required");
+ info.classList.remove("hidden");
+ }
+ }, false);
+
+ return MovLib;
+ };
+
+})(window.MovLib);
diff --git a/pool/shard000/JavaScript/0002879_jquery.imeta.steps._btn.js b/pool/shard000/JavaScript/0002879_jquery.imeta.steps._btn.js
new file mode 100644
index 0000000000000000000000000000000000000000..5f2d67e46151eee9ca77600934f00e2ebf031664
--- /dev/null
+++ b/pool/shard000/JavaScript/0002879_jquery.imeta.steps._btn.js
@@ -0,0 +1,41 @@
+jQuery.imeta.steps.btn = {
+ ok : function(e, v) {
+ var elId = e.target.id;
+ var id = elId.split(".")[0];
+ $("#" + id).ajaxSubmit(
+ {
+ type : "POST",
+ url : "ImetaAction!editElementSubmit.action",
+ dataType : "json",
+ data : {
+ id : id,
+ roType : jQuery.iPortalTab.OBJECT_TYPE_TRANS,
+ roName : e.target.getAttribute("transName"),
+ directoryId : e.target
+ .getAttribute("directoryId"),
+ elementName : e.target.getAttribute("stepName")
+ },
+ success : function(json) {
+ if (json.oldName != json.newName) {
+ var el = jQuery.imenu.iContent
+ .getCanvasElByText(json.oldName,
+ 'step');
+ jQuery.imenu.iContent.updateEl(el, {
+ stepName : json.newName,
+ bText : [ json.newName ]
+ });
+ jQuery.imenu.iContent.redraw();
+ }
+ jQuery.iPortalTab
+ .updateActiveTab(jQuery.iPortalTab.TYPE_ACTION_CHANGE_STEP);
+ $("#window-" + id).remove();
+ $.imessagebox("#ibody", json);
+ }
+ });
+ },
+ cancel : function(e, v) {
+ var elId = e.target.id;
+ var id = elId.split(".")[0];
+ $("#window-" + id).remove();
+ }
+};
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002886_MemoryController.js b/pool/shard000/JavaScript/0002886_MemoryController.js
new file mode 100644
index 0000000000000000000000000000000000000000..27661ee30ac26f83985a8b7edec026b34d958497
--- /dev/null
+++ b/pool/shard000/JavaScript/0002886_MemoryController.js
@@ -0,0 +1,36 @@
+(function () {
+ angular
+ .module('app')
+ .controller('MemoryController', [
+ MemoryController
+ ]);
+
+ function MemoryController() {
+ var vm = this;
+
+ // TODO: move data to the service
+ vm.memoryChartData = [ {key: 'memory', y: 42}, { key: 'free', y: 58} ];
+
+ vm.chartOptions = {
+ chart: {
+ type: 'pieChart',
+ height: 210,
+ donut: true,
+ pie: {
+ startAngle: function (d) { return d.startAngle/2 -Math.PI/2 },
+ endAngle: function (d) { return d.endAngle/2 -Math.PI/2 }
+ },
+ x: function (d) { return d.key; },
+ y: function (d) { return d.y; },
+ valueFormat: (d3.format(".0f")),
+ color: ['rgb(0, 150, 136)', 'rgb(191, 191, 191)'],
+ showLabels: false,
+ showLegend: false,
+ tooltips: false,
+ title: '42%',
+ titleOffset: -10,
+ margin: { bottom: -80, left: -20, right: -20 }
+ }
+ };
+ }
+})();
diff --git a/pool/shard000/JavaScript/0002888_mockJiraApi.js b/pool/shard000/JavaScript/0002888_mockJiraApi.js
new file mode 100644
index 0000000000000000000000000000000000000000..27b69cca212f2e9517c6ca60e46e07663ea1cc4c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002888_mockJiraApi.js
@@ -0,0 +1,168 @@
+jiraApiImport = require('../../src/jiraApi.gs');
+jest.mock('../../src/jiraApi.gs', () => jest.fn());
+
+const jiraApiMock = {
+ call: jest.fn(),
+ withSuccessHandler: jest.fn(),
+ withFailureHandler: jest.fn(),
+ getResponse: jest.fn(),
+ resetMocks: resetMockFunction,
+ setNextJiraResponse: setNextJiraResponse,
+ setAllResponsesSuccesfull: setAllResponsesSuccesfull,
+ setAllResponsesFail: setAllResponsesFail,
+ setResponseSequence: setResponseSequence
+};
+
+function initJiraApiMockMethods() {
+ jiraApiMock.call.mockImplementation(() => {
+ return jiraApiMock;
+ });
+ jiraApiMock.withSuccessHandler.mockImplementation(() => {
+ return jiraApiMock;
+ });
+ jiraApiMock.withFailureHandler.mockImplementation(() => {
+ return jiraApiMock;
+ });
+ jiraApiMock.getResponse.mockImplementation(() => {
+ return {};
+ });
+}
+
+/**
+ * Resets the mock functions so it is reset for a new test
+ */
+function resetMockFunction() {
+ jiraApiMock.call.mockReset();
+ jiraApiMock.withSuccessHandler.mockReset();
+ jiraApiMock.withFailureHandler.mockReset();
+ jiraApiMock.getResponse.mockReset();
+ initJiraApiMockMethods();
+}
+
+/**
+ * Sets the next mock response from the JIRA API
+ * @param {integer} httpStatusCode - the HTTP code to return
+ * @param {string} expectedMethodCall - the method call expected - this is tested to verify
+ * @param {string} dataToReturn - the data to return to mock the API response
+ */
+function setNextJiraResponse(httpStatusCode, expectedMethodCall, dataToReturn) {
+ if (httpStatusCode == null) {
+ httpStatusCode = 200;
+ }
+ jiraApiMock.call.mockImplementationOnce((method, params) => {
+ expect(method).toBe(expectedMethodCall);
+ return {
+ call: jiraApiMock.call,
+ withSuccessHandler: function (calback) {
+ calback(dataToReturn, null, httpStatusCode);
+ return jiraApiMock;
+ },
+ withFailureHandler: jiraApiMock.withFailureHandler
+ }
+ })
+}
+
+/**
+ * Sets a sequence of responses from the mocked API
+ * @param {array} sequenceArray response - each response is an object with the fields
+ * statusCode - HTTP status code
+ * method - the expected HTTP method
+ * success - true of false, if statusCode is null, a true value will return a HTTP 200, if false HTTP 500
+ */
+function setResponseSequence(sequenceArray) {
+ var index = 0;
+ var currentResponse = null;
+ if (index < sequenceArray.length) {
+ jiraApiMock.call.mockImplementation((method, params) => {
+ if (index >= sequenceArray.length) {
+ throw "setResponseSequence index=" + index + " which exceeds the number of items in the sequenceArray";
+ }
+ currentResponse = sequenceArray[index];
+ index++;
+ if (currentResponse.statusCode == null) {
+ if (currentResponse.success) {
+ currentResponse.statusCode = 200;
+ } else {
+ currentResponse.statusCode = 500;
+ }
+ }
+ if (currentResponse.method == null) {
+ currentResponse.method = "get;"
+ }
+
+ return jiraApiMock;
+ });
+ jiraApiMock.withSuccessHandler.mockImplementation(function (callback) {
+ if (currentResponse.success) {
+ callback(currentResponse.respData, null, currentResponse.statusCode);
+ }
+ return jiraApiMock;
+ });
+
+ jiraApiMock.withFailureHandler.mockImplementation(function (callback) {
+ if (!currentResponse.success) {
+ callback(currentResponse.respData, null, currentResponse.statusCode);
+ }
+ return jiraApiMock;
+ });
+
+ jiraApiMock.getResponse.mockImplementation(function () {
+ return currentResponse;
+ });
+ }
+}
+
+/**
+ * All calls to the mock API will return with succes and the specified dummy data.
+ * @param {integer} httpStatusCode - if this is not set a HTTP 200 will be returned
+ * @param {object} dummyDataToReturn - this is the json object that will be returned
+ */
+function setAllResponsesSuccesfull(httpStatusCode, dummyDataToReturn) {
+ if (httpStatusCode == null) {
+ httpStatusCode = 200;
+ }
+ resetMockFunction();
+ jiraApiMock.withSuccessHandler.mockImplementation(function (calback) {
+ calback(dummyDataToReturn, null, httpStatusCode);
+ return jiraApiMock;
+ });
+ jiraApiMock.getResponse.mockImplementation(() => {
+ return { 'respData': dummyDataToReturn, 'httpResp': null, 'statusCode': httpStatusCode, 'method': 'get', success: true };
+ });
+}
+/**
+ * All calls to the mock API will return with error and the specified dummy data.
+ * @param {integer} httpStatusCode - if this is not set a HTTP 500 will be returned
+ * @param {object} dummyDataToReturn - this is the json object that will be returned
+ */
+function setAllResponsesFail(httpStatusCode, dummyDataToReturn) {
+ if (httpStatusCode == null) {
+ httpStatusCode = 500;
+ }
+ resetMockFunction();
+ jiraApiMock.withFailureHandler.mockImplementation(function (calback) {
+ calback(dummyDataToReturn, null, httpStatusCode);
+ return jiraApiMock;
+ });
+ jiraApiMock.getResponse.mockImplementation(() => {
+ return {
+ 'respData': dummyDataToReturn,
+ 'httpResp': null,
+ 'statusCode': httpStatusCode,
+ 'method': 'get',
+ success: false
+ };
+ });
+}
+
+function mockJiraApiConstructor() {
+ this.call = jiraApiMock.call;
+ this.withSuccessHandler = jiraApiMock.withSuccessHandler;
+ this.withFailureHandler = jiraApiMock.withFailureHandler;
+ this.getResponse = jiraApiMock.getResponse;
+}
+
+initJiraApiMockMethods();
+jiraApiImport.mockImplementation(mockJiraApiConstructor);
+
+module.exports = jiraApiMock;
diff --git a/pool/shard000/JavaScript/0002890_my-script.js b/pool/shard000/JavaScript/0002890_my-script.js
new file mode 100644
index 0000000000000000000000000000000000000000..90bdec80ba5f75c95deb4e093313700e93384764
--- /dev/null
+++ b/pool/shard000/JavaScript/0002890_my-script.js
@@ -0,0 +1,63 @@
+/*
+Name: Ultimate Taxonomy Manager
+URI: http://taxonomymanager.wordpress.com/
+*/
+jQuery(document).ready(function() {
+ //var xydac_field = jQuery("a[id^='xydac_add_image']").attr('name');
+ /* jQuery("form[id='addtag']").submit(function() {
+ if("" ==jQuery("form[id='text'][name='"+xydac_field+"']").attr('value'))
+ jQuery("img[id=" +xydac_field+ "]").attr('src','');
+ }); */
+ jQuery("form[id='addtag'] input[id='submit']").click(function() {
+ jQuery("form[id='addtag'] img[class='xydac_cat']").attr('src','../wp-includes/images/blank.gif');
+ });
+ //Click on Add image
+ var xydac_field='';
+ jQuery("a[id^='xydac_add_image']").click(function() {
+ xydac_field = jQuery(this).attr('name');
+ tb_show('Add an Image', 'media-upload.php?type=image&TB_iframe=true');
+ return false;
+ });
+ //Click on Remove Image
+ jQuery("a[id^='xydac_remove_image']").click(function() {
+ xydac_field = jQuery(this).attr('name');
+ jQuery("img[id=" +xydac_field+ "]").attr('src','../wp-includes/images/blank.gif');
+ jQuery("input[type='text'][name='"+xydac_field+"']").attr('value','');
+ return false;
+ });
+
+ window.send_to_editor = function(html) {
+ var imgurl = jQuery('img',html).attr('src');
+ jQuery("img[id=" +xydac_field+ "]").attr('src',imgurl);
+ jQuery("input[type='text'][name='"+xydac_field+"']").attr('value',imgurl);
+ jQuery("p.description").attr('value',html);
+
+ tb_remove();
+ }
+ //Taxonomy Page Script
+
+
+ jQuery("div#xydac_panel_notice").hide();
+ jQuery("div[id^=xydac_panel]").hide();
+ jQuery("select#xy_tax\\[args\\]\\[rewrite\\]\\[val\\]").change(function(){
+ if(jQuery(this).val() == 'false')
+ {jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[slug\\]").hide();
+ jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[with_front\\]").hide();}
+ else
+ {jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[slug\\]").show();
+ jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[with_front\\]").show();}
+
+ });
+ jQuery("input#xydac_temp").click(function(){
+ jQuery("div[id^=xydac_panel]").toggle("slow");
+ jQuery("div#xydac_panel_notice").toggle();
+ jQuery("input#xydac_temp").toggle();
+ if(jQuery("select#xy_tax\\[args\\]\\[rewrite\\]\\[val\\]").val() == 'false')
+ {jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[slug\\]").hide();
+ jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[with_front\\]").hide();}
+ else
+ {jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[slug\\]").show();
+ jQuery("div#xydac_panel_xy_tax\\[args\\]\\[rewrite\\]\\[with_front\\]").show();}
+ return false;
+ });
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002891_index.js b/pool/shard000/JavaScript/0002891_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..73a361b3201ecf0c9b31ab6288a4cf479f8b80f7
--- /dev/null
+++ b/pool/shard000/JavaScript/0002891_index.js
@@ -0,0 +1,212 @@
+import max from 'mout/object/max';
+
+import AbstractImageBuilder from '../AbstractImageBuilder';
+import CanvasOffscreenBuffer from '../../../Common/Misc/CanvasOffscreenBuffer';
+
+export default class CompositeImageBuilder extends AbstractImageBuilder {
+
+ // ------------------------------------------------------------------------
+
+ constructor(queryDataModel, pipelineModel) {
+ super({ queryDataModel, pipelineModel, handleRecord: true, dimensions: queryDataModel.originalData.CompositePipeline.dimensions });
+
+ this.metadata = queryDataModel.originalData.CompositePipeline;
+ this.compositeMap = {};
+ this.offsetMap = {};
+ this.spriteSize = max(this.metadata.offset);
+ this.query = null;
+ this.composite = null;
+
+ this.bgCanvas = new CanvasOffscreenBuffer(this.metadata.dimensions[0], this.metadata.dimensions[1]);
+ this.registerObjectToFree(this.bgCanvas);
+
+ this.fgCanvas = null;
+
+ this.registerSubscription(queryDataModel.onDataChange((data, envelope) => {
+ this.sprite = data.sprite;
+ this.composite = data.composite.data['pixel-order'].split('+');
+ this.updateCompositeMap(this.query, this.composite);
+ this.render();
+ }));
+
+ this.registerSubscription(this.pipelineModel.onChange((data, envelope) => {
+ this.setPipelineQuery(data);
+ }));
+
+ this.setPipelineQuery(this.pipelineModel.getPipelineQuery());
+ }
+
+ // ------------------------------------------------------------------------
+
+ updateOffsetMap(query) {
+ var layers = this.metadata.layers,
+ count = layers.length,
+ offsets = this.metadata.offset;
+
+ this.offsetMap = {};
+ this.compositeMap = {};
+ for (let idx = 0; idx < count; idx++) {
+ const fieldCode = query[(idx * 2) + 1];
+ if (fieldCode === '_') {
+ this.offsetMap[layers[idx]] = -1;
+ } else {
+ this.offsetMap[layers[idx]] = this.spriteSize - offsets[layers[idx] + fieldCode];
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ updateCompositeMap(query, composite) {
+ if (query === null || composite === null) {
+ return;
+ }
+ const compositeArray = composite,
+ map = this.compositeMap;
+
+ let count = compositeArray.length;
+ while (count) {
+ count -= 1;
+ const key = compositeArray[count];
+ if (key[0] === '@') {
+ // Skip pixels
+ } else if ({}.hasOwnProperty.call(map, key)) {
+ // Already computed
+ } else {
+ let offset = -1;
+ for (let i = 0, size = key.length; i < size; i++) {
+ offset = this.offsetMap[key[i]];
+ if (offset !== -1) {
+ i = size;
+ }
+ }
+ map[key] = offset;
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ pushToFrontAsImage(width, height) {
+ var ctx = null;
+
+ // Make sure we have a foreground buffer
+ if (this.fgCanvas) {
+ this.fgCanvas.size(width, height);
+ } else {
+ this.fgCanvas = new CanvasOffscreenBuffer(width, height);
+ this.registerObjectToFree(this.fgCanvas);
+ }
+
+ ctx = this.fgCanvas.get2DContext();
+ ctx.drawImage(this.bgCanvas.el, 0, 0, width, height, 0, 0, width, height);
+
+ const readyImage = {
+ url: this.fgCanvas.toDataURL(),
+ builder: this,
+ };
+
+ // Let everyone know the image is ready
+ this.imageReady(readyImage);
+ }
+
+ // ------------------------------------------------------------------------
+
+ pushToFrontAsBuffer(width, height) {
+ var readyImage = {
+ canvas: this.bgCanvas.el,
+ imageData: this.bgCanvas.el.getContext('2d').getImageData(0, 0, width, height),
+ area: [0, 0, width, height],
+ outputSize: [width, height],
+ builder: this,
+ arguments: this.queryDataModel.getQuery(),
+ };
+
+ // Add pipeline info + ts
+ readyImage.arguments.pipeline = this.query;
+
+ // Let everyone know the image is ready
+ this.imageReady(readyImage);
+
+ // In case of exploration trigger next data fetch
+ this.queryDataModel.nextExploration();
+ }
+
+ // ------------------------------------------------------------------------
+
+ setPipelineQuery(query) {
+ if (this.query !== query) {
+ this.query = query;
+ this.updateOffsetMap(query);
+ this.updateCompositeMap(query, this.composite);
+ this.render();
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ render() {
+ if (!this.sprite) {
+ this.queryDataModel.fetchData();
+ return;
+ }
+ if (this.query === null) {
+ return;
+ }
+
+ const ctx = this.bgCanvas.get2DContext(),
+ dimensions = this.metadata.dimensions,
+ compositeArray = this.composite,
+ count = compositeArray.length,
+ modulo = dimensions[0];
+
+ let offset = 1,
+ x = 0,
+ y = 0;
+
+ function addToX(delta) {
+ x += delta;
+ y += Math.floor(x / modulo);
+ x %= modulo;
+ }
+
+ if (this.sprite.image.complete) {
+ // Free callback if any
+ if (this.sprite.image.onload) {
+ this.sprite.image.onload = null;
+ }
+
+ ctx.clearRect(0, 0, dimensions[0], dimensions[1]);
+ for (let idx = 0; idx < count; idx++) {
+ const key = compositeArray[idx];
+ if (key[0] === '@') {
+ // Shift (x,y)
+ addToX(Number(key.replace(/@/, '+')));
+ } else {
+ offset = this.compositeMap[key];
+ if (offset !== -1) {
+ ctx.drawImage(this.sprite.image, x, y + (dimensions[1] * offset), 1, 1, x, y, 1, 1);
+ }
+ addToX(1);
+ }
+ }
+
+ this.pushToFrontAsBuffer(dimensions[0], dimensions[1]);
+ } else {
+ this.sprite.image.onload = () => {
+ this.render();
+ };
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ destroy() {
+ super.destroy();
+
+ this.bgCanvas = null;
+ this.fgCanvas = null;
+ this.compositeMap = null;
+ this.offsetMap = null;
+ }
+}
diff --git a/pool/shard000/JavaScript/0002894_drag.js b/pool/shard000/JavaScript/0002894_drag.js
new file mode 100644
index 0000000000000000000000000000000000000000..f42ef3baad2f89dd97ad589408b8c124dc733487
--- /dev/null
+++ b/pool/shard000/JavaScript/0002894_drag.js
@@ -0,0 +1,115 @@
+/**
+ * Hilo 1.0.0 for kissy
+ * Copyright 2016 alibaba.com
+ * Licensed under the MIT License
+ */
+KISSY.add('hilo/util/drag', function(S, Class, Hilo){
+
+/**
+ * Hilo
+ * Copyright 2015 alibaba.com
+ * Licensed under the MIT License
+ */
+
+/**
+ *
+ *
+ * 使用示例:
+ *
+ * var bmp = new Bitmap({image:img});
+ * Hilo.copy(bmp, Hilo.drag);
+ * bmp.startDrag([0, 0, 550, 400]);
+ *
+ * @class drag是一个包含拖拽功能的mixin。可以通过 Class.mix(view, drag)或Hilo.copy(view, drag)来为view增加拖拽功能。
+ * @mixin
+ * @static
+ * @module hilo/util/drag
+ * @requires hilo/core/Class
+ * @requires hilo/core/Hilo
+ */
+var drag = {
+ /**
+ * 开始拖拽
+ * @param {Array} bounds 拖拽范围,基于父容器坐标系,[x, y, width, height], 默认无限制
+ */
+ startDrag:function(bounds){
+ var that = this;
+ var stage;
+ var bounds = bounds||[-Infinity, -Infinity, Infinity, Infinity];
+ var mouse = {
+ x:0,
+ y:0,
+ preX:0,
+ preY:0
+ };
+ var minX = bounds[0];
+ var minY = bounds[1];
+ var maxX = bounds[2] == Infinity?Infinity:minX + bounds[2];
+ var maxY = bounds[3] == Infinity?Infinity:minY + bounds[3];
+
+ function onStart(e){
+ e.stopPropagation();
+ updateMouse(e);
+ that.off(Hilo.event.POINTER_START, onStart);
+
+ that.fire("dragStart", mouse);
+
+ that.__dragX = that.x - mouse.x;
+ that.__dragY = that.y - mouse.y;
+
+ if(!stage){
+ stage = this.getStage();
+ }
+ stage.on(Hilo.event.POINTER_MOVE, onMove);
+ document.addEventListener(Hilo.event.POINTER_END, onStop);
+ }
+
+ function onStop(e){
+ document.removeEventListener(Hilo.event.POINTER_END, onStop);
+ stage && stage.off(Hilo.event.POINTER_MOVE, onMove);
+
+ that.fire("dragEnd", mouse);
+ that.on(Hilo.event.POINTER_START, onStart);
+ }
+
+ function onMove(e){
+ updateMouse(e);
+
+ that.fire("dragMove", mouse);
+
+ var x = mouse.x + that.__dragX;
+ var y = mouse.y + that.__dragY;
+
+ that.x = Math.max(minX, Math.min(maxX, x));
+ that.y = Math.max(minY, Math.min(maxY, y));
+ }
+
+ function updateMouse(e){
+ mouse.preX = mouse.x;
+ mouse.preY = mouse.y;
+ mouse.x = e.stageX;
+ mouse.y = e.stageY;
+ }
+
+ function stopDrag(){
+ document.removeEventListener(Hilo.event.POINTER_END, onStop);
+ stage && stage.off(Hilo.event.POINTER_MOVE, onMove);
+ that.off(Hilo.event.POINTER_START, onStart);
+ }
+ that.on(Hilo.event.POINTER_START, onStart);
+
+ that.stopDrag = stopDrag;
+ },
+ /**
+ * 停止拖拽
+ */
+ stopDrag:function(){
+
+ }
+};
+
+return drag;
+
+}, {
+ requires: ['hilo/core/Class', 'hilo/core/Hilo']
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002896_Game.js b/pool/shard000/JavaScript/0002896_Game.js
new file mode 100644
index 0000000000000000000000000000000000000000..9d713ea53c7b47c27e66849196655f01fa8737f5
--- /dev/null
+++ b/pool/shard000/JavaScript/0002896_Game.js
@@ -0,0 +1,73 @@
+"use strict"
+
+const Ball = require("./Ball")
+const Paddle = require("./Paddle")
+const SAT = require("sat")
+const fond = require("../..")
+const { Canvas2d, Keyboard } = fond
+
+class Game
+{
+ constructor ()
+ {
+ this.ball = new Ball()
+ this.paddles = [
+ new Paddle({ x: 0, y: 250 }, { up: "w", down: "s" }),
+ new Paddle({ x: 475, y: 250 }, { up: "ArrowUp", down: "ArrowDown" }),
+ ]
+ }
+ enter ()
+ {
+ this.canvas2d = new Canvas2d()
+ this.canvas2d.resize(500, 500)
+ this.canvas2d.addToDom()
+ Keyboard.addEvents()
+ }
+ leave ()
+ {
+ this.canvas2d.removeFromDom()
+ Keyboard.removeEvents()
+ }
+ update (dt)
+ {
+ this.paddles.forEach((paddle) => paddle.update(dt))
+ this.ball.update(dt)
+ const ballShape = this.ball.getShape()
+ const response = new SAT.Response()
+ const collision = this.paddles.some((paddle) =>
+ {
+ const paddleShape = paddle.getShape()
+ response.clear()
+ return SAT.testPolygonCircle(paddleShape, ballShape, response)
+ })
+ if (collision)
+ {
+ this.ball.position.x += response.overlapV.x
+ this.ball.position.y += response.overlapV.y
+ }
+ if (collision && response.overlapV.y === 0)
+ {
+ this.ball.paddleBounce()
+ }
+ else if (collision && response.overlapV.y !== 0)
+ {
+ this.ball.wallBounce()
+ }
+ if (this.ball.position.y < 0 + this.ball.radius)
+ {
+ this.ball.wallBounce()
+ }
+ else if (this.ball.position.y > 500 - this.ball.radius)
+ {
+ this.ball.wallBounce()
+ }
+ }
+ draw ()
+ {
+ this.canvas2d.clear()
+ this.ball.draw(this.canvas2d)
+ this.paddles.forEach((paddle) => paddle.draw(this.canvas2d))
+ }
+}
+
+module.exports = Game
diff --git a/pool/shard000/JavaScript/0002905_15.9.3.2-1.js b/pool/shard000/JavaScript/0002905_15.9.3.2-1.js
new file mode 100644
index 0000000000000000000000000000000000000000..ae0502be64a6ed21bd74a25333baef2ea283226c
--- /dev/null
+++ b/pool/shard000/JavaScript/0002905_15.9.3.2-1.js
@@ -0,0 +1,151 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla Communicator client code, released
+ * March 31, 1998.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+gTestfile = '15.9.3.2-1.js';
+
+/**
+ File Name: 15.9.3.1.js
+ ECMA Section: 15.9.3.1 new Date (year, month, date, hours, minutes, seconds, ms)
+ Description: The [[Prototype]] property of the newly constructed
+ object is set to the original Date prototype object,
+ the one that is the initial value of Date.prototype.
+
+ The [[Class]] property of the newly constructed object
+ is set as follows:
+ 1. Call ToNumber(year)
+ 2. Call ToNumber(month)
+ 3. Call ToNumber(date)
+ 4. Call ToNumber(hours)
+ 5. Call ToNumber(minutes)
+ 6. Call ToNumber(seconds)
+ 7. Call ToNumber(ms)
+ 8. If Result(1)is NaN and 0 <= ToInteger(Result(1)) <=
+ 99, Result(8) is 1900+ToInteger(Result(1)); otherwise,
+ Result(8) is Result(1)
+ 9. Compute MakeDay(Result(8), Result(2), Result(3)
+ 10. Compute MakeTime(Result(4), Result(5), Result(6),
+ Result(7)
+ 11. Compute MakeDate(Result(9), Result(10))
+ 12. Set the [[Value]] property of the newly constructed
+ object to TimeClip(UTC(Result(11))).
+
+
+ This tests the returned value of a newly constructed
+ Date object.
+
+ Author: christine@netscape.com
+ Date: 7 july 1997
+*/
+
+var TIME = 0;
+var UTC_YEAR = 1;
+var UTC_MONTH = 2;
+var UTC_DATE = 3;
+var UTC_DAY = 4;
+var UTC_HOURS = 5;
+var UTC_MINUTES = 6;
+var UTC_SECONDS = 7;
+var UTC_MS = 8;
+
+var YEAR = 9;
+var MONTH = 10;
+var DATE = 11;
+var DAY = 12;
+var HOURS = 13;
+var MINUTES = 14;
+var SECONDS = 15;
+var MS = 16;
+
+// for TCMS, the gTestcases array must be global.
+var SECTION = "15.9.3.1";
+var TITLE = "Date( year, month, date, hours, minutes, seconds )";
+startTest();
+
+writeHeaderToLog( SECTION+" " +TITLE );
+
+// Dates around 1970
+
+addNewTestCase( new Date( 1969,11,31,15,59,59),
+ "new Date( 1969,11,31,15,59,59)",
+ [-1000,1969,11,31,3,23,59,59,0,1969,11,31,3,15,59,59,0] );
+
+addNewTestCase( new Date( 1969,11,31,16,0,0),
+ "new Date( 1969,11,31,16,0,0)",
+ [0,1970,0,1,4,0,0,0,0,1969,11,31,3,16,0,0,0] );
+
+addNewTestCase( new Date( 1969,11,31,23,59,59),
+ "new Date( 1969,11,31,23,59,59)",
+ [28799000,1970,0,1,4,7,59,59,0,1969,11,31,3,23,59,59,0] );
+
+addNewTestCase( new Date( 1970, 0, 1, 0, 0, 0),
+ "new Date( 1970, 0, 1, 0, 0, 0)",
+ [28800000,1970,0,1,4,8,0,0,0,1970,0,1,4,0,0,0,0] );
+
+addNewTestCase( new Date( 1969,11,31,16,0,0),
+ "new Date( 1969,11,31,16,0,0)",
+ [0,1970,0,1,4,0,0,0,0,1969,11,31,3,16,0,0,0] );
+
+test();
+
+function addNewTestCase( DateCase, DateString, ResultArray ) {
+ //adjust hard-coded ResultArray for tester's timezone instead of PST
+ adjustResultArray(ResultArray);
+
+
+ new TestCase( SECTION, DateString+".getTime()", ResultArray[TIME], DateCase.getTime() );
+ new TestCase( SECTION, DateString+".valueOf()", ResultArray[TIME], DateCase.valueOf() );
+
+ new TestCase( SECTION, DateString+".getUTCFullYear()", ResultArray[UTC_YEAR], DateCase.getUTCFullYear() );
+ new TestCase( SECTION, DateString+".getUTCMonth()", ResultArray[UTC_MONTH], DateCase.getUTCMonth() );
+ new TestCase( SECTION, DateString+".getUTCDate()", ResultArray[UTC_DATE], DateCase.getUTCDate() );
+ new TestCase( SECTION, DateString+".getUTCDay()", ResultArray[UTC_DAY], DateCase.getUTCDay() );
+ new TestCase( SECTION, DateString+".getUTCHours()", ResultArray[UTC_HOURS], DateCase.getUTCHours() );
+ new TestCase( SECTION, DateString+".getUTCMinutes()", ResultArray[UTC_MINUTES],DateCase.getUTCMinutes() );
+ new TestCase( SECTION, DateString+".getUTCSeconds()", ResultArray[UTC_SECONDS],DateCase.getUTCSeconds() );
+ new TestCase( SECTION, DateString+".getUTCMilliseconds()", ResultArray[UTC_MS], DateCase.getUTCMilliseconds() );
+
+ new TestCase( SECTION, DateString+".getFullYear()", ResultArray[YEAR], DateCase.getFullYear() );
+ new TestCase( SECTION, DateString+".getMonth()", ResultArray[MONTH], DateCase.getMonth() );
+ new TestCase( SECTION, DateString+".getDate()", ResultArray[DATE], DateCase.getDate() );
+ new TestCase( SECTION, DateString+".getDay()", ResultArray[DAY], DateCase.getDay() );
+ new TestCase( SECTION, DateString+".getHours()", ResultArray[HOURS], DateCase.getHours() );
+ new TestCase( SECTION, DateString+".getMinutes()", ResultArray[MINUTES], DateCase.getMinutes() );
+ new TestCase( SECTION, DateString+".getSeconds()", ResultArray[SECONDS], DateCase.getSeconds() );
+ new TestCase( SECTION, DateString+".getMilliseconds()", ResultArray[MS], DateCase.getMilliseconds() );
+
+}
diff --git a/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js b/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js
new file mode 100644
index 0000000000000000000000000000000000000000..be3a5335dbe9ef9e9d60b15d06993dd753ecf049
--- /dev/null
+++ b/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js
@@ -0,0 +1,27 @@
+/*
+Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
+Mocha integration test from: microformats-v2/h-event/justaname
+The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
+*/
+
+assert = chai.assert;
+
+
+describe('h-event', function() {
+ var htmlFragment = "IndieWebCamp 2012
";
+ var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"]}}],"rels":{},"rel-urls":{}};
+
+ it('justaname', function(){
+ var doc, dom, node, options, parser, found;
+ dom = new DOMParser();
+ doc = dom.parseFromString( htmlFragment, 'text/html' );
+ options ={
+ 'document': doc,
+ 'node': doc,
+ 'baseUrl': 'http://example.com',
+ 'dateFormat': 'html5'
+ };
+ found = Microformats.get( options );
+ assert.deepEqual(found, expected);
+ });
+});
diff --git a/pool/shard000/JavaScript/0002910_index.js b/pool/shard000/JavaScript/0002910_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..a09cad37f2cb65a5aeffa976f376dabb14b0772b
--- /dev/null
+++ b/pool/shard000/JavaScript/0002910_index.js
@@ -0,0 +1,57 @@
+const {
+ Nuxt,
+ Builder,
+} = require('nuxt')
+
+
+/* API server start */
+require('./models')
+const express = require('express')
+
+const app = express()
+const bodyParser = require('body-parser')
+const cookieParser = require('cookie-parser')
+const path = require('path')
+const cors = require('cors')
+const staticServer = express.static(path.resolve(__dirname, '../public'), { maxAge: 1000 * 60 * 60 * 24 })
+const globalConfig = require('./config/global.config')
+const handle = require('./middlewares/handle.middleware')
+const validate = require('./middlewares/validate.middleware')
+const domain = require('./middlewares/domain.middleware')
+const router = require('./router')
+
+app.enable('trust proxy')
+app.use(cors({ origin: globalConfig.app.domain, credentials: true }))
+ .use(domain)
+ .use(bodyParser.json({ limit: '50mb' }))
+ .use(cookieParser())
+ .use('/public', staticServer)
+ .use(handle)
+ .use(validate)
+ .use(router)
+
+/* API server end */
+
+// Import and Set Nuxt.js options
+let config = require('../nuxt.config.js')
+config.dev = !(process.env.NODE_ENV === 'production')
+
+async function start() {
+ // Init Nuxt.js
+ const nuxt = new Nuxt(config)
+
+ // Build only in dev mode
+ if (config.dev) {
+ const builder = new Builder(nuxt)
+ await builder.build()
+ }
+
+ // Give nuxt middleware to express
+ app.use(nuxt.render)
+
+ // Listen the server
+ app.listen(3025, () => {
+ console.log(`server started at ${globalConfig.app.domain}`)
+ })
+}
+start()
diff --git a/pool/shard000/JavaScript/0002911_lowercase_pipe.js b/pool/shard000/JavaScript/0002911_lowercase_pipe.js
new file mode 100644
index 0000000000000000000000000000000000000000..a14d3686a072943eb7c410be539fb71fd73c03db
--- /dev/null
+++ b/pool/shard000/JavaScript/0002911_lowercase_pipe.js
@@ -0,0 +1,51 @@
+/**
+ * @license
+ * Copyright Google Inc. All Rights Reserved.
+ *
+ * Use of this source code is governed by an MIT-style license that can be
+ * found in the LICENSE file at https://angular.io/license
+ */
+import { Pipe } from '@angular/core';
+import { isBlank } from '../facade/lang';
+import { InvalidPipeArgumentError } from './invalid_pipe_argument_error';
+/**
+ * *
+ * Converts value into a lowercase string using `String.prototype.toLowerCase()`.
+ * *
+ * ### Example
+ * *
+ * {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe'}
+ * *
+ */
+export var LowerCasePipe = (function () {
+ function LowerCasePipe() {
+ }
+ /**
+ * @param {?} value
+ * @return {?}
+ */
+ LowerCasePipe.prototype.transform = function (value) {
+ if (isBlank(value))
+ return value;
+ if (typeof value !== 'string') {
+ throw new InvalidPipeArgumentError(LowerCasePipe, value);
+ }
+ return value.toLowerCase();
+ };
+ LowerCasePipe.decorators = [
+ { type: Pipe, args: [{ name: 'lowercase' },] },
+ ];
+ /** @nocollapse */
+ LowerCasePipe.ctorParameters = function () { return []; };
+ return LowerCasePipe;
+}());
+function LowerCasePipe_tsickle_Closure_declarations() {
+ /** @type {?} */
+ LowerCasePipe.decorators;
+ /**
+ * @nocollapse
+ * @type {?}
+ */
+ LowerCasePipe.ctorParameters;
+}
+//# sourceMappingURL=lowercase_pipe.js.map
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0002914_usemin.js b/pool/shard000/JavaScript/0002914_usemin.js
new file mode 100644
index 0000000000000000000000000000000000000000..bc0d5bbf9b85438f22f3fd60031bc34f5bae7c77
--- /dev/null
+++ b/pool/shard000/JavaScript/0002914_usemin.js
@@ -0,0 +1,34 @@
+/**
+ * usemin
+ * ======
+ *
+ * Performs rewrites based on rev and the useminPrepare configuration.
+ *
+ * Link: https://github.com/yeoman/grunt-usemin
+ */
+
+'use strict';
+
+module.exports = function (grunt) {
+ return {
+ html: ['<%= pkg.config.public %>/{,*/}*.html'],
+ css: ['<%= pkg.config.public %>/styles/{,*/}*.css'],
+ options: {
+ assetsDirs: ['<%= pkg.config.public %>'],
+ blockReplacements: {
+ js: function (block) {
+
+ var asyncScripts = [
+ 'scripts/all.js'
+ ];
+
+ var isAsync = block.async || asyncScripts.indexOf(block.dest) > -1;
+
+ return isAsync ?
+ '');
+ jsCount++;
+ jsSize += js.length;
+ }
+
+ if (options.css) {
+ $(':not(noscript) > link[rel="stylesheet"]').each(function() {
+ var regex = /([,\s,:]url\(['"]?(?!data:))([^\)'"]+)(?=['"]?\))/gi;
+ var href = $(this).attr('href');
+
+ if (options.baseDir) {
+ baseDir = path.resolve(options.baseDir);
+ }
+
+ var stylePath = path.resolve(baseDir, href);
+
+ if (url.parse(href).hostname || /^\/\//.test(href)) {
+
+ if (options.remote) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', href, false);
+ xhr.send(null);
+
+ if (xhr.readyState === 4) {
+ injectStyle($(this), xhr.responseText);
+ }
+ } else {
+ grunt.log.warn('Remote stylesheet "' + href + '" found. Skipping.');
+ return;
+ }
+
+ } else if (href) {
+
+ if (!grunt.file.exists(stylePath)) {
+ grunt.log.warn('Stylesheet "' + href + '" not found.');
+ return;
+ }
+
+ var css = grunt.file.read(stylePath);
+
+ if (options.rebase) {
+ css = css.replace(regex, function(whole, front, href) {
+ if (url.parse(href).hostname) {
+ return whole;
+ }
+ return front + path.relative(baseDir, path.resolve(path.dirname(stylePath), href)).replace(/\\/g, '/');
+ });
+ }
+
+ injectStyle($(this), css);
+
+ }
+
+ });
+ }
+
+ if (options.js) {
+ $('head script[src]').each(function() {
+ var href = $(this).attr('src');
+
+ if (options.baseDir) {
+ baseDir = path.resolve(options.baseDir);
+ }
+
+ var stylePath = path.resolve(baseDir, href);
+
+ var scriptPath = path.resolve(baseDir, href);
+
+ if (url.parse(href).hostname || /^\/\//.test(href)) {
+
+ if (options.remote) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', href, false);
+ xhr.send(null);
+
+ if (xhr.readyState === 4) {
+ injectScript($(this), xhr.responseText);
+ }
+ } else {
+ grunt.log.warn('Remote script "' + href + '" found. Skipping.');
+ return;
+ }
+
+ } else if (href) {
+
+ if (!grunt.file.exists(scriptPath)) {
+ grunt.log.warn('Script "' + href + '" not found.');
+ return;
+ }
+
+ var js = grunt.file.read(scriptPath);
+
+ injectScript($(this), js);
+
+ }
+
+ });
+ }
+
+ if (jsCount || cssCount) {
+ grunt.file.write(f.dest, $.html());
+ if (options.css) {
+ grunt.log.writeln(cssCount + ' stylesheet' + (cssCount > 1 ? 's' : '') + ' of size ' + filesize(cssSize) + ' inlined into "' + f.dest + '".');
+ }
+ if (options.js) {
+ grunt.log.writeln(jsCount + ' script' + (jsCount > 1 ? 's' : '') + ' of size ' + filesize(jsSize) + ' inlined into "' + f.dest + '".');
+ }
+ }
+
+ });
+
+ });
+
+};
diff --git a/pool/shard000/JavaScript/0003637_index.js b/pool/shard000/JavaScript/0003637_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..32bc15ad9ff413d17cf1d29fc9fa28280e2a7208
--- /dev/null
+++ b/pool/shard000/JavaScript/0003637_index.js
@@ -0,0 +1,17 @@
+(function () {
+ 'use strict';
+
+ var Static = require('node-static');
+
+ module.exports = function (dir, port) {
+ var fileServer = new Static.Server(dir || './');
+
+ return require('http').createServer(function (req, res) {
+ req.addListener('end', function () {
+ fileServer.serve(req, res);
+ }).resume();
+ }).listen(port || 8080);
+
+ };
+
+})();
diff --git a/pool/shard000/JavaScript/0003638_server.js b/pool/shard000/JavaScript/0003638_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..af53860a0d50096da0ad0e08c2c51cb48a4b3c25
--- /dev/null
+++ b/pool/shard000/JavaScript/0003638_server.js
@@ -0,0 +1,25 @@
+// Dependencias
+var express = require('express');
+var MongoClient = require('mongodb').MongoClient;
+var bodyParser = require('body-parser');
+var logger = require('morgan');
+
+// Instancia aplicación
+var app = module.exports = express();
+var port = process.env.PORT || 80;
+
+MongoClient.connect('mongodb://localhost:27017/planetasDB', function(err, db) {
+ if(err) throw err;
+
+ //Middleware
+ app.use(bodyParser.json());
+ app.use(logger('dev'));
+
+ // Rutas
+ var Planetas = require('./routes/planetas');
+ var planetasRouter = new Planetas(db).router;
+ app.use('/planetas', planetasRouter);
+
+ app.listen(port);
+ console.log('Servidor iniciado en el puerto ' + port);
+});
diff --git a/pool/shard000/JavaScript/0003639_index.js b/pool/shard000/JavaScript/0003639_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..e8c341de68fab65f9de74d4fca29e8a3a2411155
--- /dev/null
+++ b/pool/shard000/JavaScript/0003639_index.js
@@ -0,0 +1,131 @@
+/*
+ MIT License http://www.opensource.org/licenses/mit-license.php
+ Author Tobias Koppers @sokra
+*/
+
+"use strict";
+
+const fs = require("fs");
+const CachedInputFileSystem = require("./CachedInputFileSystem");
+const ResolverFactory = require("./ResolverFactory");
+
+/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */
+/** @typedef {import("./Resolver")} Resolver */
+/** @typedef {import("./Resolver").FileSystem} FileSystem */
+/** @typedef {import("./Resolver").ResolveContext} ResolveContext */
+/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
+/** @typedef {import("./ResolverFactory").Plugin} Plugin */
+/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */
+
+const nodeFileSystem = new CachedInputFileSystem(fs, 4000);
+
+const nodeContext = {
+ environments: ["node+es3+es5+process+native"]
+};
+
+const asyncResolver = ResolverFactory.createResolver({
+ conditionNames: ["node"],
+ extensions: [".js", ".json", ".node"],
+ fileSystem: nodeFileSystem
+});
+function resolve(context, path, request, resolveContext, callback) {
+ if (typeof context === "string") {
+ callback = resolveContext;
+ resolveContext = request;
+ request = path;
+ path = context;
+ context = nodeContext;
+ }
+ if (typeof callback !== "function") {
+ callback = resolveContext;
+ }
+ asyncResolver.resolve(context, path, request, resolveContext, callback);
+}
+
+const syncResolver = ResolverFactory.createResolver({
+ conditionNames: ["node"],
+ extensions: [".js", ".json", ".node"],
+ useSyncFileSystemCalls: true,
+ fileSystem: nodeFileSystem
+});
+function resolveSync(context, path, request) {
+ if (typeof context === "string") {
+ request = path;
+ path = context;
+ context = nodeContext;
+ }
+ return syncResolver.resolveSync(context, path, request);
+}
+
+function create(options) {
+ options = {
+ fileSystem: nodeFileSystem,
+ ...options
+ };
+ const resolver = ResolverFactory.createResolver(options);
+ return function (context, path, request, resolveContext, callback) {
+ if (typeof context === "string") {
+ callback = resolveContext;
+ resolveContext = request;
+ request = path;
+ path = context;
+ context = nodeContext;
+ }
+ if (typeof callback !== "function") {
+ callback = resolveContext;
+ }
+ resolver.resolve(context, path, request, resolveContext, callback);
+ };
+}
+
+function createSync(options) {
+ options = {
+ useSyncFileSystemCalls: true,
+ fileSystem: nodeFileSystem,
+ ...options
+ };
+ const resolver = ResolverFactory.createResolver(options);
+ return function (context, path, request) {
+ if (typeof context === "string") {
+ request = path;
+ path = context;
+ context = nodeContext;
+ }
+ return resolver.resolveSync(context, path, request);
+ };
+}
+
+/**
+ * @template A
+ * @template B
+ * @param {A} obj input a
+ * @param {B} exports input b
+ * @returns {A & B} merged
+ */
+const mergeExports = (obj, exports) => {
+ const descriptors = Object.getOwnPropertyDescriptors(exports);
+ Object.defineProperties(obj, descriptors);
+ return /** @type {A & B} */ (Object.freeze(obj));
+};
+
+module.exports = mergeExports(resolve, {
+ get sync() {
+ return resolveSync;
+ },
+ create: mergeExports(create, {
+ get sync() {
+ return createSync;
+ }
+ }),
+ ResolverFactory,
+ CachedInputFileSystem,
+ get CloneBasenamePlugin() {
+ return require("./CloneBasenamePlugin");
+ },
+ get LogInfoPlugin() {
+ return require("./LogInfoPlugin");
+ },
+ get forEachBail() {
+ return require("./forEachBail");
+ }
+});
diff --git a/pool/shard000/JavaScript/0003640_plugin.js b/pool/shard000/JavaScript/0003640_plugin.js
new file mode 100644
index 0000000000000000000000000000000000000000..f4320f4e52e609743a762f544ff5de200dd45470
--- /dev/null
+++ b/pool/shard000/JavaScript/0003640_plugin.js
@@ -0,0 +1,201 @@
+/*
+Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
+For licensing, see LICENSE.html or http://ckeditor.com/license
+*/
+
+/**
+ * @fileOverview The "elementspath" plugin. It shows all elements in the DOM
+ * parent tree relative to the current selection in the editing area.
+ */
+
+(function()
+{
+ var commands =
+ {
+ toolbarFocus :
+ {
+ exec : function( editor )
+ {
+ var idBase = editor._.elementsPath.idBase;
+ var element = CKEDITOR.document.getById( idBase + '0' );
+
+ // Make the first button focus accessible for IE. (#3417)
+ // Adobe AIR instead need while of delay.
+ element && element.focus( CKEDITOR.env.ie || CKEDITOR.env.air );
+ }
+ }
+ };
+
+ var emptyHtml = ' ';
+
+ CKEDITOR.plugins.add( 'elementspath',
+ {
+ requires : [ 'selection' ],
+
+ init : function( editor )
+ {
+ var spaceId = 'cke_path_' + editor.name;
+ var spaceElement;
+ var getSpaceElement = function()
+ {
+ if ( !spaceElement )
+ spaceElement = CKEDITOR.document.getById( spaceId );
+ return spaceElement;
+ };
+
+ var idBase = 'cke_elementspath_' + CKEDITOR.tools.getNextNumber() + '_';
+
+ editor._.elementsPath = { idBase : idBase, filters : [] };
+
+ editor.on( 'themeSpace', function( event )
+ {
+ if ( event.data.space == 'bottom' )
+ {
+ event.data.html +=
+ '' + editor.lang.elementsPath.eleLabel + ' ' +
+ '' + emptyHtml + '
';
+ }
+ });
+
+ function onClick( elementIndex )
+ {
+ editor.focus();
+ var element = editor._.elementsPath.list[ elementIndex ];
+ if ( element.is( 'body' ) )
+ {
+ var range = new CKEDITOR.dom.range( editor.document );
+ range.selectNodeContents( element );
+ range.select();
+ }
+ else
+ editor.getSelection().selectElement( element );
+ }
+
+ var onClickHanlder = CKEDITOR.tools.addFunction( onClick );
+
+ var onKeyDownHandler = CKEDITOR.tools.addFunction( function( elementIndex, ev )
+ {
+ var idBase = editor._.elementsPath.idBase,
+ element;
+
+ ev = new CKEDITOR.dom.event( ev );
+
+ var rtl = editor.lang.dir == 'rtl';
+ switch ( ev.getKeystroke() )
+ {
+ case rtl ? 39 : 37 : // LEFT-ARROW
+ case 9 : // TAB
+ element = CKEDITOR.document.getById( idBase + ( elementIndex + 1 ) );
+ if ( !element )
+ element = CKEDITOR.document.getById( idBase + '0' );
+ element.focus();
+ return false;
+
+ case rtl ? 37 : 39 : // RIGHT-ARROW
+ case CKEDITOR.SHIFT + 9 : // SHIFT + TAB
+ element = CKEDITOR.document.getById( idBase + ( elementIndex - 1 ) );
+ if ( !element )
+ element = CKEDITOR.document.getById( idBase + ( editor._.elementsPath.list.length - 1 ) );
+ element.focus();
+ return false;
+
+ case 27 : // ESC
+ editor.focus();
+ return false;
+
+ case 13 : // ENTER // Opera
+ case 32 : // SPACE
+ onClick( elementIndex );
+ return false;
+ }
+ return true;
+ });
+
+ editor.on( 'selectionChange', function( ev )
+ {
+ var env = CKEDITOR.env,
+ selection = ev.data.selection,
+ element = selection.getStartElement(),
+ html = [],
+ editor = ev.editor,
+ elementsList = editor._.elementsPath.list = [],
+ filters = editor._.elementsPath.filters;
+
+ while ( element )
+ {
+ var ignore = 0;
+ for ( var i = 0; i < filters.length; i++ )
+ {
+ if ( filters[ i ]( element ) === false )
+ {
+ ignore = 1;
+ break;
+ }
+ }
+
+ if ( !ignore )
+ {
+ var index = elementsList.push( element ) - 1;
+ var name;
+ if ( element.data( 'cke-real-element-type' ) )
+ name = element.data( 'cke-real-element-type' );
+ else
+ name = element.getName();
+
+ // Use this variable to add conditional stuff to the
+ // HTML (because we are doing it in reverse order... unshift).
+ var extra = '';
+
+ // Some browsers don't cancel key events in the keydown but in the
+ // keypress.
+ // TODO: Check if really needed for Gecko+Mac.
+ if ( env.opera || ( env.gecko && env.mac ) )
+ extra += ' onkeypress="return false;"';
+
+ // With Firefox, we need to force the button to redraw, otherwise it
+ // will remain in the focus state.
+ if ( env.gecko )
+ extra += ' onblur="this.style.cssText = this.style.cssText;"';
+
+ var label = editor.lang.elementsPath.eleTitle.replace( /%1/, name );
+ html.unshift(
+ '',
+ name,
+ '' + label + ' ',
+ ' ' );
+
+ }
+
+ if ( name == 'body' )
+ break;
+
+ element = element.getParent();
+ }
+
+ var space = getSpaceElement();
+ space.setHtml( html.join('') + emptyHtml );
+ editor.fire( 'elementsPathUpdate', { space : space } );
+ });
+
+ editor.on( 'contentDomUnload', function()
+ {
+ // If the spaceElement hasn't been initialized, don't try to do it at this time
+ // Only reuse existing reference.
+ spaceElement && spaceElement.setHtml( emptyHtml );
+ });
+
+ editor.addCommand( 'elementsPathFocus', commands.toolbarFocus );
+ }
+ });
+})();
diff --git a/pool/shard000/JavaScript/0003642_test.js b/pool/shard000/JavaScript/0003642_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..adf72aeadfa1350fa6732e9a2386c7e5a8febaf6
--- /dev/null
+++ b/pool/shard000/JavaScript/0003642_test.js
@@ -0,0 +1,281 @@
+'use strict';
+
+const test = require('ava');
+const fs = require('fs');
+const gutil = require('gulp-util');
+const image = require('..');
+
+test('should minify PNG images with pngquant', t => {
+ const stream = image({
+ pngquant : true,
+ optipng : false,
+ zopflipng : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.png').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.png`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.png`)
+ }));
+
+ stream.end();
+});
+
+test('should minify PNG images with optipng', t => {
+ const stream = image({
+ pngquant : false,
+ optipng : true,
+ zopflipng : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.png').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.png`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.png`)
+ }));
+
+ stream.end();
+});
+
+test('should minify PNG images with zopflipng', t => {
+ const stream = image({
+ pngquant : false,
+ optipng : false,
+ zopflipng : true
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.png').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.png`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.png`)
+ }));
+
+ stream.end();
+});
+
+test('should not minify PNG images when related options are disabled', t => {
+ const stream = image({
+ pngquant : false,
+ optipng : false,
+ zopflipng : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.png').size;
+ const after = file.contents.length;
+ t.true(after === before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.png`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.png`)
+ }));
+
+ stream.end();
+});
+
+test('should minify JPG images with jpegRecompress', t => {
+ const stream = image({
+ jpegRecompress : true,
+ jpegoptim : false,
+ mozjpeg : false,
+ guetzli : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.jpg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.jpg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`)
+ }));
+
+ stream.end();
+});
+
+test('should minify JPG images with jpegoptim', t => {
+ const stream = image({
+ jpegRecompress : false,
+ jpegoptim : true,
+ mozjpeg : false,
+ guetzli : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.jpg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.jpg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`)
+ }));
+
+ stream.end();
+});
+
+test('should minify JPG images with mozjpeg', t => {
+ const stream = image({
+ jpegRecompress : false,
+ jpegoptim : false,
+ mozjpeg : true,
+ guetzli : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.jpg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.jpg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`)
+ }));
+
+ stream.end();
+});
+
+test('should minify JPG images with guetzli', t => {
+ const stream = image({
+ jpegRecompress : false,
+ jpegoptim : false,
+ mozjpeg : false,
+ guetzli : true
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.jpg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.jpg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`)
+ }));
+
+ stream.end();
+});
+
+test('should not minify JPG images when related options are disabled', t => {
+ const stream = image({
+ jpegRecompress : false,
+ jpegoptim : false,
+ mozjpeg : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.jpg').size;
+ const after = file.contents.length;
+ t.true(after === before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.jpg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`)
+ }));
+
+ stream.end();
+});
+
+test('should minify GIF images', t => {
+ const stream = image();
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.gif').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.gif`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.gif`)
+ }));
+
+ stream.end();
+});
+
+test('should not minify GIF images when related options are disabled', t => {
+ const stream = image({
+ gifsicle : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.gif').size;
+ const after = file.contents.length;
+ t.true(after === before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.gif`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.gif`)
+ }));
+
+ stream.end();
+});
+
+test('should minify SVG images', t => {
+ const stream = image();
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.svg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.svg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.svg`)
+ }));
+});
+
+test('should not minify SVG images when related options are disabled', t => {
+ const stream = image({
+ svgo : false
+ });
+
+ stream.on('data', file => {
+ const before = fs.statSync('test/fixtures/test.svg').size;
+ const after = file.contents.length;
+ t.true(after < before);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}/fixtures/test.svg`,
+ contents : fs.readFileSync(`${__dirname}/fixtures/test.svg`)
+ }));
+});
+
+test('should skip unsupported images', t => {
+ const stream = image();
+
+ stream.on('data', file => {
+ t.is(file.contents, null);
+ });
+
+ stream.write(new gutil.File({
+ path : `${__dirname}fixtures/test.bmp`
+ }));
+
+ stream.end();
+});
diff --git a/pool/shard000/JavaScript/0003643_utils.js b/pool/shard000/JavaScript/0003643_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..edd9c77d58a114c448cdc50fe7f00fc9f88df834
--- /dev/null
+++ b/pool/shard000/JavaScript/0003643_utils.js
@@ -0,0 +1,68 @@
+'use strict';
+
+/**
+ * @ngdoc service
+ * @name sdcApp.Utils
+ * @description
+ * # Utils
+ * Service in the sdcApp.
+ */
+angular.module('Sdc')
+ .factory('Utils', function () {
+ var service = {
+ /**
+ * Macro for checking if things are defined or null.
+ * Help from: http://stackoverflow.com/a/17910655/687274
+ * @param obj
+ * @returns {boolean}
+ */
+ isUndefinedOrNull: function(obj) {
+ return !angular.isDefined(obj) || obj===null;
+ },
+
+ /**
+ * obj.toLocalString() replacement, as its unreliable across different web renderers.
+ * Help from: http://stackoverflow.com/a/16157942
+ * @param x
+ * @param sep
+ * @param grp
+ * @returns {*}
+ */
+ localeString: function(x, sep, grp) {
+ var sx = (''+x).split('.'), s = '', i, j;
+ sep = sep || (sep = ','); // default seperator
+ grp = grp || grp === 0 || (grp = 3); // default grouping
+ i = sx[0].length;
+ while (i > grp) {
+ j = i - grp;
+ s = sep + sx[0].slice(j, i) + s;
+ i = j;
+ }
+ s = sx[0].slice(0, i) + s;
+ sx[0] = s;
+ return sx.join('.');
+ }
+ };
+
+ return service;
+ })
+
+/**
+ * localstorage service, as per: http://learn.ionicframework.com/formulas/localstorage/#
+ */
+ .factory('$localstorage', function($window) {
+ return {
+ set: function(key, value) {
+ $window.localStorage[key] = value;
+ },
+ get: function(key, defaultValue) {
+ return $window.localStorage[key] || defaultValue;
+ },
+ setObject: function(key, value) {
+ $window.localStorage[key] = JSON.stringify(value);
+ },
+ getObject: function(key) {
+ return JSON.parse($window.localStorage[key] || '{}');
+ }
+ };
+ });
diff --git a/pool/shard000/JavaScript/0003644_user.js b/pool/shard000/JavaScript/0003644_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..908b70d4a639e0784982b63c499c31a3978a64e4
--- /dev/null
+++ b/pool/shard000/JavaScript/0003644_user.js
@@ -0,0 +1,113 @@
+/**
+ * Stack Rank
+ * Copyright (C) 2016 Mule Dojo
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ *
+ * @category Code
+ * @package models
+ * @author Ignacio R. Galieri
+ * @copyright 2016 Mule Dojo
+ * @license GPL-3.0
+ * @link https://github.com/MuleDojo/stackrank
+ */
+"use strict";
+
+var crypto = require('crypto');
+
+class User {
+ /**
+ * Constructor
+ *
+ * @constructor
+ * @api public
+ */
+ constructor () {
+ this.firstname = '';
+ this.lastname = '';
+ this.email = '';
+ this.tasks = [];
+ this._id = null;
+ }
+ /**
+ * addTask
+ *
+ * Add a New Task.
+ *
+ * @param {Task} task A new Task
+ *
+ * @return void
+ * @api public
+ */
+ addTask(task) {
+ task._id = crypto.createHash('md5').update(JSON.stringify(task)).digest("hex");
+ this.tasks.push(task);
+ }
+ /**
+ * deleteTask
+ *
+ * Delete a Task.
+ *
+ * @param {Task} task Task for delete
+ *
+ * @return void
+ * @api public
+ */
+ deleteTask(task) {
+ let index = this.tasks.findIndex(function (obj) {
+ return obj._id == task._id;
+ });
+
+ if (index > -1) {
+ this.tasks.splice(index, 1);
+ }
+ }
+ /**
+ * sortTasks
+ *
+ * Order task by urgency, importance and dateAdmission
+ *
+ * @param {Function} callback Callback
+ *
+ * @return void
+ * @api public
+ */
+ sortTasks(callback) {
+ var orderByProperty = function orderByProperty(prop) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function (b, a) {
+ var value1 = a[prop];
+ if (a[prop] instanceof Date) {
+ value1 = a[prop].getTime();
+ }
+ var value2 = b[prop];
+ if (b[prop] instanceof Date) {
+ value2 = b[prop].getTime();
+ }
+
+ var equality = value1 - value2;
+ if (equality === 0 && arguments.length > 1) {
+ return orderByProperty.apply(null, args)(b, a);
+ }
+ return equality;
+ };
+ };
+
+ this.tasks.sort(orderByProperty('urgency', 'importance', 'dateAdmission'));
+
+ callback(false);
+ }
+}
+
+module.exports = User;
diff --git a/pool/shard000/JavaScript/0003646_PluginCache.js b/pool/shard000/JavaScript/0003646_PluginCache.js
new file mode 100644
index 0000000000000000000000000000000000000000..5debe7827eecefca0a4c84bcb003710f15bafc01
--- /dev/null
+++ b/pool/shard000/JavaScript/0003646_PluginCache.js
@@ -0,0 +1,177 @@
+/**
+ * @author Richard Davey
+ * @copyright 2018 Photon Storm Ltd.
+ * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+ */
+
+// Contains the plugins that Phaser uses globally and locally.
+// These are the source objects, not instantiated.
+var corePlugins = {};
+
+// Contains the plugins that the dev has loaded into their game
+// These are the source objects, not instantiated.
+var customPlugins = {};
+
+/**
+ * @typedef {object} CorePluginContainer
+ *
+ * @property {string} key - The unique name of this plugin in the core plugin cache.
+ * @property {function} plugin - The plugin to be stored. Should be the source object, not instantiated.
+ * @property {string} [mapping] - If this plugin is to be injected into the Scene Systems, this is the property key map used.
+ * @property {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin?
+ */
+
+/**
+ * @typedef {object} CustomPluginContainer
+ *
+ * @property {string} key - The unique name of this plugin in the custom plugin cache.
+ * @property {function} plugin - The plugin to be stored. Should be the source object, not instantiated.
+ */
+
+var PluginCache = {};
+
+/**
+ * Static method called directly by the Core internal Plugins.
+ * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin)
+ * Plugin is the object to instantiate to create the plugin
+ * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input)
+ *
+ * @method Phaser.Plugins.PluginCache.register
+ * @since 3.8.0
+ *
+ * @param {string} key - A reference used to get this plugin from the plugin cache.
+ * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated.
+ * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used.
+ * @param {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin?
+ */
+PluginCache.register = function (key, plugin, mapping, custom)
+{
+ if (custom === undefined) { custom = false; }
+
+ corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom };
+};
+
+/**
+ * Stores a custom plugin in the global plugin cache.
+ * The key must be unique, within the scope of the cache.
+ *
+ * @method Phaser.Plugins.PluginCache.registerCustom
+ * @since 3.8.0
+ *
+ * @param {string} key - A reference used to get this plugin from the plugin cache.
+ * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated.
+ * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used.
+ */
+PluginCache.registerCustom = function (key, plugin, mapping)
+{
+ customPlugins[key] = { plugin: plugin, mapping: mapping };
+};
+
+/**
+ * Checks if the given key is already being used in the core plugin cache.
+ *
+ * @method Phaser.Plugins.PluginCache.hasCore
+ * @since 3.8.0
+ *
+ * @param {string} key - The key to check for.
+ *
+ * @return {boolean} `true` if the key is already in use in the core cache, otherwise `false`.
+ */
+PluginCache.hasCore = function (key)
+{
+ return corePlugins.hasOwnProperty(key);
+};
+
+/**
+ * Checks if the given key is already being used in the custom plugin cache.
+ *
+ * @method Phaser.Plugins.PluginCache.hasCustom
+ * @since 3.8.0
+ *
+ * @param {string} key - The key to check for.
+ *
+ * @return {boolean} `true` if the key is already in use in the custom cache, otherwise `false`.
+ */
+PluginCache.hasCustom = function (key)
+{
+ return customPlugins.hasOwnProperty(key);
+};
+
+/**
+ * Returns the core plugin object from the cache based on the given key.
+ *
+ * @method Phaser.Plugins.PluginCache.getCore
+ * @since 3.8.0
+ *
+ * @param {string} key - The key of the core plugin to get.
+ *
+ * @return {CorePluginContainer} The core plugin object.
+ */
+PluginCache.getCore = function (key)
+{
+ return corePlugins[key];
+};
+
+/**
+ * Returns the custom plugin object from the cache based on the given key.
+ *
+ * @method Phaser.Plugins.PluginCache.getCustom
+ * @since 3.8.0
+ *
+ * @param {string} key - The key of the custom plugin to get.
+ *
+ * @return {CustomPluginContainer} The custom plugin object.
+ */
+PluginCache.getCustom = function (key)
+{
+ return customPlugins[key];
+};
+
+/**
+ * Returns an object from the custom cache based on the given key that can be instantiated.
+ *
+ * @method Phaser.Plugins.PluginCache.getCustomClass
+ * @since 3.8.0
+ *
+ * @param {string} key - The key of the custom plugin to get.
+ *
+ * @return {function} The custom plugin object.
+ */
+PluginCache.getCustomClass = function (key)
+{
+ return (customPlugins.hasOwnProperty(key)) ? customPlugins[key].plugin : null;
+};
+
+/**
+ * Removes a core plugin based on the given key.
+ *
+ * @method Phaser.Plugins.PluginCache.remove
+ * @since 3.8.0
+ *
+ * @param {string} key - The key of the core plugin to remove.
+ */
+PluginCache.remove = function (key)
+{
+ if (corePlugins.hasOwnProperty(key))
+ {
+ delete corePlugins[key];
+ }
+};
+
+/**
+ * Removes a custom plugin based on the given key.
+ *
+ * @method Phaser.Plugins.PluginCache.removeCustom
+ * @since 3.8.0
+ *
+ * @param {string} key - The key of the custom plugin to remove.
+ */
+PluginCache.removeCustom = function (key)
+{
+ if (customPlugins.hasOwnProperty(key))
+ {
+ delete customPlugins[key];
+ }
+};
+
+module.exports = PluginCache;
diff --git a/pool/shard000/JavaScript/0003653_mongoDBClient.js b/pool/shard000/JavaScript/0003653_mongoDBClient.js
new file mode 100644
index 0000000000000000000000000000000000000000..cd35e24874a490596b1f4c41a41f6e932b0318df
--- /dev/null
+++ b/pool/shard000/JavaScript/0003653_mongoDBClient.js
@@ -0,0 +1,35 @@
+/**
+ * Created by jude on 28/11/2016.
+ */
+var mongoose = require('mongoose');
+
+mongoose.connect('mongodb://localhost/piData');
+
+var db = mongoose.connection;
+
+// data structure
+var venueSchema = mongoose.Schema(
+ {
+ _id: String,
+ distance : String,
+ mac_short : String,
+ mac : String,
+ venueid : String,
+ samples : Number,
+ captime : Number
+ }
+);
+
+mongoose.model('venueinfo', venueSchema, 'venueinfo');
+
+db.on('error', console.error.bind(console, 'connection error.....'));
+db.once('open', function callback(){
+ console.log('Pi database is now open!')
+});
+
+module.exports = {
+ mongoose: function () {
+ return mongoose;
+ }
+};
+
diff --git a/pool/shard000/JavaScript/0003654_static.js b/pool/shard000/JavaScript/0003654_static.js
new file mode 100644
index 0000000000000000000000000000000000000000..d9d32f4a7c4dc6bcc7f20132199217b65065b239
--- /dev/null
+++ b/pool/shard000/JavaScript/0003654_static.js
@@ -0,0 +1,31 @@
+var B = require('../').Buffer
+var test = require('tape')
+if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false
+
+test('Buffer.isEncoding', function (t) {
+ t.equal(B.isEncoding('HEX'), true)
+ t.equal(B.isEncoding('hex'), true)
+ t.equal(B.isEncoding('bad'), false)
+ t.end()
+})
+
+test('Buffer.isBuffer', function (t) {
+ t.equal(B.isBuffer(new B('hey', 'utf8')), true)
+ t.equal(B.isBuffer(new B([1, 2, 3], 'utf8')), true)
+ t.equal(B.isBuffer('hey'), false)
+ t.end()
+})
+
+test('Buffer.toArrayBuffer', function (t) {
+ var data = [1, 2, 3, 4, 5, 6, 7, 8]
+ if (typeof Uint8Array !== 'undefined') {
+ var result = new B(data).toArrayBuffer()
+ var expected = new Uint8Array(data).buffer
+ for (var i = 0; i < expected.byteLength; i++) {
+ t.equal(result[i], expected[i])
+ }
+ } else {
+ t.pass('No toArrayBuffer() method provided in old browsers')
+ }
+ t.end()
+})
diff --git a/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js b/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js
new file mode 100644
index 0000000000000000000000000000000000000000..d30bc147580514839030618ee5fbb904f65da641
--- /dev/null
+++ b/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js
@@ -0,0 +1,163 @@
+'use strict';
+
+(function() {
+ // Compartments Controller Spec
+ describe('Compartments Controller Tests', function() {
+ // Initialize global variables
+ var CompartmentsController,
+ scope,
+ $httpBackend,
+ $stateParams,
+ $location;
+
+ // The $resource service augments the response object with methods for updating and deleting the resource.
+ // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
+ // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
+ // When the toEqualData matcher compares two objects, it takes only object properties into
+ // account and ignores methods.
+ beforeEach(function() {
+ jasmine.addMatchers({
+ toEqualData: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ return {
+ pass: angular.equals(actual, expected)
+ };
+ }
+ };
+ }
+ });
+ });
+
+ // Then we can start by loading the main application module
+ beforeEach(module(ApplicationConfiguration.applicationModuleName));
+
+ // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
+ // This allows us to inject a service but then attach it to a variable
+ // with the same name as the service.
+ beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
+ // Set a new global scope
+ scope = $rootScope.$new();
+
+ // Point global variables to injected services
+ $stateParams = _$stateParams_;
+ $httpBackend = _$httpBackend_;
+ $location = _$location_;
+
+ // Initialize the Compartments controller.
+ CompartmentsController = $controller('CompartmentsController', {
+ $scope: scope
+ });
+ }));
+
+ it('$scope.find() should create an array with at least one Compartment object fetched from XHR', inject(function(Compartments) {
+ // Create sample Compartment using the Compartments service
+ var sampleCompartment = new Compartments({
+ name: 'New Compartment'
+ });
+
+ // Create a sample Compartments array that includes the new Compartment
+ var sampleCompartments = [sampleCompartment];
+
+ // Set GET response
+ $httpBackend.expectGET('api/compartments').respond(sampleCompartments);
+
+ // Run controller functionality
+ scope.find();
+ $httpBackend.flush();
+
+ // Test scope value
+ expect(scope.compartments).toEqualData(sampleCompartments);
+ }));
+
+ it('$scope.findOne() should create an array with one Compartment object fetched from XHR using a compartmentId URL parameter', inject(function(Compartments) {
+ // Define a sample Compartment object
+ var sampleCompartment = new Compartments({
+ name: 'New Compartment'
+ });
+
+ // Set the URL parameter
+ $stateParams.compartmentId = '525a8422f6d0f87f0e407a33';
+
+ // Set GET response
+ $httpBackend.expectGET(/api\/compartments\/([0-9a-fA-F]{24})$/).respond(sampleCompartment);
+
+ // Run controller functionality
+ scope.findOne();
+ $httpBackend.flush();
+
+ // Test scope value
+ expect(scope.compartment).toEqualData(sampleCompartment);
+ }));
+
+ it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Compartments) {
+ // Create a sample Compartment object
+ var sampleCompartmentPostData = new Compartments({
+ name: 'New Compartment'
+ });
+
+ // Create a sample Compartment response
+ var sampleCompartmentResponse = new Compartments({
+ _id: '525cf20451979dea2c000001',
+ name: 'New Compartment'
+ });
+
+ // Fixture mock form input values
+ scope.name = 'New Compartment';
+
+ // Set POST response
+ $httpBackend.expectPOST('api/compartments', sampleCompartmentPostData).respond(sampleCompartmentResponse);
+
+ // Run controller functionality
+ scope.create();
+ $httpBackend.flush();
+
+ // Test form inputs are reset
+ expect(scope.name).toEqual('');
+
+ // Test URL redirection after the Compartment was created
+ expect($location.path()).toBe('/compartments/' + sampleCompartmentResponse._id);
+ }));
+
+ it('$scope.update() should update a valid Compartment', inject(function(Compartments) {
+ // Define a sample Compartment put data
+ var sampleCompartmentPutData = new Compartments({
+ _id: '525cf20451979dea2c000001',
+ name: 'New Compartment'
+ });
+
+ // Mock Compartment in scope
+ scope.compartment = sampleCompartmentPutData;
+
+ // Set PUT response
+ $httpBackend.expectPUT(/api\/compartments\/([0-9a-fA-F]{24})$/).respond();
+
+ // Run controller functionality
+ scope.update();
+ $httpBackend.flush();
+
+ // Test URL location to new object
+ expect($location.path()).toBe('/compartments/' + sampleCompartmentPutData._id);
+ }));
+
+ it('$scope.remove() should send a DELETE request with a valid compartmentId and remove the Compartment from the scope', inject(function(Compartments) {
+ // Create new Compartment object
+ var sampleCompartment = new Compartments({
+ _id: '525a8422f6d0f87f0e407a33'
+ });
+
+ // Create new Compartments array and include the Compartment
+ scope.compartments = [sampleCompartment];
+
+ // Set expected DELETE response
+ $httpBackend.expectDELETE(/api\/compartments\/([0-9a-fA-F]{24})$/).respond(204);
+
+ // Run controller functionality
+ scope.remove(sampleCompartment);
+ $httpBackend.flush();
+
+ // Test array after successful delete
+ expect(scope.compartments.length).toBe(0);
+ }));
+ });
+}());
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003656_status.js b/pool/shard000/JavaScript/0003656_status.js
new file mode 100644
index 0000000000000000000000000000000000000000..a33c7ae09c53e1ebc0b314cf0344f8b594679724
--- /dev/null
+++ b/pool/shard000/JavaScript/0003656_status.js
@@ -0,0 +1,29 @@
+angular.module('bhima.controllers')
+ .controller('RequisitionStatusModalController', RequisitionStatusModalController);
+
+RequisitionStatusModalController.$inject = [
+ '$uibModalInstance', 'NotifyService', 'StockService', 'data',
+];
+
+function RequisitionStatusModalController(Instance, Notify, Stock, Data) {
+ const vm = this;
+
+ // global variables
+ vm.requisition = Data;
+
+ // expose to view
+ vm.close = Instance.close;
+ vm.submit = submit;
+
+ // submit the choice
+ function submit() {
+ const data = { status_id : vm.status };
+
+ Stock.stockRequisition.update(vm.requisition.uuid, data)
+ .then(() => {
+ Instance.close();
+ })
+ .catch(Notify.handleError);
+ }
+
+}
diff --git a/pool/shard000/JavaScript/0003660_DistinguishedDojo.js b/pool/shard000/JavaScript/0003660_DistinguishedDojo.js
new file mode 100644
index 0000000000000000000000000000000000000000..50f921c7e7940b3336f60a664b8694353806a9e2
--- /dev/null
+++ b/pool/shard000/JavaScript/0003660_DistinguishedDojo.js
@@ -0,0 +1,37 @@
+const DrawCard = require('../../drawcard');
+const AbilityDsl = require('../../abilitydsl');
+const { TargetModes, TokenTypes } = require('../../Constants');
+
+class DistinguishedDojo extends DrawCard {
+ setupCardAbilities() {
+ this.reaction({
+ title: 'Place an honor token',
+ when: {
+ afterDuel: (event, context) => event.winner && event.winner.controller === context.source.controller
+ },
+ limit: AbilityDsl.limit.perRound(3),
+ gameAction: AbilityDsl.actions.addToken(),
+ then: context => ({
+ target: {
+ mode: TargetModes.Select,
+ activePromptTitle: 'Sacrifice ' + context.source.name + '?',
+ choices: {
+ 'Yes': AbilityDsl.actions.sacrifice({ target: context.source }),
+ 'No': () => true
+ }
+ },
+ message: '{0} chooses {3}to sacrifice {1}',
+ messageArgs: context => context.select === 'No' ? 'not ' : '',
+ then: subThenContext => ({
+ gameAction: AbilityDsl.actions.gainHonor({ amount: subThenContext.source.getTokenCount(TokenTypes.Honor) }),
+ message: '{0} uses {1} to gain {3} honor',
+ messageArgs: [subThenContext.source.getTokenCount(TokenTypes.Honor)]
+ })
+ })
+ });
+ }
+}
+
+DistinguishedDojo.id = 'distinguished-dojo';
+
+module.exports = DistinguishedDojo;
diff --git a/pool/shard000/JavaScript/0003663_main.js b/pool/shard000/JavaScript/0003663_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..1321e682550a3e3d6b8e2f6982acab456bdf4ffa
--- /dev/null
+++ b/pool/shard000/JavaScript/0003663_main.js
@@ -0,0 +1,106 @@
+var input1, input2, button, configInput, configEnable, configDisable, results;
+
+var validity = {aspect1: false, aspect2: false};//Stores whether the users's aspect names are valid or not
+
+$(initLib);
+
+$(function(){//When the page is loaded, do the following.
+ //These lines locate and save the page elements that are important for the script:
+ input1 = $('#aspect1');//The starting aspect textbox,
+ input2 = $('#aspect2');//the ending aspect textbox,
+ button = $('#connect');//the "Connect" button,
+ configInput = $('#config-input'); configEnable = $('#config-enable'); configDisable = $('#config-disable');//the configuration section's fields,
+ results = $('#results');//and the column where the connection is displayed.
+
+ input1.add(input2).on('propertychange change keyup input paste', {showErrors: false}, validate)
+ .on('focusout', {showErrors: true}, validate)
+ .each(function(index){
+ if(aspects.selected[this.value]){
+ $(this).prev().addClass('w3-text-green');
+ validity[this.id] = true;
+ }else button.addClass('w3-disabled');
+ });
+ if(validity.aspect1 && validity.aspect2) makeConnection();
+
+ configInput.on('propertychange change keyup input paste', function(){
+ var node = nodes[this.value.toLowerCase()];
+ configEnable.toggleClass('w3-disabled', !node || node.active);
+ configDisable.toggleClass('w3-disabled', !node || !node.active);
+ });
+ configEnable.on('click', function(){
+ if(!$(this).hasClass('w3-disabled')) nodes[configInput.val().toLowerCase()].active = true;
+ configEnable.addClass('w3-disabled');
+ configDisable.removeClass('w3-disabled');
+ $('#disabled-list > li[data-aspect=' + configInput.val().toLowerCase() + ']').remove();
+ });
+ configDisable.on('click', function(){
+ if(!$(this).hasClass('w3-disabled')) nodes[configInput.val().toLowerCase()].active = false;
+ configEnable.removeClass('w3-disabled');
+ configDisable.addClass('w3-disabled');
+ var aspect = aspects.selected[configInput.val().toLowerCase()];
+ $(' ').attr('data-aspect', aspect.name).append(" ").append(aspect.displayName).appendTo('#disabled-list');
+ });
+
+ button.on('click', function(){//When the "Connect" button is clicked,
+ if(!button.hasClass('w3-disabled')) makeConnection();//If the button is active (two valid aspects have been inputted), make and display the connection.
+ });
+
+ $('#results-header').append(removeButton(function(){
+ results.empty();
+ }));
+});
+
+function validate(event){
+ var asp = (this.value || '').toLowerCase();
+ validity[this.id] = aspects.selected[asp] ? true : false;//If an aspect exists with the name inputted into this field, mark this field valid.
+ $(this).prev().toggleClass('w3-text-green', validity[this.id]);//If the aspect is valid, make the label text green;
+ $(this).prev().toggleClass('w3-text-red', !validity[this.id]);//otherwise, make it red.
+ button.toggleClass('w3-disabled', !validity.aspect1 || !validity.aspect2);//If either aspect is invalid, disable the "Connect" button.
+
+ if(event.data.showErrors){
+ var errorBox = $('#error' + this.id.slice(-1));
+ if(validity[this.id]) errorBox.empty();
+ else errorBox.text("Unknown aspect '" + asp.slice(0, 1).toUpperCase() + asp.slice(1) + "'.");
+ }
+}
+
+function makeConnection(){
+ var asp1 = input1.val().toLowerCase(), asp2 = input2.val().toLowerCase();//Get aspect names from the two input fields.
+
+ var row = $('
').addClass('chain');
+
+ var chain = nodes.connect(asp1, asp2);//Find the connection between the two aspects (returns an array of aspect names from start to end).
+
+ for(var i=0; i').addClass('chain-element w3-tooltip');
+ $(' ').attr('src', chain[i].aspect.iconURL).appendTo(container);
+
+ var tooltip = $(' ').addClass('w3-text w3-tag w3-round-large').css('padding-bottom', '8px').appendTo(container);
+ tooltip.append("" + chain[i].aspect.displayName + " ")
+ .append("" + chain[i].aspect.displayDescription+ " ");
+ if(!chain[i].aspect.isPrimal()){
+ tooltip.append(' ');
+ var comps = chain[i].aspect.components;
+ for(var j=0; j ");
+ if(j+1 < comps.length) tooltip.append("add ");
+ }
+ }
+ container.appendTo(row);
+ if(i+1 < chain.length) row.append("keyboard_arrow_right ");
+ }
+ row.append(removeButton(function(event){
+ $(this).parent().remove();
+ }))
+ results.append(row);
+}
+
+function removeButton(handler){
+ return $(' ').addClass('w3-btn w3-red remove').append("delete ").on('click', handler);
+}
+
+function updateVersion(){
+ for(var name in nodes) delete nodes[name];
+ initLib();
+ results.empty();
+}
diff --git a/pool/shard000/JavaScript/0003667_counterStore.js b/pool/shard000/JavaScript/0003667_counterStore.js
new file mode 100644
index 0000000000000000000000000000000000000000..50defcea989777b3f8b20d80570678fee05535b8
--- /dev/null
+++ b/pool/shard000/JavaScript/0003667_counterStore.js
@@ -0,0 +1,31 @@
+import { createStore } from 'fluxible/addons';
+import constants from './constants';
+
+export default createStore({
+ storeName: 'Counter',
+
+ handlers: {
+ [constants.SET_VALUE]: 'setValue',
+ [constants.INCREMENT]: 'increment'
+ },
+
+ setValue(value = 0) {
+ this.value = value;
+ this.emitChange();
+ },
+
+ increment(count = 1) {
+ this.value += count;
+ this.emitChange();
+ },
+
+ dehydrate() {
+ return {
+ value: this.value
+ };
+ },
+
+ rehydrate(state) {
+ this.value = state.value;
+ }
+});
diff --git a/pool/shard000/JavaScript/0003669_reset.finish.controller.js b/pool/shard000/JavaScript/0003669_reset.finish.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..dfb13a8f6378fd634e37b7351124431b133f03a9
--- /dev/null
+++ b/pool/shard000/JavaScript/0003669_reset.finish.controller.js
@@ -0,0 +1,39 @@
+(function() {
+ 'use strict';
+
+ angular
+ .module('coocotteApp')
+ .controller('ResetFinishController', ResetFinishController);
+
+ ResetFinishController.$inject = ['$stateParams', '$timeout', 'Auth', 'LoginService'];
+
+ function ResetFinishController ($stateParams, $timeout, Auth, LoginService) {
+ var vm = this;
+
+ vm.keyMissing = angular.isUndefined($stateParams.key);
+ vm.confirmPassword = null;
+ vm.doNotMatch = null;
+ vm.error = null;
+ vm.finishReset = finishReset;
+ vm.login = LoginService.open;
+ vm.resetAccount = {};
+ vm.success = null;
+
+ $timeout(function (){angular.element('#password').focus();});
+
+ function finishReset() {
+ vm.doNotMatch = null;
+ vm.error = null;
+ if (vm.resetAccount.password !== vm.confirmPassword) {
+ vm.doNotMatch = 'ERROR';
+ } else {
+ Auth.resetPasswordFinish({key: $stateParams.key, newPassword: vm.resetAccount.password}).then(function () {
+ vm.success = 'OK';
+ }).catch(function () {
+ vm.success = null;
+ vm.error = 'ERROR';
+ });
+ }
+ }
+ }
+})();
diff --git a/pool/shard000/JavaScript/0003672_mongodb.js b/pool/shard000/JavaScript/0003672_mongodb.js
new file mode 100644
index 0000000000000000000000000000000000000000..563bb3aa70fc5c0b9a86cc65342de5bf35ba5cc1
--- /dev/null
+++ b/pool/shard000/JavaScript/0003672_mongodb.js
@@ -0,0 +1,31 @@
+/*
+@title Write docusment to MongoDB
+*/
+
+var MongoClient = require('mongodb').MongoClient;
+
+module.exports = function(req, res, next){
+ req
+ .app
+ .mongodb
+ .creds()
+ .then((cred) => {
+ MongoClient.connect(cred.connection_string, function(err, db) {
+ if (err) {
+ return res.status(500).send(err);
+ }
+
+ var collection = db.collection('people');
+ collection.insert({ name : 'john smith' }, (err, result) => {
+ if (err) {
+ return res.status(500).send(err);
+ }
+
+ res.send(result);
+
+ db.close();
+ });
+ });
+ })
+ .catch((err) => res.status(err.statusCode || 500).send(err.error || err));
+};
diff --git a/pool/shard000/JavaScript/0003673_wsserver.js b/pool/shard000/JavaScript/0003673_wsserver.js
new file mode 100644
index 0000000000000000000000000000000000000000..50684f4abbdf72438cfafae6335ae39abd02aa7a
--- /dev/null
+++ b/pool/shard000/JavaScript/0003673_wsserver.js
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+var WebSocketServer = require('websocket').server;
+var http = require('http');
+
+var server = http.createServer(function(request, response) {
+ console.log(request.url);
+ response.writeHead(404);
+ response.end();
+});
+
+server.listen(5050, function() {
+ console.log('Server is listening on port 5050');
+});
+
+wsServer = new WebSocketServer({
+ httpServer: server,
+ autoAcceptConnections: false
+});
+
+wsServer.on('request', function(request) {
+ var connection = request.accept('echo-protocol', request.origin);
+
+ connection.on('message', function(message) {
+ connection.sendUTF(message.utf8Data);
+ console.log('message: ' + message.utf8Data);
+ });
+
+ connection.on('close', function(reasonCode, description) {
+ console.log('closed');
+ });
+});
diff --git a/pool/shard000/JavaScript/0003674_index.js b/pool/shard000/JavaScript/0003674_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..bcd2a68ed37ec43e825c14fb7a221383a56b6419
--- /dev/null
+++ b/pool/shard000/JavaScript/0003674_index.js
@@ -0,0 +1,56 @@
+// Uji Coba
+
+var spawn = require('child_process').spawn;
+var async = require('async');
+var moment = require('moment');
+var fs = require('fs');
+
+require('events').EventEmitter.prototype._maxListeners = 1000000;
+
+
+// Configuration
+var server = process.argv[2];
+var mountPoint = process.argv[3];
+var instancesPerServer = process.argv[4];
+var timePerRequest = process.argv[5];
+
+var success = 0;
+var fail = 0;
+
+// Create array with instancePerServer times element for the sake of async library
+var arr = []
+for(var i=0; i < instancesPerServer; i++) {
+ arr.push(i);
+}
+async.each(arr, function(i, callback) {
+ // Do a curl
+ var stdout = "";
+ var start = moment(new Date());
+ var ps = spawn('curl', ['-o', '/dev/null', '-m', timePerRequest, '-s',
+ '-w', "%{size_download}", 'http://' + server + mountPoint]);
+
+
+ ps.stdout.on('data', function(data) {
+ stdout += data.toString();
+ });
+
+ ps.stderr.pipe(process.stdout);
+
+ ps.on('exit', function() {
+ var end = moment(new Date());
+ var result = parseFloat(stdout) / 1024;
+ var diff = moment.duration(end.diff(start));
+
+ if(diff.asSeconds() < timePerRequest) {
+ fail++;
+ } else {
+ success++;
+ }
+
+ callback();
+ });
+
+
+}, function(err) {
+ console.log(success)
+});
diff --git a/pool/shard000/JavaScript/0003677_get-random-value-test.js b/pool/shard000/JavaScript/0003677_get-random-value-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..475973333b7bf111f84a21f09c12f62af4ce54b2
--- /dev/null
+++ b/pool/shard000/JavaScript/0003677_get-random-value-test.js
@@ -0,0 +1,25 @@
+describe("get random value", () => {
+ let mockGetRandomValues, getRandomValue;
+
+ beforeEach(() => {
+ mockGetRandomValues = jest.fn(() => [2]);
+
+ jest.mock("../../../source/iml/global.js", () => ({
+ crypto: {
+ getRandomValues: mockGetRandomValues
+ }
+ }));
+
+ getRandomValue = require("../../../source/iml/get-random-value.js").default;
+ });
+
+ it("should be called with a Uint32Array", () => {
+ getRandomValue();
+
+ expect(mockGetRandomValues).toHaveBeenCalledOnceWith(new Uint32Array(1));
+ });
+
+ it("should return the result of crypto.getRandomValues", () => {
+ expect(getRandomValue()).toBe(2);
+ });
+});
diff --git a/pool/shard000/JavaScript/0003678_html_comment_spec.js b/pool/shard000/JavaScript/0003678_html_comment_spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..e66af1d4d8c980359bca8d1b70d828de444b87b5
--- /dev/null
+++ b/pool/shard000/JavaScript/0003678_html_comment_spec.js
@@ -0,0 +1,67 @@
+'use strict';
+
+var HTMLCommentWidget = require('../../../../src/template/widgets/html_comment.js');
+
+describe('html_comment.js public API', function() {
+ it('should be a function', function() {
+ expect(HTMLCommentWidget).to.be.a('function');
+ expect(HTMLCommentWidget).to.have.length(1);
+ });
+ describe('html_comment prototype', function() {
+ var comment, text;
+ beforeEach(function() {
+ text = 'comment';
+ comment = new HTMLCommentWidget(text);
+ });
+ it('should have a property text', function() {
+ expect(comment.text).to.equal(text);
+ });
+ it('should have a property type', function() {
+ expect(comment.type).to.equal('Widget');
+ });
+ describe('HtmlComment.init', function() {
+ it('should have an init function', function() {
+ expect(comment.init).to.be.a('function');
+ expect(comment.init).to.have.length(0);
+ expect(comment.init).to.equal(HTMLCommentWidget.prototype.init);
+ });
+ it('should create an HTML comment node', function() {
+ var output = comment.init();
+ expect(output.nodeType).to.equal(document.COMMENT_NODE);
+ expect(output.nodeValue).to.equal(text);
+ });
+ });
+ describe('HtmlComment.update', function() {
+ it('should have an update function', function() {
+ expect(comment.update).to.be.a('function');
+ expect(comment.update).to.have.length(2);
+ expect(comment.update).to.equal(HTMLCommentWidget.prototype.update);
+ });
+ it('should update a node', function() {
+ var prev = new HTMLCommentWidget('old value');
+ var elem = prev.init();
+ comment.update(prev, elem);
+ expect(elem.nodeValue).to.equal(text);
+ });
+ it('should not a node if the values match', function() {
+ var oldValue = 'old value';
+ var prev = new HTMLCommentWidget(oldValue);
+ var elem = prev.init();
+ comment.update(comment, elem);
+ expect(elem.nodeValue).to.equal(oldValue);
+ });
+ });
+ if (typeof TUNGSTENJS_DEBUG_MODE !== 'undefined') {
+ describe('HtmlComment.templateToString', function() {
+ it('should have a templateToString function', function() {
+ expect(comment.templateToString).to.be.a('function');
+ expect(comment.templateToString).to.have.length(0);
+ expect(comment.templateToString).to.equal(HTMLCommentWidget.prototype.templateToString);
+ });
+ it('should be able to create a debugger html block', function() {
+ expect(comment.templateToString()).to.equal('');
+ });
+ });
+ }
+ });
+});
diff --git a/pool/shard000/JavaScript/0003680_user.js b/pool/shard000/JavaScript/0003680_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..73cb91db92e20478915c0e57d953d1163f4d7eb5
--- /dev/null
+++ b/pool/shard000/JavaScript/0003680_user.js
@@ -0,0 +1,203 @@
+describe("mtapi", function () {
+ 'use strict';
+
+ beforeEach(function () {
+ var flag;
+ require(['js/mtapi/user', 'js/cache'], function () {
+ flag = true;
+ });
+ waitsFor(function () {
+ return flag;
+ });
+ });
+
+ describe("user", function () {
+ beforeEach(function () {
+ window.Mock.alwaysFail = null;
+ window.Mock.returnFailRequest = null;
+ window.Mock.failPermission = null;
+
+ window.Mock.throwUserItem = {
+ displayName: "Yutaka Yamaguchi",
+ email: "yyamaguchi@sixapart.com",
+ id: "1",
+ language: "ja",
+ name: "yyamaguchi",
+ updatable: true,
+ url: "",
+ userpicUrl: ""
+ };
+
+ window.Mock.throwPermissionItems = [{
+ "permissions": ["administer", "create_blog", "create_website", "edit_templates", "manage_plugins", "view_log"],
+ "blog": null
+ }, {
+ "permissions": ["administer_blog", "administer_website", "comment", "create_post", "edit_all_posts", "edit_assets", "edit_categories", "edit_config", "edit_notifications", "edit_tags", "edit_templates", "manage_feedback", "manage_member_blogs", "manage_pages", "manage_themes", "manage_users", "publish_post", "rebuild", "save_image_defaults", "send_notifications", "set_publish_paths", "upload", "view_blog_log"],
+ "blog": {
+ "id": "1"
+ }
+ }];
+
+ require('js/cache').clearAll();
+ });
+
+ it("get user", function () {
+ var cache = require('js/cache');
+ var getUser = require('js/mtapi/user');
+ var dfd = getUser();
+ var user, flag, permCollection;
+ runs(function () {
+ dfd.done(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ });
+ });
+
+ waitsFor(function () {
+ return flag;
+ }, 'get user with js/mtapi/user', 3000);
+
+ runs(function () {
+ expect(user).toBeDefined();
+ expect(user.id).toEqual(window.Mock.throwUserItem.id);
+ expect(user.language).toEqual(window.Mock.throwUserItem.language);
+ expect(user.displayName).toEqual(window.Mock.throwUserItem.displayName);
+ expect(user.permissions).toBeDefined();
+ var expectedSystemPerm = window.Mock.throwPermissionItems[0].permissions;
+ expect(user.permissions.length).toEqual(expectedSystemPerm.length);
+ _.forEach(user.permissions, function (perm) {
+ var find = _.find(expectedSystemPerm, function (expectPerm) {
+ return perm === expectPerm;
+ });
+ expect(find).not.toBeNull();
+ });
+
+ expect(permCollection).toBeDefined();
+ expect(permCollection.totalResults).toEqual(window.Mock.throwPermissionItems.length);
+ });
+ });
+
+ it("when user request failed, return failed", function () {
+ window.Mock.returnFailRequest = 'get User request failed';
+
+ var mtapi = require('js/mtapi');
+ spyOn(mtapi.api, 'listPermissionsForUser').andCallThrough();
+
+ var cache = require('js/cache');
+ var getUser = require('js/mtapi/user');
+ var dfd = getUser();
+ spyOn(dfd, 'fail').andCallThrough();
+
+ var user, flag, permCollection;
+ runs(function () {
+ dfd.done(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ });
+ dfd.fail(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ })
+ });
+
+ waitsFor(function () {
+ return flag;
+ }, 'get user with js/mtapi/user', 3000);
+
+ runs(function () {
+ expect(dfd.fail).toHaveBeenCalled();
+ expect(mtapi.api.listPermissionsForUser).not.toHaveBeenCalled();
+ expect(user.error).toBeDefined();
+ expect(user.error.message).toEqual(window.Mock.returnFailRequest);
+ expect(user.id).not.toBeDefined();
+ expect(user.permissions).not.toBeDefined();
+
+ expect(permCollection).toBeNull();
+ });
+ });
+
+ it("when user only has blog permissions, user.permissions should be null", function () {
+ window.Mock.throwPermissionItems = [{
+ "permissions": ["administer_blog", "administer_website", "comment", "create_post", "edit_all_posts", "edit_assets", "edit_categories", "edit_config", "edit_notifications", "edit_tags", "edit_templates", "manage_feedback", "manage_member_blogs", "manage_pages", "manage_themes", "manage_users", "publish_post", "rebuild", "save_image_defaults", "send_notifications", "set_publish_paths", "upload", "view_blog_log"],
+ "blog": {
+ "id": "1"
+ }
+ }];
+
+ var cache = require('js/cache');
+ var getUser = require('js/mtapi/user');
+ var dfd = getUser();
+ var user, flag, permCollection;
+ runs(function () {
+ dfd.done(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ });
+ });
+
+ waitsFor(function () {
+ return flag;
+ }, 'get user with js/mtapi/user', 3000);
+
+ runs(function () {
+ expect(user).toBeDefined();
+ expect(user.id).toEqual(window.Mock.throwUserItem.id);
+ expect(user.language).toEqual(window.Mock.throwUserItem.language);
+ expect(user.displayName).toEqual(window.Mock.throwUserItem.displayName);
+ expect(user.permissions).toBeNull();
+
+ expect(permCollection).toBeDefined();
+ expect(permCollection.totalResults).toEqual(window.Mock.throwPermissionItems.length);
+ });
+ });
+
+ it("when permission request failed, get user request should be failed", function () {
+ window.Mock.failPermission = 'Failed to get permissions';
+
+ var cache = require('js/cache');
+ var getUser = require('js/mtapi/user');
+ var dfd = getUser();
+ spyOn(dfd, 'fail').andCallThrough();
+
+ var user, flag, permCollection;
+ runs(function () {
+ dfd.done(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ });
+ dfd.fail(function (resp) {
+ user = resp;
+ permCollection = cache.get('user', 'perms');
+ flag = true;
+ })
+ });
+
+ waitsFor(function () {
+ return flag;
+ }, 'get user with js/mtapi/user', 3000);
+
+ runs(function () {
+ expect(dfd.fail).toHaveBeenCalled();
+ expect(user.error).toBeDefined();
+ expect(user.error.message).toEqual(window.Mock.failPermission)
+ expect(user.id).not.toBeDefined();
+ expect(user.permissions).not.toBeDefined();
+
+ expect(permCollection).toBeNull();
+ });
+ });
+ });
+
+ afterEach(function () {
+ window.Mock.throwUserItem = null;
+ window.Mock.throwPermissionItems = null;
+ window.Mock.returnFailRequest = null;
+ window.Mock.alwaysFail = null;
+ window.Mock.failPermission = null;
+ });
+});
diff --git a/pool/shard000/JavaScript/0003681_Application.js b/pool/shard000/JavaScript/0003681_Application.js
new file mode 100644
index 0000000000000000000000000000000000000000..cd8287c9739e2267ea0e5f0ab42fd475a66c0cba
--- /dev/null
+++ b/pool/shard000/JavaScript/0003681_Application.js
@@ -0,0 +1,146 @@
+var React = require('react');
+var assign = require('object-assign');
+
+var Constants = require('./constants/AppConstants');
+
+var NAVIGATOR = Constants.Types.NAVIGATOR;
+var SETTINGS = Constants.Types.SETTINGS;
+var AUTH = Constants.Types.AUTH;
+var USERS = Constants.Types.USERS;
+var GUEST_ID = Constants.DataStates.GUEST_ID;
+
+
+/* Constructor */
+function App(props, context) {
+ React.Component.call(this, props);
+
+ this.handleChange = this.handleChange.bind(this);
+ this.navigate = this.navigate.bind(this);
+ this.buildHref = this.buildHref.bind(this);
+
+ this.state = this.selectState(props, context);
+}
+App.prototype = Object.create(React.Component.prototype);
+App.prototype.constructor = App;
+
+
+/* Statics */
+App.propTypes = {
+ api: React.PropTypes.object,
+ action: React.PropTypes.object.isRequired,
+ router: React.PropTypes.object.isRequired,
+ container: React.PropTypes.object.isRequired
+};
+
+App.childContextTypes = {
+ api: React.PropTypes.object,
+ navigate: React.PropTypes.func,
+ buildHref: React.PropTypes.func,
+ container: React.PropTypes.object
+};
+
+
+/* Members */
+assign(App.prototype, {
+ getChildContext: function() {
+ return {
+ api: this.props.api,
+ navigate: this.navigate,
+ buildHref: this.buildHref,
+ container: this.props.container
+ }
+ },
+
+ componentDidMount: function() {
+ this.subKey = this.props.container.subscribe([AUTH, SETTINGS], this.handleChange);
+ },
+
+ componentWillUnmount: function() {
+ this.props.container.unsubscribe(this.subKey);
+ },
+
+ handleChange: function() {
+ this.setState(this.selectState(this.props, this.context));
+ },
+
+ selectState: function(props, context) {
+ var state = props.container.getState([SETTINGS, AUTH, USERS]);
+ var currentUser;
+
+ if (state[AUTH].get('loginStatus')) {
+ currentUser = state[USERS][state[AUTH].get('currentUser')];
+ }
+ else {
+ currentUser = { _id: GUEST_ID };
+ }
+
+ return {
+ settings: state[SETTINGS],
+ currentUser: currentUser
+ };
+ },
+
+ render: function() {
+ var action = this.props.action;
+ var handler = React.createElement(getHandler(action), action);
+ var Layout = getLayout(action);
+
+ return React.createElement("div", {className: "app-root"},
+ React.createElement(Layout, {
+ action: action,
+ settings: this.state.settings,
+ currentUser: this.state.currentUser
+ }, handler)
+ );
+ },
+
+ navigate: function(target, reload) {
+ if (typeof target === 'string') {
+ this.props.container.action(NAVIGATOR, 'gotoUrl', [target, reload]);
+ }
+ else if (target && target.action) {
+ var href = this.buildHref(target);
+
+ this.props.container.action(NAVIGATOR, 'gotoUrl', [href, reload]);
+ }
+ },
+
+ buildHref: function(config) {
+ return this.props.router.buildHref(config);
+ }
+});
+
+module.exports = App;
+
+function getHandler(action) {
+ // Not found page pls
+ var handler = require('./pages/MainPage');
+
+ switch(action.action) {
+ case 'MainPage':
+ handler = require('./pages/MainPage');
+ break;
+ case 'ArticlePage':
+ handler = require('./pages/ArticlePage');
+ break;
+ case 'LoginPage':
+ handler = require('./pages/LoginPage');
+ break;
+ case 'RegisterPage':
+ handler = require('./pages/RegisterPage');
+ break;
+ case 'LogoutPage':
+ handler = require('./pages/LogoutPage');
+ break;
+ }
+
+ return handler;
+}
+
+var getLayout = function(action) {
+ var Layout = require('./layouts/MainLayout');
+
+ // Switch by action layout
+
+ return Layout;
+}
diff --git a/pool/shard000/JavaScript/0003682_search-list.js b/pool/shard000/JavaScript/0003682_search-list.js
new file mode 100644
index 0000000000000000000000000000000000000000..171d542be4a0717047a3f126a490881ddc0ee003
--- /dev/null
+++ b/pool/shard000/JavaScript/0003682_search-list.js
@@ -0,0 +1,159 @@
+/**
+ * 绑定搜索列表
+ * .binder-search-list
+ * 表单里面支持配置数据:
+ * data-target :数据显示区域,jquery selector,,默认就是当前的binder-search-lis
+ * data-tpl : 对应模板文件
+ * data-key : 对应的数据key,默认就是data
+ * data-callback :默认的操作执行完毕之后所需要的执行的callback方法。
+ * data-first-load : false | true , 第一页页面出现后是否加载。默认不加载
+ *
+ * 表单里面输入框支持的class属性
+ * .binder-enter-key: 绑定回车事件
+ * .no-binder : 不绑定change事件
+ */
+var G_BIND_SEARCH_LIST_BEFORE_LOADING = 'G_BIND_SEARCH_LIST_BEFORE_LOADING';
+var G_BIND_SEARCH_LIST_LOAD_SUCC = 'G_BIND_SEARCH_LIST_LOAD_SUCC';
+
+(function(){
+ var defaultOptions = {
+ firstLoad : false,
+ key : 'data',
+ emptyTip : '没有合适数据'
+ }
+ var searchIdKey = "binder-search-id";
+ var id = 0;
+ /**
+ *
+ * @param options
+ * {
+ * form : // 对应的表单
+ * }
+ * @constructor
+ */
+ var SearchListBinder = function(obj,options){
+ Q.extend(options,defaultOptions);
+
+ this.jDom = $(obj);
+ this.jDom.data(searchIdKey,searchIdKey + (id++)); // 记住id
+ this.options = options;
+ this.jTarget = $(options.target);
+ if(this.jTarget.length==0)
+ this.jTarget = this.jDom;
+
+ this.jTemplate = this.jTarget.find('.binder-template');
+ this.tplId = options.tpl;
+ this.showPage = this.jTarget.find('.binder-pager').length>0;
+ this.key = options.key;
+ this.callback = options.callback;
+
+
+ var that = this;
+ this.jTemplate.css('position','relative');
+
+ this.jDom.submit(function(){
+ var formDataStr = that.jDom.serialize();
+
+ var url = window.encodeURIComponent(that.jDom.attr('action'));
+console.log(that.jDom.attr('action'));
+ // 广播
+ Q.notify.broadcast(G_BIND_SEARCH_LIST_BEFORE_LOADING,{
+ jDom : this.jDom
+ });
+ that.jTemplate.append('');
+ Q.proxy(url,formDataStr,that.tplId,function(data){
+ that.jTarget.find('.absolute-loading').remove();
+
+ var renderData = {}
+ renderData[that.key] = data.data;
+ // 后台返回数据有分页则返回record字段,否则只有data字段
+ if((data.data.record && data.data.record.length == 0) || (data.data && data.data.length == 0)){
+ // 没有数据
+ that.jTemplate.html(''+that.options.emptyTip+'
');
+ that.jTarget.find('.binder-pager').html('');
+ }else {
+ var html = template.render(that.tplId, renderData);
+ that.jTemplate.html(html);
+
+ // 刷新分页
+ if (that.showPage) {
+ that.jTarget.find('.binder-pager').html(Q.widget.page.createPage(data.data));
+ // 绑定1个id
+ that.jTarget.find('.binder-pager').data(searchIdKey,that.jDom.data(searchIdKey));
+ }
+ }
+
+ // 重设当前页分页隐藏域的值,这样在重新搜索的时候才能从第一页开始
+ that.jDom.find('input[name="pageno"]').val(1);
+
+ // 广播
+ Q.notify.broadcast(G_BIND_SEARCH_LIST_LOAD_SUCC,{
+ jDom : that.jDom,
+ "data" : data
+ });
+ if(that.callback)
+ window[that.callback](renderData)
+ },function(){
+ that.jTemplate.find('.absolute-loading').remove();
+ });
+
+ //拦截submit表单提交
+ return false;
+ });
+
+ this.jDom.find('input,select,textarea').live('change',function(){
+ var jThis = $(this);
+ // no-binder。binder-enter-key 2个样式不直接引发sumbit
+ if(jThis.hasClass("no-binder") || jThis.hasClass("binder-enter-key")){
+ return;
+ }
+
+ //延迟300毫秒,可能会有其他的时间对form进行操作。确保提交时候form是最终形态
+ var tmp = function(){
+ return function(){
+ that.jDom.submit();
+ }
+ }();
+
+ setTimeout(tmp, 300)
+ });
+
+ // 如果分页组件不在jDom中,需要绑定分页组件
+ if(this.jDom.find('input[name="pageno"]').length == 0){
+ // 创建1个分页隐藏域
+ this.jDom.append(' ');
+ // 监听组件
+ that.jTarget.find('.binder-pager input[name="pageno"]').live('change',function(e){
+ if(that.jTarget.find('.binder-pager').data(searchIdKey) != that.jDom.data(searchIdKey)){
+ // 非当前表单
+ return;
+ }
+ // 组织冒泡,防止其他的绑定了该事件
+ e.stopPropagation();
+ that.jDom.find('input[name="pageno"]').val(this.value).change();
+ });
+ }
+ // 监听回车事件
+ this.jDom.find('.binder-enter-key').bind('keyup',function(e){
+ if(e.keyCode == 13){
+ that.jDom.submit();
+ return false;
+ }
+ });
+
+ // 是否需要第一次加载
+ if(options.firstLoad){
+ this.jDom.submit();
+ }
+ return this;
+ };
+
+ $(document).ready(function(){
+ // 自动绑定所有列表
+ $('.binder-search-list').each(function(){
+ var options = Q.attrWrapOptions(this);
+ new SearchListBinder(this,options);
+ });
+ });
+
+})();
diff --git a/pool/shard000/JavaScript/0003683_jsonpPromise.js b/pool/shard000/JavaScript/0003683_jsonpPromise.js
new file mode 100644
index 0000000000000000000000000000000000000000..0120afd9c83d652cb4f85cef18cbc1a4e769352b
--- /dev/null
+++ b/pool/shard000/JavaScript/0003683_jsonpPromise.js
@@ -0,0 +1,43 @@
+const defaultOpts = {
+ prefix: '__jp',
+ param: 'callback',
+ timeout: 30 * 1000
+};
+
+const randomID = () => {
+ return Math.random().toString(16).replace('.', '');
+};
+
+const enc = encodeURIComponent;
+
+function jsonp (url, opts = {}) {
+ return new Promise((resolve, reject) => {
+ opts = Object.assign({ name: randomID() }, defaultOpts, opts);
+ console.log(opts);
+
+ const timer = setTimeout(() => {
+ reject(new Error('Request timeout.'));
+ }, opts.timeout);
+
+ const success = (data) => {
+ clearTimeout(timer);
+ resolve(data);
+ };
+
+ const funcName = opts.prefix + opts.name;
+ window[ funcName ] = success;
+
+ const script = document.createElement('script');
+ script.addEventListener('error', (err) => {
+ clearTimeout(timer);
+ console.log(err);
+ reject(err);
+ });
+ const reqUrl =
+ url + ( (!url.match(/\?/)) ? '?' : '&' ) + `${ opts.param }=${ enc(funcName) }`;
+ script.setAttribute('src', reqUrl);
+ document.head.appendChild(script);
+ });
+}
+
+export default jsonp;
diff --git a/pool/shard000/JavaScript/0003690_blockgraph.js b/pool/shard000/JavaScript/0003690_blockgraph.js
new file mode 100644
index 0000000000000000000000000000000000000000..e7b933b31f92c34910b2c15a94a7ae9d3cdd8d3c
--- /dev/null
+++ b/pool/shard000/JavaScript/0003690_blockgraph.js
@@ -0,0 +1,295 @@
+(function () {
+ 'use strict';
+
+ /**
+ * desc: functions for square blocks created by neighbouring dots
+ * @author: Vishal Kumar
+ * E-mail: vishal.rgiit@gmail.com
+ * Github: vishalok12
+ */
+
+ /**
+ * contains information about the blocks
+ */
+ function BlockGraph(dotMap) {
+ var i, j;
+ var blocks = [];
+ var upLayerLength, downLayerLength;
+
+ for (i = 0; i < dotMap.length - 1; i++) {
+ upLayerLength = dotMap[i].length;
+ downLayerLength = dotMap[i+1].length;
+ blocks[i] = [];
+
+ for (j = 0; j < Math.min(upLayerLength, downLayerLength) - 1; j++) {
+ blocks[i][j] = new Block(i, j);
+ }
+ }
+ this.blocks = blocks;
+ }
+
+ /**
+ * a square area covered by 4 individual edges
+ */
+ function Block(i, j) {
+ var attr = {};
+ attr.top = null;
+ attr.bottom = null;
+ attr.left = null;
+ attr.right = null;
+ attr.selected = 0;
+ attr.userAcquired = null;
+ this._attr = attr;
+ this._row = i;
+ this._column = j;
+ }
+
+ /**
+ * get the attribute value
+ * @param {String} attr
+ * @return {*} value of attr
+ */
+ Block.prototype.get = function(attr) {
+ if (this._attr.hasOwnProperty(attr)) {
+ return this._attr[attr];
+ }
+ };
+
+ /**
+ * set the value of the block attribute
+ * @param {String} attr
+ * @param {*} value
+ */
+ Block.prototype.set = function(attr, value) {
+ if (this._attr.hasOwnProperty(attr)) {
+ if (this._row === 0 && this._column === 1) console.log(attr);
+ this._attr[attr] = value;
+ if (['top', 'bottom', 'left', 'right'].indexOf(attr) > -1) {
+ this._attr.selected += 1;
+ }
+ } else {
+ throw new Error(attr + ' is not defined in object');
+ }
+ };
+
+ /**
+ * get whether the block has all the edges selected
+ * @return {Boolean} acquired
+ */
+ Block.prototype.acquired = function() {
+ if (this.get('selected') === 4) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * get whether the edge is selected
+ * @param {Object|Number} row1 {row: row1, column: coln1} in case of object
+ * @param {Object|Number} coln1 {row: row2, column: coln2} in case of object
+ * @param {Number|undefined} row2
+ * @param {Number|undefined} coln2
+ * @return {Boolean} selected
+ */
+ BlockGraph.prototype.isEdgeSelected = function(row1, coln1, row2, coln2) {
+ if (typeof row1 === 'object') {
+ var sourceIndex = row1;
+ var destIndex = coln1;
+ row1 = sourceIndex.row;
+ coln1 = sourceIndex.column;
+ row2 = destIndex.row;
+ coln2 = destIndex.column;
+ }
+ var minRow = Math.min(row1, row2);
+ var minColn = Math.min(coln1, coln2);
+ var blocks = this.blocks;
+
+ // find the block the edge belongs to
+ if (minRow < blocks.length) {
+ var blocksRow = blocks[minRow];
+ if (minColn < blocksRow.length) {
+ if (row1 - row2) {
+ return blocks[minRow][minColn].get('left');
+ } else {
+ return blocks[minRow][minColn].get('top');
+ }
+ } else {
+ return blocks[minRow][minColn - 1].get('right');
+ }
+ } else {
+ return blocks[minRow - 1][minColn].get('bottom');
+ }
+ };
+
+ /**
+ * mark the edge as selected
+ * @param {Object} sourceIndex {row: rowIndex, column: columnIndex}
+ * @param {Object} destIndex
+ * @return {Boolean} acquired true if a block is captured by player
+ */
+ BlockGraph.prototype.addToBlockData = function(sourceIndex, destIndex) {
+ var row, column;
+ var blocks = this.blocks;
+ var numOfBlocksAquired = 0;
+
+ // get the blocks the edge belongs to
+ if (sourceIndex.row === destIndex.row) {
+ row = sourceIndex.row;
+ column = Math.min(sourceIndex.column, destIndex.column);
+ if (row < blocks.length) {
+ blocks[row][column].set('top', 1);
+ if (blocks[row][column].acquired()) {
+ numOfBlocksAquired++;
+ blocks[row][column].set('userAcquired', vApp.moveEnabled);
+ }
+ }
+ if (row > 0) {
+ blocks[row - 1][column].set('bottom', 1);
+ if (blocks[row - 1][column].acquired()) {
+ numOfBlocksAquired++;
+ blocks[row - 1][column].set('userAcquired', vApp.moveEnabled);
+ }
+ }
+ } else if (sourceIndex.column === destIndex.column) {
+ row = Math.min(sourceIndex.row, destIndex.row);
+ column = sourceIndex.column;
+ if (column < blocks[row].length) {
+ blocks[row][column].set('left', 1);
+ if (blocks[row][column].acquired()) {
+ numOfBlocksAquired++;
+ blocks[row][column].set('userAcquired', vApp.moveEnabled);
+ }
+ }
+ if (column > 0) {
+ blocks[row][column - 1].set('right', 1);
+ if (blocks[row][column - 1].acquired()) {
+ numOfBlocksAquired++;
+ blocks[row][column - 1].set('userAcquired', vApp.moveEnabled);
+ }
+ }
+ }
+
+ // log the last turn
+ vApp.lastTurn = {
+ sourceIndex: sourceIndex,
+ destIndex: destIndex
+ }
+
+ return numOfBlocksAquired;
+ };
+
+ /**
+ * returns the blocks which contains the edge passed in parameter
+ * @param {Object} dotIndex1
+ * @param {Object} dotIndex2
+ * @param {Boolean} options.acquired
+ * @return {Array.} blocks
+ */
+ BlockGraph.prototype.getNeighbourBlocks = function(dotIndex1, dotIndex2, options) {
+ var nBlocks = [];
+ var blocks = this.blocks;
+ var minRow = Math.min(dotIndex1.row, dotIndex2.row);
+ var minColn = Math.min(dotIndex1.column, dotIndex2.column);
+
+ if (minRow < blocks.length && minColn < blocks[minRow].length) {
+ nBlocks.push(blocks[minRow][minColn]);
+ }
+ if (dotIndex1.row === dotIndex2.row && // rows of the two dots are same
+ minRow > 0) {
+ nBlocks.push(blocks[minRow - 1][minColn]);
+ } else if (dotIndex1.column === dotIndex2.column && // columns of the two dots are same
+ minColn > 0) {
+ nBlocks.push(blocks[minRow][minColn - 1]);
+ }
+
+ if (options) {
+ if(!options.acquired) {
+ nBlocks = nBlocks.filter(function(block) {
+ return !block.acquired();
+ });
+ }
+ if (options.otherThan) {
+ nBlocks = nBlocks.filter(function(block) {
+ return !(_.isEqual(block, options.otherThan));
+ });
+ }
+ }
+
+ return nBlocks;
+ };
+
+ /**
+ * get all the unselected edges of a block
+ * @param {Block} block
+ * @param {Array.} edges
+ */
+ BlockGraph.prototype.unselectedEdges = function(block) {
+ var edges = [];
+ // get all the edges with the value null
+ if (block.get('top') === null) {
+ edges.push({
+ sourceIndex: {row: block._row, column: block._column},
+ destIndex: {row: block._row, column: block._column + 1}
+ });
+ }
+ if (block.get('bottom') === null) {
+ edges.push({
+ sourceIndex: {row: block._row + 1, column: block._column},
+ destIndex: {row: block._row + 1, column: block._column + 1}
+ });
+ }
+ if (block.get('left') === null) {
+ edges.push({
+ sourceIndex: {row: block._row, column: block._column},
+ destIndex: {row: block._row + 1, column: block._column}
+ });
+ }
+ if (block.get('right') === null) {
+ edges.push({
+ sourceIndex: {row: block._row, column: block._column + 1},
+ destIndex: {row: block._row + 1, column: block._column + 1}
+ });
+ }
+ return edges;
+ }
+
+ /**
+ * get the sides in the graph which follows the condition passed
+ * @param {Integer} minDrawnEdges minimum selected edge in block
+ * @param {Integer} maxDrawnEdges maximum selected edge in block
+ */
+ BlockGraph.prototype.sidesInBlock = function(minDrawnEdges, maxDrawnEdges) {
+ var blocks = this.blocks;
+ var row, column;
+ var blocksRow, block;
+ var drawnSidesCount;
+ var acceptedEdges = [], unselectedEdges;
+ var that = this;
+
+ for (row = 0; row < blocks.length; row++) {
+ blocksRow = blocks[row];
+
+ for (column = 0; column < blocksRow.length; column++) {
+ block = blocksRow[column];
+ drawnSidesCount = block.get('selected');
+
+ if (drawnSidesCount <= maxDrawnEdges && drawnSidesCount >= minDrawnEdges) {
+ unselectedEdges = this.unselectedEdges(block);
+ acceptedEdges = acceptedEdges.concat(unselectedEdges.filter(function(edge) {
+ var nBlocks = that.getNeighbourBlocks(edge.sourceIndex, edge.destIndex);
+ return nBlocks.every(function(block) {
+ var selectedEdges = block.get('selected');
+ return selectedEdges <= maxDrawnEdges &&
+ selectedEdges >= minDrawnEdges;
+ });
+ }));
+ }
+ }
+ }
+ return acceptedEdges;
+ };
+
+ window.vBlockGraph = BlockGraph;
+
+})();
diff --git a/pool/shard000/JavaScript/0003693_browsersync.js b/pool/shard000/JavaScript/0003693_browsersync.js
new file mode 100644
index 0000000000000000000000000000000000000000..f6932ba882185af7cf2041d80a387448e3842238
--- /dev/null
+++ b/pool/shard000/JavaScript/0003693_browsersync.js
@@ -0,0 +1,73 @@
+
+
+// IN THE DOGBOX AS WAS KILLING THE BROWSER
+var gulp = require('gulp');
+var browserSync = require('browser-sync');
+var reload = browserSync.reload;
+
+
+var cfg = require('../config/gulp');
+
+// Watch Files For Changes & Reload
+gulp.task('serve', ['scriptsAngular'], function () {
+ browserSync({
+ notify: false,
+ // Run as an https by uncommenting 'https: true'
+ // Note: this uses an unsigned certificate which on first access
+ // will present a certificate warning in the browser.
+ // https: true,
+ server: {
+ baseDir: ['build']
+ }
+ });
+
+ // gulp.watch('build/assets/js/**').on('change', function(file) {
+ // server.changed(file.path);
+ // watch for browserify change app.js
+ gulp.watch(
+ cfg.uri[cfg.siteBuild].watchJS,
+ { maxListeners: 999999 },
+ ['browserifyAngular', reload]
+ );
+
+ // Watch for new styles
+ gulp.watch(cfg.common.styles, { maxListeners: 999999 }, ['styles', reload ]);
+
+ // Watch src js files should be updated with watchify
+ // gulp.watch(cfg.common.appScripts, ['scripts', reload]);
+ // Watch test.spec.js files
+ // gulp.watch('./build/assets/js/app.js', [reload]);
+ // Watch templates
+ gulp.watch(cfg.common.html, { maxListeners: 999999 }, ['scriptsAngular', reload]);
+ // Watch images
+ gulp.watch(cfg.common.images, { maxListeners: 999999 }, ['images', reload]);
+ // Watch others assets, pretty fast so grouped
+ gulp.watch([
+ cfg.uri[cfg.siteBuild].fonts,
+ cfg.uri[cfg.siteBuild].meta,
+ cfg.uri[cfg.siteBuild].icons
+ ],
+ { maxListeners: 999999 },
+ ['assets']);
+
+ gulp.watch(cfg.uri[cfg.siteBuild].indexHtml, ['indexHtml', reload]);
+
+ // Watch for new content
+ gulp.watch(
+ cfg.uri[cfg.siteBuild].contentDir + '/**/*',
+ { maxListeners: 999999 },
+ ['fetchContent', 'sheets', reload]
+ );
+
+ // Watch for new content
+ gulp.watch([
+ cfg.common.markdown,
+ cfg.common.buildHelpers,
+ cfg.uri[cfg.siteBuild].templates + '**/*'
+ ],
+ [
+ 'metalsmith', reload
+ ]
+ );
+
+});
diff --git a/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js b/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..4a088ea70f0614f795f40989eeebf8f16af68343
--- /dev/null
+++ b/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js
@@ -0,0 +1,43 @@
+/* jshint -W117, -W030 */
+describe('layout', function () {
+ describe('SidebarController', function () {
+ var controller,
+ di,
+ view1 = 'app/products/products.html';
+
+ beforeEach(function() {
+ module('app', specHelper.fakeLogger);
+ specHelper.injector(function($controller, $httpBackend, $location, $rootScope,
+ $state, $templateCache, productsService) {});
+ di = function di() {
+ $rootScope.$digest();
+ };
+ });
+
+ beforeEach(function () {
+ controller = $controller('SidebarController');
+ $templateCache.put(view1, '');
+ });
+
+ // it('should have a base attribute for / to return `true`', function () {
+ // $location.path('/');
+ // di();
+ // expect(controller.isCurrent($state.current)).to.be.true;
+ // });
+
+ // it('should have isCurrent() for non route not return `current`', function () {
+ // $location.path('/invalid');
+ // di();
+ // expect(controller.isCurrent({title: 'invalid'})).to.be.false;
+ // });
+
+ // it('$broadcast and $stateChangeStart event', function () {
+ // var toState = {
+ // hideSidebar: true
+ // };
+ // controller.isCurrent($state.current);
+ // $rootScope.$broadcast('$stateChangeStart', {}, toState);
+ // di();
+ // });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003697_identity.js b/pool/shard000/JavaScript/0003697_identity.js
new file mode 100644
index 0000000000000000000000000000000000000000..39350caf49ecdb2042c5cb2ded17ed889fb60ceb
--- /dev/null
+++ b/pool/shard000/JavaScript/0003697_identity.js
@@ -0,0 +1,23 @@
+(function () {
+
+ function identityService($window, UsersResource) {
+ var user;
+ if ($window.bootstrappedUserObject) {
+ user = new UsersResource();
+ angular.extend(user, $window.bootstrappedUserObject);
+ }
+ return {
+ currentUser: user,
+ isAuthenticated: function() {
+ return !!this.currentUser;
+ },
+ isAuthorizedForRole: function(role) {
+ return !!this.currentUser && this.currentUser.roles.indexOf(role) > -1;
+ }
+ }
+ }
+
+ angular
+ .module('app.services')
+ .factory('identity', ['$window', 'UsersResource', identityService]);
+}());
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003700_controller.js b/pool/shard000/JavaScript/0003700_controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..aa06ad8a64470077ff5826e95c36145b138c692c
--- /dev/null
+++ b/pool/shard000/JavaScript/0003700_controller.js
@@ -0,0 +1,39 @@
+(function () {
+
+ // Main module
+ var app = angular.module('odalic-app');
+
+ // Controller
+ var currentFolder = $.getPathForRelativePath('');
+ app.controller('odalic-chngpasswdcnf-ctrl', function ($scope, rest, $routeParams, $auth) {
+
+ // Initialization
+ $scope.dataload = {};
+ $scope.status = 'default';
+ $scope.confirmation = {
+ alertSuccess: {},
+ alertFailure: {}
+ };
+
+ // Actions to take upon page load
+ var token = $routeParams['token'];
+
+ // Send the token
+ rest.users.password.confirm(token).exec(
+ // Success
+ function (response) {
+ $auth.logout();
+ $scope.status = 'success';
+ $scope.dataload.show = true;
+ },
+
+ // Failure
+ function (response) {
+ $scope.status = 'failure';
+ $scope.dataload.show = true;
+ }
+ );
+
+ });
+
+})();
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003708_gl-group-members-map.js b/pool/shard000/JavaScript/0003708_gl-group-members-map.js
new file mode 100644
index 0000000000000000000000000000000000000000..a4d76bc85ad6c9ffd5c9e6da6fb307c96bfb4776
--- /dev/null
+++ b/pool/shard000/JavaScript/0003708_gl-group-members-map.js
@@ -0,0 +1,94 @@
+jQuery(window).ready(function($){
+
+ $('#gmw-gl-group-members-map-wrapper').slideToggle('fast', function() {
+ var glgmMap = new google.maps.Map(document.getElementById('gmw-gl-group-members-map'), {
+ zoom: 8,
+ panControl: true,
+ zoomControl: true,
+ mapTypeControl: true,
+ center: new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng),
+ mapTypeId: google.maps.MapTypeId['ROADMAP']
+ });
+
+ var latlngbounds = new google.maps.LatLngBounds();
+
+ if ( glgmMapArgs.your_lat && glgmMapArgs.your_lng ) {
+ var yourLocation = new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng);
+ latlngbounds.extend(yourLocation);
+
+ marker = new google.maps.Marker({
+ position: new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng),
+ map: glgmMap,
+ icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
+ });
+ }
+
+ var i;
+ var gmiw = false;
+ gmMarkers = [];
+
+ for (i = 0; i < glgmGroups.length; i++) {
+ console.log(glgmGroups[i]);
+ if ( glgmGroups[i]['latLng'] != undefined ) {
+ var mapIcon, shadow;
+
+ var groupLocation = new google.maps.LatLng(glgmGroups[i]['latLng'][0]['lat'], glgmGroups[i]['latLng'][0]['long']);
+ latlngbounds.extend(groupLocation);
+
+ mapIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ glgmGroups[i]['mc'] +'|FF776B|000000';
+ shadow = 'https://chart.googleapis.com/chart?chst=d_map_pin_shadow';
+
+ gmMarkers[i] = new google.maps.Marker({
+ position: groupLocation,
+ icon:mapIcon,
+ map:glgmMap,
+ shadow: shadow,
+ id:i
+ });
+
+ with ({ gmMarker: gmMarkers[i] }) {
+ google.maps.event.addListener(gmMarker, 'click', function() {
+ if (gmiw) {
+ gmiw.close();
+ gmiw = null;
+ }
+ gmiw = new google.maps.InfoWindow({
+ content: getGMWIContent(gmMarker.id),
+ });
+ gmiw.open(glgmMap, gmMarker);
+ });
+ }
+ }
+ }
+
+ glgmMap.fitBounds(latlngbounds);
+
+ if ( glgmGroups.length == 1 && !glgmMapArgs.your_lat ) {
+ blistener = google.maps.event.addListener( ( glgmMap ), 'bounds_changed', function(event) {
+ this.setZoom(11);
+ google.maps.event.removeListener(blistener);
+ });
+ }
+
+ function getGMWIContent(i) {
+
+ var content = "";
+ content += '';
+ content += '
' + glgmGroups[i]['avatar'] + '
';
+ content += '
';
+ content += '
';
+ content += ' ';
+ content += 'Address: ' + glgmGroups[i]['latLng'][0]['address'] + ' ';
+ //if ( glgmMapArgs.units_array != false )
+ //content += 'Distance: ' + glgmGroups[i]['distance'] + ' ' + glgmMapArgs.units_array['name'] + ' ';
+ content += '
';
+ content += '
';
+ content += '
';
+ return content;
+ }
+ });
+});
+
+
+
+
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003709_PluginManager.js b/pool/shard000/JavaScript/0003709_PluginManager.js
new file mode 100644
index 0000000000000000000000000000000000000000..def86a36650df9a96c9f50a2d29522adf062ce88
--- /dev/null
+++ b/pool/shard000/JavaScript/0003709_PluginManager.js
@@ -0,0 +1,146 @@
+/*globals define*/
+/*
+ * All functions not prepended with an '_' are considered actions callable
+ * from the commandline. The name of the file is considered the name of the
+ * item.
+ *
+ * This convention is most important bc of the addition of a preprocessing
+ * function to all these functions in the ComponentManager constructor.
+ */
+
+"use strict";
+var _ = require("lodash"),
+ R = require("ramda"),
+ path = require("path"),
+ exists = require("exists-file"),
+ rm_rf = require("rimraf"),
+ fs = require("fs"),
+ childProcess = require("child_process"),
+ utils = require("./utils"),
+ ComponentManager = require("./ComponentManager"),
+ PluginGenerator = require("./shim/PluginGenerator"),
+ PluginHelpers = require("./shim/PluginHelpers"),
+ metadata = require("webgme-engine/src/plugin/coreplugins/PluginGenerator/metadata.json"),
+ RAW_CONFIG = metadata.configStructure;
+
+var PluginManager = function (logger) {
+ ComponentManager.call(this, "plugin", logger);
+};
+
+_.extend(PluginManager.prototype, ComponentManager.prototype);
+
+/**
+ * Functions to create the config flag from the WebGME's
+ * PluginGenerator options. They are organized by type.
+ *
+ * @return {undefined}
+ */
+PluginManager.prototype._getOptions = function () {
+ return RAW_CONFIG.map(function (config) {
+ return PluginHelpers.getConfigValue[config.valueType](config);
+ }).filter(function (opt) {
+ return opt.name.indexOf("meta") === -1;
+ });
+};
+
+PluginManager.prototype._parseConfig = function (options) {
+ var config = PluginHelpers.getConfig(RAW_CONFIG, options);
+
+ // We don't support the meta flag as we don't provide access to any project
+ config.meta = false;
+
+ // If pluginName was not set in the options, set it to the pluginId
+ config.pluginName = options.pluginName || options.pluginID;
+
+ return config;
+};
+
+/**
+ * Create a new plugin
+ *
+ * @param args
+ * @return {undefined}
+ */
+PluginManager.prototype.new = function (options, callback) {
+ // Set the config options from the command line flags
+ var self = this,
+ config = this._parseConfig(options),
+ pluginGenerator = new PluginGenerator(this._logger, config);
+
+ pluginGenerator.main((e) => {
+ if (e) {
+ return callback(e);
+ }
+
+ // Get the src, test paths
+ var paths = R.mapObjIndexed(
+ function (empty, type) {
+ return `${type}/plugins/${config.pluginID}`;
+ },
+ { src: null, test: null }
+ );
+
+ // Store the plugin info in the webgme-setup.json file
+ var pluginConfig = {
+ src: paths.src,
+ test: paths.test,
+ };
+ this._register(config.pluginID, pluginConfig);
+ this._logger.write("Created new plugin at " + paths.src);
+ // If templates were generated, run `combine_templates`
+ this._combineTemplates(paths.src, function (err) {
+ if (err) {
+ callback(err);
+ } else {
+ if (
+ options.language &&
+ options.language.toLowerCase() !== "javascript"
+ ) {
+ var packageJSON = utils.getPackageJSON();
+
+ if (!packageJSON.dependencies["webgme-bindings"]) {
+ packageJSON.dependencies["webgme-bindings"] = "latest";
+ utils.writePackageJSON(packageJSON);
+ }
+
+ self._logger.write(
+ "Added webgme-bindings to dependencies - do npm install"
+ );
+ }
+
+ callback(null);
+ }
+ });
+ });
+};
+
+PluginManager.prototype._combineTemplates = function (srcPath, callback) {
+ var root = utils.getRootPath(),
+ scriptDir = path.join(root, srcPath, "Templates"),
+ scriptPath = path.join(scriptDir, "combine_templates.js"),
+ job;
+
+ if (exists(scriptPath)) {
+ job = childProcess.fork(scriptPath, [], {
+ cwd: scriptDir,
+ silent: true,
+ });
+ this._logger.write('running "combine_templates"...');
+ this._logger.writeStream(job.stdout);
+ this._logger.errorStream(job.stderr);
+
+ job.on("close", (code) => {
+ var err = null;
+ if (code !== 0) {
+ // Failure...
+ err = `Could not combine templates for plugin`;
+ this._logger.error(err);
+ }
+ callback(err);
+ });
+ } else {
+ callback(null);
+ }
+};
+
+module.exports = PluginManager;
diff --git a/pool/shard000/JavaScript/0003710_reader_send_email.js b/pool/shard000/JavaScript/0003710_reader_send_email.js
new file mode 100644
index 0000000000000000000000000000000000000000..9bedaf7840e674a0ac336d524cc74e0777ee86d6
--- /dev/null
+++ b/pool/shard000/JavaScript/0003710_reader_send_email.js
@@ -0,0 +1,257 @@
+NEWSBLUR.ReaderSendEmail = function(story, options) {
+ var defaults = {};
+
+ _.bindAll(this, 'close', 'save_callback', 'error');
+
+ this.options = $.extend({}, defaults, options);
+ this.model = NEWSBLUR.assets;
+ this.story = story;
+ this.feed_id = this.story.get('story_feed_id');
+ this.feed = this.model.get_feed(this.feed_id);
+
+ this.runner();
+};
+
+NEWSBLUR.ReaderSendEmail.prototype = new NEWSBLUR.Modal;
+
+_.extend(NEWSBLUR.ReaderSendEmail.prototype, {
+
+ runner: function() {
+ _.bindAll(this, 'save');
+ this.options.onOpen = _.bind(function() {
+ $('input[name=to]', this.$modal).focus();
+ }, this);
+ this.make_modal();
+ this.open_modal();
+ this.existing_emails = $.evalJSON($.cookie('NB:email:addresses')) || [];
+ this.autocomplete_emails();
+
+ if (!NEWSBLUR.Globals.is_authenticated) {
+ this.save_callback({'code': -1, 'message': '你必须登录之后才能通过邮件发送文章。'});
+ }
+
+ this.$modal.bind('click', $.rescope(this.handle_click, this));
+ $('input, textarea', this.$modal).bind('keydown', 'ctrl+return', this.save);
+ $('input, textarea', this.$modal).bind('keydown', 'meta+return', this.save);
+ },
+
+ make_modal: function() {
+ var self = this;
+
+ this.$modal = $.make('div', { className: 'NB-modal-email NB-modal' }, [
+ $.make('span', { className: 'NB-modal-loading NB-spinner'}),
+ $.make('div', { className: 'NB-modal-error'}),
+ $.make('h2', { className: 'NB-modal-title' }, '通过邮件发送文章'),
+ $.make('h2', { className: 'NB-modal-subtitle' }, [
+ (this.feed && $.make('div', { className: 'NB-modal-email-feed' }, [
+ $.make('img', { className: 'NB-modal-feed-image feed_favicon', src: $.favicon(this.feed) }),
+ $.make('div', { className: 'NB-modal-feed-title' }, this.feed.get('feed_title'))
+ ])),
+ $.make('div', { className: 'NB-modal-email-story-title' }, this.story.story_title),
+ $.make('div', { className: 'NB-modal-email-story-permalink' }, this.story.story_permalink)
+ ]),
+ $.make('div', { className: 'NB-modal-email-to-container' }, [
+ $.make('label', { 'for': 'NB-send-email-to' }, [
+ ' 接收方邮件地址:'
+ ]),
+ $.make('input', { className: 'NB-input NB-modal-to', name: 'to', id: 'NB-send-email-to', value:
+ ($.cookie('NB:email:to') || "") })
+ ]),
+ $.make('div', { className: 'NB-modal-email-explanation' }, [
+ "您可以选择添加一段评论,此评论会显示在文章的上方。"
+ ]),
+ $.make('div', { className: 'NB-modal-email-comments-container' }, [
+ $.make('textarea', { className: 'NB-modal-email-comments' })
+ ]),
+ $.make('div', { className: 'NB-modal-email-from-container' }, [
+ $.make('div', [
+ $.make('label', { 'for': 'NB-send-email-from-name' }, [
+ ' 你的姓名:'
+ ]),
+ $.make('input', { className: 'NB-input NB-modal-email-from', name: 'from_name', id: 'NB-send-email-from-name', value: this.model.preference('full_name') || NEWSBLUR.Globals.username || '' })
+ ]),
+ $.make('div', { style: 'margin-top: 8px' }, [
+ $.make('label', { 'for': 'NB-send-email-from-email' }, [
+ ' 你的邮箱:'
+ ]),
+ $.make('input', { className: 'NB-input NB-modal-email-from', name: 'from_email', id: 'NB-send-email-from-email', value: NEWSBLUR.Globals.email || this.model.preference('email') || '' })
+ ]),
+ $.make('div', { style: 'margin-top: 8px' }, [
+ $.make('label', { 'for': 'NB-send-email-cc' }, [
+ ' CC 我:'
+ ]),
+ $.make('div', { className: 'NB-modal-email-cc-wrapper' }, [
+ $.make('input', { className: 'NB-modal-email-cc', name: 'email_cc', id: 'NB-send-email-cc', type: "checkbox", checked: this.model.preference('email_cc') }),
+ $.make('label', { 'for': 'NB-send-email-cc' }, [
+ "给我发送一封此邮件的拷贝"
+ ])
+ ])
+ ])
+ ]),
+ $.make('form', { className: 'NB-recommend-form' }, [
+ $.make('div', { className: 'NB-error' }),
+ $.make('div', { className: 'NB-modal-submit' }, [
+ $.make('input', { type: 'submit', className: 'NB-modal-submit-button NB-modal-submit-green', value: '发送文章' }),
+ ' 或 ',
+ $.make('a', { href: '#', className: 'NB-modal-emailclient' }, '在邮件客户端中打开')
+ ])
+ ])
+ ]);
+ },
+
+ save: function(e) {
+ var from_name = $('input[name=from_name]', this.$modal).val();
+ var from_email = $('input[name=from_email]', this.$modal).val();
+ var to = $('input[name=to]', this.$modal).val();
+ var email_cc = $('input[name=email_cc]', this.$modal).is(":checked");
+ var comments = $('textarea', this.$modal).val();
+ var $save = $('input[type=submit]', this.$modal);
+ var $error = $('.NB-modal-error', this.$modal);
+
+ $error.hide();
+ $save.addClass('NB-disabled').val('Sending...');
+ $('.NB-modal-loading', this.$modal).addClass('NB-active');
+ this.model.preference('full_name', from_name);
+ this.model.preference('email', from_email);
+ this.model.preference('email_cc', email_cc);
+ $('.NB-error', this.$modal).fadeOut(500);
+
+ this.model.send_story_email({
+ story_id : this.story.id,
+ feed_id : this.feed_id,
+ from_name : from_name,
+ from_email : from_email,
+ email_cc : email_cc,
+ to : to,
+ comments : comments
+ }, this.save_callback, this.error);
+ },
+
+ save_callback: function(data) {
+ var $save = $('input[type=submit]', this.$modal);
+ if (!data || data.code < 0) {
+ $('.NB-error', this.$modal).html(data.message).fadeIn(500);
+ $('.NB-modal-loading', this.$modal).removeClass('NB-active');
+ $save.removeClass('NB-disabled').val('Send this story');
+ } else {
+ $save.val('Sent!');
+ $.cookie('NB:email:to', $('input[name=to]', this.$modal).val());
+ var emails = $('input[name=to]', this.$modal).val();
+ emails = emails.replace(/[, ]+/g, ' ').split(' ');
+ emails = _.uniq(this.existing_emails.concat(emails));
+ emails = _.map(emails, function(e) { return _.string.trim(e); });
+ emails = _.compact(emails);
+ $.cookie('NB:email:addresses', $.toJSON(emails), {expires: 365*10});
+ this.close();
+ }
+ },
+
+ error: function(data) {
+ var $error = $('.NB-modal-error', this.$modal);
+ var $save = $('input[type=submit]', this.$modal);
+ $error.show();
+ if (!data) {
+ $error.text("There was a issue on the backend with sending your email. Sorry about this! It has been noted and will be fixed soon. You should probably send this manually now.");
+ } else {
+ $('.NB-error', this.$modal).html(data.message).fadeIn(500);
+ }
+ $save.removeClass('NB-disabled').val('Send this story');
+ $('.NB-modal-loading', this.$modal).removeClass('NB-active');
+ },
+
+ open_email_client: function() {
+ var from_name = $('input[name=from_name]', this.$modal).val();
+ var from_email = $('input[name=from_email]', this.$modal).val();
+ var to = $('input[name=to]', this.$modal).val();
+ var comments = $('textarea', this.$modal).val();
+
+ var url = [
+ 'mailto:',
+ to,
+ '?subject=',
+ from_name,
+ ' 给您共享了一篇文章:',
+ this.story.story_title,
+ '&body=',
+ comments,
+ '%0D%0A%0D%0A--%0D%0A%0D%0A',
+ this.story.story_permalink,
+ '%0D%0A%0D%0A',
+ $(this.story.story_content).text(),
+ '%0D%0A%0D%0A',
+ '--',
+ '%0D%0A%0D%0A',
+ '通过 NewsZeit.com 共享'
+ ].join('');
+ window.open(url);
+ },
+
+ autocomplete_emails: function() {
+ var $to = $('input[name=to]', this.$modal);
+ var existing_emails = this.existing_emails;
+
+ var split = function(val) {
+ return val.split( /,\s*/ );
+ };
+ var extractLast = function(term) {
+ return split( term ).pop();
+ };
+
+ $to
+ // don't navigate away from the field on tab when selecting an item
+ .bind( "keydown", function( event ) {
+ if ( event.keyCode === $.ui.keyCode.TAB &&
+ $( this ).data( "ui-autocomplete" ).menu.active ) {
+ event.preventDefault();
+ }
+ })
+ .autocomplete({
+ delay: 0,
+ minLength: 0,
+ appendTo: '.NB-modal-email',
+ source: function( request, response ) {
+ // delegate back to autocomplete, but extract the last term
+ console.log(["autocomplete", request, request.term, existing_emails]);
+ response( $.ui.autocomplete.filter(
+ existing_emails, extractLast( request.term ) ) );
+ },
+ focus: function() {
+ // prevent value inserted on focus
+ return false;
+ },
+ select: function( event, ui ) {
+ var terms = split( this.value );
+ // remove the current input
+ terms.pop();
+ // add the selected item
+ terms.push( ui.item.value );
+ // add placeholder to get the comma-and-space at the end
+ terms.push( "" );
+ this.value = terms.join( ", " );
+ return false;
+ }
+ });
+ },
+
+ // ===========
+ // = Actions =
+ // ===========
+
+ handle_click: function(elem, e) {
+ var self = this;
+
+ $.targetIs(e, { tagSelector: '.NB-modal-submit-button' }, function($t, $p) {
+ e.preventDefault();
+
+ self.save();
+ return false;
+ });
+ $.targetIs(e, { tagSelector: '.NB-modal-emailclient' }, function($t, $p) {
+ e.preventDefault();
+
+ self.open_email_client();
+ return false;
+ });
+ }
+
+});
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003713_participants.js b/pool/shard000/JavaScript/0003713_participants.js
new file mode 100644
index 0000000000000000000000000000000000000000..434bdeb9c89377da89ee0f11ebac412657139044
--- /dev/null
+++ b/pool/shard000/JavaScript/0003713_participants.js
@@ -0,0 +1,71 @@
+/*
+ * The MIT License
+ * Copyright (c) 2014-2016 Nick Guletskii
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+const controller =
+ /* @ngInject*/
+ ($scope, $stateParams, $rootScope, $q, users, userCount, ContestService) => {
+ const updateParticipants = () => {
+ $q.all({
+ users: ContestService.getContestParticipantsPage($stateParams.contestId,
+ $stateParams.page),
+ count: ContestService.countContestParticipants($stateParams.contestId)
+ })
+ .then(({
+ users,
+ count
+ }) => {
+ $scope.users = users;
+ $scope.userCount = count;
+ });
+ };
+ $rootScope.$on("userTimeExtendedInContest", updateParticipants);
+ $scope.page = $stateParams.page;
+ $scope.users = users;
+ $scope.userCount = userCount;
+ };
+
+export default {
+ "name": "contestParticipantsList",
+ "url": "/contest/{contestId:[0-9]+}/participants?userId",
+ "templateUrl": "/partials/contests/contest/participants.html",
+ controller,
+ "params": {
+ "page": "1"
+ },
+ "resolve": {
+ "users": (ContestService, $stateParams) =>
+ ContestService.getContestParticipantsPage(
+ $stateParams.contestId,
+ $stateParams.page),
+ "userCount": (ContestService, $stateParams) =>
+ ContestService.countContestParticipants($stateParams.contestId)
+ },
+ "data": {
+ canAccess:
+ /* @ngInject*/
+ ($refStateParams, PromiseUtils, SecurityService) =>
+ PromiseUtils.and(
+ SecurityService.hasPermission("approved"),
+ SecurityService.hasContestPermission($refStateParams.contestId,
+ "view_participants"))
+ }
+};
diff --git a/pool/shard000/JavaScript/0003717_extensionSvc.js b/pool/shard000/JavaScript/0003717_extensionSvc.js
new file mode 100644
index 0000000000000000000000000000000000000000..2eb6d35f5a751aca71f3c6e8050bea49f4d2e55b
--- /dev/null
+++ b/pool/shard000/JavaScript/0003717_extensionSvc.js
@@ -0,0 +1,37 @@
+const getOptionsListeners = [];
+const initConverterListeners = [];
+const sectionPreviewListeners = [];
+
+export default {
+ onGetOptions(listener) {
+ getOptionsListeners.push(listener);
+ },
+
+ onInitConverter(priority, listener) {
+ initConverterListeners[priority] = listener;
+ },
+
+ onSectionPreview(listener) {
+ sectionPreviewListeners.push(listener);
+ },
+
+ getOptions(properties, isCurrentFile) {
+ return getOptionsListeners.reduce((options, listener) => {
+ listener(options, properties, isCurrentFile);
+ return options;
+ }, {});
+ },
+
+ initConverter(markdown, options) {
+ // Use forEach as it's a sparsed array
+ initConverterListeners.forEach((listener) => {
+ listener(markdown, options);
+ });
+ },
+
+ sectionPreview(elt, options) {
+ sectionPreviewListeners.forEach((listener) => {
+ listener(elt, options);
+ });
+ },
+};
diff --git a/pool/shard000/JavaScript/0003723_Shell.js b/pool/shard000/JavaScript/0003723_Shell.js
new file mode 100644
index 0000000000000000000000000000000000000000..8ef004aacf4a39bec089415b6d5c638155b83c0b
--- /dev/null
+++ b/pool/shard000/JavaScript/0003723_Shell.js
@@ -0,0 +1,65 @@
+const Interpreter = require('./Interpreter')
+const Filesystem = require('./Filesystem')
+
+const ENV = require('../configs/environment')
+
+/**
+ * Shell Class inherits from Interpreter
+ * Options:
+ * - filesystem {Object}
+ * - commands {Object}
+ * - env {Object} all extra mocked variables
+ */
+class Shell extends Interpreter{
+ constructor({ filesystem = undefined, commands = undefined, env = {} } = {}) {
+ super()
+
+ this.polyfills()
+
+ this.Classes = {
+ Command: require('./Command'),
+ File: require('./File')
+ }
+
+ /**
+ * Create the virtual filesystem
+ * @return reference to instance of @class Filesystem
+ */
+ this.fs = new Filesystem(filesystem, this)
+ this.env = {
+ ...ENV,
+ ...env
+ }
+
+ // Init builtin commands, @method in parent
+ // pass shell reference
+ this.ShellCommands = this.registerCommands(this)
+ this.ShellCommands = {
+ ...this.ShellCommands,
+ ...this.registerCommands(this, commands),
+ }
+ }
+
+ polyfills() {
+ if (!global.Promise) {
+ global.Promise = require('promise-polyfill').Promise
+ }
+ if (!global.fetch) {
+ global.fetch = require('whatwg-fetch')
+ }
+ return true
+ }
+
+ /**
+ * Pass control to Interpreter
+ * @return [String] OR {Promise} to resolve from your wrapper.
+ */
+ run(cmd) {
+ return this.exec(cmd)
+ }
+}
+
+// Object.defineProperty(Shell.prototype, 'fs', { writable: true, enumerable: false })
+// Object.defineProperty(Shell.prototype, 'ShellCommands', { writable: true, enumerable: false })
+
+module.exports = Shell
diff --git a/pool/shard000/JavaScript/0003727_startup.js b/pool/shard000/JavaScript/0003727_startup.js
new file mode 100644
index 0000000000000000000000000000000000000000..9882b477a723435049d184316c8b4aa9f97188e4
--- /dev/null
+++ b/pool/shard000/JavaScript/0003727_startup.js
@@ -0,0 +1,25 @@
+Meteor.startup(function () {
+ // Add hosts features for testing
+ if (Hosts.find().count() === 0 ) {
+ _.each(hostFixtures, function (host) {
+ Hosts.insert(host);
+ });
+ }
+ if (Notifications.find().count() === 0 ) {
+ _.each(notificationsFixtures, function (notification) {
+ Notifications.insert(notification);
+ });
+ }
+
+ if (Meteor.isServer) {
+ Meteor.methods({
+ updateHostStatus: function (hostname) {
+ var url = 'http://' + hostname,
+ result = Meteor.http.get(url, {timeout: 30000});
+ if (result.statusCode === 200) {
+ return 'ok';
+ }
+ }
+ });
+ }
+});
diff --git a/pool/shard000/JavaScript/0003728_toRedshift.js b/pool/shard000/JavaScript/0003728_toRedshift.js
new file mode 100644
index 0000000000000000000000000000000000000000..6705d85ca518b2cfe939918a83c1077c8aa3f692
--- /dev/null
+++ b/pool/shard000/JavaScript/0003728_toRedshift.js
@@ -0,0 +1,125 @@
+var
+ pg = require('pg'),
+ AWS = require('aws-sdk'),
+ uuid = require('uuid'),
+ src_path = process.env.MODULE_PATH || ".",
+ readTable = require(src_path+"/readTable"),
+ rs_username = process.env.RSDB_USERNAME || "imagedb",
+ rs_password = process.env.RSDB_PASSWORD || "ImageDbuser7",
+ rs_database = process.env.RSDB_DATABASE || "defaultdb",
+ debug = "true" == (process.env.APP_DEBUG || "false"),
+ rs_port = process.env.RSDB_PORT || 5439,
+ cage = process.env.CAGE || "ci",
+ customer = process.env.CUSTOMER || "shoppertrak",
+ rs_host = process.env.RSDB_HOST || "redshift."+cage+"."+customer+".47lining.com",
+ rsCopy = new Object();
+
+function writeDynamoToRedshift(table, callback) {
+ writeToRedshift("'dynamodb://"+table+"'", "READRATIO 100", callback);
+}
+
+function writeS3ToRedshift(bucketName, key, callback) {
+ writeToRedshift("'s3://"+bucketName+"/"+key+"'", " JSON 'auto'", callback);
+}
+
+function writeToRedshift(from_str, args, callback) {
+ var accessKeyId = "", secretAccessKey = "";
+ if (AWS.config.credentials == undefined) {
+ // Now set temporary credentials seeded from the master credentials
+ AWS.config.credentials = new AWS.EC2MetadataCredentials({
+ httpOptions: { timeout: 5000 } // 5 second timeout
+ });
+ AWS.config.credentials.refresh();
+ }
+ accessKeyId = AWS.config.credentials.accessKeyId;
+ secretAccessKey = AWS.config.credentials.secretAccessKey;
+ var query = "COPY imageprocessingtable from "+ from_str
+ +" credentials 'aws_access_key_id="+accessKeyId+";aws_secret_access_key="+secretAccessKey+"' "
+ + args
+ +" TIMEFORMAT AS 'YYYY:MM:DD HH:MI:SS' "
+ ;
+ var outer_callback = callback;
+ console.log("Connecting to "+rs_database+" on "+rs_host);
+ var conString = "postgres://"+rs_username+":"+rs_password+"@"+
+ rs_host+":"+rs_port+"/"+rs_database;
+
+ var client = new pg.Client(
+ {
+ user: rs_username,
+ database: rs_database,
+ password: rs_password,
+ port: rs_port,
+ host: rs_host
+ }
+ );
+ client.connect(function(err) {
+ if(err) {
+ return console.error('could not connect to postgres', err);
+ }
+ if (debug) console.log("About to run Query: "+query);
+ client.query(query, "",
+ function(err, result) {
+ if (debug) console.log(">>> query callback.. ");
+ client.end();
+ if (err) {
+ console.log("ERROR: "+err);
+ }
+ if (outer_callback) {
+ if (debug) console.log(">>> outer callback.. ");
+ outer_callback(err, "All done - don't write database");
+ if (debug) console.log("<<< outer callback.. ");
+ }
+ if (debug) console.log("<<< query callback.. ");
+ }
+ );
+ if (debug) console.log("<<< connect callback.. ");
+ });
+
+ if (debug) console.log("<<< writeToRedshift");
+}
+
+function writeToS3(dynamo_data, callback) {
+ // N.B. this might take a wad of memory all items and strings -
+ // TODO look at stream implementation
+ bucketName = 'dynamo-archive-'+uuid.v4();
+ console.log(">>> writingTo S3 bucket "+bucketName+", rows: "+dynamo_data.length);
+ var output_data = "";
+ for (i = 0; i < dynamo_data.length; i++) {
+ output_data = output_data + JSON.stringify(dynamo_data[i].attrs);
+ }
+ var s3 = new AWS.S3();
+ s3.createBucket({Bucket: bucketName}, function(err, data) {
+ if (err) console.log(err, err.stack); // an error occurred
+ else {
+ // console.log(">>> s3.upload.. ");
+ s3.putObject({Bucket: bucketName, Body: output_data, Key: 'imageproc.json'}, function(err, data) {
+ if (err) console.log(err, err.stack); // an error occurred
+ else {
+ writeToRedshift(bucketName, 'imageproc.json', callback);
+ }
+ });
+ }
+ });
+}
+
+rsCopy.copyDynamoToRedshiftViaS3 = function(region, dyn_tablename, query_data, callback) {
+ if (debug) console.log(">>> copyToRedshiftViaS3: "+dyn_tablename);
+ AWS.config.update({ region: region });
+ readTable.scanMetadata(dyn_tablename,
+ function(err, data) {
+ if (err) {
+ console.log(err);
+ callback(err);
+ return;
+ }
+ writeToS3(data.Items, callback);
+ }
+ );
+};
+
+rsCopy.copyDynamoToRedshift = function(region, dyn_tablename, query_data, callback) {
+ if (debug) console.log(">>> copyToRedshift: "+dyn_tablename);
+ AWS.config.update({ region: region });
+ writeDynamoToRedshift(dyn_tablename, callback);
+};
+module.exports=rsCopy;
diff --git a/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js b/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js
new file mode 100644
index 0000000000000000000000000000000000000000..c442202be5960ea983428f79dfb61772e56acd8d
--- /dev/null
+++ b/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js
@@ -0,0 +1,87 @@
+app.controller('ProjectClassifyCtrl', function($scope, $state, $stateParams, bugPage, DiffService) {
+ angular.extend($scope, bugPage);
+ $scope.changedFiles = [];
+ $scope.currentBug = null;
+ $scope.bugKeyUrl = null;
+ $scope.classificationHasChanged = false;
+ $scope.classification = {
+ 'bug': null,
+ 'user': null,
+ 'lineChangeClassifications': []
+ };
+ $scope.sendClassificationFn = debounce(function() {
+ console.log('about to send classification');
+ }, 500);
+
+ if ($stateParams.bug) {
+ $scope.bugKeyUrl = $stateParams.bug;
+ for (var i = 0; i < $scope.bugs.length; i++) {
+ if ($scope.bugs[i].key == $scope.bugKeyUrl) {
+ var bug = $scope.bugs[i];
+ $scope.currentBug = bug;
+
+ DiffService.computeDiff(bug, function(result) {
+ angular.extend($scope, result);
+ });
+ }
+ }
+ }
+
+ $scope.classify = function(change, classificationForm) {
+ console.log('in classify');
+ var elementFound = false;
+ var lineChange;
+
+ if (change.deletion !== null) {
+ lineChange = change.deletion;
+ } else {
+ lineChange = change.addition;
+ }
+
+ var newLineChangeClassification = {
+ 'lineChange': lineChange,
+ 'classification': null,
+ 'lineChangeClassificationForm': classificationForm
+ };
+
+ for (var i = 0; i < $scope.classification.lineChangeClassifications.length; i++) {
+ var lineChangeClassification = $scope.classification.lineChangeClassifications[i];
+
+ if (lineChangeClassification.lineChange.oldLineNumber == lineChange.oldLineNumber) {
+ elementFound = true;
+ $scope.classification.lineChangeClassifications[i] = newLineChangeClassification;
+ }
+ }
+
+ if (!elementFound) {
+ $scope.classification.lineChangeClassifications.push(newLineChangeClassification);
+ }
+
+ $scope.sendClassificationFn();
+ };
+
+ $scope.$watch('data.currentPage', function(newPage, oldPage) {
+ if (newPage !== oldPage) {
+ $state.transitionTo('project.classify', {name: $stateParams.name, page: $scope.data.currentPage}, {reload: true});
+ }
+ });
+
+ $scope.setCurrentBug = function(bug) {
+ $state.transitionTo('project.classify', {name: $stateParams.name, page: $scope.data.currentPage, bug: bug.key}, {reload: true});
+ };
+
+ function debounce(func, wait, immediate) {
+ var timeout;
+ return function() {
+ var context = this, args = arguments;
+ var later = function() {
+ timeout = null;
+ if (!immediate) func.apply(context, args);
+ };
+ var callNow = immediate && !timeout;
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ if (callNow) func.apply(context, args);
+ };
+ }
+});
diff --git a/pool/shard000/JavaScript/0003732_deals.js b/pool/shard000/JavaScript/0003732_deals.js
new file mode 100644
index 0000000000000000000000000000000000000000..033b8cd3edcd89a3dfb1a9024653e9c6f31d627b
--- /dev/null
+++ b/pool/shard000/JavaScript/0003732_deals.js
@@ -0,0 +1,213 @@
+var pageSize = DEFAULT_PAGE_SIZE;
+var currPageNumber = 0;
+
+var dealSortDirection = false;
+var dealOrderBy = DEFAULT_DEALS_SORT_FIELD;
+
+$(document).ready(function() {
+ $('#endDate, #create_tender_enddate').datepicker({
+ format: 'mm-dd-yyyy',
+ startDate: '-5y'
+ });
+
+ $('#pagination_dealsnum').on('change', function() {
+ pageSize = this.value;
+ currPageNumber = 0;
+ showDealsPage(currPageNumber);
+ });
+
+ showDeals();
+ $('#search_deals').keypress(function(e) {
+ if (e.keyCode == ENTER_BUTTON_CODE) {
+ pageSize = $('#pagination_dealsnum').val();
+ currPageNumber = 0;
+ showDealsPage(currPageNumber);
+ return false;
+ }
+ });
+
+ $("#deal_title").click(function(){
+ sortDeals("proposal.tender.title","deal_title");
+ });
+
+ $("#deal_date").click(function(){
+ sortDeals("date","deal_date");
+ });
+
+ $("#deal_status").click(function(){
+ sortDeals("status.name","deal_status");
+ });
+
+ $("#deal_sum").click(function(){
+ sortDeals("sum","deal_sum");
+ });
+});
+
+function showDeals() {
+ var queryParams = '';
+ if(getCookie("userRole") != "undefined") {
+ var userRole = getCookie("userRole");
+ queryParams += (queryParams.length==0)?"userRole=" + userRole : "&userRole=" + userRole;
+ }
+
+ if($('#search_deals').val()!=""){
+ queryParams += (queryParams.length==0)?"searchParam="+$('#search_deals').val():"&searchParam="+$('#search_deals').val();
+ }
+
+ showDealsPagination(queryParams);
+
+ queryParams += (queryParams.length==0)?"pageSize="+pageSize:"&pageSize="+pageSize;
+ queryParams += "&pageNumber=" + currPageNumber + "&sortDirection=" +
+ ((!dealSortDirection)?"desc":"asc") + "&orderBy=" + dealOrderBy;
+
+ $.ajax({
+ url: DEALS_URL,
+ type: "GET",
+ data: queryParams,
+ async: false,
+ dataType:'json',
+
+ success: function(data) {
+ var html = '';
+ var dataSize = data.length;
+
+ if(dataSize > 0) {
+ for (var i = 0; i < dataSize; i++) {
+ html += '' + data[i].title + ' ' +
+ '' + unixTimeConverter(data[i].date) + ' ' +
+ '' + data[i].businessPartner + ' ' +
+ '' + data[i].status + ' ' +
+ '' + data[i].sum + ' ' +
+ '' +
+ '' +
+ 'Action ' +
+ '' +
+ '
' +
+ ' ';
+ }
+
+ $('#deals_user_message').html('');
+ $('#deal_items').show();
+ $('#deals').html(html);
+ $('#pagination').show();
+ $('.new_deal_notification').html("");
+ } else {
+ $('#deals_user_message').html('No deals found ').show();
+ $('#deal_items').hide();
+ $('#pagination').hide();
+ }
+ },
+ error:function(){
+ alert("ERROR");
+ }
+ });
+
+ $.ajax({
+ url: MYDEALS_DATE_URL,
+ type: "PUT",
+ dataType: "json",
+ async: false,
+ success:function(data) {
+ $('.new_deal_notification').html("");
+ }
+ });
+}
+
+function unixTimeConverter(timestamp){
+ var date = new Date(timestamp);
+ var year = date.getFullYear();
+ var month = date.getMonth();
+ var day = date.getDate();
+
+ if(day <= 9) day = "0" + day;
+ if(month <= 9) month = "0" + month;
+
+ return day + "/" + month + "/" + year;
+}
+
+function closeDeal() {
+ var str = '';
+ str += "statusName=" + DEAL_STATUS;
+ $.ajax({
+ url: DEALS_URL+"/" + $('#close_deal_id').val() + "?" + str,
+ type: "PUT",
+
+ success: function(data){
+ closeDealModalWindow('close_deal_mod_wind');
+ showDeals()},
+ error: function(){
+ alert("Can't close this deal")
+ }
+ })
+}
+
+function writeCloseDealId(id) {
+ document.getElementById('close_deal_id').value = id;
+}
+
+function closeDealModalWindow(id) {
+ $('#' + id).modal('hide');
+}
+
+function showDealsPagination(queryParams) {
+ $.ajax({
+ url: DEALS_NUMBER_URL,
+ async: false,
+ type: "GET",
+ data: queryParams,
+ dataType:'json',
+
+ success: function(data) {
+ var dataSize = data;
+ var pageNumber = Math.ceil(dataSize / pageSize);
+
+ if(dataSize > 0 && pageSize < dataSize) {
+ var html = '';
+ html += '« ';
+ for(var z=1;z<=pageNumber;z++) {
+ html += ''+z+' ';
+ }
+ html += '» ';
+
+ $('.page_pagination').html(html).show();
+ $('#pagination').show();
+
+ if(currPageNumber != 0) {
+ document.getElementById('prev_page').setAttribute("onclick", "showDealsPage("+(currPageNumber-1)+");");
+ }
+
+ if(currPageNumber != pageNumber-1) {
+ document.getElementById('next_page').setAttribute("onclick", "showDealsPage("+(currPageNumber+1)+");");
+ }
+ } else {
+ $('.page_pagination').hide();
+ }
+ },
+ error:function(){
+ $('#pagination').hide();
+ }
+ });
+}
+
+function showDealsPage(pageNumber) {
+ currPageNumber = pageNumber;
+ showDeals();
+}
+
+function sortDeals(orderByField, elementId) {
+ dealSortDirection = (dealOrderBy == orderByField) ? !dealSortDirection : false;
+ dealOrderBy = orderByField;
+
+ $('#deal_items .sortable').removeClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
+ if(dealSortDirection == false) {
+ $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
+ } else {
+ $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
+ }
+
+ showDeals();
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003735_group-repertories.js b/pool/shard000/JavaScript/0003735_group-repertories.js
new file mode 100644
index 0000000000000000000000000000000000000000..fc111aa01fcb3d4541c3a6a4af66c56d08a1029a
--- /dev/null
+++ b/pool/shard000/JavaScript/0003735_group-repertories.js
@@ -0,0 +1,69 @@
+import Component from '@ember/component';
+import { inject as service } from '@ember/service';
+import { sort} from '@ember/object/computed';
+import { computed} from '@ember/object';
+import { task, timeout } from 'ember-concurrency';
+import { denodeify } from 'rsvp'
+
+export default Component.extend({
+ store: service(),
+ algolia: service(),
+ currentUser: service(),
+ customCollapsed: true,
+ customCollapsed2: true,
+ customCollapsed4: true,
+ customCollapsed5: true,
+ sortedRepertoriesProperties: [
+ 'chartTitle',
+ ],
+ group: computed(
+ 'model', function() {
+ return this.store.findRecord('group', this.model.groupId);
+ }),
+ sortedRepertories: sort(
+ 'group.repertories',
+ 'sortedRepertoriesProperties'
+ ),
+ flashMessages: service(),
+ searchChart: task(function* (term){
+ yield timeout(600);
+ let func = denodeify(this.algolia.search.bind(this.algolia))
+ let res = yield func({ indexName: 'Chart', query: term})
+ return res.hits
+ }),
+ deleteRepertory: task(function *(repertory) {
+ try {
+ yield repertory.destroyRecord();
+ this.flashMessages.success("Deleted!");
+ } catch(e) {
+ this.flashMessages.danger("Problem!");
+ }
+ }).drop(),
+ createRepertoryModal: false,
+ createRepertoryModalError: false,
+ saveRepertory: task(function* (c){
+ try {
+ let chart = yield this.store.findRecord('chart', c.objectID)
+ let repertory = yield this.store.createRecord('repertory', {
+ chart: chart,
+ group: this.group,
+ }).save();
+ yield repertory.activate({
+ 'by': this.get('currentUser.user.id'),
+ });
+ this.set('createRepertoryModal', false);
+ this.set('createRepertoryModalError', false);
+ this.flashMessages.success("Created!");
+ } catch(e) {
+ e.errors.forEach((e) => {
+ this.set('createRepertoryModalError', true);
+ this.flashMessages.danger(e.detail);
+ })
+ }
+ }).drop(),
+ actions: {
+ cancelRepertory(repertory){
+ repertory.deleteRecord();
+ },
+ }
+});
diff --git a/pool/shard000/JavaScript/0003739_86print.js b/pool/shard000/JavaScript/0003739_86print.js
new file mode 100644
index 0000000000000000000000000000000000000000..2fa17a005aee799c66b074ddac5fa261466f591e
--- /dev/null
+++ b/pool/shard000/JavaScript/0003739_86print.js
@@ -0,0 +1,60 @@
+/*
+//
+// HELP for Alasql.js
+// Date: 03.11.2014
+// (c) 2014, Andrey Gershun
+//
+*/
+
+/**
+ Print statement
+ @class
+ @param {object} params Initial setup properties
+*/
+
+yy.Print = function (params) { return yy.extend(this, params); }
+
+/**
+ Generate SQL string
+ @this Print statement object
+*/
+yy.Print.prototype.toString = function() {
+ var s = 'PRINT';
+ if(this.statement) s += ' '+this.statement.toString();
+ return s;
+}
+
+
+/**
+ Print result of select statement or expression
+ @param {string} databaseid Database identificator
+ @param {object} params Query parameters
+ @param {statement-callback} cb Callback function
+ @this Print statement object
+*/
+yy.Print.prototype.execute = function (databaseid,params,cb) {
+// console.log(this.url);
+ var self = this;
+ var res = 1;
+//console.log(this);
+ alasql.precompile(this,databaseid,params); /** @todo Change from alasql to this */
+
+ if(this.exprs && this.exprs.length >0) {
+ var rs = this.exprs.map(function(expr){
+
+// console.log('var y;return '+expr.toJS('({})','', null));
+ var exprfn = new Function("params,alasql,p",'var y;return '+expr.toJS('({})','', null)).bind(self);
+ var r = exprfn(params,alasql);
+ return JSONtoString(r);
+ });
+ console.log.apply(console,rs);
+ } else if(this.select) {
+ var r = this.select.execute(databaseid,params);
+ console.log(JSONtoString(r));
+ } else {
+ console.log();
+ }
+
+ if(cb) res = cb(res);
+ return res;
+};
diff --git a/pool/shard000/JavaScript/0003740_events.js b/pool/shard000/JavaScript/0003740_events.js
new file mode 100644
index 0000000000000000000000000000000000000000..e8888a7f2283ac6e27389aa6492a0645aedaa982
--- /dev/null
+++ b/pool/shard000/JavaScript/0003740_events.js
@@ -0,0 +1,43 @@
+define([
+ 'assert', 'sinon', 'underscore', 'fossil/module', 'fossil/services/events'
+], function (assert, sinon, _, Module, Events) {
+ "use strict";
+ suite('services/events', function () {
+ var methods = ['on', 'off', 'once', 'trigger'];
+ var events, module, fooSpy;
+
+ setup(function () {
+ fooSpy = sinon.spy();
+ events = new Events();
+ module = new Module();
+ events.on('foo', fooSpy);
+ module.use('events', events);
+ });
+
+ suite('#use', function () {
+ test('should add app! modifier', function () {
+ module.trigger('app!foo');
+
+ assert.ok(fooSpy.calledOnce);
+ });
+ });
+
+ suite('#dispose', function () {
+ test('should remove app! modifier', function () {
+ module.dispose('events', events);
+ module.trigger('app!foo');
+
+ assert.ok(!fooSpy.called);
+ });
+ });
+
+ suite('app! modifier', function () {
+ test('should pass arguments', function () {
+ module.trigger('app!foo', 'bar', 'baz');
+
+ assert.ok(fooSpy.calledOnce);
+ assert.ok(fooSpy.calledWith('bar', 'baz'));
+ });
+ });
+ });
+});
diff --git a/pool/shard000/JavaScript/0003746_expander.js b/pool/shard000/JavaScript/0003746_expander.js
new file mode 100644
index 0000000000000000000000000000000000000000..49f22674dedb10366ed4ced6c8a294298cb1b582
--- /dev/null
+++ b/pool/shard000/JavaScript/0003746_expander.js
@@ -0,0 +1,134 @@
+// TODO: opts.pre||post : does that actor run before or after the evals
+
+module.exports = Expander;
+
+var promise = require('when').promise;
+var sequence = require('when/sequence');
+var compiler = require('./compiler');
+var path = require('path');
+
+function Expander() {}
+
+Expander.perform = function(opts, inArgs, arg) {
+ return promise(function(resolve, reject, notify) {
+
+ var template = arg.actions[0].expansion;
+ if (!template) return resolve(arg);
+
+ var expansions = [];
+ var embedded;
+ var origPaths;
+ var part = '';
+ var parts = [];
+
+ for (var i = template.length - 1; i >= 0; i--) {
+ if (template[i]+template[i-1] == '}}') {
+ i--;
+ embedded = '';
+ parts.unshift(part);
+ part = '';
+ continue;
+ }
+ if (template[i]+template[i-1] == '{{') {
+ expansions.push({eval:embedded});
+ embedded = undefined
+ i--;
+ continue;
+ }
+ if (typeof embedded !== 'undefined') {
+ embedded = template[i] + embedded.toString();
+ }
+ else {
+ part = template[i] + part;
+ }
+ }
+
+ parts.unshift(part); // ?
+
+ if (expansions.length > 0) {
+
+ // update module require paths to the callers perspective
+
+ origPaths = module.paths;
+ module.paths = Expander.callerPaths(opts.$$caller.FileName, []);
+
+ arg.actions[0].expansion = ''; // rebuilding it
+ var first = parts.pop();
+ return sequence(expansions.map(function(expansion){
+ return function() {
+ return promise(function(resolve, reject, notify) {
+ compiler.perform(opts, arg, inArgs, expansion).then(
+ function(result) {
+
+
+ var part = parts.pop();
+ var copy = arg.actions;
+
+ if (part.match(/^(in\.|out\.)/)) part = ''; // ?
+
+ if (result instanceof Array && result.length > 0) {
+
+ arg.actions = [];
+ arg.asArray = true;
+
+ copy.forEach(function(action) {
+ result.forEach(function(result) {
+ var newAction = {};
+ Object.keys(action).forEach(function(key) {
+ newAction[key] = action[key];
+ });
+
+ if (first == '' && part == '' &&
+ (typeof action.expansion == 'undefined'
+ || action.expansion == '')) {
+ newAction.expansion = result;
+ }
+ else newAction.expansion = part + result + action.expansion + first;
+ arg.actions.push(newAction);
+ });
+ })
+ return resolve();
+ }
+
+ arg.actions.forEach(function(action) {
+ if (first == '' && part == '' &&
+ (typeof action.expansion == 'undefined'
+ || action.expansion == '')) {
+ action.expansion = result
+ } else {
+ action.expansion = part + result + action.expansion + first;
+ }
+ });
+
+ first = '';
+ resolve();
+ },
+ reject,
+ notify
+ )
+ });
+ }
+ })).then(
+ function() {
+ module.paths = origPaths;
+ resolve(arg);
+ },
+ function(e) {
+ module.paths = origPaths;
+ reject(e);
+ },
+ notify
+ );
+ } else {
+ arg.asArray = false;
+ resolve(arg);
+ }
+ });
+}
+
+Expander.callerPaths = function(filename, paths) {
+ var dirname = path.dirname(filename);
+ if (dirname == filename) return paths;
+ paths.push(path.normalize(dirname + path.sep + 'node_modules'));
+ return Expander.callerPaths(dirname, paths);
+}
diff --git a/pool/shard000/JavaScript/0003757_events.spec.js b/pool/shard000/JavaScript/0003757_events.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..e9fc11d64364497cbff71fc141f32f0cf3354ad7
--- /dev/null
+++ b/pool/shard000/JavaScript/0003757_events.spec.js
@@ -0,0 +1,44 @@
+'use strict';
+
+describe('DOM-related events', function() {
+ var $tree;
+ var tree;
+
+ before(function() {
+ helpers.createTreeContainer();
+
+ $tree = $('.tree');
+
+ tree = new InspireTree({
+ data: [{
+ text: 'A'
+ }]
+ });
+
+ new InspireTreeDOM(tree, {
+ target: $tree
+ });
+ });
+
+ it('provides a preventTreeDefault method', function(done) {
+ tree.on('node.click', function(event) {
+ expect(event.preventTreeDefault).to.be.a('function');
+ done();
+ });
+
+ // Inferno doesn't like jquery's click
+ $tree.find('a.title')[0].click();
+ });
+
+ it('passes handler as an argument', function(done) {
+ tree.on('node.click', function(event, node, handler) {
+ expect(handler).to.be.a('function');
+ done();
+ });
+
+ // Inferno doesn't like jquery's click
+ $tree.find('a.title')[0].click();
+ });
+
+ after(helpers.clearDOM);
+});
diff --git a/pool/shard000/JavaScript/0003759_mtof.js b/pool/shard000/JavaScript/0003759_mtof.js
new file mode 100644
index 0000000000000000000000000000000000000000..c46fc89089141ce3b32391be24d92675b4c7a2bd
--- /dev/null
+++ b/pool/shard000/JavaScript/0003759_mtof.js
@@ -0,0 +1,36 @@
+'use strict'
+
+let gen = require('./gen.js')
+
+let proto = {
+ name:'mtof',
+
+ gen() {
+ let out,
+ inputs = gen.getInputs( this )
+
+ if( isNaN( inputs[0] ) ) {
+ gen.closures.add({ [ this.name ]: Math.exp })
+
+ out = `( ${this.tuning} * gen.exp( .057762265 * (${inputs[0]} - 69) ) )`
+
+ } else {
+ out = this.tuning * Math.exp( .057762265 * ( inputs[0] - 69) )
+ }
+
+ return out
+ }
+}
+
+module.exports = ( x, props ) => {
+ let ugen = Object.create( proto ),
+ defaults = { tuning:440 }
+
+ if( props !== undefined ) Object.assign( props.defaults )
+
+ Object.assign( ugen, defaults )
+ ugen.inputs = [ x ]
+
+
+ return ugen
+}
diff --git a/pool/shard000/JavaScript/0003762_Gulpfile.js b/pool/shard000/JavaScript/0003762_Gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..3ddd822f64c5d87fd4fc61a738187985591cceaf
--- /dev/null
+++ b/pool/shard000/JavaScript/0003762_Gulpfile.js
@@ -0,0 +1,98 @@
+require('es6-promise').polyfill();
+
+var gulp = require('gulp'),
+ sass = require('gulp-sass'),
+ postcss = require('gulp-postcss'),
+ autoprefixer = require('autoprefixer'),
+ minifyCss = require('gulp-minify-css'),
+ uglify = require('gulp-uglify')
+ rename = require('gulp-rename')
+ del = require('del')
+;
+
+var CSS_BUILDDIR = './assets/css/';
+var JS_BUILDDIR = './assets/js/';
+
+gulp.task('build', function() {
+
+ // Generate CSS
+ gulp.src(['./assets/css/src/main.scss'])
+ .pipe(sass({precision: 8}).on('error', sass.logError))
+ .pipe(postcss([
+ autoprefixer({browsers: [
+ "Android 2.3",
+ "Android >= 4",
+ "Chrome >= 20",
+ "Firefox >= 24",
+ "Explorer >= 8",
+ "iOS >= 6",
+ "Opera >= 12",
+ "Safari >= 6"
+ ]})
+ ]))
+ .pipe(gulp.dest(CSS_BUILDDIR))
+ .pipe(minifyCss({keepSpecialComments: 0}))
+ .pipe(rename({extname: '.min.css'}))
+ .pipe(gulp.dest(CSS_BUILDDIR))
+ ;
+
+ // Minify Bootstrap Javascript files
+ gulp.src('./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js')
+ .pipe(rename({basename: "main"}))
+ .pipe(gulp.dest(JS_BUILDDIR))
+ .pipe(uglify().on('error', function (e) { console.log(e); }))
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(gulp.dest(JS_BUILDDIR))
+ ;
+
+ // Minify Theme Customizer file
+ gulp.src('./assets/js/src/theme-customizer.js')
+ .pipe(gulp.dest(JS_BUILDDIR))
+ .pipe(uglify().on('error', function (e) { console.log(e); }))
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(gulp.dest(JS_BUILDDIR))
+ ;
+
+ // Minify html5shiv
+ gulp.src('./node_modules/html5shiv/src/html5shiv.js')
+ .pipe(gulp.dest(JS_BUILDDIR))
+ .pipe(uglify().on('error', function (e) { console.log(e); }))
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(gulp.dest(JS_BUILDDIR))
+ ;
+
+ // Minify respond.js
+ gulp.src('./node_modules/respond.js/src/respond.js')
+ .pipe(gulp.dest(JS_BUILDDIR))
+ .pipe(uglify().on('error', function (e) { console.log(e); }))
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(gulp.dest(JS_BUILDDIR))
+ ;
+
+ // Copy fonts
+ gulp.src(['./node_modules/font-awesome/fonts/**/*'])
+ .pipe(gulp.dest('./assets/fonts/'))
+ ;
+
+ return gulp.src([
+ './assets/css/*.css',
+ './assets/fonts/**/*',
+ './assets/js/*.js',
+ './includes/**/*',
+ './languages/**/*',
+ './page-templates/**/*',
+ './templates/**/*',
+ './*.php',
+ './LICENSE.txt',
+ './README.txt',
+ './screenshot.png',
+ './style.css'
+ ], {base:"."})
+ .pipe(gulp.dest('./ltk-foundation/'));
+
+});
+
+gulp.task('clean', function() {
+ del('./ltk-foundation/**/*');
+ return del('./ltk-foundation');
+});
diff --git a/pool/shard000/JavaScript/0003764_wysiwyg.js b/pool/shard000/JavaScript/0003764_wysiwyg.js
new file mode 100644
index 0000000000000000000000000000000000000000..be76cf1cac81d13d689ac31de82c93f6b542aca0
--- /dev/null
+++ b/pool/shard000/JavaScript/0003764_wysiwyg.js
@@ -0,0 +1,143 @@
+window.Wy = {
+ split: function(){
+ var sel, range;
+ if (window.getSelection){
+ // IE9 and non-IE
+ sel = window.getSelection();
+ if (sel.getRangeAt && sel.rangeCount) {
+ range = sel.getRangeAt(0);
+ C.log(range);
+
+ var node = range.startContainer.parentNode,
+ text = range.startContainer.textContent,
+ start = range.startOffset;
+
+ var time = $(node).data('time');
+
+ var $t1 = $(''+text.substr(0, start)+' ').data('time', time),
+ $t2 = $(''+text.substr(start)+' ').data('time', time + 0.1);
+
+ if(node.tagName == 'I'){
+ $t2.insertAfter(node).blink('yellow');
+ $t1.insertAfter(node).blink('orange');
+ $(node).remove();
+ }
+ else{
+ $(node).empty().append($t1).append($t2);
+ }
+
+ return $t2;
+ }
+ } else if (document.selection && document.selection.type != "Control") {
+ // IE < 9
+ //document.selection.createRange().pasteHTML(html);
+ }
+ },
+
+ tagSelection: function(){
+ if(window.getSelection){
+ var sel = window.getSelection();
+ if(sel.getRangeAt && sel.rangeCount){
+ var range = sel.getRangeAt(0).cloneRange();
+
+ var node = range.startContainer.parentNode,
+ text = range.startContainer.textContent,
+ start = range.startOffset;
+
+ var node = document.createElement('span');
+ $(node).addClass('mark');
+ range.surroundContents(node);
+
+ //sel.removeAllRanges();
+ //sel.addRange(range);
+
+ return node;
+ }
+ }
+ },
+
+ paste: function(html){
+ var sel, range;
+ if (window.getSelection){
+ sel = window.getSelection();
+ if(sel.getRangeAt && sel.rangeCount){
+ range = sel.getRangeAt(0);
+
+ var node = range.startContainer.parentNode;
+
+ return $(html).insertAfter(node);
+ }
+ }
+ },
+
+ getSelection: function(){
+ var sel, range;
+ if(window.getSelection){
+ sel = window.getSelection();
+ if(sel.getRangeAt && sel.rangeCount){
+ range = sel.getRangeAt(0);
+
+ C.log(range);
+
+ var startNode = range.startContainer.parentNode,
+ endNode = range.endContainer.parentNode,
+ start = range.startOffset;
+
+ if(startNode == endNode) return false;
+ return $(startNode).nextUntil(endNode).add(startNode).add(endNode);
+ }
+ }
+ },
+
+ space: function(){
+ var sel, range;
+ if (window.getSelection){
+ // IE9 and non-IE
+ sel = window.getSelection();
+ if(sel.getRangeAt && sel.rangeCount){
+ range = sel.getRangeAt(0);
+ C.log(range);
+
+ var node = range.startContainer.parentNode,
+ text = range.startContainer.textContent,
+ start = range.startOffset;
+
+ var time = $(node).data('time');
+
+ var $t2 = Wy.split();
+ $t2.before(' ');
+
+ return $t2;
+ }
+ }
+ },
+
+ placeCaret: function(node, l){
+ if(window.getSelection){
+ var range = document.createRange();
+
+ if(!l) l = 0;
+ if(l == 0 && !node.innerHTML){
+ node.innerHTML = '';
+ l++;
+ }
+
+ range.setStart(node, l);
+ range.collapse(true);
+
+ var sel = window.getSelection();
+ sel.removeAllRanges();
+ sel.addRange(range);
+ }
+ },
+
+ increase: function(string, by){
+ return string.replace(
+ /[-]?((0|[1-9][0-9]*)(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?/g,
+ function(str, p1, p2, p3, p4, offset, s){
+ if(by < 1) return (Math.round((parseFloat(str) + by) * 100) / 100).toFixed(2);
+ return parseFloat(str) + by;
+ }
+ );
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003765_filter.js b/pool/shard000/JavaScript/0003765_filter.js
new file mode 100644
index 0000000000000000000000000000000000000000..708c76b6c9bec7d2ab3622c8bde0527dee6bd823
--- /dev/null
+++ b/pool/shard000/JavaScript/0003765_filter.js
@@ -0,0 +1,96 @@
+var renderer = PIXI.autoDetectRenderer(800, 600);
+document.body.appendChild(renderer.view);
+
+// create the root of the scene graph
+var stage = new PIXI.Container();
+
+stage.interactive = true;
+
+var bg = PIXI.Sprite.fromImage('_assets/BGrotate.jpg');
+bg.anchor.set(0.5);
+
+bg.position.x = renderer.width / 2;
+bg.position.y = renderer.height / 2;
+
+var filter = new PIXI.filters.ColorMatrixFilter();
+
+var container = new PIXI.Container();
+container.position.x = renderer.width / 2;
+container.position.y = renderer.height / 2;
+
+var bgFront = PIXI.Sprite.fromImage('_assets/SceneRotate.jpg');
+bgFront.anchor.set(0.5);
+
+container.addChild(bgFront);
+
+var light2 = PIXI.Sprite.fromImage('_assets/LightRotate2.png');
+light2.anchor.set(0.5);
+container.addChild(light2);
+
+var light1 = PIXI.Sprite.fromImage('_assets/LightRotate1.png');
+light1.anchor.set(0.5);
+container.addChild(light1);
+
+var panda = PIXI.Sprite.fromImage('_assets/panda.png');
+panda.anchor.set(0.5);
+
+container.addChild(panda);
+
+stage.addChild(container);
+
+stage.filters = [filter];
+
+var count = 0;
+var switchy = false;
+
+stage.on('click', onClick);
+stage.on('tap', onClick);
+
+function onClick()
+{
+ switchy = !switchy;
+
+ if (!switchy)
+ {
+ stage.filters = [filter];
+ }
+ else
+ {
+ stage.filters = null;
+ }
+}
+
+var help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' });
+help.position.y = renderer.height - 25;
+help.position.x = 10;
+
+stage.addChild(help);
+
+requestAnimationFrame(animate);
+
+function animate() {
+ bg.rotation += 0.01;
+ bgFront.rotation -= 0.01;
+
+ light1.rotation += 0.02;
+ light2.rotation += 0.01;
+
+ panda.scale.x = 1 + Math.sin(count) * 0.04;
+ panda.scale.y = 1 + Math.cos(count) * 0.04;
+
+ count += 0.1;
+
+ var matrix = filter.matrix;
+
+ matrix[1] = Math.sin(count) * 3;
+ matrix[2] = Math.cos(count);
+ matrix[3] = Math.cos(count) * 1.5;
+ matrix[4] = Math.sin(count / 3) * 2;
+ matrix[5] = Math.sin(count / 2);
+ matrix[6] = Math.sin(count / 4);
+
+ renderer.render(stage);
+ requestAnimationFrame(animate);
+}
+
+
diff --git a/pool/shard000/JavaScript/0003771_main.js b/pool/shard000/JavaScript/0003771_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..17736ef86227243db18a42538bed8c9470eb35dd
--- /dev/null
+++ b/pool/shard000/JavaScript/0003771_main.js
@@ -0,0 +1,230 @@
+/* globals toolbarSearch, menu, isRtl, fireGlobalEvent, CachedChatSubscription, DynamicCss */
+import Clipboard from 'clipboard';
+import s from 'underscore.string';
+
+RocketChat.settings.collection.find({_id:/theme-color-rc/i}, {fields:{ value: 1 }}).observe({changed: () => { DynamicCss.run(true); }});
+
+this.isFirefox = navigator.userAgent.match(/Firefox\/(\d+)\.\d/);
+
+Template.body.onRendered(function() {
+ new Clipboard('.clipboard');
+
+ $(document.body).on('keydown', function(e) {
+ if ((e.keyCode === 80 || e.keyCode === 75) && (e.ctrlKey === true || e.metaKey === true) && e.shiftKey === false) {
+ e.preventDefault();
+ e.stopPropagation();
+ toolbarSearch.focus(true);
+ }
+ const unread = Session.get('unread');
+ if (e.keyCode === 27 && e.shiftKey === true && (unread != null) && unread !== '') {
+ e.preventDefault();
+ e.stopPropagation();
+ modal.open({
+ title: t('Clear_all_unreads_question'),
+ type: 'warning',
+ confirmButtonText: t('Yes_clear_all'),
+ showCancelButton: true,
+ cancelButtonText: t('Cancel'),
+ confirmButtonColor: '#DD6B55'
+ }, function() {
+ const subscriptions = ChatSubscription.find({
+ open: true
+ }, {
+ fields: {
+ unread: 1,
+ alert: 1,
+ rid: 1,
+ t: 1,
+ name: 1,
+ ls: 1
+ }
+ });
+
+ subscriptions.forEach((subscription) =>{
+ if (subscription.alert || subscription.unread > 0) {
+ Meteor.call('readMessages', subscription.rid);
+ }
+ });
+ });
+ }
+ });
+
+ $(document.body).on('keydown', function(e) {
+ const target = e.target;
+ if (e.ctrlKey === true || e.metaKey === true) {
+ return;
+ }
+ if (!(e.keyCode > 45 && e.keyCode < 91 || e.keyCode === 8)) {
+ return;
+ }
+ if (/input|textarea|select/i.test(target.tagName)) {
+ return;
+ }
+ if (target.id === 'pswp') {
+ return;
+ }
+ const inputMessage = $('.rc-message-box__textarea');
+ if (inputMessage.length === 0) {
+ return;
+ }
+ inputMessage.focus();
+ });
+
+ $(document.body).on('click', function(e) {
+ if (e.target.tagName === 'A') {
+ const link = e.currentTarget;
+ if (link.origin === s.rtrim(Meteor.absoluteUrl(), '/') && /msg=([a-zA-Z0-9]+)/.test(link.search)) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (RocketChat.Layout.isEmbedded()) {
+ return fireGlobalEvent('click-message-link', {
+ link: link.pathname + link.search
+ });
+ }
+ return FlowRouter.go(link.pathname + link.search, null, FlowRouter.current().queryParams);
+ }
+ }
+ });
+
+ Tracker.autorun(function(c) {
+ const w = window;
+ const d = document;
+ const script = 'script';
+ const l = 'dataLayer';
+ const i = RocketChat.settings.get('GoogleTagManager_id');
+ if (Match.test(i, String) && i.trim() !== '') {
+ c.stop();
+ return (function(w, d, s, l, i) {
+ w[l] = w[l] || [];
+ w[l].push({
+ 'gtm.start': new Date().getTime(),
+ event: 'gtm.js'
+ });
+ const f = d.getElementsByTagName(s)[0];
+ const j = d.createElement(s);
+ const dl = l !== 'dataLayer' ? `&l=${ l }` : '';
+ j.async = true;
+ j.src = `//www.googletagmanager.com/gtm.js?id=${ i }${ dl }`;
+ return f.parentNode.insertBefore(j, f);
+ }(w, d, script, l, i));
+ }
+ });
+ if (Meteor.isCordova) {
+ return $(document.body).addClass('is-cordova');
+ }
+});
+
+RocketChat.mainReady = new ReactiveVar(false);
+Template.main.helpers({
+ removeSidenav() {
+ const { modal } = this;
+ return (modal || typeof modal === 'function' ? modal() : modal) || RocketChat.Layout.isEmbedded();
+ },
+ siteName() {
+ return RocketChat.settings.get('Site_Name');
+ },
+ logged() {
+ if (Meteor.userId() != null || (RocketChat.settings.get('Accounts_AllowAnonymousRead') === true && Session.get('forceLogin') !== true)) {
+ $('html').addClass('noscroll').removeClass('scroll');
+ return true;
+ } else {
+ $('html').addClass('scroll').removeClass('noscroll');
+ return false;
+ }
+ },
+ useIframe() {
+ const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined';
+ return iframeEnabled && RocketChat.iframeLogin.reactiveEnabled.get();
+ },
+ iframeUrl() {
+ const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined';
+ return iframeEnabled && RocketChat.iframeLogin.reactiveIframeUrl.get();
+ },
+ subsReady() {
+ const routerReady = FlowRouter.subsReady('userData', 'activeUsers');
+ const subscriptionsReady = CachedChatSubscription.ready.get();
+ const settingsReady = RocketChat.settings.cachedCollection.ready.get();
+ const ready = (Meteor.userId() == null) || (routerReady && subscriptionsReady && settingsReady);
+ RocketChat.CachedCollectionManager.syncEnabled = ready;
+ Meteor.defer(() => {
+ RocketChat.mainReady.set(ready);
+ });
+ return ready;
+ },
+ hasUsername() {
+ return (Meteor.userId() != null && Meteor.user().username != null) || (Meteor.userId() == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === true);
+ },
+ requirePasswordChange() {
+ const user = Meteor.user();
+ return user && user.requirePasswordChange === true;
+ },
+ CustomScriptLoggedOut() {
+ const script = RocketChat.settings.get('Custom_Script_Logged_Out') || '';
+ if (script.trim()) {
+ eval(script);//eslint-disable-line
+ }
+ },
+ CustomScriptLoggedIn() {
+ const script = RocketChat.settings.get('Custom_Script_Logged_In') || '';
+ if (script.trim()) {
+ eval(script);//eslint-disable-line
+ }
+ },
+ embeddedVersion() {
+ if (RocketChat.Layout.isEmbedded()) {
+ return 'embedded-view';
+ }
+ },
+ showSetupWizard() {
+ const userId = Meteor.userId();
+ const Show_Setup_Wizard = RocketChat.settings.get('Show_Setup_Wizard');
+
+ return (!userId && Show_Setup_Wizard === 'pending') || (userId && RocketChat.authz.hasRole(userId, 'admin') && Show_Setup_Wizard === 'in_progress');
+ }
+});
+
+Template.main.events({
+ 'click .burger'() {
+ return menu.toggle();
+ }
+});
+
+Template.main.onRendered(function() {
+ document.body.classList[(isRtl(localStorage.getItem('userLanguage'))? 'add': 'remove')]('rtl');
+ $('#initial-page-loading').remove();
+ window.addEventListener('focus', function() {
+ return Meteor.setTimeout(function() {
+ if (!$(':focus').is('INPUT,TEXTAREA')) {
+ return $('.input-message').focus();
+ }
+ }, 100);
+ });
+ return Tracker.autorun(function() {
+ const userId = Meteor.userId();
+ const Show_Setup_Wizard = RocketChat.settings.get('Show_Setup_Wizard');
+
+ if ((!userId && Show_Setup_Wizard === 'pending') || (userId && RocketChat.authz.hasRole(userId, 'admin') && Show_Setup_Wizard === 'in_progress')) {
+ FlowRouter.go('setup-wizard');
+ }
+ if (RocketChat.getUserPreference(userId, 'hideUsernames')) {
+ $(document.body).on('mouseleave', 'button.thumb', function() {
+ return RocketChat.tooltip.hide();
+ });
+ return $(document.body).on('mouseenter', 'button.thumb', function(e) {
+ const avatarElem = $(e.currentTarget);
+ const username = avatarElem.attr('data-username');
+ if (username) {
+ e.stopPropagation();
+ return RocketChat.tooltip.showElement($('').text(username), avatarElem);
+ }
+ });
+ } else {
+ $(document.body).off('mouseenter', 'button.thumb');
+ return $(document.body).off('mouseleave', 'button.thumb');
+ }
+ });
+});
+
+Meteor.startup(function() {
+ return fireGlobalEvent('startup', true);
+});
diff --git a/pool/shard000/JavaScript/0003772_ForkTool.js b/pool/shard000/JavaScript/0003772_ForkTool.js
new file mode 100644
index 0000000000000000000000000000000000000000..58a6e8cd533a5b277d189d0cc1d245c2007fa679
--- /dev/null
+++ b/pool/shard000/JavaScript/0003772_ForkTool.js
@@ -0,0 +1,120 @@
+/**
+ * Created by Jacky.Gao on 2017-07-10.
+ */
+import BaseTool from './BaseTool.js';
+import ForkNode from './ForkNode.js';
+import EventSelectDialog from './dialog/EventSelectDialog.js';
+
+export default class ForkTool extends BaseTool{
+ getType(){
+ return '分支';
+ }
+ getIcon(){
+ return ` `
+ }
+ newNode(){
+ return new ForkNode();
+ }
+ getConfigs(){
+ return {
+ in:-1,
+ out:-1,
+ single:false
+ };
+ }
+ getPropertiesProducer(){
+ const _this=this;
+ return function (){
+ const g=$(`
`);
+ g.append(_this.getCommonProperties(this));
+ return g;
+ }
+ }
+
+ buildConnectionCondition(target){
+ const group=$(`
+ 连线条件配置 `);
+
+ const noneConditionRadio=$(` 无条件
`);
+ group.append(noneConditionRadio);
+
+ const exprGroup=$(`
`);
+ group.append(exprGroup);
+ const exprConditionRadio=$(` 表达式条件 `);
+ exprGroup.append(exprConditionRadio);
+ const exprEditor=$(` `);
+ exprGroup.append(exprEditor);
+ exprEditor.val(target.expression || '');
+ exprEditor.change(function(){
+ target.expression=$(this).val();
+ });
+
+ const beanGroup=$(`
`);
+ group.append(beanGroup);
+ const beanConditionRadio=$(` 条件Bean `);
+ beanGroup.append(beanConditionRadio);
+ const tip='一个实现了com.bstek.uflo.process.handler.ConditionHandler接口,配置在Spring中的Bean Id';
+ const beanEditor=$(` `);
+ beanGroup.append(beanEditor);
+ beanEditor.change(function(){
+ target.handlerBean=$(this).val();
+ });
+ const beanSelectButton=$(`选择 `);
+ beanGroup.append(beanSelectButton);
+ exprEditor.prop('readOnly',true);
+ beanEditor.prop('readOnly',true);
+ beanSelectButton.attr('disabled',true);
+ if(target.conditionType==='Expression'){
+ exprEditor.prop('readOnly',false);
+ exprConditionRadio.children('input').attr('checked',true);
+ }else if(target.conditionType==='Handler'){
+ beanEditor.prop('readOnly',false);
+ beanConditionRadio.children('input').attr('checked',true);
+ }else{
+ noneConditionRadio.children('input').attr('checked',true);
+ }
+
+ const dialog=new EventSelectDialog(`选择${tip}`);
+ beanSelectButton.click(()=>{
+ dialog.show('ConditionHandler',function(beanId){
+ beanEditor.val(beanId);
+ target.handlerBean=beanId;
+ });
+ });
+ noneConditionRadio.children('input').click(function(){
+ exprEditor.prop('readOnly',true);
+ beanEditor.prop('readOnly',true);
+ beanSelectButton.attr('disabled',true);
+ target.conditionType=null;
+ target.handlerBean=null;
+ target.expression=null;
+ });
+
+ exprConditionRadio.children('input').click(function(){
+ exprEditor.prop('readOnly',false);
+ beanEditor.prop('readOnly',true);
+ beanSelectButton.attr('disabled',true);
+ target.conditionType='Expression';
+ target.handlerBean=null;
+ });
+
+ beanConditionRadio.children('input').click(function(){
+ exprEditor.prop('readOnly',true);
+ beanEditor.prop('readOnly',false);
+ beanSelectButton.attr('disabled',false);
+ target.conditionType='Handler';
+ target.expression=null;
+ });
+
+ return group;
+ }
+
+ getConnectionPropertiesProducer(){
+ const _this=this;
+ return function (target){
+ const g=$(`
`);
+ g.append(_this.buildConnectionCondition(this));
+ return g;
+ }
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003773_update-controller.js b/pool/shard000/JavaScript/0003773_update-controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..cbea696cd98be4a97ad79a7e5b23bd1e588b7d3a
--- /dev/null
+++ b/pool/shard000/JavaScript/0003773_update-controller.js
@@ -0,0 +1,35 @@
+(function($) {
+ var ngmod = angular.module("framework.controllers", ["framework.systemParamService"]);
+
+ ngmod.controller("systemParamUpdateCtrl",function($scope,systemParamRES,systemParamTRES){
+ systemParamRES.get({
+ method:"detail",
+ id :$.query.get("id")
+ }, function(detailPproject) {
+ $scope.project = detailPproject.model;
+ });
+
+
+ systemParamTRES.get({
+ method:"tlist",
+ category : "SIMPLE"
+ }, function(project) {
+ $scope.typeList = project.models;
+ });
+ $scope.save = function(invalid) {
+ if(invalid){
+ alert('错误!必填信息不能为空,请检查表单项!');
+ return;
+ }
+ systemParamRES.save({'method':"update"},$scope.project, function(project) {
+ if(project.respCode=="00"){
+ alert('操作成功');
+ window.location.href="systemParamList.shtml";
+ }else {
+ alert('操作失败'+project.respDesc);
+ }
+ });
+ };
+ });
+
+})(jQuery);
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003774_svg-collection.js b/pool/shard000/JavaScript/0003774_svg-collection.js
new file mode 100644
index 0000000000000000000000000000000000000000..73d1fe838a9a137208b4443351ace1cf37cdfac1
--- /dev/null
+++ b/pool/shard000/JavaScript/0003774_svg-collection.js
@@ -0,0 +1,32 @@
+import _ from "underscore";
+import {Collection} from "backbone";
+import FileModel from "./svg-model.js";
+import Colorfy from "./../utils/colorfy.js";
+
+export default class FileCollection extends Collection {
+ initialize(models, options) {
+ this.model = FileModel;
+ this.config = options.config;
+ }
+
+ /**
+ * split the file into multiple files if it has colors, then add it to the collection
+ * @param {File} file A svg that was dropped
+ */
+ addFile(file) {
+ var name = file.name.split(".svg")[0];
+ var extraColors = this.config.get("colors");
+ var colorfy = new Colorfy(name, extraColors, this.config.toJSON());
+
+ // build files for each color
+ _.each(colorfy.colors, (color, colorName) => {
+ let name = `${colorfy.originalFilepath}-${colorName}`;
+ this.add({ file, color, name })
+ });
+
+ // don't add base SVG if it had colors and the dynamicColorOnly option was true
+ if (_.isEmpty(colorfy.colors) || !this.config.get("dynamicColorOnly")) {
+ this.add({ file, name: colorfy.originalFilepath });
+ }
+ }
+}
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003776_server.js b/pool/shard000/JavaScript/0003776_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..4abd9b209471cfc674cd4ecfa7b2859e56bda890
--- /dev/null
+++ b/pool/shard000/JavaScript/0003776_server.js
@@ -0,0 +1,25 @@
+const cluster = require('cluster');
+const http = require('http');
+const os = require('os');
+const _ = require('lodash');
+
+const appFactory = require('./app');
+
+
+async function main() {
+
+ if (cluster.isMaster) {
+ console.log(`Master ${process.pid} is running`);
+ _.times(os.cpus().length, () => cluster.fork());
+ cluster.on('exit', (worker, code, signal) => {
+ console.log(`Worker ${worker.process.pid} died`);
+ });
+ } else {
+ const app = await appFactory.create();
+ const port = _.get(app.cfg, 'listen.port', 3030);
+ app.listen(port);
+ console.log(`Worker ${process.pid} started`);
+ }
+}
+
+main().catch(ex => console.error(ex));
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js b/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js
new file mode 100644
index 0000000000000000000000000000000000000000..4ebad4956040a612a219124bdfdbbb64b31d0a0c
--- /dev/null
+++ b/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js
@@ -0,0 +1,40 @@
+var cycleRepository = require('../CARLI/Entity/CycleRepository');
+var historicalPricingMigration = require('./historicalPricing');
+var Q = require('q');
+
+/**
+ * This script goes through all of the cycles and fills in historical pricing for all of the offerings in each.
+ */
+
+migrateHistoricalPricingForAllCyclesSerially();
+
+
+function migrateHistoricalPricingForAllCyclesSerially() {
+ return cycleRepository.listActiveCycles()
+ .then(function (cycles) {
+ var cycleList = cycles;
+ return migrateHistoricalPricingForNextCycle();
+
+ function migrateHistoricalPricingForNextCycle() {
+ var cycle = cycleList.pop();
+
+ if (!cycle) {
+ return;
+ }
+
+ return historicalPricingMigration.populateHistoricalPricingForCycle(cycle.id)
+ .then(migrateHistoricalPricingForNextCycle)
+ .catch(function (e) {
+ Logger.log(e);
+ });
+ }
+ })
+ .done();
+}
+
+function populateOneCycle(cycleId){
+ return historicalPricingMigration.populateHistoricalPricingForCycle(cycleId)
+ .catch(function (e) {
+ Logger.log(e);
+ });
+}
diff --git a/pool/shard000/JavaScript/0003778_appVersion.js b/pool/shard000/JavaScript/0003778_appVersion.js
new file mode 100644
index 0000000000000000000000000000000000000000..b563a3b54d5a3c50a6a828a1dbe3006905a175b5
--- /dev/null
+++ b/pool/shard000/JavaScript/0003778_appVersion.js
@@ -0,0 +1,15 @@
+function AppVersion() { }
+
+AppVersion.prototype.getVersionNumber = function(successCallback, errorCallback) {
+ cordova.exec(successCallback, errorCallback, "AppVersion", "getVersionNumber", []);
+};
+
+AppVersion.prototype.getBuildNumber = function(successCallback, errorCallback) {
+ cordova.exec(successCallback, errorCallback, "AppVersion", "getBuildNumber", []);
+};
+
+AppVersion.prototype.geAlbumPermission = function(successCallback, errorCallback) {
+ cordova.exec(successCallback, errorCallback, "AppVersion", "geAlbumPermission", []);
+};
+
+module.exports = new AppVersion();
diff --git a/pool/shard000/JavaScript/0003780_webpack.config.js b/pool/shard000/JavaScript/0003780_webpack.config.js
new file mode 100644
index 0000000000000000000000000000000000000000..2323f8300e6b9383715304744b1303954db65cb1
--- /dev/null
+++ b/pool/shard000/JavaScript/0003780_webpack.config.js
@@ -0,0 +1,218 @@
+// @AngularClass
+
+// Helper
+var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
+var NODE_ENV = process.env.NODE_ENV || 'development';
+
+// Node
+var webpack = require('webpack');
+var path = require('path');
+var pkg = require('./package.json');
+
+// Webpack Plugins
+var OccurenceOrderPlugin = webpack.optimize.OccurenceOrderPlugin;
+var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
+var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
+var DedupePlugin = webpack.optimize.DedupePlugin;
+var DefinePlugin = webpack.DefinePlugin;
+var BannerPlugin = webpack.BannerPlugin;
+
+
+/*
+ * Config
+ */
+
+var config = {
+ devtool: 'source-map',
+ // devtool: 'eval',
+
+ debug: true,
+ cache: true,
+ // our Development Server configs
+ devServer: {
+ inline: true,
+ colors: true,
+ historyApiFallback: true,
+ contentBase: 'src/public',
+ publicPath: '/__build__'
+ },
+
+ //
+ entry: {
+ 'angular2': [
+ // Angular 2 Deps
+ 'zone.js',
+ 'reflect-metadata',
+ 'rtts_assert/rtts_assert',
+ 'angular2/angular2'
+ ],
+ 'app': [
+ // App
+
+ /*
+ * include any 3rd party js lib here
+ */
+
+ './src/app/bootstrap'
+ ]
+ },
+
+ // Config for our build files
+ output: {
+ path: root('__build__'),
+ filename: '[name].js',
+ // filename: '[name].[hash].js',
+ sourceMapFilename: '[name].js.map',
+ chunkFilename: '[id].chunk.js'
+ // publicPath: 'http://mycdn.com/'
+ },
+
+ resolve: {
+ root: __dirname,
+ extensions: ['','.ts','.js','.json'],
+ alias: {
+ // we can switch between development and production
+ // 'angular2': 'node_modules/angular2/ts',
+ // 'angular2': 'angular2/ts/dev',
+
+ 'app': 'src/app',
+ 'common': 'src/common',
+
+ // 'components': 'src/app/components'
+ // 'services': '/app/services/*.js',
+ // 'stores/*': '/app/stores/*.js'
+ // 'angular2': 'angular2/es6/dev'
+ }
+ },
+
+ /*
+ * When using `templateUrl` and `styleUrls` please use `__filename`
+ * rather than `module.id` for `moduleId` in `@View`
+ */
+ node: {
+ __filename: true
+ },
+
+ module: {
+ loaders: [
+ // Support for *.json files.
+ { test: /\.json$/, loader: 'json' },
+
+ // Support for CSS as raw text
+ { test: /\.css$/, loader: 'raw' },
+
+ // support for .html as raw text
+ { test: /\.html$/, loader: 'raw' },
+
+ // Support for .ts files.
+ { test: /\.ts$/, loader: 'typescript-simple?&ignoreWarnings[]=2300&ignoreWarnings[]=2309', exclude: [
+ /\.spec\.ts$/,
+ /\.e2e\.ts$/,
+ /web_modules/,
+ /test/,
+ /node_modules/
+ ]
+ }
+ ],
+ noParse: [
+ /rtts_assert\/src\/rtts_assert/
+ ]
+ },
+
+ // plugins: plugins, // see below
+ context: __dirname,
+ stats: { colors: true, reasons: true }
+};
+
+
+var commons_chunks_plugins = [
+ {
+ name: 'angular2',
+ minChunks: Infinity,
+ filename: 'angular2.js'
+ },
+ {
+ name: 'common',
+ filename: 'common.js'
+ }
+]
+
+
+//
+var environment_plugins = {
+
+ all: [
+ new DefinePlugin({
+ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
+ 'VERSION': pkg.version
+ }),
+ new OccurenceOrderPlugin(),
+ new DedupePlugin(),
+ ],
+
+ production: [
+ new UglifyJsPlugin({
+ compress: {
+ warnings: false,
+ drop_debugger: false
+ },
+ output: {
+ comments: false
+ },
+ beautify: false
+ }),
+ new BannerPlugin(getBanner(), {entryOnly: true})
+ ],
+
+ development: [
+ /* Dev Plugin */
+ // new webpack.HotModuleReplacementPlugin(),
+ ]
+
+}//env
+
+
+
+
+
+
+
+
+
+if (NODE_ENV === 'production') {
+ // replace filename `.js` with `.min.js`
+ config.output.filename = config.output.filename.replace('.js', '.min.js');
+ config.output.sourceMapFilename = config.output.sourceMapFilename.replace('.js', '.min.js');
+ commons_chunks_plugins = commons_chunks_plugins.map(function(chunk) {
+ return chunk.filename.replace('.js', '.min.js');
+ });
+}
+else if (NODE_ENV === 'development') {
+ // any development actions here
+}
+
+// create CommonsChunkPlugin instance for each config
+var combine_common_chunks = commons_chunks_plugins.map(function(config) {
+ return new CommonsChunkPlugin(config);
+});
+
+// conbine everything
+config.plugins = [].concat(combine_common_chunks, environment_plugins.all, environment_plugins[NODE_ENV]);
+
+
+module.exports = config;
+
+// Helper functions
+function getBanner() {
+ return 'Angular2 Webpack Starter v'+ pkg.version +' by @gdi2990 from @AngularClass';
+}
+
+function root(args) {
+ args = sliceArgs(arguments, 0);
+ return path.join.apply(path, [__dirname].concat(args));
+}
+function rootNode(args) {
+ args = sliceArgs(arguments, 0);
+ return root.apply(path, ['node_modules'].concat(args));
+}
+
diff --git a/pool/shard000/JavaScript/0003783_index.js b/pool/shard000/JavaScript/0003783_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..fbd8f5ce3413a1c3cd5d970e7b854e2d20503da7
--- /dev/null
+++ b/pool/shard000/JavaScript/0003783_index.js
@@ -0,0 +1,50 @@
+'use strict';
+
+var path = require('path');
+var _ = require('lodash');
+
+function requiredProcessEnv(name) {
+ if (!process.env[name]) {
+ throw new Error('You must set the ' + name + ' environment variable');
+ }
+ return process.env[name];
+}
+
+// All configurations will extend these options
+// ============================================
+var all = {
+ env: process.env.NODE_ENV,
+
+ // Root path of server
+ root: path.normalize(__dirname + '/../../..'),
+
+ // Server port
+ port: process.env.PORT || 9000,
+
+ // Server IP
+ ip: process.env.IP || '0.0.0.0',
+
+ // Should we populate the DB with sample data?
+ seedDB: false,
+
+ // Secret for session, you will want to change this and make it an environment variable
+ secrets: {
+ session: 'wsproto1-secret'
+ },
+
+ // MongoDB connection options
+ mongo: {
+ options: {
+ db: {
+ safe: true
+ }
+ }
+ }
+};
+
+// Export the config object based on the NODE_ENV
+// ==============================================
+module.exports = _.merge(
+ all,
+ require('./shared'),
+ require('./' + process.env.NODE_ENV + '.js') || {});
diff --git a/pool/shard000/JavaScript/0003786_x-list.js b/pool/shard000/JavaScript/0003786_x-list.js
new file mode 100644
index 0000000000000000000000000000000000000000..faa612e5c2ed43c5dd8b2ef197ce78787b8e5a33
--- /dev/null
+++ b/pool/shard000/JavaScript/0003786_x-list.js
@@ -0,0 +1,272 @@
+import Component from '@ember/component';
+import { run, scheduleOnce } from '@ember/runloop';
+import { task, timeout } from 'ember-concurrency';
+import ResizableColumns from 'ember-inspector/libs/resizable-columns';
+import LocalStorageService from 'ember-inspector/services/storage/local';
+import { inject as service } from '@ember/service';
+import { readOnly, reads } from '@ember/object/computed';
+
+const CHECK_HTML = '✓';
+
+export default Component.extend({
+ /**
+ * @property classNames
+ * @type {Array}
+ */
+ classNames: ['list'],
+
+ /**
+ * Class to pass to each row in `vertical-collection`.
+ *
+ * @property itemClass
+ * @type {String}
+ * @default ''
+ */
+ itemClass: '',
+
+ /**
+ * Layout service used to listen to changes to the application
+ * layout such as resizing of the main nav or object inspector.
+ *
+ * @property layoutService
+ * @type {Service}
+ */
+ layoutService: service('layout'),
+
+ /**
+ * Indicate the table's header's height in pixels.
+ * Set this to `0` when there's no header.
+ *
+ * @property headerHeight
+ * @type {Number}
+ * @default 31
+ */
+ headerHeight: 31,
+
+ /**
+ * The name of the list. Used for `js-` classes added
+ * to elements of the list. Also used as the default
+ * key for schema caching.
+ *
+ * @property name
+ * @type {String}
+ */
+ name: null,
+
+ /**
+ * Service used for storage. Storage is
+ * needed for caching of widths and visibility of columns.
+ * The default storage service is local storage however we
+ * fall back to memory storage if local storage is disabled (For
+ * example as a security setting in Chrome).
+ *
+ * @property storage
+ * @return {Service}
+ */
+ storage: service(`storage/${LocalStorageService.STORAGE_TYPE_TO_USE}`),
+
+
+ /**
+ * The key used to cache the current schema. Defaults
+ * to the list's name.
+ *
+ * @property storageKey
+ * @type {String}
+ */
+ storageKey: reads('name'),
+
+ /**
+ * The schema that contains the list's columns,
+ * their ids, names, and default visibility.
+ *
+ * @property schema
+ * @type {Object}
+ */
+ schema: null,
+
+ /**
+ * The array of columns including their ids, names,
+ * and widths. This array only contains the currently
+ * visible columns.
+ *
+ * @property columns
+ * @type {Array}
+ */
+ columns: readOnly('resizableColumns.columns'),
+
+ /**
+ * Hook called whenever attributes are updated.
+ * We use this to listen to changes to the schema.
+ * If the schema changes for an existing `x-list` component
+ * (happens when switching model types for example), we need
+ * to rebuild the columns from scratch.
+ *
+ * @method didUpdateAttrs
+ * @param {Object} newAttrs and oldAttrs
+ */
+ didUpdateAttrs() {
+ let oldSchema = this.get('oldSchema');
+ let newSchema = this.get('schema');
+ if (newSchema && newSchema !== oldSchema) {
+ scheduleOnce('actions', this, this.setupColumns);
+ }
+ this.set('oldSchema', newSchema);
+ return this._super(...arguments);
+ },
+
+ /**
+ * The instance responsible for building the `columns`
+ * array. This means that this instance controls
+ * the widths of the columns as well as their visibility.
+ *
+ * @property resizableColumns
+ * @type {ResizableColumn}
+ */
+ resizableColumns: null,
+
+ /**
+ * The minimum width a column can be resized to.
+ * It should be high enough so that the column is still
+ * visible and resizable.
+ *
+ * @property minWidth
+ * @type {Number}
+ * @default 10
+ */
+ minWidth: 10,
+
+ didInsertElement() {
+ scheduleOnce('afterRender', this, this.setupColumns);
+ this.onResize = () => {
+ this.get('debounceColumnWidths').perform();
+ };
+ window.addEventListener(`resize.${this.get('elementId')}`, this.onResize);
+ this.get('layoutService').on('resize', this.onResize);
+ return this._super(...arguments);
+ },
+
+ /**
+ * Setup the context menu which allows the user
+ * to toggle the visibility of each column.
+ *
+ * The context menu opened by right clicking on the table's
+ * header.
+ *
+ * @method setupContextMenu
+ */
+ setupContextMenu() {
+ let menu = this.resizableColumns.getColumnVisibility().reduce((arr, { id, name, visible }) => {
+ let check = `${CHECK_HTML}`;
+ if (!visible) {
+ check = `${check} `;
+ }
+ name = `${check} ${name}`;
+ arr.push({
+ name,
+ title: name,
+ fn: run.bind(this, this.toggleColumnVisibility, id)
+ });
+ return arr;
+ }, []);
+
+ this.showBasicContext = (e) => {
+ basicContext.show(menu, e);
+ };
+
+ const listHeader = this.element.querySelector('.list__header');
+ if (listHeader) {
+ listHeader.addEventListener('contextmenu', this.showBasicContext);
+ }
+ },
+
+ /**
+ * Toggle a column's visibility. This is called
+ * when a user clicks on a specific column in the context
+ * menu. After toggling visibility it destroys the current
+ * context menu and rebuilds it with the updated column data.
+ *
+ * @method toggleColumnVisibility
+ * @param {String} id The column's id
+ */
+ toggleColumnVisibility(id) {
+ this.resizableColumns.toggleVisibility(id);
+ const listHeader = this.element.querySelector('.list__header');
+ if (listHeader) {
+ listHeader.removeEventListener('contextmenu', this.showBasicContext);
+ }
+ this.setupContextMenu();
+ },
+
+ /**
+ * Restartable `ember-concurrency` task called whenever
+ * the table widths need to be recalculated due to some
+ * resizing of the window or application.
+ *
+ * @property debounceColumnWidths
+ * @type {Object} Ember Concurrency task
+ */
+ debounceColumnWidths: task(function* () {
+ yield timeout(100);
+ this.resizableColumns.setTableWidth(this.getTableWidth());
+ }).restartable(),
+
+ /**
+ * Hook called when the component element will be destroyed.
+ * Clean up everything.
+ *
+ * @method willDestroyElement
+ */
+ willDestroyElement() {
+ window.removeEventListener(`.${this.elementId}`, this.onResize);
+ const listHeader = this.element.querySelector('.list__header');
+ if (listHeader) {
+ listHeader.removeEventListener('contextmenu', this.showBasicContext);
+ }
+ this.get('layoutService').off('resize', this.onResize);
+ return this._super(...arguments);
+ },
+
+ /**
+ * Returns the table's width in pixels.
+ *
+ * @method getTableWidth
+ * @return {Number} The width in pixels
+ */
+ getTableWidth() {
+ return this.element.querySelector('.list__table-container').clientWidth;
+ },
+
+ /**
+ * Creates a new `ResizableColumns` instance which
+ * will calculate the columns' width and visibility.
+ *
+ * @method setupColumns
+ */
+ setupColumns() {
+ let resizableColumns = new ResizableColumns({
+ key: this.get('storageKey'),
+ tableWidth: this.getTableWidth(),
+ minWidth: this.get('minWidth'),
+ storage: this.get('storage'),
+ columnSchema: this.get('schema.columns') || []
+ });
+ resizableColumns.build();
+ this.set('resizableColumns', resizableColumns);
+ this.setupContextMenu();
+ },
+
+ actions: {
+ /**
+ * Called whenever a column is resized using the draggable handle.
+ * It is responsible for updating the column info by notifying
+ * `resizableColumns` about the update.
+ *
+ * @method didResize
+ * @param {String} id The column's id
+ * @param {Number} width The new width
+ */
+ didResize(id, width) {
+ this.resizableColumns.updateColumnWidth(id, width);
+ }
+ }
+});
diff --git a/pool/shard000/JavaScript/0003787_ReviewRow.test.js b/pool/shard000/JavaScript/0003787_ReviewRow.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..6cfdd4bc9c0e5e638d1ebf8f9fdd24173b1b5796
--- /dev/null
+++ b/pool/shard000/JavaScript/0003787_ReviewRow.test.js
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2020 Verizon Media
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import React from 'react';
+import { render } from '@testing-library/react';
+import ReviewRow from '../../../components/review/ReviewRow';
+import { colors } from '../../../components/denali/styles';
+
+describe('ReviewRow', () => {
+ it('should render', () => {
+ let details = {
+ memberName: 'user.member',
+ };
+ let domain = 'domain';
+ let role = 'roleName';
+ let color = colors.row;
+ let idx = '50';
+ const { getByTestId } = render(
+
+ );
+ const reviewRow = getByTestId('review-row');
+
+ expect(reviewRow).toMatchSnapshot();
+ });
+});
diff --git a/pool/shard000/JavaScript/0003789_keyboard.js b/pool/shard000/JavaScript/0003789_keyboard.js
new file mode 100644
index 0000000000000000000000000000000000000000..54403e4a6ed73e7349b2317872bed55f48ee43d2
--- /dev/null
+++ b/pool/shard000/JavaScript/0003789_keyboard.js
@@ -0,0 +1,133 @@
+/*
+ Keyboard
+ Keyboard class
+ By Luke Nickerson, 2016
+*/
+(function(){
+ var Keyboard = function(){
+ this.keyDownActions = {};
+ this.keyUpActions = {};
+ this._keyCodeMap = {
+ "9": "TAB",
+
+ "13": "ENTER",
+
+ "27": "ESC",
+
+ "32": "SPACE",
+
+ "37": "LEFT",
+ "38": "UP",
+ "39": "RIGHT",
+ "40": "DOWN",
+
+ "48": "0",
+ "49": "1",
+ "50": "2",
+ "51": "3",
+ "52": "4",
+ "53": "5",
+ "54": "6",
+ "55": "7",
+ "56": "8",
+ "57": "9",
+
+ "65": "a",
+
+ "68": "d",
+ "69": "e",
+
+ "81": "q",
+
+ "83": "s",
+
+ "87": "w",
+ "88": "x",
+
+ "90": "z",
+
+ "112": "F1",
+ "113": "F2",
+ "114": "F3",
+ "115": "F4",
+ "116": "F5",
+ "117": "F6",
+ "118": "F7",
+ "119": "F8",
+ "120": "F9",
+ "121": "F10",
+ "122": "F11",
+ "123": "F12",
+
+ };
+ };
+
+ Keyboard.prototype.getKeyFromKeyCode = function (keyCode) {
+ return this._keyCodeMap[keyCode];
+ };
+
+ Keyboard.prototype._isFunctionKey = function (keyCode) {
+ keyCode = parseInt(keyCode);
+ return (keyCode >= 112 && keyCode <= 123) ? true : false;
+ }
+
+ Keyboard.prototype.tap = function (key) {
+ this._fireAction(key, this.keyDownActions);
+ this._fireAction(key, this.keyUpActions);
+ };
+
+ Keyboard.prototype._fireAction = function (key, keyActions) {
+ var action = this.keyDownActions[key];
+ if (typeof action === 'function') {
+ action(key);
+ return true;
+ } else {
+ console.warn("KB action not found", key);
+ return false;
+ }
+ };
+
+ Keyboard.prototype.setup = function (options) {
+ var kb = this;
+ options = options || {};
+ options.keyDownActions = options.keyDownActions || {};
+ if (options.wasd) {
+ if (typeof options.keyDownActions["w"] !== 'function') {
+ options.keyDownActions["w"] = options.keyDownActions["UP"];
+ }
+ if (typeof options.keyDownActions["a"] !== 'function') {
+ options.keyDownActions["a"] = options.keyDownActions["LEFT"];
+ }
+ if (typeof options.keyDownActions["s"] !== 'function') {
+ options.keyDownActions["s"] = options.keyDownActions["DOWN"];
+ }
+ if (typeof options.keyDownActions["d"] !== 'function') {
+ options.keyDownActions["d"] = options.keyDownActions["RIGHT"];
+ }
+ }
+ kb.keyDownActions = options.keyDownActions;
+ //console.log(kb.keyDownActions);
+ kb.clear();
+
+ $(document).on('keydown', function(e){
+ kb._fireAction(kb.getKeyFromKeyCode(e.which), options.keyDownActions);
+ //console.log(e.which);
+ if (!kb._isFunctionKey(e.which)) {
+ e.preventDefault();
+ }
+ }).on('keyup', function(e){
+ // ***
+ });
+ return kb;
+ };
+
+ Keyboard.prototype.clear = function () {
+ $(document).off('keydown').off('keyup');
+ };
+
+
+
+ if (typeof RocketBoots == "object") {
+ RocketBoots.installComponent("keyboard", "Keyboard", Keyboard);
+ } else window.Keyboard = Keyboard;
+})();
\ No newline at end of file
diff --git a/pool/shard000/JavaScript/0003793_index.js b/pool/shard000/JavaScript/0003793_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..b652090cd51d3a2d5ededb89739f17c5ef9652a7
--- /dev/null
+++ b/pool/shard000/JavaScript/0003793_index.js
@@ -0,0 +1,17 @@
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+import { withRouter } from 'react-router';
+import reducer from './ModuleStreamDetailsReducer';
+import * as moduleStreamDetailsActions from './ModuleStreamDetailsActions';
+import ModuleStreamDetails from './ModuleStreamDetails';
+
+const mapStateToProps = state => ({
+ moduleStreamDetails: state.katello.moduleStreamDetails,
+});
+
+const actions = { ...moduleStreamDetailsActions };
+const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
+
+export const moduleStreamDetails = reducer;
+
+export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ModuleStreamDetails));
diff --git a/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js b/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..cc7d87abac5952069aecb575cc803831a3f63aa4
--- /dev/null
+++ b/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js
@@ -0,0 +1,23 @@
+var JsonTaskRequestTranslator = require("../../../lib/engine/common/json_task_request_translator");
+var TaskRequest = require("../../../lib/engine/common/task_request");
+
+describe("JsonTaskRequestTranslator", function(){
+ beforeEach(function(){
+ this.raw_task_request = JSON.stringify({
+ task_id: "123",
+ context: "foo",
+ locals: "bar",
+ code: "baz"
+ });
+ this.translator = JsonTaskRequestTranslator.create();
+ });
+
+ it("translates a JSON string into a TaskRequest object", function(){
+ var translated_task_request = this.translator.translate(this.raw_task_request);
+ expect(translated_task_request instanceof TaskRequest).toBeTruthy();
+ expect(translated_task_request.getTaskId()).toBe("123");
+ expect(translated_task_request.getContext()).toBe("foo");
+ expect(translated_task_request.getLocals()).toBe("bar");
+ expect(translated_task_request.getCode()).toBe("baz");
+ });
+});
\ No newline at end of file