diff --git a/pool/shard004/JavaScript/0026537_multiline-ternary.js b/pool/shard004/JavaScript/0026537_multiline-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..0c971cc52142eeb3733efcac7a567e99c6affd46 --- /dev/null +++ b/pool/shard004/JavaScript/0026537_multiline-ternary.js @@ -0,0 +1,66 @@ +/** + * @fileoverview Enforce newlines between operands of ternary expressions + * @author Kai Cataldo + */ + +"use strict"; + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "enforce newlines between operands of ternary expressions", + category: "Stylistic Issues", + recommended: false + }, + schema: [] + }, + + create(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tests whether node is preceded by supplied tokens + * @param {ASTNode} node - node to check + * @param {ASTNode} parentNode - parent of node to report + * @returns {void} + * @private + */ + function reportError(node, parentNode) { + context.report({ + node, + message: "Expected newline between {{typeOfError}} of ternary expression.", + data: { + typeOfError: node === parentNode.test ? "test and consequent" : "consequent and alternate" + } + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression(node) { + const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent); + const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate); + + if (areTestAndConsequentOnSameLine) { + reportError(node.test, node); + } + + if (areConsequentAndAlternateOnSameLine) { + reportError(node.consequent, node); + } + } + }; + } +}; diff --git a/pool/shard004/JavaScript/0026540_addfire.js b/pool/shard004/JavaScript/0026540_addfire.js new file mode 100644 index 0000000000000000000000000000000000000000..2d53c80b41ef8ac4986af04e0b139be49718d3ce --- /dev/null +++ b/pool/shard004/JavaScript/0026540_addfire.js @@ -0,0 +1,14 @@ +window.prepareFire = function() { + var fire = new BABYLON.FireMaterial("fire", scene); + fire.diffuseTexture = new BABYLON.Texture("/playground/textures/fire/diffuse.png", scene); + fire.distortionTexture = new BABYLON.Texture("/playground/textures/fire/distortion.png", scene); + fire.opacityTexture = new BABYLON.Texture("/playground/textures/fire/opacity.png", scene); + + registerRangeUI("fire", "speed", 0, 20, function(value) { + fire.speed = value; + }, function() { + return fire.speed; + }); + + return fire; +}; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026544_reset-password.js b/pool/shard004/JavaScript/0026544_reset-password.js new file mode 100644 index 0000000000000000000000000000000000000000..167e848c7ec357b70909947d10dc6e29d570f395 --- /dev/null +++ b/pool/shard004/JavaScript/0026544_reset-password.js @@ -0,0 +1,44 @@ +var keystone = require('keystone'), + User = keystone.list('User'); + +exports = module.exports = function(req, res) { + + var view = new keystone.View(req, res), + locals = res.locals; + + view.on('init', function(next) { + + console.log(req.params.key); + + User.model.findOne().where('resetPasswordKey', req.params.key).exec(function(err, user) { + if (err) return next(err); + if (!user) { + req.flash('error', "Sorry, that reset password key isn't valid."); + return res.redirect('/forgot-password'); + } + locals.found = user; + next(); + }); + + }); + + view.on('post', { action: 'reset-password' }, function(next) { + + if (req.body.password != req.body.password_confirm) { + req.flash('error', 'Please make sure both passwords match.'); + return next(); + } + + locals.found.password = req.body.password; + locals.found.resetPasswordKey = ''; + locals.found.save(function(err) { + if (err) return next(err); + req.flash('success', 'We changed your password, please sign in.'); + res.redirect('/signin'); + }); + + }); + + view.render('reset-password'); + +} diff --git a/pool/shard004/JavaScript/0026545_generator.js b/pool/shard004/JavaScript/0026545_generator.js new file mode 100644 index 0000000000000000000000000000000000000000..54be72f2567349d64a079d1354eaf0c0d71b8793 --- /dev/null +++ b/pool/shard004/JavaScript/0026545_generator.js @@ -0,0 +1,42 @@ +"use strict"; + +import path from "path"; +import uniq from "lodash/uniq"; + +import SiteGenerator from "./generator/index.jsx"; +import locales from "./src/localization"; + +class Generator extends SiteGenerator { + onProcessPath(filePath) { + if (filePath === "/:lang/entry/:name") { + const allEntries = ["test"]; + return allEntries.map((name)=> filePath.replace(":name", name)); + } else { + return super.onProcessPath(filePath); + } + } + matchUrl(url, locale) { + /* eslint class-methods-use-this: 0 */ + return url.replace(":lang", locale); + } + writeFile(url, html, origUrl) { + /* eslint prefer-template: 0 */ + const filePath = origUrl === "/:lang" ? + path.join(url, "index.html") : + `${url}.html`; + this.writer.writeFile(filePath, html); + } +} + +const g = new Generator(); +const urls = Object.keys(locales).reduce( + (urls, locale)=> + g.generate(locale, (url)=> { + if (url === "/404" && locale !== "en") { + return true; + } + }).concat(urls), []); + +const sitemapUrls = uniq(urls).filter((p)=> p !== "/"); + +g.generateSitemap(sitemapUrls, "http://example.com"); diff --git a/pool/shard004/JavaScript/0026548_NodeAttachmentMap.js b/pool/shard004/JavaScript/0026548_NodeAttachmentMap.js new file mode 100644 index 0000000000000000000000000000000000000000..abd4b052fe4f9d853c06c26ef66a2da9ec98ae06 --- /dev/null +++ b/pool/shard004/JavaScript/0026548_NodeAttachmentMap.js @@ -0,0 +1,43 @@ +(function(window) +{ + var Gitana = window.Gitana; + + Gitana.NodeAttachmentMap = Gitana.BinaryAttachmentMap.extend( + /** @lends Gitana.NodeAttachmentMap.prototype */ + { + /** + * @constructs + * @augments Gitana.BinaryAttachmentMap + * + * @class Provides access to node attachments + * + * @param repository + * @param map + */ + constructor: function(persistable, object) + { + this.base(persistable, object); + + this.objectType = function() { return "Gitana.NodeAttachmentMap"; }; + }, + + /** + * @override + */ + clone: function() + { + return new Gitana.NodeAttachmentMap(this.__persistable(), this); + }, + + /** + * @param json + */ + buildObject: function(attachment) + { + return new Gitana.NodeAttachment(this.__persistable(), attachment); + } + + + }); + +})(window); diff --git a/pool/shard004/JavaScript/0026550_aroon.js b/pool/shard004/JavaScript/0026550_aroon.js new file mode 100644 index 0000000000000000000000000000000000000000..959d1af0140667ec68953ec1521963973f01e075 --- /dev/null +++ b/pool/shard004/JavaScript/0026550_aroon.js @@ -0,0 +1,71 @@ +'use strict'; + +module.exports = function(indicatorMixin, accessor_ohlc) { // Injected dependencies + return function() { // Closure function + var p = {}, // Container for private, direct access mixed in variables + period = 20, + overbought = 70, + middle = 0, + oversold = 30; + + function indicator(data) { + return data.map(function(d, i) { + if(i >= (period-1)){ + var max = 0; + var maxi = 0; + var min = 10000; + var mini = 0; + for (var j = 0; j < period; j++) { + if( p.accessor.h(data[i-j]) > max){ + max = p.accessor.h(data[i-j]); + maxi = j; + } + if( p.accessor.l(data[i-j]) < min){ + min = p.accessor.l(data[i-j]); + mini = j; + } + } + var up = ((period-maxi)/period)*100; + var down = ((period-mini)/period)*100; + var oscillator = up - down; + return datum(p.accessor.d(d), up,down, oscillator, middle, overbought, oversold); + } + else return datum(p.accessor.d(d)); + }).filter(function(d) { return d.up; }); + } + + indicator.period = function(_) { + if (!arguments.length) return period; + period = _; + return indicator; + }; + + indicator.overbought = function(_) { + if (!arguments.length) return overbought; + overbought = _; + return indicator; + }; + + indicator.middle = function(_) { + if (!arguments.length) return middle; + middle = _; + return indicator; + }; + + indicator.oversold = function(_) { + if (!arguments.length) return oversold; + oversold = _; + return indicator; + }; + + // Mixin 'superclass' methods and variables + indicatorMixin(indicator, p).accessor(accessor_ohlc()); + + return indicator; + }; +}; + +function datum(date, up,down,oscillator, middle, overbought, oversold) { + if(up) return { date: date, up: up,down:down,oscillator:oscillator, middle: middle, overbought: overbought, oversold: oversold }; + else return { date: date, up: null,down:null,oscillator:null, middle: null, overbought: null, oversold: null }; +} diff --git a/pool/shard004/JavaScript/0026552_lodashModule.js b/pool/shard004/JavaScript/0026552_lodashModule.js new file mode 100644 index 0000000000000000000000000000000000000000..72986243e4a60555d73833588e2d07050800c630 --- /dev/null +++ b/pool/shard004/JavaScript/0026552_lodashModule.js @@ -0,0 +1,32 @@ +var _ = require('lodash'); +var lodashtemplate = require('html!./lodashdemo.html'); +var lodashModule = module.exports = function(){ + this.init(); +}; + +var p = lodashModule.prototype; + +p.init=function(){ + console.log('goto render'); + this.render(); +}; + +p.render = function(){ + if(_.isFunction(this.beforeRender)) this.beforeRender(); + if(_.isFunction(this.afterRender)) this.afterRender(); +}; + +p.beforeRender=function(){ + console.log('goto templateRender'); + this.templateRender(); +}; +p.templateRender = function(){ + var compiled = _.template(lodashtemplate); + //$('div').append(compiled({ + // test:111 + //})); +} + +p.afterRender=function(){ + console.log('render end'); +}; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026555_routes.js b/pool/shard004/JavaScript/0026555_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..ef3edbaccea207d6112710acff45f6cd8bd0fb41 --- /dev/null +++ b/pool/shard004/JavaScript/0026555_routes.js @@ -0,0 +1,30 @@ +'use strict'; + +var api = require('./controllers/api'), + index = require('./controllers'); + +/** + * Application routes + */ +module.exports = function (app) { + + // Server API Routes + app.route('/api/tech') + .get(api.technologies); + + app.route('/api/developers') + .get(api.developers); + + + // All undefined api routes should return a 404 + app.route('/api/*') + .get(function (req, res) { + res.send(404); + }); + + // All other routes to use Angular routing in app/scripts/app.js + app.route('/partials/*') + .get(index.partials); + app.route('/*') + .get(index.index); +}; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026556_chkInternalIP.js b/pool/shard004/JavaScript/0026556_chkInternalIP.js new file mode 100644 index 0000000000000000000000000000000000000000..97f8a7047c7405f0a5128cb942756935de135c31 --- /dev/null +++ b/pool/shard004/JavaScript/0026556_chkInternalIP.js @@ -0,0 +1,17 @@ +Meteor.methods({ + chkInternalIP(username) { + var access = RocketChat.settings.get('allowexternal'); + var departmentsToAssign = access.split(/\s*,\s*/); + var IsAllAccess = departmentsToAssign.indexOf('*') > -1; + var IsUserAccess = departmentsToAssign.indexOf(username) > -1; + if (IsAllAccess || IsUserAccess) { + console.log('default access'); + return true; + } else + console.log(username + ' - ' + this.connection.httpHeaders['x-forwarded-for']); + var Iplist = this.connection.httpHeaders['x-forwarded-for'].split(","); + var Ip = Iplist[0]; + var url = RocketChat.settings.get('COMMAPI') + "/ChatService.svc/IsInternalIP/" + Ip; + return HTTP.call("GET", url, { headers: { "accept": "application/json" } }).data; + } +}); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026558_photo.js b/pool/shard004/JavaScript/0026558_photo.js new file mode 100644 index 0000000000000000000000000000000000000000..c72724718f8192f72501e6a649afb8b5ce15b497 --- /dev/null +++ b/pool/shard004/JavaScript/0026558_photo.js @@ -0,0 +1,80 @@ +// Generated by CoffeeScript 1.9.3 +var Photo, app, doPipe, downloader; + +Photo = require('../models/photo'); + +downloader = require('../helpers/downloader'); + +app = null; + +module.exports.setApp = function(ref) { + return app = ref; +}; + +module.exports.fetch = function(req, res, next, id) { + if (id.indexOf('.jpg') > 0) { + id = id.substring(0, id.length - 4); + } + return Photo.find(id, (function(_this) { + return function(err, photo) { + if (err) { + return next(err); + } else if (!photo) { + return next(NotFound("Photo " + id)); + } else { + req.photo = photo; + return next(); + } + }; + })(this)); +}; + +doPipe = function(req, which, download, res, next) { + var binaryPath, disposition, onError, ref1, ref2, request; + if (download) { + disposition = 'attachment; filename=' + req.photo.title; + res.setHeader('Content-disposition', disposition); + } + onError = function(err) { + if (err) { + return next(err); + } + }; + if ((ref1 = req.photo._attachments) != null ? ref1[which] : void 0) { + binaryPath = "/data/" + req.photo.id + "/attachments/" + which; + return request = downloader.download(binaryPath, function(stream) { + if (stream.statusCode === 200) { + res.on('close', function() { + return request.abort(); + }); + return stream.pipe(res); + } else { + return res.sendfile('./server/img/error.gif'); + } + }); + } else if ((ref2 = req.photo.binary) != null ? ref2[which] : void 0) { + binaryPath = "/data/" + req.photo.id + "/binaries/" + which; + return request = downloader.download(binaryPath, function(stream) { + if (stream.statusCode === 200) { + res.on('close', function() { + return request.abort(); + }); + return stream.pipe(res); + } else { + return res.sendfile('./server/img/error.gif'); + } + }); + } else { + return res.sendfile('./server/img/error.gif'); + } +}; + +module.exports.thumb = function(req, res, next) { + return doPipe(req, 'thumb', false, res, next); +}; + +module.exports.raw = function(req, res, next) { + var ref1, ref2, ref3, which; + which = ((ref1 = req.photo._attachments) != null ? ref1.raw : void 0) ? 'raw' : ((ref2 = req.photo.binary) != null ? ref2.raw : void 0) ? 'raw' : ((ref3 = req.photo.binary) != null ? ref3.file : void 0) ? 'file' : 'file'; + return doPipe(req, which, true, res, next); +}; diff --git a/pool/shard004/JavaScript/0026560_load-map.js b/pool/shard004/JavaScript/0026560_load-map.js new file mode 100644 index 0000000000000000000000000000000000000000..84a60b5697acab560fb5053ffac5930a5c10736b --- /dev/null +++ b/pool/shard004/JavaScript/0026560_load-map.js @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var map; + +function loadLeafletMap() { + + var deviceLocationID = "#device-location", + locations = $(deviceLocationID).data("locations"), + location_lat = $(deviceLocationID).data("lat"), + location_long = $(deviceLocationID).data("long"), + container = "device-location", + zoomLevel = 13, + tileSet = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", + attribution = "© OpenStreetMap contributors"; + + if (location_long && location_lat) { + + map = L.map(container).setView([location_lat, location_long], zoomLevel); + L.tileLayer(tileSet, {attribution: attribution}).addTo(map); + + var m = L.marker([location_lat, location_long], {"opacity": 0.70}).addTo(map).bindPopup("Your device is here"); + m.on('mouseover', function (e) { + this.openPopup(); + }); + m.on('mouseout', function (e) { + this.closePopup(); + }); + $("#map-error").hide(); + $("#device-location").show(); + setTimeout(function(){ map.invalidateSize()}, 400); + } else { + $("#device-location").hide(); + $("#map-error").show(); + } +} + +$(".media.tab-responsive [data-toggle=tab]").on("shown.bs.tab", function (e) { + var activeTabPane = $(e.target).attr("href"); + var activeListGroupItem = $(".media .list-group-item.active"); + + $(activeTabPane).removeClass("visible-xs-block"); + $(activeTabPane).siblings().not(".arrow-left").addClass("visible-xs-block"); + positionArrow(activeListGroupItem); +}); + +$(".media.tab-responsive .tab-content").on("shown.bs.collapse", function (e) { + var thisParent = $(e.target).parent(); + var activeTabPaneCaret = thisParent.find('.caret-updown'); + var activeTabPaneCaretSiblings = thisParent.siblings().find('.caret-updown'); + + activeTabPaneCaret.removeClass("fw-up").addClass("fw-down"); + activeTabPaneCaretSiblings.removeClass("fw-down").addClass("fw-up"); +}); + + +$('.media.tab-responsive a[data-toggle="collapse"]').on('click',function(){ + var clickedPanel = $(this).attr('href'); + + if($(clickedPanel).hasClass('in')){ + $(clickedPanel).collapse('hide'); + }else{ + $(clickedPanel).collapse('show'); + } +}); + +$(document).ready(function () { + $(".location_tab").on("click", function () { + console.log('here'); + loadLeafletMap(); + }); +}); diff --git a/pool/shard004/JavaScript/0026561_ng.directive_ngInclude.jqlite_test.js b/pool/shard004/JavaScript/0026561_ng.directive_ngInclude.jqlite_test.js new file mode 100644 index 0000000000000000000000000000000000000000..d49dc3f1ae6fe9e20783729f342d3661d0ba431d --- /dev/null +++ b/pool/shard004/JavaScript/0026561_ng.directive_ngInclude.jqlite_test.js @@ -0,0 +1,34 @@ +describe("api/ng.directive:ngInclude", function() { + beforeEach(function() { + browser.get("index-nocache.html#!/api/ng.directive:ngInclude"); + }); + +var templateSelect = element(by.model('template')); +var includeElem = element(by.css('.doc-example-live [ng-include]')); + +it('should load template1.html', function() { + expect(includeElem.getText()).toMatch(/Content of template1.html/); +}); + +it('should load template2.html', function() { + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + // See https://github.com/angular/protractor/issues/480 + return; + } + templateSelect.click(); + templateSelect.element.all(by.css('option')).get(2).click(); + expect(includeElem.getText()).toMatch(/Content of template2.html/); +}); + +it('should change to blank', function() { + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + return; + } + templateSelect.click(); + templateSelect.element.all(by.css('option')).get(0).click(); + expect(includeElem.isPresent()).toBe(false); +}); + +}); diff --git a/pool/shard004/JavaScript/0026567_session.js b/pool/shard004/JavaScript/0026567_session.js new file mode 100644 index 0000000000000000000000000000000000000000..28fbd15d410dd4b63fb8a6610ede57d608919ac5 --- /dev/null +++ b/pool/shard004/JavaScript/0026567_session.js @@ -0,0 +1,51 @@ +(function() { + 'use strict'; + + function session($state, $timeout, auth, fbutil) { + var sessionData = {}; + + init(); + return sessionData; + + function init(){ + auth.$onAuth(onAuth); + } + + function onAuth(authObj){ + if(authObj){ + var profilePath = ['profiles', authObj.uid]; + var prefPath = ['preferences', authObj.uid]; + var channelPath = ['preferences', authObj.uid, 'channels']; + + sessionData.user = fbutil.syncObject(profilePath); + sessionData.prefs = fbutil.syncObject(prefPath); + sessionData.channels = fbutil.syncArray(channelPath); + + var channelRef = fbutil.ref(channelPath); + + channelRef.once('value', function onDataInit(){ + channelRef.initialized = true; + }); + + channelRef.on('child_removed', function onChannelLeave(snapshot){ + if(channelRef.initialized !== true){ + return; + } + + $state.transitionTo('root.home.channel', {channel: 'general'}); + }); + + sessionData.uid = authObj.uid; + } else { + try { + sessionData.user.$destroy(); + } catch(e){} + sessionData.user = null; + $state.transitionTo('login'); + } + } + } + + angular.module('common.firebase') + .factory('session', session); +})(); diff --git a/pool/shard004/JavaScript/0026568_DesignerNav.js b/pool/shard004/JavaScript/0026568_DesignerNav.js new file mode 100644 index 0000000000000000000000000000000000000000..32c956b0b6964246bb20d23c6cb687a75fd578a3 --- /dev/null +++ b/pool/shard004/JavaScript/0026568_DesignerNav.js @@ -0,0 +1,58 @@ +/** + * Created by dllo on 17/8/29. + */ +import React, {Component} from 'react' +import '../../assets/styles/miss/Miss.styl' +const logoArr = ['子类:', '网页设计App', '设计移动网页/H5 页面设计', '活动页面设计', 'icon设计', 'banner 设计', '其它 UI 设计'] +class DesignerNav extends Component { + constructor(props) { + super(props) + this.state = { + array: [] + } + } + clickLogo = () => { + console.log(123) + var navChild = document.getElementsByClassName('wxj_nav1')[0] + navChild.innerHTML = '' + for (let i = 0; i < logoArr.length; i++) { + var aBiaoQian = document.createElement('a') + navChild.appendChild(aBiaoQian) + var liBiaoQian = document.createElement('li') + liBiaoQian.innerHTML = logoArr[i] + aBiaoQian.appendChild(liBiaoQian) + } + } + render () { + return ( +
' + + '' + + '{{site.siteName}}: ' + + '' + + '{{site.count || "N/A"}} Running Jobs' + + '' + + '
' + + 'This is not a P
"); + assert.include(out.get("compiled"), "This is not a P"); + done(); + } + }); + }); + + it("Does an include with a HL filter", function(done) { + + var site = crossbow.builder({ + config: { + base: "test/fixtures" + } + }); + + var item = site.add({key: "src/docs/index.html", content: "{{inc src='_includes/button.html' filter='hl'}}"}); + + site.freeze(); + + site.compile({ + item: item, + cb: function (err, out) { + assert.include(out.get("compiled"), '<'); // jshint ignore:line
+ done();
+ }
+ });
+ });
+ it("includes with correct context", function (done) {
+
+ var site = crossbow.builder({
+ config: {
+ base: "test/fixtures"
+ },
+ data: {
+ buttons: ["one", "two"],
+ site: {
+ title: "Crossbow"
+ }
+ }
+ });
+
+ var item = site.add({key: "src/docs/index.html", content: ":{{#each buttons}}{{inc src='context.html' title='Param title'}}{{/each}}:"});
+
+ site.freeze();
+
+ site.compile({
+ item: item,
+ cb: function (err, out) {
+ var compiled = out.get("compiled");
+ assert.include(compiled, "Site Title: Crossbow");
+ assert.include(compiled, "Page Url: /src/docs/index.html");
+ assert.include(compiled, "Param Title: Param title");
+ done();
+ }
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026654_adff06c4cdf63693395a023ef358c3d9b77cceb1.js b/pool/shard004/JavaScript/0026654_adff06c4cdf63693395a023ef358c3d9b77cceb1.js
new file mode 100644
index 0000000000000000000000000000000000000000..be2ee917f94af2bc3e6bac38deaaae6245f91ce0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026654_adff06c4cdf63693395a023ef358c3d9b77cceb1.js
@@ -0,0 +1,93 @@
+"use strict";
+var autoprefixer = require('autoprefixer');
+var cssnano = require('cssnano');
+var gulp = require('gulp');
+var gulpLoadPlugins = require('gulp-load-plugins');
+var merge = require('merge-stream');
+var util = require('gulp-util');
+var path_1 = require('path');
+var config_1 = require('../../config');
+var plugins = gulpLoadPlugins();
+var cleanCss = require('gulp-clean-css');
+var gulpConcatCssConfig = config_1.default.getPluginConfig('gulp-concat-css');
+var processors = [
+ autoprefixer({
+ browsers: config_1.default.BROWSER_LIST
+ })
+];
+var reportPostCssError = function (e) { return util.log(util.colors.red(e.message)); };
+var isProd = config_1.default.ENV === 'prod';
+if (isProd) {
+ processors.push(cssnano({
+ discardComments: { removeAll: true },
+ discardUnused: false,
+ zindex: false,
+ reduceIdents: false
+ }));
+}
+function prepareTemplates() {
+ return gulp.src(path_1.join(config_1.default.APP_SRC, '**', '*.html'))
+ .pipe(gulp.dest(config_1.default.TMP_DIR));
+}
+function processComponentStylesheets() {
+ return config_1.default.ENABLE_SCSS ? processComponentScss() : processComponentCss();
+}
+function processComponentScss() {
+ return gulp.src(path_1.join(config_1.default.APP_SRC, '**', '*.scss'))
+ .pipe(isProd ? plugins.cached('process-component-scss') : plugins.util.noop())
+ .pipe(isProd ? plugins.progeny() : plugins.util.noop())
+ .pipe(plugins.sourcemaps.init())
+ .pipe(plugins.sass(config_1.default.getPluginConfig('gulp-sass')).on('error', plugins.sass.logError))
+ .pipe(plugins.postcss(processors))
+ .on('error', reportPostCssError)
+ .pipe(plugins.sourcemaps.write(isProd ? '.' : ''))
+ .pipe(gulp.dest(isProd ? config_1.default.TMP_DIR : config_1.default.APP_DEST));
+}
+function processComponentCss() {
+ return gulp.src([
+ path_1.join(config_1.default.APP_SRC, '**', '*.css'),
+ '!' + path_1.join(config_1.default.APP_SRC, 'assets', '**', '*.css')
+ ])
+ .pipe(isProd ? plugins.cached('process-component-css') : plugins.util.noop())
+ .pipe(plugins.postcss(processors))
+ .on('error', reportPostCssError)
+ .pipe(gulp.dest(isProd ? config_1.default.TMP_DIR : config_1.default.APP_DEST));
+}
+function processExternalStylesheets() {
+ return config_1.default.ENABLE_SCSS ? processAllExternalStylesheets() : processExternalCss();
+}
+function processAllExternalStylesheets() {
+ return merge(getExternalCssStream(), getExternalScssStream())
+ .pipe(isProd ? plugins.concatCss(gulpConcatCssConfig.targetFile, gulpConcatCssConfig.options) : plugins.util.noop())
+ .pipe(plugins.postcss(processors))
+ .on('error', reportPostCssError)
+ .pipe(isProd ? cleanCss() : plugins.util.noop())
+ .pipe(gulp.dest(config_1.default.CSS_DEST));
+}
+function getExternalCssStream() {
+ return gulp.src(getExternalCss())
+ .pipe(isProd ? plugins.cached('process-external-css') : plugins.util.noop());
+}
+function getExternalCss() {
+ return config_1.default.DEPENDENCIES.filter(function (dep) { return /\.css$/.test(dep.src); }).map(function (dep) { return dep.src; });
+}
+function getExternalScssStream() {
+ return gulp.src(getExternalScss())
+ .pipe(isProd ? plugins.cached('process-external-scss') : plugins.util.noop())
+ .pipe(isProd ? plugins.progeny() : plugins.util.noop())
+ .pipe(plugins.sass(config_1.default.getPluginConfig('gulp-sass')).on('error', plugins.sass.logError));
+}
+function getExternalScss() {
+ return config_1.default.DEPENDENCIES.filter(function (dep) { return /\.scss$/.test(dep.src); }).map(function (dep) { return dep.src; })
+ .concat([path_1.join(config_1.default.CSS_SRC, '**', '*.scss')]);
+}
+function processExternalCss() {
+ return getExternalCssStream()
+ .pipe(plugins.postcss(processors))
+ .pipe(isProd ? plugins.concatCss(gulpConcatCssConfig.targetFile, gulpConcatCssConfig.options) : plugins.util.noop())
+ .on('error', reportPostCssError)
+ .pipe(isProd ? cleanCss() : plugins.util.noop())
+ .pipe(gulp.dest(config_1.default.CSS_DEST));
+}
+module.exports = function () { return merge(processComponentStylesheets(), prepareTemplates(), processExternalStylesheets()); };
+//# sourceMappingURL=/var/www/html/s3b4a2/ts-node/d945a700a6de3ebc7d7e631a73475997a3f6f55f/adff06c4cdf63693395a023ef358c3d9b77cceb1.js.map
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026656_source-map.js b/pool/shard004/JavaScript/0026656_source-map.js
new file mode 100644
index 0000000000000000000000000000000000000000..c2055cbfbac53d14a3fed3bcbe4b416bee708b61
--- /dev/null
+++ b/pool/shard004/JavaScript/0026656_source-map.js
@@ -0,0 +1,88 @@
+"use strict";
+
+var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
+
+var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
+
+var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
+
+exports.__esModule = true;
+
+var _sourceMap = require("source-map");
+
+var _sourceMap2 = _interopRequireDefault(_sourceMap);
+
+var _babelTypes = require("babel-types");
+
+var t = _interopRequireWildcard(_babelTypes);
+
+/**
+ * Build a sourcemap.
+ */
+
+var SourceMap = (function () {
+ function SourceMap(position, opts, code) {
+ _classCallCheck(this, SourceMap);
+
+ this.position = position;
+ this.opts = opts;
+
+ if (opts.sourceMaps) {
+ this.map = new _sourceMap2["default"].SourceMapGenerator({
+ file: opts.sourceMapTarget,
+ sourceRoot: opts.sourceRoot
+ });
+
+ this.map.setSourceContent(opts.sourceFileName, code);
+ } else {
+ this.map = null;
+ }
+ }
+
+ /**
+ * Get the sourcemap.
+ */
+
+ SourceMap.prototype.get = function get() {
+ var map = this.map;
+ if (map) {
+ return map.toJSON();
+ } else {
+ return map;
+ }
+ };
+
+ /**
+ * Mark a node's generated position, and add it to the sourcemap.
+ */
+
+ SourceMap.prototype.mark = function mark(node, type) {
+ var loc = node.loc;
+ if (!loc) return; // no location info
+
+ var map = this.map;
+ if (!map) return; // no source map
+
+ if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
+
+ var position = this.position;
+
+ var generated = {
+ line: position.line,
+ column: position.column
+ };
+
+ var original = loc[type];
+
+ map.addMapping({
+ source: this.opts.sourceFileName,
+ generated: generated,
+ original: original
+ });
+ };
+
+ return SourceMap;
+})();
+
+exports["default"] = SourceMap;
+module.exports = exports["default"];
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026659_css-toggle.js b/pool/shard004/JavaScript/0026659_css-toggle.js
new file mode 100644
index 0000000000000000000000000000000000000000..b92fa8bbdcb467f050babfbf7f309a5000c84c64
--- /dev/null
+++ b/pool/shard004/JavaScript/0026659_css-toggle.js
@@ -0,0 +1,27 @@
+(function () {
+ 'use strict';
+ describe('Testing css-toggle', function () {
+ var constants;
+ beforeEach(function () {
+ module('Tombola.NoughtAndCrosses.cssSelection');
+ inject(function ($injector) {
+ constants = $injector.get('cssToggle');
+ });
+ });
+
+ it('Ensures the default css is main.css', function () {
+ constants.cssStyle.should.equal('main.css');
+ });
+
+ it('Ensures that toggling the css will result in altSkin.css', function () {
+ constants.toggleCss();
+ constants.cssStyle.should.equal('altSkin.css');
+ });
+
+ it('Ensures that toggling two times will put the css back to main.css', function () {
+ constants.toggleCss();
+ constants.toggleCss();
+ constants.cssStyle.should.equal('main.css');
+ });
+ });
+})();
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026660_searchService.js b/pool/shard004/JavaScript/0026660_searchService.js
new file mode 100644
index 0000000000000000000000000000000000000000..02a3e3f3909628fb53c5cc6da5fa93fb5bde1e9e
--- /dev/null
+++ b/pool/shard004/JavaScript/0026660_searchService.js
@@ -0,0 +1,119 @@
+'use strict';
+(function () {
+ var module = angular.module('tink.gis');
+ var service = function (ResultsData, map) {
+ var _service = {};
+ _service.DeleteFeature = function (feature) {
+ var featureOfArray = ResultsData.JsonFeatures.find(x => x.layerName == feature.layerName && x.id == feature.id);
+ var featureIndex = ResultsData.JsonFeatures.indexOf(featureOfArray);
+ if (featureIndex > -1) {
+ if (featureOfArray.mapItem) {
+ map.removeLayer(featureOfArray.mapItem);
+ }
+ ResultsData.JsonFeatures.splice(featureIndex, 1);
+ }
+ };
+ _service.DeleteFeatureGroup = function (featureGroupName) {
+ let toDelFeatures = [];
+ ResultsData.JsonFeatures.forEach(function (feature) {
+ if (feature.layerName === featureGroupName) {
+ toDelFeatures.push(feature);
+ }
+ });
+ toDelFeatures.forEach(feat => {
+ _service.DeleteFeature(feat);
+ });
+
+ };
+ _service.ExportToCSV = function () {
+ var csvContent = "", dataString = "", layName = "";
+ csvContent += 'sep=;\n';
+ csvContent += 'Laag;\n';
+ _.sortBy(ResultsData.JsonFeatures, x => x.layerName).forEach(function (feature, index) {
+ if (layName !== feature.layerName) {
+ layName = feature.layerName.replace(';', ',');
+ var tmparr = [];
+ for (var name in feature.properties) {
+ tmparr.push(name.replace(';', ','));
+ }
+ //adding geometry fields
+ tmparr.push("TYPE");
+ tmparr.push("Geometry");
+ var layfirstline = tmparr.join(";");
+
+ csvContent += layName + ";" + layfirstline + '\n';
+ }
+ var infoArray = _.values(feature.properties);
+ //adding geometry field values
+ infoArray.push(feature.geometry.type);
+ infoArray.push(feature.geometry.coordinates);
+ infoArray.unshift(layName);
+ dataString = infoArray.join(";");
+ console.log(dataString);
+ // csvContent += dataString + "\n";
+ csvContent += index < ResultsData.JsonFeatures.length ? dataString + '\n' : dataString;
+
+ });
+ var a = document.createElement('a');
+ a.href = 'data:attachment/csv,' + escape(csvContent);
+ a.target = '_blank';
+ a.download = 'exportsik.csv';
+
+ document.body.appendChild(a);
+ a.click();
+ };
+ _service.ExportOneToCSV = function (result) {
+ var props = Object.getOwnPropertyNames(result.properties).map(k => ({ key: k, value: result.properties[k] }));
+ var geo = Object.getOwnPropertyNames(result.geometry).map(k => ({ key: k, value: result.geometry[k] }));
+ //Pushing both seperately
+ props.push(geo[0]);
+ props.push(geo[1]);
+ var csvContent = "", dataString = "", layName = "";
+ csvContent += 'sep=;\n'
+ csvContent += 'Laag;' + result.layerName + '\n';
+ props.forEach(function (prop) {
+ if (prop.key) {
+ prop.key = prop.key.toString().replace(';', ',')
+ }
+ if (prop.value) {
+ prop.value = prop.value.toString().replace(';', ',')
+ }
+ csvContent += prop.key + ';' + prop.value + '\n';
+ })
+ var a = document.createElement('a');
+ a.href = 'data:attachment/csv,' + escape(csvContent);
+ a.target = '_blank';
+ a.download = 'exportsik.csv';
+
+ document.body.appendChild(a);
+ a.click();
+ }
+ _service.GetNextResult = function () {
+ var index = ResultsData.JsonFeatures.indexOf(ResultsData.SelectedFeature);
+ var layerName = ResultsData.SelectedFeature.layerName;
+ if (index < ResultsData.JsonFeatures.length - 1) { // check for nextResult exists
+ var nextItem = ResultsData.JsonFeatures[index + 1];
+ if (nextItem.layerName === layerName) {
+ return nextItem;
+ }
+ }
+ return null;
+
+ };
+ _service.GetPrevResult = function () {
+ var index = ResultsData.JsonFeatures.indexOf(ResultsData.SelectedFeature);
+ var layerName = ResultsData.SelectedFeature.layerName;
+ if (index > 0) { // check or prevResult exists
+ var prevItem = ResultsData.JsonFeatures[index - 1];
+ if (prevItem.layerName === layerName) {
+ return prevItem;
+ }
+ }
+ return null;
+ };
+
+ return _service;
+ };
+ module.factory("SearchService", service);
+})();
+
diff --git a/pool/shard004/JavaScript/0026662_theme-filters.js b/pool/shard004/JavaScript/0026662_theme-filters.js
new file mode 100644
index 0000000000000000000000000000000000000000..e6a55c629be7e864442149f55c181bc8152d1e32
--- /dev/null
+++ b/pool/shard004/JavaScript/0026662_theme-filters.js
@@ -0,0 +1,84 @@
+/**
+ * Tests for theme-filters.js
+ */
+
+/**
+ * External dependencies
+ */
+import { assert } from 'chai';
+
+/**
+ * Internal dependencies
+ */
+import {
+ getFilter,
+ getSortedFilterTerms,
+ stripFilters,
+ sortFilterTerms,
+} from '../theme-filters.js';
+
+describe( 'theme-filters', () => {
+ describe( 'getFilter', () => {
+ it( 'should return taxonomy:term filter given the term', () => {
+ assert.equal( getFilter( 'pink' ), 'color:pink' );
+ assert.equal( getFilter( 'real-estate' ), 'subject:real-estate' );
+ } );
+
+ it( 'should return empty string given an invalid term', () => {
+ assert.equal( getFilter( '' ), '' );
+ assert.equal( getFilter( ' ' ), '' );
+ assert.equal( getFilter( ' pink' ), '' );
+ assert.equal( getFilter( 'pink ' ), '' );
+ assert.equal( getFilter( 'ponk' ), '' );
+ } );
+ } );
+
+ describe( 'sortFilterTerms', () => {
+ it( 'should alpha sort by taxonomy:term', () => {
+ const sorted = sortFilterTerms(
+ [ 'post-slider', 'blue', 'yellow' ]
+ );
+ // alpha-sort following strings:
+ // 'feature:post-slider'
+ // 'color:blue'
+ // 'color:yellow'
+ assert.deepEqual( sorted, [ 'blue', 'yellow', 'post-slider' ] );
+ } );
+
+ it( 'should strip invalid terms', () => {
+ const sorted = sortFilterTerms(
+ [ 'yellow', 'yaya', 'blue' ]
+ );
+ assert.deepEqual( sorted, [ 'blue', 'yellow' ] );
+ } );
+ } );
+
+ describe( 'getSortedFilterTerms', () => {
+ it( 'should return terms from a mixed input string', () => {
+ const terms = getSortedFilterTerms( 'blah rah color:blue yah feature: post-slider blah' );
+ assert.equal( terms, 'blue,post-slider' );
+ } );
+
+ it( 'should ignore invalid filters', () => {
+ const terms = getSortedFilterTerms( 'color:lazer-puce subject:business' );
+ assert.equal( terms, 'business' );
+ } );
+
+ it( 'should return empty string if no valid filters', () => {
+ const terms = getSortedFilterTerms( 'blah color:lazer-puce' );
+ assert.equal( terms, '' );
+ } );
+ } );
+
+ describe( 'stripFilters', () => {
+ it( 'should strip filters from a mixed input string', () => {
+ const remaining = stripFilters( 'blah color:blue yah' );
+ assert.equal( remaining, 'blah yah' );
+ } );
+
+ it( 'should still strip invalid filters', () => {
+ const remaining = stripFilters( 'color:blue twenty color:lazer-puce' );
+ assert.equal( remaining, 'twenty' );
+ } );
+ } );
+} );
diff --git a/pool/shard004/JavaScript/0026666_boardFactory.js b/pool/shard004/JavaScript/0026666_boardFactory.js
new file mode 100644
index 0000000000000000000000000000000000000000..c6e5b850daff1dfab012fec1ae0fdaa13c0376bc
--- /dev/null
+++ b/pool/shard004/JavaScript/0026666_boardFactory.js
@@ -0,0 +1,85 @@
+angular.module('OpenEXP')
+ .factory('boardFactory', () => {
+
+ // requirements
+ const OpenBCIBoard = require('openbci-sdk');
+ const ourBoard = new OpenBCIBoard.OpenBCIBoard();
+ // var fs = require('fs')
+ // var wstream = fs.createWriteStream('triggerTest_500samples_jitter.txt');
+
+ // return a promise to listen devices
+ var listDevices = () => {
+ return new Promise((res,rej) => {
+ ourBoard.listPorts().then((value) => {
+ res(value)
+ }).catch((err) => {
+ console.log("error!")
+ })
+ })
+ };
+
+ // auto-connect to the board and return an array if the board isn't found
+ var tryAutoConnect = () => {
+ return new Promise((res, rej) => {
+ ourBoard.autoFindOpenBCIBoard().then((value) => {
+ if(Array.isArray(value)) {
+ /**Unable to auto find OpenBCI board*/
+ res(value);
+ console.log("Board not auto-detected. Returning list of ports.")
+ } else {
+ console.log("Auto-detected board! Connecting...")
+ res(connect(value))
+ }
+ }).catch((err) => {
+ console.log("error!")
+ })
+ })
+ };
+
+ // initialize storage object
+ var storage = {};
+
+ // connect to the board and start streaming if no errors
+ var connect = (portName) => {
+ return new Promise((res, rej) => {
+ ourBoard.connect(portName)
+ .then(() => {
+ ourBoard.on('ready', () => {
+ ourBoard.streamStart();
+ console.log('Connected!')
+ counter = 0;
+ ourBoard.on('sample', (sample) => {
+ // wstream.write(sample.auxData[0] + ',' + sample.auxData[2] + '\n');
+ // console.log(sample.channelData[0] + '\n')
+ storage[counter] = sample;
+ counter+=1;
+ })
+ })
+ }).catch((err) => {
+ console.log("error!")
+ })
+ })
+ };
+
+ // each time there is a change of type add, log it
+ var observer = (changes) => {
+ changes.forEach(change => {
+ if(change.type === "add") console.log(change)
+ })
+ };
+
+ // set up functions to toggle the observables on/off
+ var publish = () => Object.observe(storage, observer);
+ var unpublish = () => Object.unobserve(storage, observer);
+
+ // return these objects and functions
+ return {
+ board: ourBoard,
+ tryAutoConnect: tryAutoConnect,
+ listDevices: listDevices,
+ connect: connect,
+ publish: publish,
+ unpublish: unpublish
+ }
+
+});
diff --git a/pool/shard004/JavaScript/0026670_Comment.js b/pool/shard004/JavaScript/0026670_Comment.js
new file mode 100644
index 0000000000000000000000000000000000000000..6c9fdba70d52001a8b3e0796b7859937f5cc8cc8
--- /dev/null
+++ b/pool/shard004/JavaScript/0026670_Comment.js
@@ -0,0 +1,23 @@
+import React, { Component } from 'react'
+import Remarkable from 'remarkable'
+
+class Comment extends Component {
+
+ rawMarkup () {
+ const md = new Remarkable()
+ const rawMarkup = md.render(this.props.children.toString())
+ return { __html: rawMarkup }
+ }
+
+ render() {
+ return (
+
+
+ {this.props.author}
+
+
+
+ )
+ }
+}
+export default Comment
diff --git a/pool/shard004/JavaScript/0026673_video.js b/pool/shard004/JavaScript/0026673_video.js
new file mode 100644
index 0000000000000000000000000000000000000000..f6b0a6165f0599179963d5a6949671b1396a70a3
--- /dev/null
+++ b/pool/shard004/JavaScript/0026673_video.js
@@ -0,0 +1,20 @@
+Video = {};
+Video.view = Ti.UI.createView();
+Video.videoObject = null;
+
+Video.init = function()
+{
+ Video.videoObject = Titanium.Media.createVideoPlayer({
+ contentURL:'movie.mov',
+ backgroundColor:'#111',
+ movieControlMode:Titanium.Media.VIDEO_CONTROL_DEFAULT,
+ scalingMode:Titanium.Media.VIDEO_SCALING_MODE_FILL,
+ top:100,
+ movieControlStyle:Titanium.Media.VIDEO_CONTROL_EMBEDDED,
+ height:300,
+ width:400,
+ autoplay:false
+ });
+
+ Video.view.add(Video.videoObject);
+};
diff --git a/pool/shard004/JavaScript/0026675_gist-file-test.js b/pool/shard004/JavaScript/0026675_gist-file-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..b3430a692f2cc476915e7b4d4f921134477ef722
--- /dev/null
+++ b/pool/shard004/JavaScript/0026675_gist-file-test.js
@@ -0,0 +1,33 @@
+import { moduleForModel, test } from 'ember-qunit';
+import Ember from 'ember';
+import DS from 'ember-data';
+
+const { run } = Ember;
+
+moduleForModel('gist-file', 'Unit | Model | gist file', {
+ needs: ['model:gist', 'model:gist-revision', 'model:gist-version']
+});
+
+test('it calls "registerDeletedFile" on gist relationship when deleting a record', function(assert) {
+ assert.expect(1);
+
+ const adapter = DS.Adapter.extend({
+ createRecord() {
+ return Ember.RSVP.resolve({ id: 1 });
+ }
+ });
+ this.register('adapter:application', adapter);
+ const store = this.store();
+
+ run(() => {
+ const gist = store.createRecord('gist');
+ gist.registerDeletedFile = () => {
+ assert.ok(true, '"registerDeletedFile" was called');
+ };
+ const model = this.subject({ gist });
+
+ model.save().then(() => {
+ model.deleteRecord();
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0026678_Events.js b/pool/shard004/JavaScript/0026678_Events.js
new file mode 100644
index 0000000000000000000000000000000000000000..21d2c201a7208a62b6a5126c0fb4d40803b2736f
--- /dev/null
+++ b/pool/shard004/JavaScript/0026678_Events.js
@@ -0,0 +1,47 @@
+/**
+ * Events
+ *
+ * @module :: Model
+ * @description :: A short summary of how this model works and what it represents.
+ * @docs :: http://sailsjs.org/#!documentation/models
+ */
+
+module.exports = {
+ attributes: {
+ /* e.g.
+ nickname: 'string'
+ */
+ },
+
+ // Lifecycle Callbacks
+ beforeCreate: function(values, next) {
+ Tags.findOne({'tag': values['tag'].toString()}, function(err, tag) {
+ if (err)
+ return next(err);
+ if (!tag)
+ return next(new Error("No tags with the following parameters were found: {'tag': " + values['tag'] + "}"));
+ Assets.findOne({'tagID': tag.id}, function(err, asset) {
+ if (err)
+ return next(err);
+ if (!asset)
+ return next(new Error("No assets assigned to the following tag were found: {'tag': " + values['tag'] + "}"));
+ Readers.findOne({'reader': values['reader'].toString()}, function(err, reader) {
+ if (err)
+ return next(err);
+ if (!reader)
+ return next(new Error("No readers with the following parameters were found: {'reader': " + values['reader'] + "}"));
+ if (asset.currentReaderId === reader.id)
+ next();
+ else {
+ asset.currentReaderId = reader.id;
+ asset.save(function(err) {
+ if (err)
+ return next(err);
+ next();
+ });
+ }
+ });
+ });
+ });
+ }
+};
diff --git a/pool/shard004/JavaScript/0026679_gui.js b/pool/shard004/JavaScript/0026679_gui.js
new file mode 100644
index 0000000000000000000000000000000000000000..702ebba5f5daef400b69120b6e902c776ef997e4
--- /dev/null
+++ b/pool/shard004/JavaScript/0026679_gui.js
@@ -0,0 +1,157 @@
+// noinspection FunctionWithInconsistentReturnsJS
+const GUI = (function() {
+ let controller = null;
+ let settings = null;
+
+ const stateChangedEvent = () => {
+ if (settings) {
+ settings.ui.cbAutoscroll.checked = SETTINGS.autoscroll;
+ settings.ui.optsAfterFirstMsg[SETTINGS.afterFirstMsg].checked = true;
+ settings.ui.optsAfterSavedMsg[SETTINGS.afterSavedMsg].checked = true;
+
+ const autoscrollDisabled = !SETTINGS.autoscroll;
+ Object.values(settings.ui.optsAfterFirstMsg).forEach(ele => ele.disabled = autoscrollDisabled);
+ Object.values(settings.ui.optsAfterSavedMsg).forEach(ele => ele.disabled = autoscrollDisabled);
+ }
+ };
+
+ return {
+ showController() {
+ if (controller) {
+ return;
+ }
+
+ const html = `
+
+
+
+Waiting
`;
+
+ controller = {
+ styles: DOM.createStyle(`/*[CSS-CONTROLLER]*/`),
+ ele: DOM.createElement("div", document.body, "dht-ctrl", html)
+ };
+
+ controller.ui = {
+ btnSettings: DOM.id("dht-ctrl-settings"),
+ btnTrack: DOM.id("dht-ctrl-track"),
+ btnClose: DOM.id("dht-ctrl-close"),
+ textStatus: DOM.id("dht-ctrl-status")
+ };
+
+ controller.ui.btnSettings.addEventListener("click", () => {
+ this.showSettings();
+ });
+
+ controller.ui.btnTrack.addEventListener("click", () => {
+ const isTracking = !STATE.isTracking();
+ STATE.setIsTracking(isTracking);
+
+ if (!isTracking) {
+ controller.ui.textStatus.innerText = "Stopped";
+ }
+ });
+
+ controller.ui.btnClose.addEventListener("click", () => {
+ this.hideController();
+ window.DHT_ON_UNLOAD.forEach(f => f());
+ delete window.DHT_ON_UNLOAD;
+ delete window.DHT_LOADED;
+ });
+
+ STATE.onTrackingStateChanged(isTracking => {
+ controller.ui.btnTrack.innerText = isTracking ? "Pause Tracking" : "Start Tracking";
+ controller.ui.btnSettings.disabled = isTracking;
+ });
+
+ SETTINGS.onSettingsChanged(stateChangedEvent);
+ stateChangedEvent();
+ },
+
+ hideController() {
+ if (controller) {
+ DOM.removeElement(controller.ele);
+ DOM.removeElement(controller.styles);
+ controller = null;
+ }
+ },
+
+ showSettings() {
+ if (settings) {
+ return;
+ }
+
+ const radio = (type, id, label) => "
";
+ const html = `
+
+
+
+${radio("afm", "nothing", "Do Nothing")}
+${radio("afm", "pause", "Pause Tracking")}
+${radio("afm", "switch", "Switch to Next Channel")}
+
+
+${radio("asm", "nothing", "Do Nothing")}
+${radio("asm", "pause", "Pause Tracking")}
+${radio("asm", "switch", "Switch to Next Channel")}
+It is recommended to disable link and image previews to avoid putting unnecessary strain on your browser.
`;
+
+ settings = {
+ styles: DOM.createStyle(`/*[CSS-SETTINGS]*/`),
+ overlay: DOM.createElement("div", document.body, "dht-cfg-overlay"),
+ ele: DOM.createElement("div", document.body, "dht-cfg", html)
+ };
+
+ settings.overlay.addEventListener("click", () => {
+ this.hideSettings();
+ });
+
+ settings.ui = {
+ cbAutoscroll: DOM.id("dht-cfg-autoscroll"),
+ optsAfterFirstMsg: {},
+ optsAfterSavedMsg: {}
+ };
+
+ settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_NOTHING] = DOM.id("dht-cfg-afm-nothing");
+ settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_PAUSE] = DOM.id("dht-cfg-afm-pause");
+ settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_SWITCH] = DOM.id("dht-cfg-afm-switch");
+
+ settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_NOTHING] = DOM.id("dht-cfg-asm-nothing");
+ settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_PAUSE] = DOM.id("dht-cfg-asm-pause");
+ settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_SWITCH] = DOM.id("dht-cfg-asm-switch");
+
+ settings.ui.cbAutoscroll.addEventListener("change", () => {
+ SETTINGS.autoscroll = settings.ui.cbAutoscroll.checked;
+ });
+
+ Object.keys(settings.ui.optsAfterFirstMsg).forEach(key => {
+ settings.ui.optsAfterFirstMsg[key].addEventListener("click", () => {
+ SETTINGS.afterFirstMsg = key;
+ });
+ });
+
+ Object.keys(settings.ui.optsAfterSavedMsg).forEach(key => {
+ settings.ui.optsAfterSavedMsg[key].addEventListener("click", () => {
+ SETTINGS.afterSavedMsg = key;
+ });
+ });
+
+ stateChangedEvent();
+ },
+
+ hideSettings() {
+ if (settings) {
+ DOM.removeElement(settings.overlay);
+ DOM.removeElement(settings.ele);
+ DOM.removeElement(settings.styles);
+ settings = null;
+ }
+ },
+
+ setStatus(state) {
+ if (controller) {
+ controller.ui.textStatus.innerText = state;
+ }
+ }
+ };
+})();
diff --git a/pool/shard004/JavaScript/0026680_axes.js b/pool/shard004/JavaScript/0026680_axes.js
new file mode 100644
index 0000000000000000000000000000000000000000..4345276e0271d0b099986b4b3edb8fde72ffd937
--- /dev/null
+++ b/pool/shard004/JavaScript/0026680_axes.js
@@ -0,0 +1,55 @@
+import * as utils from "base/utils";
+import Component from "base/component";
+import Dialog from "components/dialogs/_dialog";
+
+import indicatorpicker from "components/indicatorpicker/indicatorpicker";
+import minmaxinputs from "components/minmaxinputs/minmaxinputs";
+
+/*
+ * Axes dialog
+ */
+
+const Axes = Dialog.extend("axes", {
+
+ /**
+ * Initializes the dialog component
+ * @param config component configuration
+ * @param context component context (parent)
+ */
+ init(config, parent) {
+ this.name = "axes";
+ const _this = this;
+
+ this.components = [{
+ component: indicatorpicker,
+ placeholder: ".vzb-xaxis-selector",
+ model: ["state.time", "state.marker.axis_x", "locale"]
+ }, {
+ component: minmaxinputs,
+ placeholder: ".vzb-xaxis-minmax",
+ model: ["state.marker", "state.time", "locale"],
+ markerID: "axis_x",
+ ui: {
+ selectDomainMinMax: false,
+ selectZoomedMinMax: true
+ }
+ }, {
+ component: indicatorpicker,
+ placeholder: ".vzb-yaxis-selector",
+ model: ["state.time", "state.marker.axis_y", "locale"]
+ }, {
+ component: minmaxinputs,
+ placeholder: ".vzb-yaxis-minmax",
+ model: ["state.marker", "state.time", "locale"],
+ markerID: "axis_y",
+ ui: {
+ selectDomainMinMax: false,
+ selectZoomedMinMax: true
+ }
+ }];
+
+ this._super(config, parent);
+ }
+});
+
+export default Axes;
diff --git a/pool/shard004/JavaScript/0026681_util.js b/pool/shard004/JavaScript/0026681_util.js
new file mode 100644
index 0000000000000000000000000000000000000000..b8d87198be46bebbdb09660571b7015751add9bf
--- /dev/null
+++ b/pool/shard004/JavaScript/0026681_util.js
@@ -0,0 +1,74 @@
+exports.parseLoginToken = function (req) {
+ // authHeader is a string that looks like this:
+ // `Streetmix realm="" loginToken="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx" userId="user"`
+ const authHeader = req.header('Authorization')
+
+ if (!authHeader) {
+ return null
+ }
+
+ const auth = authHeader.split(/\s+/)
+
+ if (auth.length < 4) {
+ return null
+ }
+
+ const authScheme = auth.shift()
+
+ // Convert the auth string to an object
+ const authObject = auth.reduce((accumulator, item) => {
+ const [key, value] = item.split('=')
+ accumulator[key] = value.replace(/(^"|"$)/g, '')
+ return accumulator
+ }, {})
+
+ if ((authScheme !== 'Streetmix') || (authObject.realm !== '')) {
+ return null
+ }
+
+ return authObject
+}
+
+exports.asStreetJson = function (street) {
+ const json = {
+ id: street.id,
+ namespacedId: street.namespaced_id,
+ name: street.name,
+ data: street.data,
+ createdAt: street.created_at,
+ updatedAt: street.updated_at,
+ originalStreetId: street.original_street_id
+ }
+ return json
+}
+
+exports.ERRORS = {
+ USER_NOT_FOUND: 'USER_NOT_FOUND',
+ INTERNAL_ERROR: 'INTERNAL_ERROR',
+ STREET_NOT_FOUND: 'STREET_NOT_FOUND',
+ STREET_DELETED: 'STREET_DELETED',
+ UNAUTHORISED_ACCESS: 'UNAUTHORISED_ACCESS',
+ FORBIDDEN_REQUEST: 'FORBIDDEN_REQUEST',
+ CANNOT_CREATE_STREET: 'CANNOT_CREATE_STREET',
+ CANNOT_UPDATE_STREET: 'CANNOT_UPDATE_STREET',
+ CANNOT_GET_STREET: 'CANNOT_GET_STREET',
+ CANNOT_GET_USER: 'CANNOT_GET_USER',
+ CANNOT_CREATE_USER: 'CANNOT_CREATE_USER'
+}
+
+exports.SAVE_THUMBNAIL_EVENTS = {
+ INITIAL: 'INITIAL',
+ SHARE: 'SHARE',
+ TIMER: 'TIMER',
+ BEFOREUNLOAD: 'BEFOREUNLOAD',
+ PREVIOUS_STREET: 'PREVIOUS_STREET',
+ TEST: 'TEST'
+}
+
+exports.requestIp = function (req) {
+ if (req.headers['x-forwarded-for'] !== undefined) {
+ return req.headers['x-forwarded-for'].split(', ')[0]
+ } else {
+ return req.connection.remoteAddress
+ }
+}
diff --git a/pool/shard004/JavaScript/0026683_date_helper.js b/pool/shard004/JavaScript/0026683_date_helper.js
new file mode 100644
index 0000000000000000000000000000000000000000..e5cedecad869d1f32c69b699592a1e8e5cebb1f4
--- /dev/null
+++ b/pool/shard004/JavaScript/0026683_date_helper.js
@@ -0,0 +1,19 @@
+'use strict';
+
+var _ = require('lodash');
+
+var dateHelper = {};
+
+dateHelper.date_to_dmy = function( date ) {
+
+ if( typeof date !== 'object' )
+ {
+ return '';
+ }
+
+ var date = new Date(date);
+ return date.getDate() + '/' + date.getMonth() + '/' + date.getYear();
+
+}
+
+module.exports = dateHelper;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026685_index.js b/pool/shard004/JavaScript/0026685_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..3670546ee43efedeb2083727a52b7a37f131b2d3
--- /dev/null
+++ b/pool/shard004/JavaScript/0026685_index.js
@@ -0,0 +1,61 @@
+import Modal from './Modal'
+
+import { VueInstance } from '../../utils/config'
+import { merge } from '../../utils/helpers'
+import { use, registerComponent, registerComponentProgrammatic } from '../../utils/plugins'
+
+let localVueInstance
+
+const ModalProgrammatic = {
+ open(params) {
+ let parent
+ if (typeof params === 'string') {
+ params = {
+ content: params
+ }
+ }
+
+ const defaultParam = {
+ programmatic: true
+ }
+ if (params.parent) {
+ parent = params.parent
+ delete params.parent
+ }
+ let slot
+ if (Array.isArray(params.content)) {
+ slot = params.content
+ delete params.content
+ }
+ const propsData = merge(defaultParam, params)
+ const vm = typeof window !== 'undefined' && window.Vue ? window.Vue : localVueInstance || VueInstance
+ const ModalComponent = vm.extend(Modal)
+ const component = new ModalComponent({
+ parent,
+ el: document.createElement('div'),
+ propsData
+ })
+ if (slot) {
+ component.$slots.default = slot
+ component.$forceUpdate()
+ }
+ return component
+ }
+}
+
+const Plugin = {
+ install(Vue) {
+ localVueInstance = Vue
+ registerComponent(Vue, Modal)
+ registerComponentProgrammatic(Vue, 'modal', ModalProgrammatic)
+ }
+}
+
+use(Plugin)
+
+export default Plugin
+
+export {
+ ModalProgrammatic,
+ Modal as BModal
+}
diff --git a/pool/shard004/JavaScript/0026687_reloadmetrics.js b/pool/shard004/JavaScript/0026687_reloadmetrics.js
new file mode 100644
index 0000000000000000000000000000000000000000..23da20aa3abc1139d843066ff2ce4f31e2bfa423
--- /dev/null
+++ b/pool/shard004/JavaScript/0026687_reloadmetrics.js
@@ -0,0 +1,115 @@
+var Promise = require('bluebird');
+var qrsInteract = require('./qrsInstance');
+var appDataSegment = require('./getAppDataSegment');
+var logger = require('./logger');
+
+var reloadMetrics = {
+
+ reloadMetrics: function(app, taskName) {
+ var currContentHash;
+ return new Promise(function(resolve, reject) {
+
+ // return appDataSegment.getAppDataSegment(app)
+ // .then(function(result)
+ // {
+ // currentContentHash = result.contentHash;
+ logger.info('reloadMetrics::Starting Task::' + taskName, { module: 'reloadmetrics' });
+ var path = "/task/start/synchronous";
+ path += "?name=" + taskName;
+ logger.debug('reloadMetrics::PATH::' + path, { module: 'reloadmetrics' });
+ return qrsInteract.Post(path, '', 'json')
+ .then(function(result) {
+ var taskId = result.body.value;
+ if (typeof result.body == 'object') {
+ logger.info('reloadMetrics::Task Started::' + taskName, { module: 'reloadmetrics' });
+ return progressCheck(taskId, function(error, result) {
+ //now that we are done, let's evaluate the result
+ if (error) {
+ logger.error('reloadMetrics::progressCheck::' + error, { module: 'reloadmetrics' });
+ reject(error);
+ } else {
+ logger.info('reloadMetrics::Task Complete::' + taskName, { module: 'reloadmetrics' });
+ var path2 = "/executionresult";
+ path2 += "?filter=executionid eq " + taskId;
+ logger.debug('reloadMetrics::PATH::' + path2, { module: 'reloadmetrics' });
+ return qrsInteract.Get(path2)
+ .then(function(reloadInfo) {
+
+ logger.info('reloadMetrics::Task Completed in ' + reloadInfo.body[0].duration + 'milliseconds', { module: 'reloadmetrics' });
+ logger.info('reloadMetrics::Final Task Message: ' + reloadInfo.body[0].details[reloadInfo.body[0].details.length - 1].message, { module: 'reloadmetrics' })
+ // hashCheck(app,currentContentHash,function(error,result)
+ // {
+ // if(error)
+ // {
+ // logger.error('reloadMetrics::progressCheck::' + error, {module: 'reloadMetrics'});
+ // reject(new Error(error));
+ // }
+ // else
+ // {
+ // logger.info('reloadMetrics::Content Hash changed on app data segment for ' + app.name, {module: 'reloadmetrics'});
+ resolve('Task Completed in ' + reloadInfo.body[0].duration + ' milliseconds with message ' + reloadInfo.body[0].details[reloadInfo.body[0].details.length - 1].message);
+ // }
+ // })
+ })
+ .catch(function(error) {
+ logger.error('reloadMetrics::Task Failure::' + error, { module: 'reloadmetrics' });
+ reject(error);
+ });
+ }
+ });
+ } else {
+ logger.error('reloadMetrics::' + JSON.stringify(result.body), { module: 'reloadmetrics' });
+ reject(result);
+ }
+ })
+ .catch(function(error) {
+ reject(error);
+ });
+ });
+ }
+};
+
+function progressCheck(id, callback) {
+ //console.log(reload);
+ var path = "/executionsession";
+ path += "?filter=id eq " + id;
+ logger.debug('progressCheck::PATH::' + path, { module: 'reloadmetrics' });
+ return qrsInteract.Get(path)
+ .then(function(reloadProgress) {
+ if (reloadProgress.body === undefined || reloadProgress.body.length == 0) {
+ logger.info('reloadMetrics::progressCheck::Task Complete', { module: 'reloadmetrics' });
+ return callback(null, 'Reload Complete');
+ } else {
+ var reloadStep = reloadProgress.body[0].executionResult.details.length;
+ logger.debug('reloadMetrics::progressCheck::' + reloadProgress.body[0].executionResult.details[reloadStep - 1].message, { module: 'reloadmetrics' });
+ return progressCheck(id, callback);
+ }
+ })
+ .catch(function(error) {
+ logger.error('reloadMetrics::progressCheck::' + error, { module: 'reloadmetrics' });
+ return callback(error);
+ });
+}
+
+function hashCheck(app, currentHash, callback) {
+ var newHash;
+ return appDataSegment.getAppDataSegment(app)
+ .then(function(result) {
+ logger.debug("AppDataSegment return value: " + JSON.stringify(result), { module: 'reloadMetrics' });
+ logger.debug('reloadMetrics::hashCheck::New Hash::' + result.contentHash, { module: 'reloadMetrics' });
+ newHash = result.contentHash;
+ if (newHash === currentHash) {
+ logger.debug('reloadMetrics::hashCheck::Has has not changed::' + newHash + '==' + currentHash, { module: 'reloadMetrics' });
+ hashCheck(app, currentHash, callback);
+ } else {
+ logger.debug('reloadMetrics::hashCheck::Has has changed::' + newHash + '!=' + currentHash, { module: 'reloadMetrics' });
+ callback(null, 'Hash Changed');
+ }
+ })
+ .catch(function(error) {
+ logger.error('reloadMetrics::hashCheck::' + JSON.stringify(error), { module: 'reloadMetrics' });
+ callback(error);
+ });
+}
+
+module.exports = reloadMetrics;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026690_TopPanel.js b/pool/shard004/JavaScript/0026690_TopPanel.js
new file mode 100644
index 0000000000000000000000000000000000000000..db39a5805d29eb6eb07ef90998c36a6618e6aea0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026690_TopPanel.js
@@ -0,0 +1,41 @@
+const ActivityRunner = require("../../abstract/ActivityRunner");
+const blessed = require("blessed");
+const ActionsInputPanel = require("../userInputActions/ActionsInputPanel");
+
+module.exports = class extends ActivityRunner {
+ constructor(parent, store) {
+ super(parent, blessed.box({
+ width: "100%",
+ height: "80%",
+ top: 0
+ }));
+ this.store = store;
+
+ this.currentActivity = undefined;
+ this.currentActivityTimestamp = undefined;
+ this.currentActivityArguments = [];
+ }
+
+ async storeListener() {
+ await this.currentActivityChangeListener();
+ }
+
+ async currentActivityChangeListener() {
+ let storeCurrentActivityTimestamp = this.store.getState().ui.currentActivity.timestamp;
+ if(storeCurrentActivityTimestamp && this.currentActivityTimestamp !== storeCurrentActivityTimestamp) {
+ this.currentActivity = this.store.getState().ui.currentActivity.activity;
+ this.currentActivityTimestamp = storeCurrentActivityTimestamp;
+ this.currentActivityArguments = this.store.getState().ui.currentActivity.arguments;
+ await this.showCurrentActivity();
+ }
+ }
+
+ async showCurrentActivity() {
+ await this.showElements([new this.currentActivity(this, this.store, this.currentActivityArguments)]);
+ }
+
+ async run() {
+ this.store.subscribe(() => this.storeListener().then());
+ await this.showElements([new ActionsInputPanel(this, this.store)]);
+ }
+};
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026692_main.js b/pool/shard004/JavaScript/0026692_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..7f380927a808cd343c8afbed813e6f2f77609188
--- /dev/null
+++ b/pool/shard004/JavaScript/0026692_main.js
@@ -0,0 +1,59 @@
+var express = require('express');
+var ntlm = require('express-ntlm');
+var ldap = require('ldapjs');
+var config = require("./config").config;
+
+var app = express();
+
+app.use(
+ function crossOrigin(req, res, next) {
+ res.header("Access-Control-Allow-Origin", config.cors.origin);
+ res.header("Access-Control-Allow-Headers", "Authorization");
+ res.header("Access-Control-Allow-Credentials", "true");
+ return next();
+ }
+);
+
+app.use(ntlm({
+ debug: function() {
+ var args = Array.prototype.slice.apply(arguments);
+ console.log.apply(null, args);
+ },
+ domain: config.ldap.domain,
+ domaincontroller: config.ldap.domaincontrollers
+}));
+
+app.get('/api/auth', function(req, res) {
+
+ var ldapclient = ldap.createClient({
+ url: 'ldap://'+config.ldap.domaincontrollers[0]+'/' + config.ldap.domaindc
+ });
+
+ var response = {
+ user: req.ntlm,
+ data: {}
+ }
+
+ var opts = {
+ filter: '(&(cn='+req.ntlm.UserName+')(objectclass=user))',
+ scope: 'sub',
+ attributes: config.ldap.userattributes
+ };
+
+ ldapclient.bind(config.ldap.username, config.ldap.password, function (err) {
+ ldapclient.search(config.ldap.usersou, opts, function (err, search) {
+ search.on('searchEntry', function (entry) {
+ response.data = entry.object;
+ res.send('' + JSON.stringify(response, null, 2) + '');
+ res.end();
+ });
+ });
+ });
+
+});
+
+var server = app.listen(config.server.port, function() {
+ var host = server.address().address;
+ var port = server.address().port;
+ console.log('idm listening at http://%s:%s', host, port);
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026695_index.js b/pool/shard004/JavaScript/0026695_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..577cde81eba2b5ca14ca9669903da1a4babfb496
--- /dev/null
+++ b/pool/shard004/JavaScript/0026695_index.js
@@ -0,0 +1,31 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { returnsArgument } from 'empty-functions';
+
+export default function AuthSchema() {
+ return ;
+}
+
+AuthSchema.propTypes = {
+ basePath: PropTypes.string.isRequired,
+ loginPath: PropTypes.string.isRequired,
+ getUserPath: PropTypes.string.isRequired,
+ defaultLoginRedirection: PropTypes.string,
+ crypto: PropTypes.func,
+ mapOnLoginRequestBody: PropTypes.func,
+ mapOnLoginResponse: PropTypes.func,
+ mapOnGetUserResponse: PropTypes.func,
+};
+
+AuthSchema.defaultProps = {
+ defaultLoginRedirection: '/',
+ mapOnLoginRequestBody: returnsArgument,
+ mapOnLoginResponse: returnsArgument,
+ mapOnGetUserResponse: returnsArgument,
+};
+
+AuthSchema.configuration = {
+ name: 'auth',
+ propType: PropTypes.object,
+ pipe: (props, auth) => Object.assign(auth, props),
+};
diff --git a/pool/shard004/JavaScript/0026698_background.js b/pool/shard004/JavaScript/0026698_background.js
new file mode 100644
index 0000000000000000000000000000000000000000..a7464685bdde530fd87aaaefe3235e88e59679b7
--- /dev/null
+++ b/pool/shard004/JavaScript/0026698_background.js
@@ -0,0 +1,217 @@
+var settings = new Store("settings", {
+ "location_imgur_location": "r/wallpaper",
+ "location_imgur_sort": "hot",
+ "location_imgur_span": "month",
+ "location_flicker_sort": "hot",
+ "location_imgur_pages": 1,
+ "search_status": true,
+ "logo_status": false,
+ "download_link": false,
+ "timing_status": true,
+ "timing_swap": 3,
+ "timing_swap": 1,
+ "active_image": 0,
+ location_imgur_preset: "r/wallpaper",
+ "background_size": "cover"
+});
+var loaded_image = '';
+/**
+ * Load Image Links into local storage
+ * @type {{local: local, imgur: imgur, flicker: flicker}}
+ */
+var load_images = {
+ local: function (callback) {
+ var except_extions = ['jpeg', 'png', 'jpg'];
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", 'file://' + settings.get('location_local_location'), true);
+ xhr.onload = function (e) {
+ var re = new RegExp("addRow[(](.*?)\",\"", "gi");
+ var matched = xhr.response.match(re);
+ var images = [];
+ matched.forEach(function (value, key) {
+ value = value.replace('addRow("', '').replace('","', '');
+ var extenstion = value.split('.').pop();
+ if (except_extions.indexOf(extenstion) !== -1 && extenstion.length > 0) {
+ images.push(value);
+ }
+ });
+ settings.set('images', images);
+ settings.set('active_image', 0);
+ callback(undefined, 'local');
+ }
+ xhr.send();
+ },
+ imgur: function (callback) {
+ if (!navigator.onLine) {
+ settings.set('images', ['lenny.jpg']);
+ settings.set('active_image', 0);
+ callback(undefined, 'default');
+ return;
+ }
+ function imgur_set_iamges(location, page) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", location + page + '.json', true);
+ xhr.responseType = "json";
+ xhr.onload = function (e) {
+ var images = [];
+ e.target.response.data.forEach(function (value) {
+ images.push('http://i.imgur.com/' + value.hash + value.ext);
+ });
+ settings.set('images', settings.get('images').concat(images));
+ settings.set('active_image', 0);
+ callback(undefined, 'imgur');
+
+ }
+ xhr.send();
+ }
+
+ var location = settings.get('location_imgur_preset') !== 'false' ? settings.get('location_imgur_preset') : settings.get('location_imgur_location').replace(/^\/|\/$/g, '');
+
+ //Check for reddit or single gallery to not do pages
+ if (location.indexOf('r/') != -1 || location == 'gallery' || location == 'g') {
+ location = 'http://imgur.com/' + location + '/' + settings.get('location_imgur_sort') + '/' + settings.get('location_imgur_span') + '/page/';
+ settings.set('images', []);
+ for (var x = 0; x < settings.get('location_imgur_pages'); x++)
+ imgur_set_iamges(location, x)
+ } else {
+ //Single Gallery View
+ imgur_set_iamges('http://imgur.com/' + location, '')
+ }
+
+
+ },
+ flicker: function (callback) {
+ callback(undefined, 'flicker');
+ },
+ 'default': function (callback) {
+ settings.set('images', ['lenny.jpg']);
+ settings.set('active_image', 0);
+ callback(undefined, 'default');
+ }
+};
+/**
+ * Set View image
+ * Functions to grab the images links
+ */
+var set_image = {
+ local: function () {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", 'file://' + settings.get('location_local_location') + '/' + settings.get('images')[settings.get('active_image')], true);
+ xhr.responseType = "blob";
+ xhr.onload = function (e) {
+ var reader = new FileReader();
+ reader.onload = function (e) {
+ loaded_image = e.target.result;
+ }
+ reader.readAsDataURL(xhr.response);
+ }
+ xhr.send();
+ },
+ imgur: function () {
+ if (!navigator.onLine) {
+ loaded_image = 'lenny.jpg';
+ return;
+ }
+ loaded_image = settings.get('images')[settings.get('active_image')]
+ },
+ flicker: function () {
+ },
+ 'default': function () {
+ loaded_image = settings.get('images')[settings.get('active_image')]
+ }
+};
+/**
+ * setInterval
+ * To Change the background image
+ * @type {undefined}
+ */
+var swap_interval = undefined;
+
+/**
+ * Get Location
+ * Check where the images should be grab from
+ * @returns {string}
+ */
+function get_location() {
+ if (settings.get('location_local_location')) {
+ return 'local';
+ } else if (settings.get('location_imgur_location') || settings.get('location_imgur_preset')) {
+ return 'imgur';
+ }
+ return 'default';
+}
+/**
+ * Get Image List
+ * Select the images from the locations
+ * if no locations then set the default image of lenny
+ * @param callback
+ */
+function get_image_list(callback) {
+ callback = callback || function () {
+ };
+ var location = get_location();
+ load_images[location](callback);
+}
+function next_image() {
+ if (settings.get('timing_random')) {
+ settings.set('active_image', Math.floor((Math.random() * settings.get('images').length)));
+ } else {
+ var next = settings.get('active_image') + 1 < settings.get('images').length ? settings.get('active_image') + 1 : 0;
+ settings.set('active_image', next);
+ }
+ set_image[get_location()]();
+}
+/**
+ * Background Swaping
+ * Remove interval if set and setup a new interval for changing new tab background images
+ */
+function background_swaping() {
+ if (swap_interval) {
+ clearInterval(swap_interval);
+ }
+ if (!navigator.onLine) {
+ swap_interval = setInterval(function () {
+ get_image_list(background_swaping);
+ }, 200);
+ } else if (settings.get('timing_status')) {
+ swap_interval = setInterval(next_image, settings.get('timing_swap') * 60 * 1000);
+ }
+}
+
+/**
+ * Inital Background loading setup
+ */
+get_image_list(function (error, location) {
+ if (error) {
+ return;
+ }
+ set_image[location]();
+ background_swaping(location);
+});
+/**
+ * Event from Setting being changed
+ * todo have events have a queue to prevent any aynsc issues
+ */
+chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
+ switch (request.event) {
+ case 'timing':
+ background_swaping();
+
+ break;
+ case 'location':
+ get_image_list();
+
+ break;
+ }
+});
+
+chrome.browserAction.onClicked.addListener(next_image);
+chrome.commands.onCommand.addListener(function (type) {
+ switch(type) {
+ case 'next-background' :
+ next_image();
+ break;
+ default :
+ break;
+ }
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026701_set_server_icon.js b/pool/shard004/JavaScript/0026701_set_server_icon.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a51c44f8221b2952d8643bfdd582170fe7da1c1
--- /dev/null
+++ b/pool/shard004/JavaScript/0026701_set_server_icon.js
@@ -0,0 +1,138 @@
+module.exports = {
+
+//---------------------------------------------------------------------
+// Action Name
+//
+// This is the name of the action displayed in the editor.
+//---------------------------------------------------------------------
+
+name: "Set Server Icon",
+
+//---------------------------------------------------------------------
+// Action Section
+//
+// This is the section the action will fall into.
+//---------------------------------------------------------------------
+
+section: "Server Control",
+
+//---------------------------------------------------------------------
+// Action Subtitle
+//
+// This function generates the subtitle displayed next to the name.
+//---------------------------------------------------------------------
+
+subtitle: function(data) {
+ const storeTypes = ["", "Temp Variable", "Server Variable", "Global Variable"];
+ return `${storeTypes[parseInt(data.storage)]} (${data.varName2})`;
+},
+
+//---------------------------------------------------------------------
+// Action Fields
+//
+// These are the fields for the action. These fields are customized
+// by creating elements with corresponding IDs in the HTML. These
+// are also the names of the fields stored in the action's JSON data.
+//---------------------------------------------------------------------
+
+fields: ["server", "varName", "storage", "varName2"],
+
+//---------------------------------------------------------------------
+// Command HTML
+//
+// This function returns a string containing the HTML used for
+// editting actions.
+//
+// The "isEvent" parameter will be true if this action is being used
+// for an event. Due to their nature, events lack certain information,
+// so edit the HTML to reflect this.
+//
+// The "data" parameter stores constants for select elements to use.
+// Each is an array: index 0 for commands, index 1 for events.
+// The names are: sendTargets, members, roles, channels,
+// messages, servers, variables
+//---------------------------------------------------------------------
+
+html: function(isEvent, data) {
+ return `
+
+
+ Server:
+
+
+
+
+
+
+ Source Image:
+
+
+
+ Variable Name:
+
+
+`
+},
+
+//---------------------------------------------------------------------
+// Action Editor Init Code
+//
+// When the HTML is first applied to the action editor, this code
+// is also run. This helps add modifications or setup reactionary
+// functions for the DOM elements.
+//---------------------------------------------------------------------
+
+init: function() {
+ const {glob, document} = this;
+
+ glob.serverChange(document.getElementById('server'), 'varNameContainer');
+},
+
+//---------------------------------------------------------------------
+// Action Bot Function
+//
+// This is the function for the action within the Bot's Action class.
+// Keep in mind event calls won't have access to the "msg" parameter,
+// so be sure to provide checks for variable existance.
+//---------------------------------------------------------------------
+
+action: function(cache) {
+ const data = cache.actions[cache.index];
+ const type = parseInt(data.server);
+ const varName = this.evalMessage(data.varName, cache);
+ const server = this.getServer(type, varName, cache);
+ if(server && server.setIcon) {
+ const type = parseInt(data.storage);
+ const varName2 = this.evalMessage(data.varName2, cache);
+ const image = this.getVariable(type, varName2, cache);
+ const Images = this.getDBM().Images;
+ Images.createBuffer(image).then(function(buffer) {
+ server.setIcon(buffer).then(function() {
+ this.callNextAction(cache);
+ }.bind(this)).catch(this.displayError.bind(this, data, cache));
+ }.bind(this)).catch(this.displayError.bind(this, data, cache));
+ } else {
+ this.callNextAction(cache);
+ }
+},
+
+//---------------------------------------------------------------------
+// Action Bot Mod
+//
+// Upon initialization of the bot, this code is run. Using the bot's
+// DBM namespace, one can add/modify existing functions if necessary.
+// In order to reduce conflictions between mods, be sure to alias
+// functions you wish to overwrite.
+//---------------------------------------------------------------------
+
+mod: function(DBM) {
+}
+
+}; // End of module
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026702_gulpfile.js b/pool/shard004/JavaScript/0026702_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..2ac1d2085fe5a557f7a70d776c8f3c780d47c825
--- /dev/null
+++ b/pool/shard004/JavaScript/0026702_gulpfile.js
@@ -0,0 +1,50 @@
+/*eslint-env node */
+'use strict';
+
+var gulp = require('gulp');
+var connect = require('gulp-connect');
+var plumber = require('gulp-plumber');
+var lint = require('gulp-eslint');
+
+var paths = {
+ src: './src',
+ html: './src/*.html',
+ js: './src/js/*.js'
+};
+
+gulp.task('connect', function () {
+ connect.server({
+ root: paths.src,
+ port: 8000,
+ livereload: true
+ });
+});
+
+gulp.task('html', function () {
+ gulp.src(paths.html)
+ .pipe(plumber())
+ .pipe(connect.reload());
+});
+
+gulp.task('js', function () {
+ gulp.src(paths.js)
+ .pipe(plumber())
+ .pipe(lint())
+ .pipe(lint.formatEach())
+ .pipe(connect.reload());
+});
+
+gulp.task('css', function () {
+ return gulp.src(paths.css)
+ .pipe(plumber())
+ .pipe(connect.reload());
+});
+
+
+gulp.task('watch', function () {
+ gulp.watch([paths.html], ['html']);
+ gulp.watch([paths.js], ['js']);
+ gulp.watch([paths.css], ['css']);
+});
+
+gulp.task('default', ['connect', 'html', 'js', 'css', 'watch']);
diff --git a/pool/shard004/JavaScript/0026703_interestController.js b/pool/shard004/JavaScript/0026703_interestController.js
new file mode 100644
index 0000000000000000000000000000000000000000..eb59b442fd81406addb8d3c86e56d1f1b2f24d37
--- /dev/null
+++ b/pool/shard004/JavaScript/0026703_interestController.js
@@ -0,0 +1,74 @@
+var Interest = require('./interest.server.model.js');
+var Idea = require('../ideas/idea.server.model.js');
+var Q = require('q');
+
+module.exports = {
+ newInterest: function (req, res, next) {
+ var interest = {};
+
+ //get interest parameters from request
+ interest.idea = req.params.idea_id;
+ interest.owner = req.user._id;
+ // interest.idea = req.body.ideaId;
+ // interest.owner = req.body.userId;
+
+ var createInterest = Q.nbind(Interest.create, Interest);
+
+ createInterest(interest)
+ .then(function (createdInterest) {
+ if (createdInterest) {
+ res.json(createdInterest);
+ }
+ })
+ .fail(function (error) {
+ next(error);
+ });
+ },
+
+ allInterests: function (req, res, next) {
+ var getIdeas = Q.nbind(Idea.find, Idea);
+ var query = req.params.room_id ? { room: req.params.room_id } : {};
+
+ // get all ideas
+ getIdeas(query)
+ .then(function(allIdeas) {
+ // if there are ideas send them in response
+ if(allIdeas) {
+ var getInterests = Q.nbind(Interest.find, Interest);
+ var query = [];
+ allIdeas.forEach(function (idea) {
+ query.push({ idea: idea._id });
+ });
+ getInterests(query)
+ .then(function (allInterests) {
+ if (allInterests) {
+ res.json(allInterests);
+ }
+ })
+ .fail(function (error) {
+ next(error);
+ });
+ }
+ })
+ .fail(function(error) {
+ next(error);
+ });
+ },
+
+ deleteInterest: function (req, res, next) {
+ var deleteInterest = Q.nbind(Interest.findOneAndRemove, Interest);
+ deleteInterest({
+ _id: req.params.interest_id
+ }).then(function (interest) {
+ if (interest) {
+ res.json({
+ message: 'Successfully deleted',
+ _id: req.params.interest_id
+ });
+ }
+ })
+ .fail(function (error) {
+ next(error);
+ });
+ }
+};
diff --git a/pool/shard004/JavaScript/0026707_parentheses.js b/pool/shard004/JavaScript/0026707_parentheses.js
new file mode 100644
index 0000000000000000000000000000000000000000..4f67833052faf6f948e9bba1aa9ab8f98da3d308
--- /dev/null
+++ b/pool/shard004/JavaScript/0026707_parentheses.js
@@ -0,0 +1,235 @@
+/* @flow */
+
+"use strict";
+
+var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
+
+exports.__esModule = true;
+exports.NullableTypeAnnotation = NullableTypeAnnotation;
+exports.UpdateExpression = UpdateExpression;
+exports.ObjectExpression = ObjectExpression;
+exports.Binary = Binary;
+exports.BinaryExpression = BinaryExpression;
+exports.SequenceExpression = SequenceExpression;
+exports.YieldExpression = YieldExpression;
+exports.ClassExpression = ClassExpression;
+exports.UnaryLike = UnaryLike;
+exports.FunctionExpression = FunctionExpression;
+exports.ArrowFunctionExpression = ArrowFunctionExpression;
+exports.ConditionalExpression = ConditionalExpression;
+exports.AssignmentExpression = AssignmentExpression;
+
+var _babelTypes = require("babel-types");
+
+var t = _interopRequireWildcard(_babelTypes);
+
+var PRECEDENCE = {
+ "||": 0,
+ "&&": 1,
+ "|": 2,
+ "^": 3,
+ "&": 4,
+ "==": 5,
+ "===": 5,
+ "!=": 5,
+ "!==": 5,
+ "<": 6,
+ ">": 6,
+ "<=": 6,
+ ">=": 6,
+ "in": 6,
+ "instanceof": 6,
+ ">>": 7,
+ "<<": 7,
+ ">>>": 7,
+ "+": 8,
+ "-": 8,
+ "*": 9,
+ "/": 9,
+ "%": 9,
+ "**": 10
+};
+
+function NullableTypeAnnotation(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ return t.isArrayTypeAnnotation(parent);
+}
+
+exports.FunctionTypeAnnotation = NullableTypeAnnotation;
+
+function UpdateExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if (t.isMemberExpression(parent) && parent.object === node) {
+ // (foo++).test()
+ return true;
+ }
+
+ return false;
+}
+
+function ObjectExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if (t.isExpressionStatement(parent)) {
+ // ({ foo: "bar" });
+ return true;
+ }
+
+ if (t.isMemberExpression(parent) && parent.object === node) {
+ // ({ foo: "bar" }).foo
+ return true;
+ }
+
+ return false;
+}
+
+function Binary(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
+ return true;
+ }
+
+ if (t.isUnaryLike(parent)) {
+ return true;
+ }
+
+ if (t.isMemberExpression(parent) && parent.object === node) {
+ return true;
+ }
+
+ if (t.isBinary(parent)) {
+ var parentOp = parent.operator;
+ var parentPos = PRECEDENCE[parentOp];
+
+ var nodeOp = node.operator;
+ var nodePos = PRECEDENCE[nodeOp];
+
+ if (parentPos > nodePos) {
+ return true;
+ }
+
+ // Logical expressions with the same precedence don't need parens.
+ if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function BinaryExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if (node.operator === "in") {
+ // let i = (1 in []);
+ if (t.isVariableDeclarator(parent)) {
+ return true;
+ }
+
+ // for ((1 in []);;);
+ if (t.isFor(parent)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function SequenceExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if (t.isForStatement(parent)) {
+ // Although parentheses wouldn"t hurt around sequence
+ // expressions in the head of for loops, traditional style
+ // dictates that e.g. i++, j++ should not be wrapped with
+ // parentheses.
+ return false;
+ }
+
+ if (t.isExpressionStatement(parent) && parent.expression === node) {
+ return false;
+ }
+
+ if (t.isReturnStatement(parent)) {
+ return false;
+ }
+
+ // Otherwise err on the side of overparenthesization, adding
+ // explicit exceptions above if this proves overzealous.
+ return true;
+}
+
+function YieldExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) || t.isYieldExpression(parent);
+}
+
+function ClassExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ // (class {});
+ if (t.isExpressionStatement(parent)) {
+ return true;
+ }
+
+ // export default (class () {});
+ if (t.isExportDeclaration(parent)) {
+ return true;
+ }
+
+ return false;
+}
+
+function UnaryLike(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ return t.isMemberExpression(parent) && parent.object === node;
+}
+
+function FunctionExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ // (function () {});
+ if (t.isExpressionStatement(parent)) {
+ return true;
+ }
+
+ return ArrowFunctionExpression(node, parent);
+}
+
+function ArrowFunctionExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ // export default (function () {});
+ if (t.isExportDeclaration(parent)) {
+ return true;
+ }
+
+ // (function test() {}).name;
+ if (t.isMemberExpression(parent) && parent.object === node) {
+ return true;
+ }
+
+ // (function () {})();
+ if (t.isCallExpression(parent) && parent.callee === node) {
+ return true;
+ }
+
+ return false;
+}
+
+function ConditionalExpression(node /*: Object*/, parent /*: Object*/) /*: boolean*/ {
+ if (t.isUnaryLike(parent)) {
+ return true;
+ }
+
+ if (t.isBinary(parent)) {
+ return true;
+ }
+
+ if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
+ if (parent.callee === node) {
+ return true;
+ }
+ }
+
+ if (t.isConditionalExpression(parent) && parent.test === node) {
+ return true;
+ }
+
+ if (t.isMemberExpression(parent) && parent.object === node) {
+ return true;
+ }
+
+ return false;
+}
+
+function AssignmentExpression(node /*: Object*/) /*: boolean*/ {
+ if (t.isObjectPattern(node.left)) {
+ return true;
+ } else {
+ return ConditionalExpression.apply(undefined, arguments);
+ }
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026714_index.js b/pool/shard004/JavaScript/0026714_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..2faedaf345cb9e4304592cad2b5e369a831d8dd3
--- /dev/null
+++ b/pool/shard004/JavaScript/0026714_index.js
@@ -0,0 +1,75 @@
+import {load as loadHTML} from 'cheerio';
+import {readFile, writeFile} from 'fs';
+import Tag from './tag';
+
+function input(file) {
+ return new Promise((resolve, reject) => {
+ readFile(file, (err, content) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(content);
+ }
+ });
+ });
+}
+
+function registerBindAttributes($el) {
+ for (let key in $el.get(0).attribs) {
+ if (key.substr(0, 5) === 'bind-') {
+ $el.addClass('bind-attribute');
+ }
+ }
+}
+
+function registerEventHandlers($el) {
+ for (let key in $el.get(0).attribs) {
+ if (key.substr(0, 2) === 'on') {
+ $el.addClass('bind-event');
+ }
+ }
+}
+
+function createTag(doc, $) {
+ let name = doc.get(0).tagName;
+ let template = doc.find('> template');
+ template.find('*').each((i, element) => {
+ let $el = $(element);
+ registerBindAttributes($el);
+ registerEventHandlers($el);
+ });
+ let script = doc.find('> script');
+ return new Tag(name, template.html(), script.text());
+}
+
+function createTags($) {
+ let docs = $(':root');
+ docs = docs.map((index, doc) => createTag($(doc), $));
+ return Array.from(docs);
+}
+
+function compileTags(tags) {
+ return tags.map((tag) => tag.compile());
+}
+
+function output(to) {
+ return (contents) => {
+ let content = contents.join('\n');
+ return new Promise((resolve, reject) => {
+ writeFile(to, content, (err) => err ? reject(err) : resolve());
+ });
+ };
+}
+
+export function compile(content, options={}) {
+ let $ = loadHTML(content, options);
+ let tags = createTags($);
+ return compileTags(tags);
+}
+
+export function compileFile(file, to, options={}) {
+ return input(file)
+ .then((content) => compile(content, options))
+ .then(output(to))
+ .catch((error) => console.error(error.stack));
+}
diff --git a/pool/shard004/JavaScript/0026716_try.hoodie.js b/pool/shard004/JavaScript/0026716_try.hoodie.js
new file mode 100644
index 0000000000000000000000000000000000000000..e50c1598c60953a42fbfccec59be2f3bd7256c23
--- /dev/null
+++ b/pool/shard004/JavaScript/0026716_try.hoodie.js
@@ -0,0 +1,26 @@
+/* global jQuery, createApp */
+
+(function($){
+ 'use strict';
+
+ $('form[action=create]').on('submit',function(event){
+ event.preventDefault();
+ var $form = $(event.target);
+ var subdomain = $('input[name=subdomain]').val();
+
+ $form.addClass('loading');
+ createApp(subdomain).then(onSuccess, onError);
+
+ function onSuccess(subdomain){
+ $form.removeClass('loading');
+ var $next = $('.current').removeClass('current').next().addClass('current');
+ $next.html( $next.html().replace(/subdomain/g, subdomain) );
+ $('#congratulations').focus();
+ }
+
+ function onError(error){
+ $form.removeClass('loading');
+ alert(error.message);
+ }
+ });
+})(jQuery);
diff --git a/pool/shard004/JavaScript/0026718_tabs.js b/pool/shard004/JavaScript/0026718_tabs.js
new file mode 100644
index 0000000000000000000000000000000000000000..65e071ea5983f255da3b8d13621bb15691f1ea9d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026718_tabs.js
@@ -0,0 +1,91 @@
+/**
+ * tabs 组件
+ *
+ * @Options
+ *
+ * @param {[String]} [event] 事件名称
+ * @param {[String]} [animateBefore] 前动画,因transition动画需要两个class支持,因此区分before和after
+ * @param {[String]} [animateAfter] 后动画,具体参考bootstrap tab的动画效果 fade & in
+ * @param {[Boolean]} [isCache] 是否缓存,ajax请求内容时使用,默认缓存
+ * @param {[Object]} [ajaxSetup] ajax 请求配置
+ *
+ *
+ * @Events
+ *
+ * $('selctor').on('tabsAjaxBefore',function(){});
+ * $('selctor').on('tabsAjaxSuccess',function(){});
+ *
+ *
+ * @Usage
+ *
+ * $('selector').IUI('tabs',{
+ * event:'mouseenter',
+ * animateBefore:'fade',
+ * animateAfter:'in'
+ * });
+ *
+ */
+
+/**
+ * [show description]
+ * @param {[jQuery Object]} target 目标元素
+ * @param {[Object]} config 配置
+ */
+
+function show(config) {
+ var el = this;
+ el.addClass('active').css('opacity',0).addClass('animate');
+ setTimeout(function() {
+ el.addClass(config.animateAfter);
+ }, 100);
+}
+module.exports = {
+ tabs: function(options) {
+ return this.each(function() {
+ var defaults = {
+ event: 'click',
+ isCache: true,
+ ajaxSetup: null
+ };
+
+ var $selector = $(this);
+ //避免与tabs嵌套tabs时冲突
+ var config = $.extend({}, defaults, options);
+
+ $selector.on(config.event + '.iui-tabs', '.tabs-item', function(event) {
+ event.preventDefault();
+ var $this = $(this);
+ var $parent = $this.parent();
+ var $target = $($this.attr('href'));
+ $target.trigger('tabsAjaxBefore', [config]);
+ // switch tabs-item class
+ $parent.addClass('active').siblings('.active').removeClass('active animate');
+ // switch tabs-content class
+ $target.siblings('.tabs-content').removeClass('active');
+
+ show.call($target, config);
+
+ if ($this.data('loaded') && config.isCache) {
+ return false;
+ }
+
+ if ($this.data('ajax')) {
+ $.ajax($.extend({
+ url: $this.data('ajax'),
+ type: 'GET',
+ dataType: 'html'
+ }, config.ajaxSetup)).then(function(res) {
+ $this.data('loaded', true);
+ $target.trigger('tabsAjaxSuccess', [res]);
+ }, function(err) {
+ console.log(err);
+ });
+ }
+
+ show.call($target, config);
+
+ });
+
+ });
+ }
+};
diff --git a/pool/shard004/JavaScript/0026720_strip-url-params.js b/pool/shard004/JavaScript/0026720_strip-url-params.js
new file mode 100644
index 0000000000000000000000000000000000000000..d05322da789bec3dce0064fefb4812bc22ab3903
--- /dev/null
+++ b/pool/shard004/JavaScript/0026720_strip-url-params.js
@@ -0,0 +1,30 @@
+"use strict";
+
+/**
+My solution to Strip Url Params kata from CodeWars: http://www.codewars.com/kata/strip-url-params
+**/
+
+function stripUrlParams(url, paramsToStrip){
+
+ var excludes = paramsToStrip || [];
+ var urlSplit, urlBase, uniques;
+
+ urlSplit = url.split('?');
+ urlBase = urlSplit[0];
+
+ if(!Array.isArray(urlSplit) || urlSplit.length < 2) {
+ return url;
+ }
+
+ uniques = urlSplit[1].split('&').filter(function(item, pos, self) {
+ var kvSplit, key, result;
+
+ kvSplit = item.split('=');
+ key = kvSplit[0]
+ result = (excludes.indexOf(key) === -1);
+ excludes.push(key);
+ return result;
+ });
+
+ return (urlBase + '?' + uniques.join('&'));
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026721_env.js b/pool/shard004/JavaScript/0026721_env.js
new file mode 100644
index 0000000000000000000000000000000000000000..2d3844f9d867409d8c4e9e0d059c413ffc1390cb
--- /dev/null
+++ b/pool/shard004/JavaScript/0026721_env.js
@@ -0,0 +1,18 @@
+var env = GLOBAL.env = {};
+
+var ENV_PREFIX = 'SEN_';
+
+var lingo = require('lingo');
+Object.keys(process.env).forEach(function(key) {
+ if (key.indexOf(ENV_PREFIX) !== 0) {
+ return;
+ }
+ env[lingo.camelcase(key.replace(ENV_PREFIX, '').toLowerCase().replace(/_/g, ' '))] = process.env[key];
+});
+
+var mergeObject = function(obj1, obj2) {
+ Object.keys(obj2).forEach(function(key) {
+ obj1[key] = obj2[key];
+ });
+};
+mergeObject(GLOBAL, require('./models'));
diff --git a/pool/shard004/JavaScript/0026723_benchmark-report.js b/pool/shard004/JavaScript/0026723_benchmark-report.js
new file mode 100644
index 0000000000000000000000000000000000000000..6e2514270f3a3f4b9fc28208ff07c607d7e190cf
--- /dev/null
+++ b/pool/shard004/JavaScript/0026723_benchmark-report.js
@@ -0,0 +1,28 @@
+const fs = require('fs')
+const path = require('path')
+const { promisify } = require('util')
+
+const chunk = require('lodash.chunk')
+
+const readFile = promisify(fs.readFile)
+
+const extractTimestamp = line => Number(line.match(/\d+$/)[0])
+
+const avg = list => list.reduce((value, item) => value += item, 0) / list.length
+
+async function main () {
+ const lines = (await readFile(path.resolve(__dirname, '../benchmark.log'))).toString().split('\n')
+
+ lines.pop()
+
+ const times = chunk(lines, 2).map(([start, end]) => {
+ return extractTimestamp(end) - extractTimestamp(start)
+ });
+
+ console.log(`samples:\t${times.length}`);
+ console.log(`avg:\t\t${avg(times)}\tms`);
+ console.log(`best:\t\t${Math.min(...times)}\tms`);
+ console.log(`worst:\t\t${Math.max(...times)}\tms`);
+}
+
+main()
diff --git a/pool/shard004/JavaScript/0026726_LeafletPageCtrl.js b/pool/shard004/JavaScript/0026726_LeafletPageCtrl.js
new file mode 100644
index 0000000000000000000000000000000000000000..fcde014ab475173d252635fc39c5d4c20fd6c9bd
--- /dev/null
+++ b/pool/shard004/JavaScript/0026726_LeafletPageCtrl.js
@@ -0,0 +1,86 @@
+/**
+ * @author v.lugovsky
+ * created on 16.12.2015
+ */
+(function () {
+ 'use strict';
+
+ angular.module('BlurAdmin.pages.maps')
+ .controller('LeafletPageCtrl', LeafletPageCtrl);
+
+ /** @ngInject */
+ function LeafletPageCtrl($timeout) {
+ var greenIcon = new L.Icon({
+ iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
+ shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
+ iconSize: [25, 41],
+ iconAnchor: [12, 41],
+ popupAnchor: [1, -34],
+ shadowSize: [41, 41]
+ });
+
+ var redIcon = new L.Icon({
+ iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
+ shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
+ iconSize: [25, 41],
+ iconAnchor: [12, 41],
+ popupAnchor: [1, -34],
+ shadowSize: [41, 41]
+ });
+ var map;
+ function initialize() {
+ L.Icon.Default.imagePath = 'assets/img/theme/vendor/leaflet/dist/images';
+ map = L.map(document.getElementById('leaflet-map')).setView([-23.599022,-46.717239], 11);
+ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
+ attribution: '© OpenStreetMap contributors'
+ }).addTo(map);
+
+
+
+ // Initialize Firebase
+ var config = {
+ apiKey: "AIzaSyBmFPVlL3koC_PvD11mD_y7y0PmQZvm54s",
+ authDomain: "medhub-3a1e3.firebaseapp.com",
+ databaseURL: "https://medhub-3a1e3.firebaseio.com",
+ storageBucket: "medhub-3a1e3.appspot.com",
+ messagingSenderId: "542735452063"
+ };
+ firebase.initializeApp(config);
+
+ var estoqueRef = firebase.database().ref('estoqueAtualPorEAN/7896016806469');
+ estoqueRef.on('child_added', function(snapshot) {
+ var item = snapshot.val();
+
+ L.marker([item.hospital.lat , item.hospital.long], {icon: greenIcon}).addTo(map)
+ .bindPopup(item.hospital.nome + '
Disponível: ' + item.quantidade)
+ .openPopup();
+
+ console.log();
+ });
+ }
+
+ function addRedPin(item) {
+ L.marker([item.hospital.lat , item.hospital.long], {icon: redIcon}).addTo(map)
+ .bindPopup(item.hospital.nome + '
Solicitando: ' + item.quantidade)
+ .openPopup();
+ }
+
+ $timeout(function(){
+ initialize();
+ }, 100);
+
+ $timeout(function(){
+ var item = {
+ hospital : {
+ nome: 'Albert Sabin',
+ lat: -23.525705,
+ long: -46.7135696,
+ },
+ quantidade: 150
+ };
+ addRedPin(item);
+ }, 5000);
+
+ }
+
+})();
diff --git a/pool/shard004/JavaScript/0026727_07-let.spec.js b/pool/shard004/JavaScript/0026727_07-let.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..3944ab97264e96592886cec5384e7e1e76addfec
--- /dev/null
+++ b/pool/shard004/JavaScript/0026727_07-let.spec.js
@@ -0,0 +1,37 @@
+// 7: block scope - let
+// To do: make all tests pass, leave the asserts unchanged!
+var assert = require('assert');
+
+describe('`let` restricts the scope of the variable to the current block', () => {
+ describe('`let` vs. `var`', () => {
+ it('`var` works as usual', () => {
+ if (true) {
+ var varX = true;
+ }
+ assert.equal(varX, true);
+ });
+
+ it('`let` restricts scope to inside the block', () => {
+ if (true) {
+ let letX = true;
+ }
+ assert.throws(() => console.log(letX));
+ });
+ });
+
+ describe('`let` usage', () => {
+ it('`let` use in `for` loops', () => {
+ let obj = { x: 1 };
+ for (let key in obj) {
+ }
+ assert.throws(() => console.log(key));
+ });
+
+ it('create artifical scope, using curly braces', () => {
+ {
+ let letX = true;
+ }
+ assert.throws(() => console.log(letX));
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0026728_benchmark.js b/pool/shard004/JavaScript/0026728_benchmark.js
new file mode 100644
index 0000000000000000000000000000000000000000..2fcb03c342dfc8c5db36b79105a789cf6937ba59
--- /dev/null
+++ b/pool/shard004/JavaScript/0026728_benchmark.js
@@ -0,0 +1,168 @@
+/*
+
+Benchmarks for the different solvers...
+
+Look at jQuery to see how they benchmark without function call overhead.
+*/
+
+require.config({
+ baseUrl: "../src/"
+});
+
+require(
+
+ ['csp', 'benchmarker'],
+
+ function(csp, benchmarker) {
+
+
+ function benchmarkMe() {
+
+ var currentdiv;
+
+ outerdiv = document.getElementById("output");
+
+
+ function pushChunkEl() {
+ currentdiv = document.createElement("table");
+ currentdiv.className = "output_table"
+ outerdiv.appendChild(currentdiv);
+ }
+
+ function getOutputEl(par) {
+ var newdiv = document.createElement("tr");
+ newdiv.className = "output_row";
+ par.appendChild(newdiv);
+ return newdiv;
+ }
+
+ //-------------------------------------------
+
+ pushChunkEl();
+
+
+ var Setup1 = function() {
+
+ this.p = csp.DiscreteProblem();
+
+ this.p.addVariable("a", [1,2,3]);
+ this.p.addVariable("b", [4,5,6]);
+ this.p.addVariable("c", [6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
+
+ this.p.addConstraint(
+ ["a", "b"],
+ function(a, b) { return a*2 === b; }
+ );
+
+ this.p.addConstraint(
+ ["b", "c"],
+ function(b, c) { return b*2 === c; }
+ );
+
+ }
+
+ benchmarker.config(getOutputEl(currentdiv));
+ benchmarker.measure(
+ "DiscreteProblem.getSolution 3 vars 2 consts",
+ 100,
+ {
+ setup: Setup1,
+ test: function() {
+ var sol = this.p.getSolution();
+ }
+ });
+
+ benchmarker.config(getOutputEl(currentdiv));
+ benchmarker.measure(
+ "DiscreteProblem.getSolutions 3 vars 2 consts",
+ 100,
+ {
+ setup: Setup1,
+ test: function() {
+ var allSoln = this.p.getSolutions();
+ }
+ });
+
+ //-------------------------------------------
+
+ pushChunkEl();
+
+
+ var Setup2 = function() {
+
+ this.p = csp.DiscreteProblem();
+
+ allVars = [];
+ for (var a = 65; a < 91; a++) {
+ allVars.push(String.fromCharCode(a));
+ this.p.addVariable(String.fromCharCode(a), [1,2,3]);
+ }
+
+
+ this.p.addConstraint(
+ ["A", "B"],
+ function(a, b) { return (a === 1); }
+ );
+
+ // this.p.addConstraint(
+ // allVars,
+ // function() {
+ // var first = 9;
+ // for (var i in arguments) {
+ //
+ // if (arguments[i] !== first) {
+ // return false;
+ // }
+ // }
+ // return true;
+ // }
+ // );
+
+
+
+ }
+
+ benchmarker.config(getOutputEl(currentdiv));
+ benchmarker.measure(
+ "DiscreteProblem.getSolution 50 vars 10 ints 2 constraintS",
+ 1,
+ {
+ setup: Setup2,
+ test: function() {
+ var sol = this.p.getSolution();
+ console.log(sol);
+ }
+ });
+
+ // benchmarker.config(getOutputEl(currentdiv));
+ // benchmarker.measure(
+ // "DiscreteProblem.getSolutions 100 vars 10 ints 1 constraint",
+ // 1,
+ // {
+ // setup: Setup2,
+ // test: function() {
+ // var allSoln = this.p.getSolutions();
+ // console.log(allSoln);
+ // }
+ // });
+
+ document.getElementById("spinner").style.display = "none";
+
+ }
+
+ document.onreadystatechange = function() {
+ if (document.readyState == "complete") {
+ document.getElementById("spinner").style.display = "block";
+ benchmarkMe();
+ }
+ }
+
+
+
+
+
+
+
+
+ }
+);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026729_bandit_model.js b/pool/shard004/JavaScript/0026729_bandit_model.js
new file mode 100644
index 0000000000000000000000000000000000000000..c94504cdb3a2d7ac5fea85c30cc758a8d9288583
--- /dev/null
+++ b/pool/shard004/JavaScript/0026729_bandit_model.js
@@ -0,0 +1,112 @@
+var assert = require('assert');
+var path = require('path');
+var root = path.join(__dirname, '..', '..');
+var dao = require(path.join(root, 'dao', 'bandit_model'));
+var Model = require(path.join(root, 'database'))('bandit_model/epsilon_greedy');
+
+describe(__filename, function () {
+ describe('interface', function () {
+ it('should have functions', function (done) {
+ assert.strictEqual(Object.keys(dao).length, 2);
+
+ assert.strictEqual(typeof dao.findById, 'function');
+ assert.strictEqual(typeof dao.remove, 'function');
+ done();
+ });
+ });
+
+ describe('findById', function () {
+ it('should return exact document', function (done) {
+ var id = null;
+ (new Model({
+ algorithm: 'EpsilonGreedy',
+ arms: [{}, {}, {}],
+ settings: {
+ epsilon: 0.75
+ }
+ })).save(function (error, document) {
+ assert.ok(!error);
+ assert.ok(document);
+ id = '' + document._id;
+
+ dao.findById(id, function (error, result) {
+ assert.ok(!error);
+ assert.ok(result);
+
+ assert.strictEqual('' + result._id, id);
+ assert.strictEqual(result.arms.length, 3);
+ assert.strictEqual(result.settings.epsilon, 0.75);
+
+ done();
+ });
+ });
+
+ after(function (done) {
+ Model.remove({_id: id}, done);
+ });
+ });
+ it('should return error when id is invalid', function (done) {
+ var id = 'lkjwelfjwlejflwejlwkjeflwejflkjflkjw;lejf;lkj';
+ dao.findById(id, function (error, result) {
+ assert.ok(error);
+ assert.ok(!result);
+ done();
+ });
+ });
+ it('should return null when document not found', function (done) {
+ var id = 'aa11aa11aa11aa11aa11aa11';
+ dao.findById(id, function (error, result) {
+ assert.ok(!error);
+ assert.strictEqual(result, null);
+ done();
+ });
+ });
+ });
+
+ describe('remove', function () {
+ it('should delete exact document', function (done) {
+ var id = null;
+ (new Model({
+ algorithm: 'EpsilonGreedy',
+ arms: [{}, {}, {}],
+ settings: {
+ epsilon: 0.75
+ }
+ })).save(function (error, document) {
+ assert.ok(!error);
+ assert.ok(document);
+
+ id = '' + document._id;
+
+ dao.remove(id, function (error) {
+ assert.ok(!error);
+
+ Model.findById(id, function (error, result) {
+ assert.ok(!error);
+ assert.strictEqual(result, null);
+
+ done();
+ });
+ });
+ });
+
+ after(function (done) {
+ Model.remove({_id: id}, done);
+ });
+ });
+ it('should return error when id is invalid', function (done) {
+ var id = 'lwljeowejowijfowiejowifweefwefwefewfwefwef';
+ dao.remove(id, function (error) {
+ assert.ok(error);
+ done();
+ });
+ });
+ it('should do nothing, when document not found', function (done) {
+ var id = 'a1a1a1a1a1a1a1a1a1a1a1a1';
+ dao.remove(id, function (error) {
+ assert.ok(!error);
+ done();
+ });
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0026733_es6.regexp.constructor.js b/pool/shard004/JavaScript/0026733_es6.regexp.constructor.js
new file mode 100644
index 0000000000000000000000000000000000000000..c69a731606b9f89365096da195ff7274c6d13d99
--- /dev/null
+++ b/pool/shard004/JavaScript/0026733_es6.regexp.constructor.js
@@ -0,0 +1,36 @@
+/* */
+var $ = require("./$"),
+ global = require("./$.global"),
+ isRegExp = require("./$.is-regexp"),
+ $flags = require("./$.flags"),
+ $RegExp = global.RegExp,
+ Base = $RegExp,
+ proto = $RegExp.prototype,
+ re1 = /a/g,
+ re2 = /a/g,
+ CORRECT_NEW = new $RegExp(re1) !== re1;
+if (require("./$.descriptors") && (!CORRECT_NEW || require("./$.fails")(function() {
+ re2[require("./$.wks")('match')] = false;
+ return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
+}))) {
+ $RegExp = function RegExp(p, f) {
+ var piRE = isRegExp(p),
+ fiU = f === undefined;
+ return !(this instanceof $RegExp) && piRE && p.constructor === $RegExp && fiU ? p : CORRECT_NEW ? new Base(piRE && !fiU ? p.source : p, f) : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f);
+ };
+ $.each.call($.getNames(Base), function(key) {
+ key in $RegExp || $.setDesc($RegExp, key, {
+ configurable: true,
+ get: function() {
+ return Base[key];
+ },
+ set: function(it) {
+ Base[key] = it;
+ }
+ });
+ });
+ proto.constructor = $RegExp;
+ $RegExp.prototype = proto;
+ require("./$.redefine")(global, 'RegExp', $RegExp);
+}
+require("./$.set-species")('RegExp');
diff --git a/pool/shard004/JavaScript/0026734_bstSequences.js b/pool/shard004/JavaScript/0026734_bstSequences.js
new file mode 100644
index 0000000000000000000000000000000000000000..5413b93669a5c876d39c68ee6f189dcca99a0277
--- /dev/null
+++ b/pool/shard004/JavaScript/0026734_bstSequences.js
@@ -0,0 +1,43 @@
+var BST = require('./../util/BST');
+
+var bstSequences = function(bst) {
+ var sequences = [];
+ var recurse = function(nodes, travelled) {
+ var noChild = true;
+ nodes.forEach((node) => {
+ if (node.left !== null && travelled[node.left.value] === undefined) {
+ noChild = false;
+ travelled[node.left.value] = true;
+ recurse(nodes.concat([node.left]), travelled);
+ delete travelled[node.left.value];
+ }
+ if (node.right !== null && travelled[node.right.value] === undefined) {
+ noChild = false;
+ travelled[node.right.value] = true;
+ recurse(nodes.concat([node.right]), travelled);
+ delete travelled[node.right.value];
+ }
+ });
+ if (noChild) {
+ sequences.push(nodes.map(node => node.value));
+ }
+ };
+ var startTravelled = {};
+ startTravelled[bst.value] = true;
+ recurse([bst], startTravelled);
+ return sequences;
+};
+
+/* TEST */
+
+/* 1, 2, 3, 4, 5, 6, 7 */
+
+var b = new BST(4);
+b.insert(2);
+b.insert(6);
+b.insert(1);
+b.insert(3);
+b.insert(5);
+b.insert(7);
+
+console.log(bstSequences(b));
diff --git a/pool/shard004/JavaScript/0026737_facts.js b/pool/shard004/JavaScript/0026737_facts.js
new file mode 100644
index 0000000000000000000000000000000000000000..ca0169efa872f0cef0e549ff35837a96f7759187
--- /dev/null
+++ b/pool/shard004/JavaScript/0026737_facts.js
@@ -0,0 +1,45 @@
+Template.facts.helpers({
+ facts: function(){
+ return Facts.find();
+ },
+
+ servers: function(){
+ return Servers.find();
+ },
+
+ isCreatingFact: function(){
+ return Session.get('isCreatingFact');
+ }
+});
+
+
+Template.facts.events({
+ "click a.create": function(e, tpl){
+ e.preventDefault();
+ Session.set('isCreatingFact', true);
+ },
+
+ "click a.cancel": function(e, tpl){
+ e.preventDefault();
+ Session.set('isCreatingFact', false);
+ },
+
+ "submit form.form-create": function(e, tpl){
+ e.preventDefault();
+ var serverOneId = tpl.$("select[name=serverOne]").val();
+ var serverTwoId = tpl.$("select[name=serverTwo]").val();
+
+ Meteor.call('factsInsert', serverOneId, serverTwoId, function(error, response){
+ if(error){
+ alert(error.reason);
+ Session.set('isCreatingFact', true);
+ Tracker.afterFlush(function(){
+ tpl.$("select[name=serverOne]").val(serverOneId);
+ tpl.$("select[name=serverTwo]").val(serverTwoId);
+ });
+ }
+ });
+
+ Session.set('isCreatingFact', false);
+ }
+});
diff --git a/pool/shard004/JavaScript/0026738_favicons.js b/pool/shard004/JavaScript/0026738_favicons.js
new file mode 100644
index 0000000000000000000000000000000000000000..d24a46d1a2c53252f0445d016a1898395be286d0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026738_favicons.js
@@ -0,0 +1,31 @@
+const fs = require("fs");
+const svg2png = require("svg2png");
+const scribbles = fs.readdirSync('./src/static/images/scribbles')
+
+fs.readdir('./data/events', (err, data) => {
+ let faviconParams = data.map(event =>
+ [event.split('.')[0], eventColor(event)]
+ );
+ faviconParams.forEach(param => createFavicon(...param))
+})
+
+const eventColor = event => (
+ JSON.parse(
+ fs.readFileSync(`./data/events/${event}`)
+ ).color
+);
+
+const createFavicon = (name, fill) => {
+ let filledSVG = getRandomScribble().replace('#FFFFFF', fill)
+ let SVGBuffer = Buffer.from(filledSVG);
+ let outputBuffer = svg2png.sync(SVGBuffer, { width: 32, height: 32 })
+ fs.writeFile(`./src/static/images/favicons/${name}.png`, outputBuffer)
+}
+
+const getRandomScribble = () => {
+ let max = scribbles.length;
+ let scribble = scribbles[randomNumber(max)];
+ return fs.readFileSync(`./src/static/images/scribbles/${scribble}`).toString();
+}
+
+const randomNumber = (max) => Math.floor(Math.random() * max);
diff --git a/pool/shard004/JavaScript/0026743_15.2.3.6-4-117.js b/pool/shard004/JavaScript/0026743_15.2.3.6-4-117.js
new file mode 100644
index 0000000000000000000000000000000000000000..406869158225c92b7fcd39bff4bfa12a49599ed5
--- /dev/null
+++ b/pool/shard004/JavaScript/0026743_15.2.3.6-4-117.js
@@ -0,0 +1,31 @@
+/// Copyright (c) 2012 Ecma International. All rights reserved.
+/**
+ * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-117.js
+ * @description Object.defineProperty - 'O' is an Array, test the length property of 'O' is own data property that overrides an inherited data property (15.4.5.1 step 1)
+ */
+
+
+function testcase() {
+ var arrObj = [0, 1, 2];
+ var arrProtoLen;
+
+ try {
+ arrProtoLen = Array.prototype.length;
+ Array.prototype.length = 0;
+
+
+ Object.defineProperty(arrObj, "2", {
+ configurable: false
+ });
+
+ Object.defineProperty(arrObj, "length", {
+ value: 1
+ });
+ return false;
+ } catch (e) {
+ return e instanceof TypeError && arrObj.length === 3 && Array.prototype.length === 0;
+ } finally {
+ Array.prototype.length = arrProtoLen;
+ }
+ }
+runTestCase(testcase);
diff --git a/pool/shard004/JavaScript/0026750_stateFilters.js b/pool/shard004/JavaScript/0026750_stateFilters.js
new file mode 100644
index 0000000000000000000000000000000000000000..eeaf870383322a5f9a48590496afc8f85925f5f2
--- /dev/null
+++ b/pool/shard004/JavaScript/0026750_stateFilters.js
@@ -0,0 +1,39 @@
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:isState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
+ */
+$IsStateFilter.$inject = ['$state'];
+function $IsStateFilter($state) {
+ var isFilter = function (state) {
+ return $state.is(state);
+ };
+ isFilter.$stateful = true;
+ return isFilter;
+}
+
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:includedByState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
+ */
+$IncludedByStateFilter.$inject = ['$state'];
+function $IncludedByStateFilter($state) {
+ var includesFilter = function (state) {
+ return $state.includes(state);
+ };
+ includesFilter.$stateful = true;
+ return includesFilter;
+}
+
+angular.module('ui.router.state')
+ .filter('isState', $IsStateFilter)
+ .filter('includedByState', $IncludedByStateFilter);
diff --git a/pool/shard004/JavaScript/0026751_homeController.js b/pool/shard004/JavaScript/0026751_homeController.js
new file mode 100644
index 0000000000000000000000000000000000000000..c0228d6de04e6a201e146ee89cda8ea0aeb2c79b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026751_homeController.js
@@ -0,0 +1,14 @@
+(function (){
+ var home = angular.module('home',['ngMaterial', 'util', 'erudioConfig']);
+
+ home.controller('HomeController',['$scope', 'Util', '$mdDialog', 'ErudioConfig', '$timeout', function($scope, Util, $mdDialog, ErudioConfig, $timeout){
+ //SETA O TITULO
+ Util.setTitulo('');
+ var attrAtiva = JSON.parse(sessionStorage.getItem("atribuicao-ativa"));
+ if (attrAtiva.grupo.nome === "Professor") {
+ $scope.professorTemplate = ErudioConfig.dominio+"/apps/professor/index/partials/index.html";
+ } else {
+ $scope.professorTemplate = "";
+ }
+ }]);
+})();
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026752_main.js b/pool/shard004/JavaScript/0026752_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..d72492c99a38b78dee5e0cb3592662260527c833
--- /dev/null
+++ b/pool/shard004/JavaScript/0026752_main.js
@@ -0,0 +1,87 @@
+/*global require, requirejs, define */
+// http://requirejs.org/docs/api.html#config
+requirejs.config(
+ {
+ baseUrl: 'scripts/',
+ waitSeconds: 50,
+ urlArgs: 'bust=' + ( new Date() ).getTime()
+ }
+);
+
+require(
+ [
+ 'src/process',
+ 'src/image',
+ 'src/file',
+ 'src/dragdrop',
+ 'src/controls',
+ 'src/export-button',
+ 'src/import-button',
+ 'src/random-button',
+ 'src/upload-imgur',
+ 'src/intro',
+ 'src/cam',
+ 'util/feature-test',
+ 'lib/signals-1.0.0'
+ ],
+ function(
+ process,
+ image,
+ file,
+ dragdrop,
+ controls,
+ export_button,
+ import_button,
+ random_button,
+ imgur,
+ intro,
+ cam,
+ testFeatures,
+ Signal
+ )
+ {
+ testFeatures( init, showError );
+
+ function init( supported_features )
+ {
+ var shared = {
+ feature: supported_features,
+ signals: {
+ 'load-file' : new Signal(),
+ 'image-loaded' : new Signal(),
+ 'set-new-src' : new Signal(),
+ 'control-set' : new Signal(),
+ 'control-updated' : new Signal(),
+ 'close-intro' : new Signal(),
+ 'image-data-url-requested' : new Signal()
+ }
+ };
+
+ process.init( shared );
+ dragdrop.init( shared );
+ export_button.init( shared );
+ controls.init( shared );
+ import_button.init( shared );
+ random_button.init( shared );
+ image.init( shared );
+ file.init( shared );
+ imgur.init( shared );
+ intro.init( shared );
+ cam.init( shared );
+ }
+
+ function showError( required_features )
+ {
+ var message = document.createElement( 'div' );
+
+ var message_text = 'sorry. it looks like your browser is missing some of the features ';
+ message_text += '(' + required_features.join( ', ' ) + ') that are required to run this ';
+ message_text += 'experiment.';
+
+ message.innerText = message_text;
+ message.className = 'missing-feature';
+
+ document.getElementsByTagName( 'body' )[0].appendChild( message );
+ }
+ }
+);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026753_sample.job.js b/pool/shard004/JavaScript/0026753_sample.job.js
new file mode 100644
index 0000000000000000000000000000000000000000..9201c2ea3e10e820d6f0000d35740f65b8a18fad
--- /dev/null
+++ b/pool/shard004/JavaScript/0026753_sample.job.js
@@ -0,0 +1,13 @@
+var current_valuation = 0;
+var current_karma = 0;
+
+setInterval(function() {
+ var last_valuation = current_valuation;
+ var last_karma = current_karma;
+ current_valuation = Math.floor(Math.random() * 100);
+ current_karma = Math.floor(Math.random() * 200000);
+
+ send_event('valuation', {current: current_valuation, last: last_valuation, title:'guy was here again'});
+ send_event('karma', {current: current_karma, last: last_karma});
+ send_event('Synergy', {value: Math.floor(Math.random() * 100)});
+}, 2 * 1000);
diff --git a/pool/shard004/JavaScript/0026755_server.js b/pool/shard004/JavaScript/0026755_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..a0bc6933657faf51481570fbc3549d3251de2888
--- /dev/null
+++ b/pool/shard004/JavaScript/0026755_server.js
@@ -0,0 +1,227 @@
+'use strict';
+var http = require('http');
+var port = 3001;
+
+var routeMap = {};
+var routeSupport = ['get', 'post', 'put', 'delete'];
+var callHistory = [];
+
+var ROOT_ENDPOINT = /^\/$/i;
+var API_ENDPOINT = /\/api/i;
+var CALL_HISTORY_ENDPOINT = /\/_call_requests/i;
+var COLON_TOKEN = /(:[^:\/]+)[^\/]?/gi;
+var COLON_REPLACE = '[^\/]+';
+
+var print = function(message) {
+ console.log([new Date(), message].join(':: '));
+};
+
+var requestIsRoot = function(req) {
+ return req.length === 0 || req.url.match(ROOT_ENDPOINT);
+};
+
+var requestIsHistory = function(req) {
+ return req.length === 0 || req.url.match(CALL_HISTORY_ENDPOINT);
+};
+
+var requestIsAPIRoute = function(req) {
+ return req.method.toLowerCase() === 'post' && req.url.match(API_ENDPOINT);
+};
+
+var isValidInt = function(value) {
+ var n = parseInt(value, 10);
+ return !isNaN(n) && value % 1 === 0;
+};
+
+var validateStatusCode = function(value) {
+ // Enhancement: Validate as proper HTTP status code.
+ return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
+};
+
+var validateDelay = function(value) {
+ // Enhancement: Validate as proper timespan.
+ return isValidInt(value) ? parseInt(value, 10) : Number.NaN;
+};
+
+var tokenizeURI = function(uri) {
+ return '^' + uri.replace(COLON_TOKEN, COLON_REPLACE) + '$';
+};
+
+var addRoute = function(route) {
+ var normalizedMethod = route.method.toLowerCase();
+ if(routeMap.hasOwnProperty(normalizedMethod)) {
+ route.regex = new RegExp(tokenizeURI(route.uri));
+ route.match = function(uri) {
+ return uri.match(this.regex);
+ };
+ routeMap[normalizedMethod].push(route);
+ }
+};
+
+var addToCallHistory = function(request, response) {
+ var callEntry = {
+ request: (typeof request === 'string') ? JSON.parse(request) : request,
+ response: (typeof response === 'string') ? JSON.parse(response) : response
+ };
+ callHistory.push(callEntry);
+ print('Added to history: ' + JSON.stringify(callEntry, null, 2));
+};
+
+var findRouteFromRequest = function(req) {
+ var routeList = routeMap[req.method.toLowerCase()];
+ var route;
+ var index;
+ if(routeList) {
+ index = routeList.length;
+ while(--index > -1) {
+ route = routeList[index];
+ if(route.match(req.url)) {
+ return route;
+ }
+ }
+ }
+ return undefined;
+};
+
+// Solution coutesy of:
+// http://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object
+var bodyParser = function(value) {
+ var data = value;
+ // Check if issuer passed as params.
+ if(!data.match(/^{(.*)/)) {
+ print('Recieved response payload as param string.');
+ data = JSON.parse('{"' + value.replace(/"/g, '\\"').replace(/&/g, '","').replace(/\=/g,'":"') + '"}');
+ data.response = JSON.parse(data.response.replace(/\\"/g, '"'));
+ print('Parsed and formatted to ' + JSON.stringify(data, null, 2));
+ }
+ // If not, assuming as json string.
+ else {
+ print('Received response payload as proper JSON string.');
+ data = JSON.parse(data);
+ print('Parsed and formatted as: ' + JSON.stringify(data, null, 2));
+ }
+ return data;
+};
+
+var establishRouteMap = function() {
+ while(routeSupport.length > 0) {
+ routeMap[routeSupport.shift()] = [];
+ }
+};
+
+var server = http.createServer(function(request, response) {
+ var data = '';
+ var body;
+
+ // Cross Domain.
+ response.setHeader('Access-Control-Allow-Origin', '*');
+ response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
+ response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
+ request.setEncoding('utf8');
+ request.on('data', function(chunk) {
+ data += chunk;
+ });
+
+ if(request.method === 'OPTIONS') {
+ request.on('end', function() {
+ response.writeHead(200);
+ response.end('\n');
+ print('OPTIONS request.');
+ });
+ }
+ else if(requestIsRoot(request)) {
+ request.on('end', function() {
+ body = JSON.stringify({result: 'hello, caddis!'}) + '\n';
+ response.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': body.length
+ });
+ response.end(body);
+ print('Root request.');
+ });
+ }
+ else if(requestIsHistory(request)) {
+ request.on('end', function() {
+ body = JSON.stringify(callHistory) + '\n';
+ response.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': body.length
+ });
+ response.end(body);
+ print('Call history request.');
+ print('Response: ' + body);
+ });
+ }
+ else if(requestIsAPIRoute(request)) {
+ request.on('end', function() {
+ var route = bodyParser(decodeURIComponent(data));
+ addRoute(route);
+ body = JSON.stringify({result: true}) + '\n';
+ response.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': body.length
+ });
+ response.end(body);
+ print('Route added to ' + route.method + '.');
+ print(JSON.stringify(route, null, 2));
+ });
+ }
+ else {
+ request.on('end', function() {
+ var route;
+ var delay;
+ var statusCode;
+ var timeout;
+ var respond;
+
+ route = findRouteFromRequest(request);
+ if(route !== undefined) {
+ delay = validateDelay(route.delay);
+ statusCode = validateStatusCode(route.status);
+ body = JSON.stringify(route.response) + '\n';
+ respond = function() {
+ response.writeHead(!isNaN(statusCode) ? statusCode : 200, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': body.length
+ });
+ response.end(body);
+
+ addToCallHistory({
+ method: request.method,
+ url: request.url,
+ statusCode: request.statusCode ? request.statusCode : 200,
+ body: data && data.length > 0 ? data : null
+ }, body);
+ };
+ print('Stored route found.');
+ print('Returning: ' + body +
+ 'after ' + (!isNaN(delay) ? delay : 0) +
+ ' milliseconds with status ' + (!isNaN(statusCode) ? statusCode : 200));
+ if(!isNaN(delay)) {
+ timeout = setTimeout(function() {
+ clearTimeout(timeout);
+ respond();
+ }, delay);
+ }
+ else {
+ respond();
+ }
+ }
+ else {
+ body = JSON.stringify({
+ message: request.url + ' not implemented.'
+ }) + '\n';
+ response.writeHead(501, {
+ 'Content-Type': 'application/json',
+ 'Content-Length': body.length
+ });
+ response.end(body);
+ }
+ });
+ }
+});
+
+establishRouteMap();
+server.listen(port);
+
+print(new Date() + ':: Caddis started on port ' + port + '.');
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026756_rpad.js b/pool/shard004/JavaScript/0026756_rpad.js
new file mode 100644
index 0000000000000000000000000000000000000000..bd139096d61822ae967f459d2fb6f88be9e4637f
--- /dev/null
+++ b/pool/shard004/JavaScript/0026756_rpad.js
@@ -0,0 +1,15 @@
+'use strict';
+
+var mout = require('mout');
+
+function rpad(Handlebars) {
+ Handlebars.registerHelper('rpad', function (context) {
+ var hash = context.hash;
+ var length = parseInt(hash.length, 10);
+ var chr = hash.char;
+
+ return mout.string.rpad(context.fn(this), length, chr);
+ });
+}
+
+module.exports = rpad;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026758_access-token.js b/pool/shard004/JavaScript/0026758_access-token.js
new file mode 100644
index 0000000000000000000000000000000000000000..731371254683d22508858567b288f8bb6b3b491a
--- /dev/null
+++ b/pool/shard004/JavaScript/0026758_access-token.js
@@ -0,0 +1,229 @@
+/*!
+ * Module Dependencies.
+ */
+
+var loopback = require('../../lib/loopback');
+var assert = require('assert');
+var uid = require('uid2');
+var DEFAULT_TOKEN_LEN = 64;
+
+/**
+ * Token based authentication and access control.
+ *
+ * **Default ACLs**
+ *
+ * - DENY EVERYONE `*`
+ * - ALLOW EVERYONE create
+ *
+ * @property {String} id Generated token ID.
+ * @property {Number} ttl Time to live in seconds, 2 weeks by default.
+ * @property {Date} created When the token was created.
+ * @property {Object} settings Extends the `Model.settings` object.
+ * @property {Number} settings.accessTokenIdLength Length of the base64-encoded string access token. Default value is 64.
+ * Increase the length for a more secure access token.
+ *
+ * @class AccessToken
+ * @inherits {PersistedModel}
+ */
+
+module.exports = function(AccessToken) {
+
+ // Workaround for https://github.com/strongloop/loopback/issues/292
+ AccessToken.definition.rawProperties.created.default =
+ AccessToken.definition.properties.created.default = function() {
+ return new Date();
+ };
+
+ /**
+ * Anonymous Token
+ *
+ * ```js
+ * assert(AccessToken.ANONYMOUS.id === '$anonymous');
+ * ```
+ */
+
+ AccessToken.ANONYMOUS = new AccessToken({id: '$anonymous'});
+
+ /**
+ * Create a cryptographically random access token id.
+ *
+ * @callback {Function} callback
+ * @param {Error} err
+ * @param {String} token
+ */
+
+ AccessToken.createAccessTokenId = function(fn) {
+ uid(this.settings.accessTokenIdLength || DEFAULT_TOKEN_LEN, function(err, guid) {
+ if (err) {
+ fn(err);
+ } else {
+ fn(null, guid);
+ }
+ });
+ };
+
+ /*!
+ * Hook to create accessToken id.
+ */
+ AccessToken.observe('before save', function(ctx, next) {
+ if (!ctx.instance || ctx.instance.id) {
+ // We are running a partial update or the instance already has an id
+ return next();
+ }
+
+ AccessToken.createAccessTokenId(function(err, id) {
+ if (err) return next(err);
+ ctx.instance.id = id;
+ next();
+ });
+ });
+
+ /**
+ * Find a token for the given `ServerRequest`.
+ *
+ * @param {ServerRequest} req
+ * @param {Object} [options] Options for finding the token
+ * @callback {Function} callback
+ * @param {Error} err
+ * @param {AccessToken} token
+ */
+
+ AccessToken.findForRequest = function(req, options, cb) {
+ if (cb === undefined && typeof options === 'function') {
+ cb = options;
+ options = {};
+ }
+
+ var id = tokenIdForRequest(req, options);
+
+ if (id) {
+ this.findById(id, function(err, token) {
+ if (err) {
+ cb(err);
+ } else if (token) {
+ token.validate(function(err, isValid) {
+ if (err) {
+ cb(err);
+ } else if (isValid) {
+ cb(null, token);
+ } else {
+ var e = new Error('Invalid Access Token');
+ e.status = e.statusCode = 401;
+ e.code = 'INVALID_TOKEN';
+ cb(e);
+ }
+ });
+ } else {
+ cb();
+ }
+ });
+ } else {
+ process.nextTick(function() {
+ cb();
+ });
+ }
+ };
+
+ /**
+ * Validate the token.
+ *
+ * @callback {Function} callback
+ * @param {Error} err
+ * @param {Boolean} isValid
+ */
+
+ AccessToken.prototype.validate = function(cb) {
+ try {
+ assert(
+ this.created && typeof this.created.getTime === 'function',
+ 'token.created must be a valid Date'
+ );
+ assert(this.ttl !== 0, 'token.ttl must be not be 0');
+ assert(this.ttl, 'token.ttl must exist');
+ assert(this.ttl >= -1, 'token.ttl must be >= -1');
+
+ var now = Date.now();
+ var created = this.created.getTime();
+ var elapsedSeconds = (now - created) / 1000;
+ var secondsToLive = this.ttl;
+ var isValid = elapsedSeconds < secondsToLive;
+
+ if (isValid) {
+ cb(null, isValid);
+ } else {
+ this.destroy(function(err) {
+ cb(err, isValid);
+ });
+ }
+ } catch (e) {
+ cb(e);
+ }
+ };
+
+ function tokenIdForRequest(req, options) {
+ var params = options.params || [];
+ var headers = options.headers || [];
+ var cookies = options.cookies || [];
+ var i = 0;
+ var length;
+ var id;
+
+ params = params.concat(['access_token']);
+ headers = headers.concat(['X-Access-Token', 'authorization']);
+ cookies = cookies.concat(['access_token', 'authorization']);
+
+ for (length = params.length; i < length; i++) {
+ var param = params[i];
+ // replacement for deprecated req.param()
+ id = req.params && req.params[param] !== undefined ? req.params[param] :
+ req.body && req.body[param] !== undefined ? req.body[param] :
+ req.query && req.query[param] !== undefined ? req.query[param] :
+ undefined;
+
+ if (typeof id === 'string') {
+ return id;
+ }
+ }
+
+ for (i = 0, length = headers.length; i < length; i++) {
+ id = req.header(headers[i]);
+
+ if (typeof id === 'string') {
+ // Add support for oAuth 2.0 bearer token
+ // http://tools.ietf.org/html/rfc6750
+ if (id.indexOf('Bearer ') === 0) {
+ id = id.substring(7);
+ // Decode from base64
+ var buf = new Buffer(id, 'base64');
+ id = buf.toString('utf8');
+ } else if (/^Basic /i.test(id)) {
+ id = id.substring(6);
+ id = (new Buffer(id, 'base64')).toString('utf8');
+ // The spec says the string is user:pass, so if we see both parts
+ // we will assume the longer of the two is the token, so we will
+ // extract "a2b2c3" from:
+ // "a2b2c3"
+ // "a2b2c3:" (curl http://a2b2c3@localhost:3000/)
+ // "token:a2b2c3" (curl http://token:a2b2c3@localhost:3000/)
+ // ":a2b2c3"
+ var parts = /^([^:]*):(.*)$/.exec(id);
+ if (parts) {
+ id = parts[2].length > parts[1].length ? parts[2] : parts[1];
+ }
+ }
+ return id;
+ }
+ }
+
+ if (req.signedCookies) {
+ for (i = 0, length = cookies.length; i < length; i++) {
+ id = req.signedCookies[cookies[i]];
+
+ if (typeof id === 'string') {
+ return id;
+ }
+ }
+ }
+ return null;
+ }
+};
diff --git a/pool/shard004/JavaScript/0026759_build_js_hardware.js b/pool/shard004/JavaScript/0026759_build_js_hardware.js
new file mode 100644
index 0000000000000000000000000000000000000000..53e1b19a2df28c247972f5ffdbea9e31349f9a1f
--- /dev/null
+++ b/pool/shard004/JavaScript/0026759_build_js_hardware.js
@@ -0,0 +1,141 @@
+#!/bin/node
+/* This builds a js file containing the addresses of a chip's peripherals and
+ the values of the bits in each register. Can be used for quickly building
+ ways to access the underlying hardware from JS */
+
+var INPUTFILE = "targetlibs/stm32f1/lib/stm32f10x.h";
+var definitions = {"STM32F10X_XL":true};
+//var INPUTFILE = "targetlibs/stm32f4/lib/stm32f4xx.h";
+//var definitions = {"STM32F401xx":true};
+var fs = require('fs');
+
+var structContents = undefined;
+var structSize = 0;
+var typeSizes = {
+ "uint32_t" : 4,
+ "uint16_t" : 2,
+ "uint8_t" : 1,
+ "CAN_FIFOMailBox_TypeDef" : NaN,
+ "CAN_TxMailBox_TypeDef" : NaN,
+ "CAN_FilterRegister_TypeDef" : NaN,
+};
+var ifDefs = [];
+
+
+var structs = {};
+
+
+fs.readFileSync(INPUTFILE).toString().replace(/(\/\*[^\n*]*)\r\n(.*\*\/)/g,"$1$2").split("\n").forEach(function(oline) {
+ //console.log(JSON.stringify(oline));
+ var line = oline.trim();
+ if (line=="") return;
+ if (line.indexOf("#ifndef ")==0) {
+ ifDefs.push(!(line.substr(8).trim() in definitions));
+ return;
+ } else if (line.indexOf("#ifdef ")==0) {
+ ifDefs.push((line.substr(7).trim() in definitions));
+ return;
+ } else if (line.indexOf("#if ")==0) {
+ console.warn("Uh-oh, we have a #if - assuming it is true:"+line);
+ ifDefs.push(true);
+ return;
+ } else if (line.indexOf("#else")==0) {
+ ifDefs[ifDefs.length-1] = !ifDefs[ifDefs.length-1];
+ return;
+ } else if (line.indexOf("#endif")==0) {
+ ifDefs.pop();
+ return;
+ }
+
+ for (var i in ifDefs)
+ if (!ifDefs[i]) return;
+
+ if (line.indexOf("#error ")==0) {
+ console.warn(line);
+ }
+
+
+ if (line.indexOf("#define")==0) {
+ line = line.substr(7).trim();
+ var i = line.indexOf(" ");
+ var dkey = line.substr(0,i);
+ var dval = line.substr(i).trim();
+ if (dval.indexOf("/*")>=0) dval = dval.substr(0,dval.indexOf("/*")).trim();
+ definitions[dkey] = dval.replace(/\(uint32_t[ ]*\)/,"");
+ } else if (line=="typedef struct") {
+ structContents = {};
+ structSize = 0;
+ } else if (line[0]=="{") {
+ } else if (line[0]=="}") {
+ if (line.indexOf("_TypeDef;")>=0) {
+ var name = line.substring(line.lastIndexOf(" ")+1,line.indexOf("_TypeDef;"));
+ structs[name] = structContents;
+ }
+ structContents = undefined;
+ } else if (structContents) {
+ if (line.substr(0,2)!="/*") {
+ if (line.substr(0,2)=="__") line=line.substr(line.indexOf(" ")+1);
+ var type = line.substr(0,line.indexOf(" "));
+ line = line.substr(line.indexOf(" ")+1).trim();
+ var name = line.substr(0,line.indexOf(";"));
+ line = line.substr(line.indexOf(";")+1).trim();
+ if (!(type in typeSizes)) throw new Error("Unknown type "+type+" in "+JSON.stringify(oline));
+ var size = typeSizes[type];
+
+ if (name.indexOf("[")>=0) {
+ var c = name.substring(name.indexOf("[")+1, name.indexOf("]"));
+ size *= c;
+ }
+ structContents[name] = { offset : structSize, size : size };
+ structSize += size;
+ }
+ }
+});
+
+//console.log(structs)
+
+// find base addresses
+var bases = {};
+for (var def in definitions) {
+ if (def.substr(-5)=="_BASE") {
+ var v = definitions[def].
+ replace(/(\()([A-Z])/,"$1 $2").
+ replace(/([A-Z])(\))/,"$1 $2").
+ split(" ");
+ v = v.map(function(tk) {
+ if (tk in bases) return bases[tk];
+ return tk;
+ });
+ bases[def] = eval(v.join(""));
+ }
+}
+
+var peripherals = ["RCC","DMA"];
+
+
+function out(s) {
+ console.log(s);
+}
+
+peripherals.forEach(function(periph) {
+ var base = bases[periph+"_BASE"];
+ var data = { a : {}, f : {} };
+ for (var key in structs[periph]) {
+ if (key.substr(0,8)=="RESERVED") continue;
+ // address
+ data.a[key] = base+structs[periph][key].offset;
+ // flags
+ var pref = periph+"_"+key+"_";
+ for (var d in definitions) {
+ if (d.substr(0,pref.length)==pref) {
+ if (!data.f[key]) data.f[key] = {};
+ try {
+ data.f[key][d.substr(pref.length)] = eval(definitions[d]);
+ } catch (e) {}
+ }
+ }
+ }
+
+ // output
+ out("var "+periph+" = "+JSON.stringify(data,null,2)+";");
+});
diff --git a/pool/shard004/JavaScript/0026760_ext-whitespace.js b/pool/shard004/JavaScript/0026760_ext-whitespace.js
new file mode 100644
index 0000000000000000000000000000000000000000..aded52be233cf7e7df89eb1ec401a5c5235c4c75
--- /dev/null
+++ b/pool/shard004/JavaScript/0026760_ext-whitespace.js
@@ -0,0 +1,185 @@
+define("ace/ext/whitespace",["require","exports","module","ace/lib/lang"], function(require, exports, module) {
+"use strict";
+
+var lang = require("../lib/lang");
+exports.$detectIndentation = function(lines, fallback) {
+ var stats = [];
+ var changes = [];
+ var tabIndents = 0;
+ var prevSpaces = 0;
+ var max = Math.min(lines.length, 1000);
+ for (var i = 0; i < max; i++) {
+ var line = lines[i];
+ if (!/^\s*[^*+\-\s]/.test(line))
+ continue;
+
+ if (line[0] == "\t") {
+ tabIndents++;
+ prevSpaces = -Number.MAX_VALUE;
+ } else {
+ var spaces = line.match(/^ */)[0].length;
+ if (spaces && line[spaces] != "\t") {
+ var diff = spaces - prevSpaces;
+ if (diff > 0 && !(prevSpaces%diff) && !(spaces%diff))
+ changes[diff] = (changes[diff] || 0) + 1;
+
+ stats[spaces] = (stats[spaces] || 0) + 1;
+ }
+ prevSpaces = spaces;
+ }
+ while (i < max && line[line.length - 1] == "/")
+ line = lines[i++];
+ }
+
+ function getScore(indent) {
+ var score = 0;
+ for (var i = indent; i < stats.length; i += indent)
+ score += stats[i] || 0;
+ return score;
+ }
+
+ var changesTotal = changes.reduce(function(a,b){return a+b}, 0);
+
+ var first = {score: 0, length: 0};
+ var spaceIndents = 0;
+ for (var i = 1; i < 12; i++) {
+ var score = getScore(i);
+ if (i == 1) {
+ spaceIndents = score;
+ score = stats[1] ? 0.9 : 0.8;
+ if (!stats.length)
+ score = 0;
+ } else
+ score /= spaceIndents;
+
+ if (changes[i])
+ score += changes[i] / changesTotal;
+
+ if (score > first.score)
+ first = {score: score, length: i};
+ }
+
+ if (first.score && first.score > 1.4)
+ var tabLength = first.length;
+
+ if (tabIndents > spaceIndents + 1) {
+ if (tabLength == 1 || spaceIndents < tabIndents / 4 || first.score < 1.8)
+ tabLength = undefined;
+ return {ch: "\t", length: tabLength};
+ }
+ if (spaceIndents > tabIndents + 1)
+ return {ch: " ", length: tabLength};
+};
+
+exports.detectIndentation = function(session) {
+ var lines = session.getLines(0, 1000);
+ var indent = exports.$detectIndentation(lines) || {};
+
+ if (indent.ch)
+ session.setUseSoftTabs(indent.ch == " ");
+
+ if (indent.length)
+ session.setTabSize(indent.length);
+ return indent;
+};
+
+exports.trimTrailingSpace = function(session, trimEmpty) {
+ var doc = session.getDocument();
+ var lines = doc.getAllLines();
+
+ var min = trimEmpty ? -1 : 0;
+
+ for (var i = 0, l=lines.length; i < l; i++) {
+ var line = lines[i];
+ var index = line.search(/\s+$/);
+
+ if (index > min)
+ doc.removeInLine(i, index, line.length);
+ }
+};
+
+exports.convertIndentation = function(session, ch, len) {
+ var oldCh = session.getTabString()[0];
+ var oldLen = session.getTabSize();
+ if (!len) len = oldLen;
+ if (!ch) ch = oldCh;
+
+ var tab = ch == "\t" ? ch: lang.stringRepeat(ch, len);
+
+ var doc = session.doc;
+ var lines = doc.getAllLines();
+
+ var cache = {};
+ var spaceCache = {};
+ for (var i = 0, l=lines.length; i < l; i++) {
+ var line = lines[i];
+ var match = line.match(/^\s*/)[0];
+ if (match) {
+ var w = session.$getStringScreenWidth(match)[0];
+ var tabCount = Math.floor(w/oldLen);
+ var reminder = w%oldLen;
+ var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
+ toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
+
+ if (toInsert != match) {
+ doc.removeInLine(i, 0, match.length);
+ doc.insertInLine({row: i, column: 0}, toInsert);
+ }
+ }
+ }
+ session.setTabSize(len);
+ session.setUseSoftTabs(ch == " ");
+};
+
+exports.$parseStringArg = function(text) {
+ var indent = {};
+ if (/t/.test(text))
+ indent.ch = "\t";
+ else if (/s/.test(text))
+ indent.ch = " ";
+ var m = text.match(/\d+/);
+ if (m)
+ indent.length = parseInt(m[0], 10);
+ return indent;
+};
+
+exports.$parseArg = function(arg) {
+ if (!arg)
+ return {};
+ if (typeof arg == "string")
+ return exports.$parseStringArg(arg);
+ if (typeof arg.text == "string")
+ return exports.$parseStringArg(arg.text);
+ return arg;
+};
+
+exports.commands = [{
+ name: "detectIndentation",
+ exec: function(editor) {
+ exports.detectIndentation(editor.session);
+ }
+}, {
+ name: "trimTrailingSpace",
+ exec: function(editor) {
+ exports.trimTrailingSpace(editor.session);
+ }
+}, {
+ name: "convertIndentation",
+ exec: function(editor, arg) {
+ var indent = exports.$parseArg(arg);
+ exports.convertIndentation(editor.session, indent.ch, indent.length);
+ }
+}, {
+ name: "setIndentation",
+ exec: function(editor, arg) {
+ var indent = exports.$parseArg(arg);
+ indent.length && editor.session.setTabSize(indent.length);
+ indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
+ }
+}];
+
+});
+ (function() {
+ window.require(["ace/ext/whitespace"], function() {});
+ })();
+
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026762_Blog.js b/pool/shard004/JavaScript/0026762_Blog.js
new file mode 100644
index 0000000000000000000000000000000000000000..0b3c252a6b78cf57fb72e0b3c1a2792d1d294cc1
--- /dev/null
+++ b/pool/shard004/JavaScript/0026762_Blog.js
@@ -0,0 +1,206 @@
+'use strict';
+
+angular.module('adminApp')
+ .controller('BlogCtrl', ['$scope', 'Bloggers', 'BlogPosts',
+ function($scope, Bloggers, BlogPosts) {
+ var date = new Date();
+ Bloggers.getBlogger(function(bloggers) {
+ $scope.bloggers = bloggers;
+
+ $scope.current = $scope.bloggers[0] || {};
+ });
+
+
+ /**
+ * Methods for Bloggers
+ *
+ */
+ $scope.selectBlogger = function(place) {
+ $scope.current = $scope.bloggers[place];
+ };
+
+ $scope.saveBlogger = function(argument) {
+ var b = $scope.current;
+ if (b.id) {
+ Bloggers.save(b, function(blogger) {
+ var i;
+ for (i = 0; i < $scope.bloggers.length; i++) {
+ if (blogger.id === $scope.bloggers[i].id) {
+ return $scope.bloggers[i] = blogger;
+ }
+ }
+ });
+ }
+ else {
+ Bloggers.add(b, function(blogger) {
+ $scope.bloggers.push(blogger);
+ $scope.current = blogger;
+ });
+ }
+ };
+
+ $scope.addBlogger = function() {
+ $scope.current = {
+ name: 'Nom',
+ header: 'images/site/tooski.png',
+ ad: ['images/site/tooski.png', ],
+ sponsors: ['images/site/tooski.png', ],
+ profilePic: 'images/site/profile.png',
+ biography: 'Biographie',
+ linkResults: 'http://'
+ };
+ return $scope.current;
+ };
+
+ $scope.deleteBlogger = function() {
+ if (confirm('Voulez-vous vraiment supprimer le blogger: ' +
+ $scope.current.name + ' ?')) {
+ Bloggers.delete($scope.current, function() {
+ var i;
+ for (i = 0; i < $scope.bloggers.length; i++) {
+ if ($scope.bloggers[i].id === $scope.current
+ .id) {
+ $scope.current = $scope.bloggers[0] ||
+ $scope.addBlogger();
+ return $scope.bloggers.splice(i, 1);
+ }
+ }
+ });
+ }
+ };
+
+ $scope.changePortrait = function(url) {
+ $scope.current.profilePic = url;
+ };
+
+ $scope.changeHeader = function(url) {
+ $scope.current.header = url;
+ };
+ $scope.addSponsors = function(url) {
+ $scope.current.sponsors.push(url);
+ };
+ $scope.addAd = function(url) {
+ $scope.current.ad.push(url);
+ };
+
+ $scope.removeSponsor = function(sponsor) {
+ var pos = $scope.current.sponsors.indexOf(sponsor);
+ $scope.current.sponsors.splice(pos, 1);
+ };
+
+ $scope.removeAd = function(ad) {
+ var pos = $scope.current.ad.indexOf(ad);
+ $scope.current.ad.splice(pos, 1);
+ };
+
+ /**
+ * Methods for BlogPosts
+ */
+
+ $scope.$watch('current', function(value) {
+ if (!value || !value.id) {
+ value = {
+ id: 0,
+ date: date,
+ };
+ }
+ BlogPosts.get(value.id, function(posts) {
+ $scope.blogPosts = posts;
+ $scope.newPost();
+ })
+ });
+
+ $scope.newPost = function() {
+ return $scope.currentPost = {
+ title: '',
+ date: date,
+ content: '',
+ blogId: $scope.current.id,
+ };
+ };
+
+ $scope.insertBlogImage = function(img) {
+ $scope.currentPost.content += '
';
+ };
+
+ $scope.savePost = function() {
+ var p = $scope.currentPost,
+ b = $scope.current,
+ newsDate = document.getElementById('newsDate')
+ .value.split('/');
+ p.date = (new Date(newsDate[2], (newsDate[1] - 1),
+ newsDate[0]))
+ .toISOString();
+ if (p.date === (new Date(date.getFullYear(), date.getMonth(),
+ date.getDate()))
+ .toISOString()) {
+ p.date = date.toISOString();
+ }
+ if (!b.id) {
+ return alert(
+ 'Il faut d\'abord créer le blogger et après écrire un post.'
+ );
+ }
+ if (p.id) {
+ BlogPosts.save(b.id, p, function(post) {
+ var i;
+ $scope.currentPost = post;
+ for (i = 0; i < $scope.blogPosts.length; i++) {
+ if ($scope.blogPosts[i].id === post.id) {
+ $scope.blogPosts[i] = post;
+ }
+ }
+ });
+ }
+ else {
+ BlogPosts.add(b.id, p, function(post) {
+ $scope.blogPosts.push(post);
+ $scope.currentPost = post;
+ });
+ }
+ };
+
+ $scope.deletePost = function(place) {
+ var p = $scope.blogPosts[place],
+ b = $scope.current;
+ if (confirm('Voulez-vous supprimer le post: ' + p.title +
+ ' ?')) {
+ BlogPosts.del(b.id, p.id, function() {
+ $scope.blogPosts.splice(place, 1);
+ });
+ }
+ };
+
+ $scope.selectPost = function(place) {
+ $scope.currentPost = $scope.blogPosts[place];
+ };
+
+
+ /**
+ * Options for TinyMCE
+ *
+ */
+ $scope.tinymceOptionsBio = {
+ selector: '#bioContent',
+ theme: 'modern',
+ fontsize_formats: "8pt 9pt 10pt 11pt 12pt 26pt 36pt",
+ toolbar1: 'bold italic | alignleft aligncenter alignright alignjustify | bullist | styleselect | fontselect | fontsizeselect',
+ image_advtab: true,
+ };
+
+ $scope.tinymceOptionsNews = {
+ selector: '#newsContent',
+ theme: 'modern',
+ fontsize_formats: "8pt 9pt 10pt 11pt 12pt 26pt 36pt",
+ plugins: [
+ 'advlist autolink lists link image charmap print preview hr anchor pagebreak',
+ 'searchreplace wordcount visualblocks visualchars code fullscreen',
+ 'insertdatetime media nonbreaking table contextmenu directionality',
+ 'emoticons template paste textcolor'
+ ],
+ toolbar1: 'undo redo | styleselect | fontselect | fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons',
+ image_advtab: true
+ };
+ }
+ ]);
diff --git a/pool/shard004/JavaScript/0026767_utility.js b/pool/shard004/JavaScript/0026767_utility.js
new file mode 100644
index 0000000000000000000000000000000000000000..2f8ae30361dedc309377f3b9cd2d3e1733713a52
--- /dev/null
+++ b/pool/shard004/JavaScript/0026767_utility.js
@@ -0,0 +1,203 @@
+/**
+ * PowerTip Utility Functions
+ *
+ * @fileoverview Private helper functions.
+ * @link https://stevenbenner.github.io/jquery-powertip/
+ * @author Steven Benner (https://stevenbenner.com/)
+ * @requires jQuery 1.7+
+ */
+
+/**
+ * Determine whether a jQuery object is an SVG element
+ * @private
+ * @param {jQuery} element The element to check
+ * @return {boolean} Whether this is an SVG element
+ */
+function isSvgElement(element) {
+ return Boolean(window.SVGElement && element[0] instanceof SVGElement);
+}
+
+/**
+ * Determines if the specified jQuery.Event object has mouse data.
+ * @private
+ * @param {jQuery.Event=} event The jQuery.Event object to test.
+ * @return {boolean} True if there is mouse data, otherwise false.
+ */
+function isMouseEvent(event) {
+ return Boolean(event && $.inArray(event.type, MOUSE_EVENTS) > -1 &&
+ typeof event.pageX === 'number');
+}
+
+/**
+ * Initializes the viewport dimension cache and hooks up the mouse position
+ * tracking and viewport dimension tracking events.
+ * Prevents attaching the events more than once.
+ * @private
+ */
+function initTracking() {
+ if (!session.mouseTrackingActive) {
+ session.mouseTrackingActive = true;
+
+ // grab the current viewport dimensions on load
+ getViewportDimensions();
+ $(getViewportDimensions);
+
+ // hook mouse move tracking
+ $document.on('mousemove' + EVENT_NAMESPACE, trackMouse);
+
+ // hook viewport dimensions tracking
+ $window.on('resize' + EVENT_NAMESPACE, trackResize);
+ $window.on('scroll' + EVENT_NAMESPACE, trackScroll);
+ }
+}
+
+/**
+ * Updates the viewport dimensions cache.
+ * @private
+ */
+function getViewportDimensions() {
+ session.scrollLeft = $window.scrollLeft();
+ session.scrollTop = $window.scrollTop();
+ session.windowWidth = $window.width();
+ session.windowHeight = $window.height();
+}
+
+/**
+ * Updates the window size info in the viewport dimensions cache.
+ * @private
+ */
+function trackResize() {
+ session.windowWidth = $window.width();
+ session.windowHeight = $window.height();
+}
+
+/**
+ * Updates the scroll offset info in the viewport dimensions cache.
+ * @private
+ */
+function trackScroll() {
+ var x = $window.scrollLeft(),
+ y = $window.scrollTop();
+ if (x !== session.scrollLeft) {
+ session.currentX += x - session.scrollLeft;
+ session.scrollLeft = x;
+ }
+ if (y !== session.scrollTop) {
+ session.currentY += y - session.scrollTop;
+ session.scrollTop = y;
+ }
+}
+
+/**
+ * Saves the current mouse coordinates to the session object.
+ * @private
+ * @param {jQuery.Event} event The mousemove event for the document.
+ */
+function trackMouse(event) {
+ session.currentX = event.pageX;
+ session.currentY = event.pageY;
+}
+
+/**
+ * Tests if the mouse is currently over the specified element.
+ * @private
+ * @param {jQuery} element The element to check for hover.
+ * @return {boolean} True if the mouse is over the element, otherwise false.
+ */
+function isMouseOver(element) {
+ // use getBoundingClientRect() because jQuery's width() and height()
+ // methods do not work with SVG elements
+ // compute width/height because those properties do not exist on the object
+ // returned by getBoundingClientRect() in older versions of IE
+ var elementPosition = element.offset(),
+ elementBox = element[0].getBoundingClientRect(),
+ elementWidth = elementBox.right - elementBox.left,
+ elementHeight = elementBox.bottom - elementBox.top;
+
+ return session.currentX >= elementPosition.left &&
+ session.currentX <= elementPosition.left + elementWidth &&
+ session.currentY >= elementPosition.top &&
+ session.currentY <= elementPosition.top + elementHeight;
+}
+
+/**
+ * Fetches the tooltip content from the specified element's data attributes.
+ * @private
+ * @param {jQuery} element The element to get the tooltip content for.
+ * @return {(string|jQuery|undefined)} The text/HTML string, jQuery object, or
+ * undefined if there was no tooltip content for the element.
+ */
+function getTooltipContent(element) {
+ var tipText = element.data(DATA_POWERTIP),
+ tipObject = element.data(DATA_POWERTIPJQ),
+ tipTarget = element.data(DATA_POWERTIPTARGET),
+ targetElement,
+ content;
+
+ if (tipText) {
+ if ($.isFunction(tipText)) {
+ tipText = tipText.call(element[0]);
+ }
+ content = tipText;
+ } else if (tipObject) {
+ if ($.isFunction(tipObject)) {
+ tipObject = tipObject.call(element[0]);
+ }
+ if (tipObject.length > 0) {
+ content = tipObject.clone(true, true);
+ }
+ } else if (tipTarget) {
+ targetElement = $('#' + tipTarget);
+ if (targetElement.length > 0) {
+ content = targetElement.html();
+ }
+ }
+
+ return content;
+}
+
+/**
+ * Finds any viewport collisions that an element (the tooltip) would have if it
+ * were absolutely positioned at the specified coordinates.
+ * @private
+ * @param {CSSCoordinates} coords Coordinates for the element.
+ * @param {number} elementWidth Width of the element in pixels.
+ * @param {number} elementHeight Height of the element in pixels.
+ * @return {number} Value with the collision flags.
+ */
+function getViewportCollisions(coords, elementWidth, elementHeight) {
+ var viewportTop = session.scrollTop,
+ viewportLeft = session.scrollLeft,
+ viewportBottom = viewportTop + session.windowHeight,
+ viewportRight = viewportLeft + session.windowWidth,
+ collisions = Collision.none;
+
+ if (coords.top < viewportTop || Math.abs(coords.bottom - session.windowHeight) - elementHeight < viewportTop) {
+ collisions |= Collision.top;
+ }
+ if (coords.top + elementHeight > viewportBottom || Math.abs(coords.bottom - session.windowHeight) > viewportBottom) {
+ collisions |= Collision.bottom;
+ }
+ if (coords.left < viewportLeft || coords.right + elementWidth > viewportRight) {
+ collisions |= Collision.left;
+ }
+ if (coords.left + elementWidth > viewportRight || coords.right < viewportLeft) {
+ collisions |= Collision.right;
+ }
+
+ return collisions;
+}
+
+/**
+ * Counts the number of bits set on a flags value.
+ * @param {number} value The flags value.
+ * @return {number} The number of bits that have been set.
+ */
+function countFlags(value) {
+ var count = 0;
+ while (value) {
+ value &= value - 1;
+ count++;
+ }
+ return count;
+}
diff --git a/pool/shard004/JavaScript/0026770_bufferBody.js b/pool/shard004/JavaScript/0026770_bufferBody.js
new file mode 100644
index 0000000000000000000000000000000000000000..91154aecdc6eece24f75252c2e6ba2ec8100c32d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026770_bufferBody.js
@@ -0,0 +1,30 @@
+const {
+ always, assoc, both, compose, curryN, ifElse,
+ is, objOf, path, pathOr
+} = require('ramda')
+
+const { assocWithP, resolve } = require('@articulate/funky')
+const rawBody = curryN(2, require('raw-body'))
+const typer = require('media-typer')
+
+const contentLength =
+ compose(Number, path(['headers', 'content-length']))
+
+const readableBody =
+ compose(is(Function), path(['body', '_read']))
+
+const bufferable =
+ both(contentLength, readableBody)
+
+const readBody = req =>
+ Promise.resolve(req)
+ .then(typer.parse)
+ .then(pathOr('utf8', ['parameters', 'charset']))
+ .catch(always('utf8'))
+ .then(objOf('encoding'))
+ .then(assoc('length', contentLength(req)))
+ .then(rawBody(req.body))
+
+// bufferBody :: Request -> Promise Request
+exports.bufferBody =
+ ifElse(bufferable, assocWithP('body', readBody), resolve)
diff --git a/pool/shard004/JavaScript/0026774_event-dialog.controller.js b/pool/shard004/JavaScript/0026774_event-dialog.controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..9629fc5f95ddb71553175ff04fc0c8c4826aa3ab
--- /dev/null
+++ b/pool/shard004/JavaScript/0026774_event-dialog.controller.js
@@ -0,0 +1,41 @@
+'use strict';
+
+angular.module('chefsApp').controller('EventDialogController',
+ ['$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Event', 'User', 'Recipe', 'SocialEntity',
+ function($scope, $stateParams, $uibModalInstance, $q, entity, Event, User, Recipe, SocialEntity) {
+
+ $scope.event = entity;
+ $scope.users = User.query();
+ $scope.recipes = Recipe.query();
+ $scope.socialentitys = SocialEntity.query({filter: 'event-is-null'});
+ $q.all([$scope.event.$promise, $scope.socialentitys.$promise]).then(function() {
+ if (!$scope.event.socialEntity.id) {
+ return $q.reject();
+ }
+ return SocialEntity.get({id : $scope.event.socialEntity.id}).$promise;
+ }).then(function(socialEntity) {
+ $scope.socialentitys.push(socialEntity);
+ });
+ $scope.load = function(id) {
+ Event.get({id : id}, function(result) {
+ $scope.event = result;
+ });
+ };
+
+ var onSaveFinished = function (result) {
+ $scope.$emit('chefsApp:eventUpdate', result);
+ $uibModalInstance.close(result);
+ };
+
+ $scope.save = function () {
+ if ($scope.event.id != null) {
+ Event.update($scope.event, onSaveFinished);
+ } else {
+ Event.save($scope.event, onSaveFinished);
+ }
+ };
+
+ $scope.clear = function() {
+ $uibModalInstance.dismiss('cancel');
+ };
+}]);
diff --git a/pool/shard004/JavaScript/0026779_bootstrap-table-fa-IR.js b/pool/shard004/JavaScript/0026779_bootstrap-table-fa-IR.js
new file mode 100644
index 0000000000000000000000000000000000000000..8e5377322c6d6c330219fd3dfe7e206e2d65bc92
--- /dev/null
+++ b/pool/shard004/JavaScript/0026779_bootstrap-table-fa-IR.js
@@ -0,0 +1,56 @@
+(function (global, factory) {
+ if (typeof define === "function" && define.amd) {
+ define([], factory);
+ } else if (typeof exports !== "undefined") {
+ factory();
+ } else {
+ var mod = {
+ exports: {}
+ };
+ factory();
+ global.bootstrapTableFaIR = mod.exports;
+ }
+})(this, function () {
+ 'use strict';
+
+ /**
+ * Bootstrap Table Persian translation
+ * Author: MJ Vakili
+ */
+ (function ($) {
+ $.fn.bootstrapTable.locales['fa-IR'] = {
+ formatLoadingMessage: function formatLoadingMessage() {
+ return 'در حال بارگذاری, لطفا صبر کنید...';
+ },
+ formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
+ return pageNumber + ' \u0631\u06A9\u0648\u0631\u062F \u062F\u0631 \u0635\u0641\u062D\u0647';
+ },
+ formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows) {
+ return '\u0646\u0645\u0627\u06CC\u0634 ' + pageFrom + ' \u062A\u0627 ' + pageTo + ' \u0627\u0632 ' + totalRows + ' \u0631\u062F\u06CC\u0641';
+ },
+ formatSearch: function formatSearch() {
+ return 'جستجو';
+ },
+ formatNoMatches: function formatNoMatches() {
+ return 'رکوردی یافت نشد.';
+ },
+ formatPaginationSwitch: function formatPaginationSwitch() {
+ return 'نمایش/مخفی صفحه بندی';
+ },
+ formatRefresh: function formatRefresh() {
+ return 'به روز رسانی';
+ },
+ formatToggle: function formatToggle() {
+ return 'تغییر نمایش';
+ },
+ formatColumns: function formatColumns() {
+ return 'سطر ها';
+ },
+ formatAllRows: function formatAllRows() {
+ return 'همه';
+ }
+ };
+
+ $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['fa-IR']);
+ })(jQuery);
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026782_data-controller.js b/pool/shard004/JavaScript/0026782_data-controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..b976c8e90bace11252363f978d88efbeff595a47
--- /dev/null
+++ b/pool/shard004/JavaScript/0026782_data-controller.js
@@ -0,0 +1,19 @@
+const twitter = require(__dirname + '/../config/twitter');
+const moment = require('moment');
+
+let lastRequest = moment();
+let recentTrends = null;
+
+exports.getTwitterTrends = (req, res) => {
+ if (recentTrends === null || moment().diff(lastRequest, 'minutes') > 60) {
+ twitter.get('trends/place.json', {
+ id: 23424934
+ }, (err, data, response) => {
+ recentTrends = data[0].trends;
+ res.status(200).send(recentTrends);
+ });
+ } else {
+ console.log('Sending old trend data.');
+ res.status(200).send(recentTrends);
+ }
+};
diff --git a/pool/shard004/JavaScript/0026784_GroupModifier.js b/pool/shard004/JavaScript/0026784_GroupModifier.js
new file mode 100644
index 0000000000000000000000000000000000000000..5b0f2703129125bc2ef281f7d734b742e2e1360b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026784_GroupModifier.js
@@ -0,0 +1,144 @@
+/* *
+ *
+ * (c) 2020-2021 Highsoft AS
+ *
+ * License: www.highcharts.com/license
+ *
+ * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
+ *
+ * Authors:
+ * - Sophie Bremer
+ *
+ * */
+'use strict';
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
+import DataModifier from './DataModifier.js';
+import DataTable from '../DataTable.js';
+import U from '../../Core/Utilities.js';
+var merge = U.merge;
+/* *
+ *
+ * Class
+ *
+ * */
+/**
+ * Groups table rows into subtables depending on column values.
+ *
+ * @private
+ */
+var GroupModifier = /** @class */ (function (_super) {
+ __extends(GroupModifier, _super);
+ /* *
+ *
+ * Constructors
+ *
+ * */
+ /**
+ * Constructs an instance of the group modifier.
+ *
+ * @param {GroupModifier.Options} [options]
+ * Options to configure the group modifier.
+ */
+ function GroupModifier(options) {
+ var _this = _super.call(this) || this;
+ _this.options = merge(GroupModifier.defaultOptions, options);
+ return _this;
+ }
+ /* *
+ *
+ * Functions
+ *
+ * */
+ /**
+ * Applies modifications to the table rows and returns a new table with
+ * subtable, containing the grouped rows. The rows of the new table contain
+ * three columns:
+ * - `groupBy`: Column name used to group rows by.
+ * - `table`: Subtable containing the grouped rows.
+ * - `value`: containing the common value of the group
+ *
+ * @param {DataTable} table
+ * Table to modify.
+ *
+ * @param {DataEventEmitter.EventDetail} [eventDetail]
+ * Custom information for pending events.
+ *
+ * @return {DataTable}
+ * Table with `modified` property as a reference.
+ */
+ GroupModifier.prototype.modifyTable = function (table, eventDetail) {
+ var modifier = this;
+ modifier.emit({ type: 'modify', detail: eventDetail, table: table });
+ var byGroups = [], tableGroups = [], valueGroups = [], groupColumn = (modifier.options.groupColumn ||
+ table.getColumnNames()[0]), valueColumn = (table.getColumn(groupColumn) ||
+ []), _a = modifier.options, invalidValues = _a.invalidValues, validValues = _a.validValues, modified = table.modified = table.clone(true, eventDetail);
+ var value, valueIndex;
+ for (var i = 0, iEnd = valueColumn.length; i < iEnd; ++i) {
+ value = valueColumn[i];
+ if (typeof value !== 'undefined') {
+ if (value instanceof DataTable ||
+ (invalidValues &&
+ invalidValues.indexOf(value) >= 0) || (validValues &&
+ validValues.indexOf(value) === -1)) {
+ continue;
+ }
+ valueIndex = valueGroups.indexOf(value);
+ if (valueIndex === -1) {
+ var newTable = new DataTable();
+ newTable.setRows([table.getRowObject(i) || {}]);
+ byGroups.push(groupColumn);
+ tableGroups.push(newTable);
+ valueGroups.push(value);
+ }
+ else {
+ tableGroups[valueIndex].setRows([table.getRow(i) || []]);
+ }
+ }
+ }
+ modified.deleteColumns();
+ modified.setColumns({
+ groupBy: byGroups,
+ table: tableGroups,
+ value: valueGroups
+ });
+ modifier.emit({ type: 'afterModify', detail: eventDetail, table: table });
+ return table;
+ };
+ /* *
+ *
+ * Static Properties
+ *
+ * */
+ /**
+ * Default options to group table rows.
+ */
+ GroupModifier.defaultOptions = {
+ modifier: 'Group',
+ groupColumn: ''
+ };
+ return GroupModifier;
+}(DataModifier));
+/* *
+ *
+ * Register
+ *
+ * */
+DataModifier.addModifier(GroupModifier);
+/* *
+ *
+ * Export
+ *
+ * */
+export default GroupModifier;
diff --git a/pool/shard004/JavaScript/0026795_dtv-artboard-presentation.js b/pool/shard004/JavaScript/0026795_dtv-artboard-presentation.js
new file mode 100644
index 0000000000000000000000000000000000000000..8064a52e6bb61636a99366a679ec3c0b5a90a263
--- /dev/null
+++ b/pool/shard004/JavaScript/0026795_dtv-artboard-presentation.js
@@ -0,0 +1,64 @@
+'use strict';
+
+angular.module('risevision.editor.directives')
+ .directive('artboardPresentation', ['editorFactory', 'artboardFactory',
+ 'placeholderFactory', 'PRESENTATION_BORDER_SIZE', '$stateParams',
+ function (editorFactory, artboardFactory, placeholderFactory,
+ PRESENTATION_BORDER_SIZE, $stateParams) {
+ return {
+ scope: true,
+ restrict: 'E',
+ templateUrl: 'partials/editor/artboard-presentation.html',
+ link: function ($scope, element, attrs) {
+ var heightIncrement = 2 * PRESENTATION_BORDER_SIZE;
+ var widthIncrement = 2 * PRESENTATION_BORDER_SIZE;
+
+ $scope.editorFactory = editorFactory;
+ $scope.placeholderFactory = placeholderFactory;
+ element.addClass('artboard-presentation');
+ artboardFactory.zoomFit();
+
+ $scope.$watch('editorFactory.presentation', function () {
+ $scope.presentation = editorFactory.presentation;
+ element.css('width', ($scope.presentation.width +
+ widthIncrement) + $scope.presentation
+ .widthUnits);
+ element.css('height', ($scope.presentation.height +
+ heightIncrement) + $scope.presentation
+ .heightUnits);
+ element.css('background', $scope.presentation.backgroundStyle);
+ element.css('backgroundSize',
+ $scope.presentation.backgroundScaleToFit ? 'contain' :
+ '');
+ element.css('transition', 'all 0s');
+ }, true);
+
+ $scope.$watch(function () {
+ return artboardFactory.zoomLevel;
+ }, function () {
+ element.css('transform', 'scale(' + artboardFactory.zoomLevel + ')');
+ element.css('transform-origin', '0% 0%');
+ element.css('transition', 'all .4s');
+ });
+
+ element.on('mousewheel DOMMouseScroll', function (e) {
+ if (e.ctrlKey) {
+ e.preventDefault();
+ $scope.$apply(function () {
+ if (e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0) {
+ artboardFactory.zoomOut();
+ } else {
+ artboardFactory.zoomIn();
+ }
+ });
+ }
+ });
+
+ $scope.showEmptyState = function () {
+ return !editorFactory.presentation.id && !$scope.hasUnsavedChanges &&
+ !$stateParams.copyOf;
+ };
+ } //link()
+ };
+ }
+ ]);
diff --git a/pool/shard004/JavaScript/0026796_HTMLFrameElement-impl.js b/pool/shard004/JavaScript/0026796_HTMLFrameElement-impl.js
new file mode 100644
index 0000000000000000000000000000000000000000..5b117fba994df3d00ef747fdd9abe63918034757
--- /dev/null
+++ b/pool/shard004/JavaScript/0026796_HTMLFrameElement-impl.js
@@ -0,0 +1,276 @@
+"use strict";
+
+const DOMException = require("domexception");
+const MIMEType = require("whatwg-mimetype");
+const whatwgEncoding = require("whatwg-encoding");
+const { parseURL, serializeURL } = require("whatwg-url");
+const sniffHTMLEncoding = require("html-encoding-sniffer");
+
+const { evaluateJavaScriptURL } = require("../window/navigation");
+const HTMLElementImpl = require("./HTMLElement-impl").implementation;
+const { reflectURLAttribute } = require("../../utils");
+const { parseIntoDocument } = require("../../browser/parser");
+const { documentBaseURL } = require("../helpers/document-base-url");
+const { fireAnEvent } = require("../helpers/events");
+const { getAttributeValue } = require("../attributes");
+const idlUtils = require("../generated/utils");
+
+function fireLoadEvent(document, frame, attaching) {
+ if (attaching) {
+ fireAnEvent("load", frame);
+
+ return;
+ }
+
+ const dummyPromise = Promise.resolve();
+
+ function onLoad() {
+ fireAnEvent("load", frame);
+ }
+
+ document._queue.push(dummyPromise, onLoad);
+}
+
+function fetchFrame(serializedURL, frame, document, contentDoc) {
+ const resourceLoader = document._resourceLoader;
+
+ let request;
+
+ function onFrameLoaded(data) {
+ const sniffOptions = {
+ defaultEncoding: document._encoding
+ };
+
+ if (request.response) {
+ const contentType = MIMEType.parse(request.response.headers["content-type"]) || new MIMEType("text/plain");
+ sniffOptions.transportLayerEncodingLabel = contentType.parameters.get("charset");
+
+ if (contentType) {
+ if (contentType.isXML()) {
+ contentDoc._parsingMode = "xml";
+ }
+ contentDoc.contentType = contentType.essence;
+ }
+ }
+
+ const encoding = sniffHTMLEncoding(data, sniffOptions);
+ contentDoc._encoding = encoding;
+
+ const html = whatwgEncoding.decode(data, contentDoc._encoding);
+
+ try {
+ parseIntoDocument(html, contentDoc);
+ } catch (error) {
+ if (
+ error instanceof DOMException &&
+ error.code === DOMException.SYNTAX_ERR &&
+ contentDoc._parsingMode === "xml"
+ ) {
+ // As defined (https://html.spec.whatwg.org/#read-xml) parsing error in XML document may be reported inline by
+ // mutating the document.
+ const element = contentDoc.createElementNS("http://www.mozilla.org/newlayout/xml/parsererror.xml", "parsererror");
+ element.textContent = error.message;
+
+ while (contentDoc.childNodes.length > 0) {
+ contentDoc.removeChild(contentDoc.lastChild);
+ }
+ contentDoc.appendChild(element);
+ } else {
+ throw error;
+ }
+ }
+
+ contentDoc.close();
+
+ return new Promise((resolve, reject) => {
+ contentDoc.addEventListener("load", resolve);
+ contentDoc.addEventListener("error", reject);
+ });
+ }
+
+ request = resourceLoader.fetch(serializedURL, {
+ element: frame,
+ onLoad: onFrameLoaded
+ });
+}
+
+function canDispatchEvents(frame, attaching) {
+ if (!attaching) {
+ return false;
+ }
+
+ return Object.keys(frame._eventListeners).length === 0;
+}
+
+function loadFrame(frame, attaching) {
+ if (frame._contentDocument) {
+ if (frame._contentDocument._defaultView) {
+ // close calls delete on its document.
+ frame._contentDocument._defaultView.close();
+ } else {
+ delete frame._contentDocument;
+ }
+ }
+
+ const parentDoc = frame._ownerDocument;
+
+ // https://html.spec.whatwg.org/#process-the-iframe-attributes
+ let url;
+ const srcAttribute = getAttributeValue(frame, "src");
+ if (srcAttribute === "") {
+ url = parseURL("about:blank");
+ } else {
+ url = parseURL(srcAttribute, { baseURL: documentBaseURL(parentDoc) || undefined }) || parseURL("about:blank");
+ }
+ const serializedURL = serializeURL(url);
+
+ // This is not great, but prevents a require cycle during webidl2js generation
+ const wnd = new parentDoc._defaultView.constructor({
+ parsingMode: "html",
+ url: url.scheme === "javascript" || serializedURL === "about:blank" ? parentDoc.URL : serializedURL,
+ resourceLoader: parentDoc._defaultView._resourceLoader,
+ referrer: parentDoc.URL,
+ cookieJar: parentDoc._cookieJar,
+ pool: parentDoc._pool,
+ encoding: parentDoc._encoding,
+ runScripts: parentDoc._defaultView._runScripts,
+ commonForOrigin: parentDoc._defaultView._commonForOrigin,
+ pretendToBeVisual: parentDoc._defaultView._pretendToBeVisual
+ });
+
+ const contentDoc = frame._contentDocument = idlUtils.implForWrapper(wnd._document);
+ const parent = parentDoc._defaultView;
+ const contentWindow = contentDoc._defaultView;
+ contentWindow._parent = parent;
+ contentWindow._top = parent.top;
+ contentWindow._frameElement = frame;
+ contentWindow._virtualConsole = parent._virtualConsole;
+
+ if (parentDoc.origin === contentDoc.origin) {
+ contentWindow._currentOriginData.windowsInSameOrigin.push(contentWindow);
+ }
+
+ const noQueue = canDispatchEvents(frame, attaching);
+
+ // Handle about:blank with a simulated load of an empty document.
+ if (serializedURL === "about:blank") {
+ // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available.
+ parseIntoDocument("", contentDoc);
+ contentDoc.close(noQueue);
+
+ if (noQueue) {
+ fireLoadEvent(parentDoc, frame, noQueue);
+ } else {
+ contentDoc.addEventListener("load", () => {
+ fireLoadEvent(parentDoc, frame);
+ });
+ }
+ } else if (url.scheme === "javascript") {
+ // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available.
+ parseIntoDocument("", contentDoc);
+ contentDoc.close(noQueue);
+ const result = evaluateJavaScriptURL(contentWindow, url);
+ if (typeof result === "string") {
+ contentDoc.body.textContent = result;
+ }
+ if (noQueue) {
+ fireLoadEvent(parentDoc, frame, noQueue);
+ } else {
+ contentDoc.addEventListener("load", () => {
+ fireLoadEvent(parentDoc, frame);
+ });
+ }
+ } else {
+ fetchFrame(serializedURL, frame, parentDoc, contentDoc);
+ }
+}
+
+function refreshAccessors(document) {
+ const window = document._defaultView;
+
+ if (!window) {
+ return;
+ }
+
+ const frames = document.querySelectorAll("iframe,frame");
+
+ // delete accessors for all frames
+ for (let i = 0; i < window._length; ++i) {
+ delete window[i];
+ }
+
+ window._length = frames.length;
+ Array.prototype.forEach.call(frames, (frame, i) => {
+ Object.defineProperty(window, i, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return frame.contentWindow;
+ }
+ });
+ });
+}
+
+class HTMLFrameElementImpl extends HTMLElementImpl {
+ constructor(args, privateData) {
+ super(args, privateData);
+ this._contentDocument = null;
+ }
+ _attrModified(name, value, oldVal) {
+ super._attrModified(name, value, oldVal);
+ if (name === "src") {
+ // iframe should never load in a document without a Window
+ // (e.g. implementation.createHTMLDocument)
+ if (this._attached && this._ownerDocument._defaultView) {
+ loadFrame(this);
+ }
+ }
+ }
+
+ _detach() {
+ super._detach();
+
+ if (this.contentWindow) {
+ this.contentWindow.close();
+ }
+
+ refreshAccessors(this._ownerDocument);
+ }
+
+ _attach() {
+ super._attach();
+
+ if (this._ownerDocument._defaultView) {
+ loadFrame(this, true);
+ }
+ refreshAccessors(this._ownerDocument);
+ }
+
+ get contentDocument() {
+ return this._contentDocument;
+ }
+
+ get contentWindow() {
+ return this.contentDocument ? this.contentDocument._defaultView : null;
+ }
+
+ get src() {
+ return reflectURLAttribute(this, "src");
+ }
+
+ set src(value) {
+ this.setAttributeNS(null, "src", value);
+ }
+
+ get longDesc() {
+ return reflectURLAttribute(this, "longdesc");
+ }
+
+ set longDesc(value) {
+ this.setAttributeNS(null, "longdesc", value);
+ }
+}
+
+module.exports = {
+ implementation: HTMLFrameElementImpl
+};
diff --git a/pool/shard004/JavaScript/0026797_Gruntfile.js b/pool/shard004/JavaScript/0026797_Gruntfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..177c2f8c39bd989c1c97476d715d78cc7ff853cd
--- /dev/null
+++ b/pool/shard004/JavaScript/0026797_Gruntfile.js
@@ -0,0 +1,82 @@
+/*
+ * grunt-jenkins-build-info
+ * https://github.com/linuxbozo/grunt-jenkins-build-info
+ *
+ * Copyright (c) 2014 M. Adam Kendall
+ * Licensed under the MIT license.
+ */
+
+'use strict';
+
+process.env.BUILD_NUMBER = process.env.BUILD_NUMBER ? process.env.BUILD_NUMBER : "foo";
+process.env.BUILD_TAG = process.env.BUILD_TAG ? process.env.BUILD_TAG : "tag";
+process.env.JOB_URL = process.env.JOB_URL ? process.env.JOB_URL : "http://example.org";
+process.env.SVN_REVISION = process.env.SVN_REVISION ? process.env.SVN_REVISION : "bar";
+process.env.GIT_COMMIT = process.env.GIT_COMMIT ? process.env.GIT_COMMIT : "baz";
+process.env.GIT_BRANCH = process.env.GIT_BRANCH ? process.env.GIT_BRANCH : "develop";
+
+module.exports = function (grunt) {
+ // load all npm grunt tasks
+ require('load-grunt-tasks')(grunt);
+
+ // Project configuration.
+ grunt.initConfig({
+ jshint: {
+ all: [
+ 'Gruntfile.js',
+ 'tasks/*.js',
+ '<%= nodeunit.tests %>'
+ ],
+ options: {
+ jshintrc: '.jshintrc',
+ reporter: require('jshint-stylish')
+ }
+ },
+
+ // Before generating any new files, remove any previously-created files.
+ clean: {
+ tests: ['tmp']
+ },
+
+ copy: {
+ tests: {
+ files: [{expand: true, flatten:true, src: ['test/actual/*'], dest: 'tmp/', filter: 'isFile'},]
+ }
+ },
+
+
+ // Configuration to be run (and then tested).
+ jenkins_build_info: {
+ main: {
+ options: {
+ files: ['tmp/test.json']
+ },
+ },
+ custom: {
+ options: {
+ files: ['tmp/test_custom.json'],
+ buildField: 'buildInfo'
+ }
+ }
+ },
+
+
+
+ // Unit tests.
+ nodeunit: {
+ tests: ['test/*_test.js']
+ }
+
+ });
+
+ // Actually load this plugin's task(s).
+ grunt.loadTasks('tasks');
+
+ // Whenever the "test" task is run, first clean the "tmp" dir, then run this
+ // plugin's task(s), then test the result.
+ grunt.registerTask('test', ['clean', 'copy', 'jenkins_build_info:main', 'jenkins_build_info:custom', 'nodeunit']);
+
+ // By default, lint and run all tests.
+ grunt.registerTask('default', ['jshint', 'test']);
+
+};
diff --git a/pool/shard004/JavaScript/0026798_bisection.test.js b/pool/shard004/JavaScript/0026798_bisection.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..da28d997c40f6d3224ccb3dc0e327915804b8eaa
--- /dev/null
+++ b/pool/shard004/JavaScript/0026798_bisection.test.js
@@ -0,0 +1,36 @@
+var should = require('should')
+ , bisection = require('../lib/bisection');
+
+var small = [0,1,2,3,5,6,7,8,9]
+ , large = [122,124,134,176,320,341,345,346,500,587,666,768,1230,23231];
+
+module.exports = {
+ 'Library version': function(){
+ bisection.version.should.match(/^\d+\.\d+\.\d+$/);
+ }
+, 'Bisection and bisection right': function(){
+ bisection.should.equal(bisection.right);
+ }
+, 'Bisection right': function(){
+ bisection(small, 4).should.equal(4);
+ bisection(small, 15).should.equal(9);
+ bisection(small, 4, 5).should.equal(5);
+ bisection(small, 12, 0, 5).should.equal(5);
+
+ bisection(large, 350).should.equal(8);
+ bisection(large, 242).should.equal(4);
+ bisection(large, 0).should.equal(0);
+ bisection(large, 232424).should.equal(14);
+ }
+, 'Bisection left': function(){
+ bisection.left(small, 4).should.equal(9);
+ bisection.left(small, 15).should.equal(0);
+ bisection.left(small, 4, 5).should.equal(9);
+ bisection.left(small, 12, 0, 5).should.equal(0);
+
+ bisection.left(large, 350).should.equal(0);
+ bisection.left(large, 242).should.equal(14);
+ bisection.left(large, 0).should.equal(14);
+ bisection.left(large, 232424).should.equal(0);
+ }
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026799_multiSelector.js b/pool/shard004/JavaScript/0026799_multiSelector.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b47024ea2f703a8ff19cb00ae3ed2f3e846e4b9
--- /dev/null
+++ b/pool/shard004/JavaScript/0026799_multiSelector.js
@@ -0,0 +1,123 @@
+function MultiSelector( list_target, list_name, max ){
+
+ this.list_target = list_target;
+ this.count = 0;
+ this.list_name = list_name;
+ this.id = 0;
+
+ // Larger than max to provide a "buffer" slot for the blank file input field
+ // (at maximum there are 'max' hidden input fields + the blank file input field
+ // that might be used if the user deletes an earlier selection)
+ //
+ // Because of this, the controller should be able to handle 1 more file than the user
+ // actually can upload.
+ this.usedIDs = new Array(max + 1);
+
+ // Initiate values
+ for (var i = 0 ; i < this.usedIDs.length ; i++)
+ {
+ this.usedIDs[i] = false;
+ }
+
+
+ if( max ){
+ this.max = max;
+ } else {
+ this.max = -1;
+ };
+
+
+ /**
+ * Add a new file input element
+ */
+ this.addElement = function( element )
+ {
+
+ if( element.tagName == 'INPUT' && element.type == 'file' ){
+
+ element.name = this.list_name + '_file_' + this.getFreeID();
+ element.multi_selector = this;
+
+ element.onchange = function(){
+
+ // New file input
+ var new_element = document.createElement( 'input' );
+ new_element.type = 'file';
+ this.parentNode.insertBefore( new_element, this );
+ this.multi_selector.addElement( new_element );
+ this.multi_selector.addListRow( this );
+
+ this.style.position = 'absolute';
+ this.style.left = '-1000px';
+
+ };
+ if( this.max != -1 && this.count >= this.max ){
+ element.disabled = true;
+ };
+
+ this.count++;
+ this.current_element = element;
+
+ } else {
+ alert( 'Error: not a file input element' );
+ };
+
+ };
+
+ /**
+ * Add a new row to the list of files
+ */
+ this.addListRow = function( element )
+ {
+
+ var new_row = document.createElement( 'div' );
+
+ var new_row_button = document.createElement( 'input' );
+ new_row_button.type = 'button';
+ new_row_button.value = 'Delete';
+
+ new_row.element = element;
+
+ // Delete button
+ new_row_button.onclick= function()
+ {
+ this.parentNode.element.parentNode.removeChild( this.parentNode.element );
+ this.parentNode.parentNode.removeChild( this.parentNode );
+ this.parentNode.element.multi_selector.count--;
+ this.parentNode.element.multi_selector.current_element.disabled = false;
+
+ // This line frees up the ID of the hidden file input that was deleted.
+ // This implementation only works for indices up to 9. TODO: general solution
+ this.parentNode.element.multi_selector.usedIDs
+ [
+ this.parentNode.element.name.charAt
+ (this.parentNode.element.name.length - 1) - 1
+ ] = false;
+
+ return false;
+ };
+
+ new_row.innerHTML = element.value;
+
+ new_row.appendChild( new_row_button );
+
+ this.list_target.appendChild( new_row );
+
+ };
+
+ /**
+ * Finds a free ID number
+ */
+ this.getFreeID = function()
+ {
+ for (var j = 0 ; j < this.usedIDs.length ; j++)
+ {
+ if (!this.usedIDs[j])
+ {
+ this.usedIDs[j] = true;
+ return (j + 1); // Eternal 0-vs-1-index-start-fight continues
+ }
+ }
+
+ }
+};
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026800_nodeinsertbefore22.js b/pool/shard004/JavaScript/0026800_nodeinsertbefore22.js
new file mode 100644
index 0000000000000000000000000000000000000000..afe7dea8c2829bc7cb7772592ad39a6d4f78b835
--- /dev/null
+++ b/pool/shard004/JavaScript/0026800_nodeinsertbefore22.js
@@ -0,0 +1,116 @@
+/*
+Copyright © 2001-2004 World Wide Web Consortium,
+(Massachusetts Institute of Technology, European Research Consortium
+for Informatics and Mathematics, Keio University). All
+Rights Reserved. This work is distributed under the W3C® Software License [1] 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.
+
+[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
+*/
+
+ /**
+ * Gets URI that identifies the test.
+ * @return uri identifier of test
+ */
+function getTargetURI() {
+ return "http://www.w3.org/2001/DOM-Test-Suite/level3/core/nodeinsertbefore22";
+ }
+
+var docsLoaded = -1000000;
+var builder = null;
+
+//
+// This function is called by the testing framework before
+// running the test suite.
+//
+// If there are no configuration exceptions, asynchronous
+// document loading is started. Otherwise, the status
+// is set to complete and the exception is immediately
+// raised when entering the body of the test.
+//
+function setUpPage() {
+ setUpPageStatus = 'running';
+ try {
+ //
+ // creates test document builder, may throw exception
+ //
+ builder = createConfiguredBuilder();
+
+ docsLoaded = 0;
+
+ var docRef = null;
+ if (typeof(this.doc) != 'undefined') {
+ docRef = this.doc;
+ }
+ docsLoaded += preload(docRef, "doc", "barfoo");
+
+ if (docsLoaded == 1) {
+ setUpPageStatus = 'complete';
+ }
+ } catch(ex) {
+ catchInitializationError(builder, ex);
+ setUpPageStatus = 'complete';
+ }
+}
+
+//
+// This method is called on the completion of
+// each asychronous load started in setUpTests.
+//
+// When every synchronous loaded document has completed,
+// the page status is changed which allows the
+// body of the test to be executed.
+function loadComplete() {
+ if (++docsLoaded == 1) {
+ setUpPageStatus = 'complete';
+ }
+}
+
+/**
+*
+ Using insertBefore on an Element node attempt to insert the ancestor of an Element node
+ before its child and verify if a HIERARCHY_REQUEST_ERR is raised.
+
+* @author IBM
+* @author Neil Delima
+* @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core#ID-952280727
+*/
+function nodeinsertbefore22() {
+ var success;
+ if(checkInitialization(builder, "nodeinsertbefore22") != null) return;
+ var doc;
+ var element;
+ var refNode;
+ var ancestor;
+ var childList;
+ var appendedChild;
+ var inserted;
+
+ var docRef = null;
+ if (typeof(this.doc) != 'undefined') {
+ docRef = this.doc;
+ }
+ doc = load(docRef, "doc", "barfoo");
+ element = doc.createElementNS("http://www.w3.org/1999/xhtml","xhtml:body");
+ refNode = doc.createElementNS("http://www.w3.org/1999/xhtml","xhtml:a");
+ ancestor = doc.createElementNS("http://www.w3.org/1999/xhtml","xhtml:p");
+ appendedChild = element.appendChild(refNode);
+ appendedChild = ancestor.appendChild(element);
+
+ {
+ success = false;
+ try {
+ inserted = element.insertBefore(ancestor,refNode);
+ }
+ catch(ex) {
+ success = (typeof(ex.code) != 'undefined' && ex.code == 3);
+ }
+ assertTrue("throw_HIERARCHY_REQUEST_ERR",success);
+ }
+
+}
+
+function runTest() {
+ nodeinsertbefore22();
+}
diff --git a/pool/shard004/JavaScript/0026801_staticHandler.js b/pool/shard004/JavaScript/0026801_staticHandler.js
new file mode 100644
index 0000000000000000000000000000000000000000..325cf9449618016044c00919585c4483fa6f8ce6
--- /dev/null
+++ b/pool/shard004/JavaScript/0026801_staticHandler.js
@@ -0,0 +1,69 @@
+const fs = require("fs");
+
+let fileType = (dataString) => {
+ let dataTypes = {
+ ".css" : "text/css",
+ ".js" : "application/javascript",
+ ".png" : "image/png",
+ ".jpg" : "image/jpg",
+ ".ico" : "image/x-icon",
+ };
+
+ for (let type in dataTypes) {
+ if (dataString.endsWith(type)) {
+ return dataTypes[type];
+ }
+ }
+};
+
+let favHandler = (req, res) => {
+ fs.readFile("./public/images/favicon.ico", (err, data) => {
+ if (err) {
+ console.log(err);
+ return;
+ }
+
+ res.writeHead(200, {
+ "content-type": fileType(req.path)
+ });
+ res.write(data);
+ res.end();
+ })
+};
+
+let resData = (req, res)=>{
+ fs.readFile("." + req.path, (err, data) => {
+ if (err) {
+ console.log(err);
+ return;
+ }
+
+ res.writeHead(200, {
+ "content-type": fileType(req.path)
+ });
+ res.write(data);
+ res.end();
+ })
+};
+
+let notFound = (req, res) => {
+ fs.readFile("./views/notFound.html", (err, data) => {
+ if (err) {
+ console.log(err);
+ return;
+ }
+
+ res.write(data);
+ res.end();
+ });
+};
+
+module.exports = (req, res) => {
+ if (req.path === "/favicon.ico" && req.method === "GET") {
+ favHandler(req, res)
+ } else if(req.path.startsWith("/public/") && req.method === "GET") {
+ resData(req, res);
+ } else {
+ notFound(req, res);
+ }
+};
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026802_Client.js b/pool/shard004/JavaScript/0026802_Client.js
new file mode 100644
index 0000000000000000000000000000000000000000..1057445146fdbc7e76d3f830367bd5f7d5915b1d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026802_Client.js
@@ -0,0 +1,87 @@
+/**
+ * this is to run on the client
+ * but im working with as a .gs file
+ */
+
+// all code for client server communication
+var Client = (function(client) {
+
+ /**
+ * generic function to execute stuff on the server
+ * @param {string} serverFunction the function to execute
+ * @param {string} successFunction what to do when it succeeds
+ * @param {*} serverArg arg to pass to the server
+ */
+ client.execute = function (serverFunction, successFunction, serverArg) {
+
+ // this executes a function asynchronously on the server
+ // under control of the client
+ google.script.run
+
+ // this will be executed if it fails
+ .withFailureHandler(function (err) {
+ App.reportMessage (err);
+ })
+
+ // this will be executed if it succeeds
+ .withSuccessHandler (successFunction)
+
+ // this is what gets executed
+ [serverFunction](serverArg);
+
+ };
+
+
+ /**
+ * get data from server
+ * @param {function} [initFunction] call on successful if its there.
+ */
+ client.getData = function () {
+
+ // ask for data
+ client.execute ( 'getData' , function (result) {
+
+ // always store the latest checksum
+ App.globals.sheet.checksum = result.checksum;
+
+ // if the position has changed, but data has not we- may need to change the selected item && re-map
+ if (App.globals.sheet.position.row !== result.position.row && !result.package) {
+
+ // change the selected option & redo & remap if necessary
+ Render.selectionChanged(result.position);
+ App.globals.sheet.position = result.position;
+
+ }
+
+ // if the checksum has changed, then data.package is defined, store an update everything
+ if (result.package) {
+ App.globals.sheet.position = result.position;
+ App.globals.sheet.package = result.package;
+
+ // build the drop down list & create map
+ Render.build();
+
+ }
+
+ // schedule the next trip
+ client.startPolling();
+
+ },App.globals.sheet.checksum);
+ }
+
+
+ /**
+ * trip to the server to look for updates
+ */
+ client.startPolling = function () {
+ setTimeout(function(){
+ client.getData();
+ }, App.globals.polling.interval);
+ };
+
+ return client;
+
+})(Client || {});
+
+
+
diff --git a/pool/shard004/JavaScript/0026803_initSkipLink.js b/pool/shard004/JavaScript/0026803_initSkipLink.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb9d3fb351a34fb9c31d1f86a5a09418d31186d0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026803_initSkipLink.js
@@ -0,0 +1,25 @@
+const initSkipLink = () => {
+ // Inspired by https://github.com/selfthinker/dokuwiki_template_writr/blob/master/js/skip-link-focus-fix.js
+
+ const skiplink = document.querySelector('[data-skiplink]');
+ const main = document.querySelector('main');
+
+ const handleBlur = () => {
+ main.removeAttribute('tabindex');
+ main.removeEventListener('blur', handleBlur);
+ main.removeEventListener('focusout', handleBlur);
+ };
+
+ const handleClick = () => {
+ main.setAttribute('tabindex', -1);
+ main.addEventListener('blur', handleBlur);
+ main.addEventListener('focusout', handleBlur);
+ main.focus();
+ };
+
+ if (skiplink && main) {
+ skiplink.addEventListener('click', handleClick);
+ }
+};
+
+export { initSkipLink };
diff --git a/pool/shard004/JavaScript/0026807_inventoryImport.js b/pool/shard004/JavaScript/0026807_inventoryImport.js
new file mode 100644
index 0000000000000000000000000000000000000000..d9d5412c464b9940762473e9aaa17585300811c6
--- /dev/null
+++ b/pool/shard004/JavaScript/0026807_inventoryImport.js
@@ -0,0 +1,161 @@
+(function() {
+ importNow();
+ downloadCsv();
+})();
+function downloadCsv() {
+ $('#import-import-download').unbind('click').bind('click', function() {
+ var link = '/inventory/import/download/';
+ $.fileDownload(link);
+ return false;
+ });
+}
+function importNow() {
+
+ var IMPORT_ERROR_MESSAGE = 'Row [NUMBER] :
[MESSAGE] ';
+
+ var IMPORT_REPORT =
+ 'We found [TOTAL] inventory in the imported file [FILE_NAME]
'+
+ ''+
+ '- [SUCCESS] total inventory will be imported
'+
+ ''+
+ '- [INV_TYPE_ITEM] Item Inventory Type
'+
+ '- [INV_TYPE_SERVICE] Service Inventory Type
'+
+ '- With [NEW] new inventory
'+
+ '- With [UPDATE] updated inventory
'+
+ '
'+
+ '- [ERROR] total inventory has error and will NOT be imported
'+
+ ''+
+ '[ERROR_MESSAGE]'+
+ '
'+
+ '
';
+
+ var IMPORT_REPORT_SUCCESS =
+ '[TOTAL] contact(s) has been successfully added.
';
+
+ var errorModal = $('#inventory-import-alert-error');
+ var errorMessage = $('#inventory-import-alert-error .alert-error-custom');
+
+ $('#inventory-import-src').unbind('change').bind('change', function() {
+ var file = document.getElementById('inventory-import-src').files[0];
+ if(typeof file !== 'undefined') {
+ $('.file-selected').html(file.name);
+ } else {
+ $('.file-selected').html(' No file selected ');
+ }
+ return false;
+ });
+
+ $('#inventory-import-now').unbind('click').bind('click', function() {
+ var file = document.getElementById('inventory-import-src').files[0];
+
+ //only if there is sleected file
+ if(typeof file === 'undefined') {
+
+ errorModal.show();
+ errorMessage.html('Please select a csv file before importing');
+
+ return false;
+ }
+
+ //only allow to upload csv file
+ if(file.type != 'text/csv' && file.type != 'application/vnd.ms-excel') {
+
+ errorModal.show();
+ errorMessage.html('Only csv file is allowed to upload');
+
+ return false;
+ }
+ var fd = new FormData();
+
+ fd.append("afile", file);
+ // These extra params aren't necessary but show that you can include other data.
+ fd.append("username", "Groucho");
+ fd.append("accountnum", 123456);
+ var xhr = new XMLHttpRequest();
+
+ xhr.open('POST', '/inventory/import/parse', true);
+
+ xhr.upload.onprogress = function(e) {
+ if(e.lengthComputable) {
+ var percentComplete = (e.loaded / e.total) * 100;
+
+ $('#inventory-import-now').
+ html('Reading and Parsing the file...').
+ attr('disabled', 'disabled');
+ }
+ };
+
+ xhr.onload = function() {
+ if(this.status == 200) {
+
+ $('#inventory-import-now').
+ html('Import Inventory').
+ removeAttr('disabled');
+
+ var response = JSON.parse(this.response);
+ var message = '';
+
+ for(i in response.data['error_message']) {
+ var errorMessage = '';
+ for(x in response.data['error_message'][i]['message']) {
+ errorMessage += response.data['error_message'][i]['message'][x]+'
';
+ }
+ message += IMPORT_ERROR_MESSAGE.
+ replace('[NUMBER]', response.data['error_message'][i]['line']).
+ replace('[MESSAGE]', errorMessage);
+ }
+
+
+ $('#inventory-import-message').show();
+ $('#inventory-import-message .alert-error-custom').html(IMPORT_REPORT.
+ replace('[TOTAL]', response.data['total']).
+ replace('[SUCCESS]', response.data['success']).
+ replace('[ERROR]', response.data['error']).
+ replace('[NEW]', response.data['new']).
+ replace('[UPDATE]', response.data['update']).
+ replace('[FILE_NAME]', file.name).
+ replace('[ERROR_MESSAGE]', message).
+ replace('[INV_TYPE_ITEM]', response.data['item_count']).
+ replace('[INV_TYPE_SERVICE]', response.data['service_count'])
+ );
+
+ continueImport(response.data['id']);
+ };
+ };
+
+ xhr.send(fd);
+
+ });
+}
+
+function continueImport(id) {
+ var button = $('#inventory-import-continue-import');
+ button.unbind('click').bind('click', function() {
+ var url = '/inventory/import/save/'+id;
+ button.
+ html('Importing...').
+ attr('disabled', 'disabled');
+ base.
+ setUrl(url).
+ get(function(response) {
+
+ $('#inventory-import-message').hide();
+ $('#inventory-import-alert-error').hide();
+
+ button.
+ html('Continue Import').
+ removeAttr('disabled');
+
+ base.notification('File successfully imported', 'inverse');
+
+ $('#inventory-import-src').val('');
+ $('.file-selected').html(' No file selected ');
+
+ }
+ );
+ return false;
+
+ });
+
+ return this;
+}
diff --git a/pool/shard004/JavaScript/0026814_watchDir.js b/pool/shard004/JavaScript/0026814_watchDir.js
new file mode 100644
index 0000000000000000000000000000000000000000..e59d9b72835e89ad367dd37fa0a9694318bc65ea
--- /dev/null
+++ b/pool/shard004/JavaScript/0026814_watchDir.js
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+import * as babel from '@babel/core';
+import path from 'path';
+import fse from 'fs-extra';
+import chokidar from 'chokidar';
+import fs from 'fs';
+import yargs from 'yargs';
+import { isJSFile } from '../libs/utils';
+
+process.on('unhandledRejection', reason => console.log(reason)); // eslint-disable-line
+process.on('uncaughtException', err => console.log(err)); // eslint-disable-line
+
+export const getBuildDestinationPath = ({ file, srcDir, buildDir }) =>
+ path.resolve(buildDir, path.relative(srcDir, file));
+
+export const compileFile = async ({ file, srcDir, buildDir }) => {
+ const destPath = getBuildDestinationPath({
+ file,
+ srcDir,
+ buildDir,
+ });
+
+ if (!isJSFile(file)) {
+ return fse.copy(file, destPath);
+ }
+
+ const { code } = await babel.transformFileAsync(file);
+ return fse.outputFile(destPath, code);
+};
+
+const run = async ({ srcDir, buildDir }) => {
+ const watcher = chokidar.watch(path.join(srcDir, '**'), {
+ ignoreInitial: true,
+ });
+
+ watcher.on('add', file => compileFile({ file, srcDir, buildDir }));
+ watcher.on('change', file => compileFile({ file, srcDir, buildDir }));
+ watcher.on('unlink', file => fs.unlinkSync(getBuildDestinationPath({ file, srcDir, buildDir })));
+ watcher.on('unlinkDir', file => fse.remove(getBuildDestinationPath({ file, srcDir, buildDir })));
+
+ return watcher;
+};
+
+const { argv } = yargs;
+
+run({
+ srcDir: argv.src || 'src',
+ buildDir: argv.build || 'build',
+});
diff --git a/pool/shard004/JavaScript/0026818_codemodules-tax.js b/pool/shard004/JavaScript/0026818_codemodules-tax.js
new file mode 100644
index 0000000000000000000000000000000000000000..6ca42235e92bfbb47304c8e41cb098459c530172
--- /dev/null
+++ b/pool/shard004/JavaScript/0026818_codemodules-tax.js
@@ -0,0 +1,99 @@
+
+app.controller("TaxController", function($scope, Evaluator, CommonInit) {
+
+ $scope.template = 'partials/tax.html';
+
+ CommonInit.init( $scope, Evaluator );
+
+ $scope.code = "laskeVerot = function(vuosipalkka) {\n // \n return 500; \n}";
+
+ $scope.init = function() {
+ $scope.session.setValue( this.code );
+
+ eval( $scope.code );
+ };
+
+ $scope.loaded = function() {
+ $scope.plot();
+ };
+
+ $scope.plot = function() {
+
+ var amount = [];
+ var share = []
+
+ for (var i = 500; i < 5000; i+= 100) {
+ var salary = i * 12;
+
+ amount.push( [i, laskeVerot( salary ) / 12 ] );
+ share.push( [i, laskeVerot( salary ) / salary * 100 ])
+ }
+
+ $.plot("#tax-plot", [
+ { data: amount, label: 'Veron määrä kuussa' },
+ { data: share, label: 'Veron määrä tuloista (%)', yaxis: 2 }
+ ], {
+ legend: { container: $('#legend') },
+ yaxes: [ {}, {
+ position: "right",
+ }]
+ } );
+
+ };
+
+ $scope._assess = function() {
+
+ var f = this.guide[ this.state ].correct;
+
+ for( var i = 500; i < 500000; i += 100 ) {
+
+ if( window.laskeVerot(i) != f(i) ) {
+ $('#tasks').effect('pulsate')
+ return false;
+ }
+ }
+
+ return true;
+
+ };
+
+ $scope.guide = [
+ {
+ text: "Muokkaa verojen laskentaa siten, kaikki maksavat 600 euron tasaveron",
+ correct: function(salary) { return 600; }
+
+ },
+ {
+ text: "Progressiivisessa verotuksessa verot mukautuvat tulojen suhteen, määritellään että alle 30000 euron vuosituloilla veroja maksetaan 600 euroa, muutoin 1000 euroa.",
+ correct: function(salary) { if( salary < 30000 ) { return 600; } else { return 1000 }; }
+ },
+ {
+ text: "Alle 16 300 euron tuloista ei kanneta veroa valtion verotuksessa",
+ correct: function(salary) {
+ if( salary < 16300 ) return 0;
+ if( salary < 30000 ) return 600;
+ return 1000;
+ }
+ },
+ {
+ text: "16 300 euron ja 24 300 euron välillä veroa maksetaan 8 euroa sekä 6.5 prosenttia kustakin ylittävästä osuudesta. Muut maksavat 1000 euron tasaveron.",
+ correct: function(salary) {
+ if( salary < 16300 ) return 0;
+ if( salary < 24300 ) return 8 + (24300-salary)*0.065;
+ return 1000;
+ }
+ },
+ {
+ text: "Lisää myös muut tulotasot verohallinnon ohjeen mukaisesti",
+ correct: function(salary) {
+ if( salary < 16300 ) return 0;
+ if( salary < 24300 ) return 8 + (salary-16300)*0.065;
+ if( salary < 39700 ) return 528 + (salary-24300)*0.175;
+ if( salary < 71400 ) return 3223 + (salary-39700)*0.215;
+ if( salary < 100000 ) return 10038.5 + (salary-71400)*0.2975;
+ return 18547+(salary-100000)*0.3175;
+ }
+ }
+ ];
+
+});
diff --git a/pool/shard004/JavaScript/0026819_note.js b/pool/shard004/JavaScript/0026819_note.js
new file mode 100644
index 0000000000000000000000000000000000000000..ec6c9162bf0d0b91f44e6f29e623e10ee59221df
--- /dev/null
+++ b/pool/shard004/JavaScript/0026819_note.js
@@ -0,0 +1,201 @@
+// Vex Flow Notation
+// Mohit Muthanna
+//
+// Copyright Mohit Muthanna 2010
+//
+// Requires vex.js.
+
+/** @constructor */
+Vex.Flow.Note = function(note_struct) {
+ if (arguments.length > 0) this.init(note_struct); }
+
+// Inherits from Vex.Flow.Tickable
+Vex.Flow.Note.prototype = new Vex.Flow.Tickable();
+Vex.Flow.Note.superclass = Vex.Flow.Tickable.prototype;
+Vex.Flow.Note.constructor = Vex.Flow.Note;
+
+Vex.Flow.Note.prototype.init = function(note_struct) {
+ var superclass = Vex.Flow.Note.superclass;
+ superclass.init.call(this);
+
+ // Sanity check
+ if (!note_struct) {
+ throw new Vex.RuntimeError("BadArguments",
+ "Note must have valid initialization data to identify " +
+ "duration and type.");
+ }
+
+ var initData = Vex.Flow.parseNoteData(note_struct);
+ if (!initData) {
+ throw new Vex.RuntimeError("BadArguments",
+ "Invalid note initialization object: " + JSON.stringify(note_struct));
+ }
+
+ // Note properties
+ this.duration = initData.duration;
+ this.dots = initData.dots;
+ this.noteType = initData.type;
+ this.ticks = initData.ticks;
+
+ if (this.positions &&
+ (typeof(this.positions) != "object" || !this.positions.length)) {
+ throw new Vex.RuntimeError(
+ "BadArguments", "Note keys must be array type.");
+ }
+
+
+ // Positioning contexts
+ this.tickContext = null; // The current tick context
+ this.modifierContext = null;
+
+ // Positioning variables
+ this.width = 0; // Width in pixels calculated after preFormat
+ this.extraLeftPx = 0; // Extra room on left for offset note head
+ this.extraRightPx = 0; // Extra room on right for offset note head
+ this.x_shift = 0; // X shift from tick context X
+ this.left_modPx = 0; // Max width of left modifiers
+ this.right_modPx = 0; // Max width of right modifiers
+ this.voice = null; // The voice that this note is in
+ this.preFormatted = false; // Is this note preFormatted?
+ this.ys = []; // list of y coordinates for each note
+ // we need to hold on to these for ties and beams.
+ // Drawing
+ this.context = null;
+ this.stave = null;
+}
+
+Vex.Flow.Note.prototype.addStroke = function(index, stroke) {
+ stroke.setNote(this);
+ stroke.setIndex(index);
+ this.modifiers.push(stroke);
+ this.setPreFormatted(false);
+ return this;
+}
+
+Vex.Flow.Note.prototype.setYs = function(ys) {
+ this.ys = ys; return this; }
+Vex.Flow.Note.prototype.getStave = function() { return this.stave; }
+Vex.Flow.Note.prototype.setStave = function(stave) {
+ this.stave = stave; return this; }
+Vex.Flow.Note.prototype.setContext = function(context) {
+ this.context = context; return this; }
+Vex.Flow.Note.prototype.getTicks = function() { return this.ticks; }
+Vex.Flow.Note.prototype.getExtraLeftPx = function() {
+ return this.extraLeftPx; }
+Vex.Flow.Note.prototype.getExtraRightPx = function() {
+ return this.extraRightPx; }
+Vex.Flow.Note.prototype.setExtraLeftPx = function(x) {
+ this.extraLeftPx = x; return this; }
+Vex.Flow.Note.prototype.setExtraRightPx = function(x) {
+ this.extraRightPx = x; return this; }
+
+Vex.Flow.Note.prototype.getYs = function() {
+ if (this.ys.length == 0) throw new Vex.RERR("NoYValues",
+ "No Y-values calculated for this note.");
+ return this.ys;
+}
+
+Vex.Flow.Note.prototype.getYForTopText = function(text_line) {
+ if (!this.stave) throw new Vex.RERR("NoStave",
+ "No stave attached to this note.");
+ return this.stave.getYForTopText(text_line);
+}
+
+Vex.Flow.Note.prototype.getVoice = function() {
+ if (!this.voice) throw new Vex.RERR("NoVoice", "Note has no voice.");
+ return this.voice;
+}
+
+Vex.Flow.Note.prototype.setVoice = function(voice) {
+ this.voice = voice;
+ this.preFormatted = false;
+ return this;
+}
+
+Vex.Flow.Note.prototype.getTickContext = function() { return this.tickContext; }
+Vex.Flow.Note.prototype.setTickContext = function(tc) {
+ this.tickContext = tc;
+ this.preFormatted = false;
+ return this;
+}
+
+Vex.Flow.Note.prototype.getDuration = function() {
+ return this.duration;
+}
+
+Vex.Flow.Note.prototype.isDotted = function() {
+ return (this.dots > 0);
+}
+
+Vex.Flow.Note.prototype.getDots = function() {
+ return this.dots;
+}
+
+Vex.Flow.Note.prototype.getNoteType = function() {
+ return this.noteType;
+}
+
+Vex.Flow.Note.prototype.setModifierContext = function(mc) {
+ this.modifierContext = mc;
+ return this;
+}
+
+Vex.Flow.Note.prototype.getMetrics = function() {
+ if (!this.preFormatted) throw new Vex.RERR("UnformattedNote",
+ "Can't call getMetrics on an unformatted note.");
+ var modLeftPx = 0;
+ var modRightPx = 0;
+ if (this.modifierContext != null) {
+ modLeftPx = this.modifierContext.state.left_shift;
+ modRightPx = this.modifierContext.state.right_shift;
+ }
+ return { noteWidth: this.getWidth() -
+ modLeftPx - modRightPx -
+ this.extraLeftPx - this.extraRightPx,
+ left_shift: this.x_shift,
+ modLeftPx: modLeftPx, modRightPx: modRightPx,
+ extraLeftPx: this.extraLeftPx, extraRightPx: this.extraRightPx };
+}
+
+Vex.Flow.Note.prototype.getWidth = function() {
+ if (!this.preFormatted) throw new Vex.RERR("UnformattedNote",
+ "Can't call GetWidth on an unformatted note.");
+ return this.width + this.x_shift +
+ (this.modifierContext ? this.modifierContext.getWidth() : 0);
+}
+
+Vex.Flow.Note.prototype.setWidth = function(width) { this.width = width; }
+
+Vex.Flow.Note.prototype.setXShift = function(x) {
+ this.x_shift = x;
+ return this;
+}
+
+Vex.Flow.Note.prototype.getX = function(x) {
+ if (!this.tickContext) throw new Vex.RERR("NoTickContext",
+ "Note needs a TickContext assigned for an X-Value");
+ return this.tickContext.getX() + this.x_shift;
+}
+
+Vex.Flow.Note.prototype.getAbsoluteX = function(x) {
+ if (!this.tickContext) throw new Vex.RERR("NoTickContext",
+ "Note needs a TickContext assigned for an X-Value");
+
+ // position note to left edge of tick context.
+ var x = this.tickContext.getX();
+ // add padding at beginning of stave
+ if (this.stave) x += this.stave.getNoteStartX() + 12;
+
+ return x;
+}
+
+Vex.Flow.Note.prototype.setPreFormatted = function(value) {
+ this.preFormatted = value;
+
+ // Maintain the width of left and right modifiers in pizels
+ if (this.preFormatted) {
+ var extra = this.tickContext.getExtraPx();
+ this.left_modPx = Math.max(this.left_modPx, extra.left);
+ this.right_modPx = Math.max(this.right_modPx, extra.right);
+ }
+}
diff --git a/pool/shard004/JavaScript/0026820_cronSelection.js b/pool/shard004/JavaScript/0026820_cronSelection.js
new file mode 100644
index 0000000000000000000000000000000000000000..8e18cf66f4170c79d6d362b4f9df21405705b0a5
--- /dev/null
+++ b/pool/shard004/JavaScript/0026820_cronSelection.js
@@ -0,0 +1,202 @@
+'use strict';
+
+angular.module('angular-cron-jobs', ['templates-angularcronjobs']);
+
+angular.module('angular-cron-jobs').directive('cronSelection', ['cronService', 'baseFrequency', function(cronService, baseFrequency) {
+ return {
+ restrict: 'EA',
+ replace: true,
+ transclude: true,
+ require: 'ngModel',
+ scope: {
+ ngModel: '=',
+ config: '=',
+ myFrequency: '=?frequency'
+ },
+ templateUrl: function(element, attributes) {
+ return attributes.template || 'cronselection.html';
+ },
+ link: function($scope, $el, $attr, $ngModel) {
+
+ var modelChanged = false;
+
+ $scope.baseFrequency = baseFrequency;
+
+ $scope.frequency = [{
+ value: 1,
+ label: 'Minute'
+ }, {
+ value: 2,
+ label: 'Hour'
+ }, {
+ value: 3,
+ label: 'Day'
+ }, {
+ value: 4,
+ label: 'Week'
+ }, {
+ value: 5,
+ label: 'Month'
+ }, {
+ value: 6,
+ label: 'Year'
+ }];
+
+ $scope.$watch('ngModel', function (newValue) {
+ if (angular.isDefined(newValue) && newValue) {
+ modelChanged = true;
+ $scope.myFrequency = cronService.fromCron(newValue, $scope.allowMultiple);
+ } else if (newValue === '') {
+ $scope.myFrequency = undefined;
+ }
+ });
+
+ if (typeof $scope.config === 'object' && !$scope.config.length) {
+ if (typeof $scope.config.options === 'object') {
+ var optionsKeyArray = Object.keys($scope.config.options);
+ for (var i in optionsKeyArray) {
+ var currentKey = optionsKeyArray[i].replace(/^allow/, '');
+ var originalKey = optionsKeyArray[i];
+ if (!$scope.config.options[originalKey]) {
+ for (var b in $scope.frequency) {
+ if ($scope.frequency[b].label === currentKey) {
+ $scope.frequency.splice(b, 1);
+ }
+ }
+ }
+ }
+ }
+ if (angular.isDefined($scope.config.allowMultiple)) {
+ $scope.allowMultiple = $scope.config.allowMultiple;
+ } else {
+ $scope.allowMultiple = false;
+ }
+ }
+
+ $scope.minuteValues = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
+ $scope.hourValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
+ $scope.dayOfMonthValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
+ $scope.dayValues = [0, 1, 2, 3, 4, 5, 6];
+ $scope.monthValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
+
+ $scope.$watch('myFrequency', function (n, o) {
+ if (n !== undefined) {
+ if (n && n.base && (!o || n.base !== o.base) && !modelChanged) {
+ setInitialValuesForBase(n);
+ } else if (n && n.base && o && o.base) {
+ modelChanged = false;
+ }
+
+ var newVal = cronService.setCron(n);
+ $ngModel.$setViewValue(newVal);
+ }
+ }, true);
+
+ function setInitialValuesForBase(freq) {
+ freq.base = parseInt(freq.base);
+
+ if (freq.base >= baseFrequency.hour) {
+ freq.minuteValues = $scope.minuteValues[0];
+ }
+
+ if (freq.base >= baseFrequency.day) {
+ freq.hourValues = $scope.hourValues[0];
+ }
+
+ if (freq.base === baseFrequency.week) {
+ freq.dayValues = $scope.dayValues[0];
+ }
+
+ if (freq.base >= baseFrequency.month) {
+ freq.dayOfMonthValues = $scope.dayOfMonthValues[0];
+ }
+
+ if (freq.base === baseFrequency.year) {
+ freq.monthValues = $scope.monthValues[0];
+ }
+ }
+ }
+ };
+}]).filter('cronNumeral', function() {
+ return function(input) {
+ switch (input) {
+ case 1:
+ return '1st';
+ case 2:
+ return '2nd';
+ case 3:
+ return '3rd';
+ case 21:
+ return '21st';
+ case 22:
+ return '22nd';
+ case 23:
+ return '23rd';
+ case 31:
+ return '31st';
+ case null:
+ return null;
+ default:
+ return input + 'th';
+ }
+ };
+}).filter('cronMonthName', function() {
+ return function(input) {
+ var months = {
+ 1: 'January',
+ 2: 'February',
+ 3: 'March',
+ 4: 'April',
+ 5: 'May',
+ 6: 'June',
+ 7: 'July',
+ 8: 'August',
+ 9: 'September',
+ 10: 'October',
+ 11: 'November',
+ 12: 'December'
+ };
+
+ if (input !== null && angular.isDefined(months[input])) {
+ return months[input];
+ } else {
+ return null;
+ }
+ };
+}).filter('cronDayName', function() {
+ return function(input) {
+ var days = {
+ 0: 'Sunday',
+ 1: 'Monday',
+ 2: 'Tuesday',
+ 3: 'Wednesday',
+ 4: 'Thursday',
+ 5: 'Friday',
+ 6: 'Saturday',
+ };
+
+ if (input !== null && angular.isDefined(days[input])) {
+ return days[input];
+ } else {
+ return null;
+ }
+ };
+}).directive('ngMultiple', ['$compile', function($compile) {
+ return {
+ terminal: true,
+ priority: 10000,
+ restrict: 'A',
+ compile: function compile(element) {
+ element.removeAttr('ng-multiple'); //remove the attribute to avoid indefinite loop
+
+ return {
+ pre: function postLink(scope, iElement) {
+ if(scope.config.allowMultiple === true) {
+ iElement[0].setAttribute('multiple', 'true'); //set the multiple directive
+ }
+ $compile(iElement)(scope);
+ }
+ };
+ },
+ };
+}]);
diff --git a/pool/shard004/JavaScript/0026825_admin.js b/pool/shard004/JavaScript/0026825_admin.js
new file mode 100644
index 0000000000000000000000000000000000000000..e6f1e61224899956639558a696d2195b27a2a06b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026825_admin.js
@@ -0,0 +1,55 @@
+function insertAtCaret(areaId,text) {
+ var txtarea = document.getElementById(areaId);
+ var scrollPos = txtarea.scrollTop;
+ var strPos = 0;
+ var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
+ "ff" : (document.selection ? "ie" : false ) );
+ if (br == "ie") {
+ txtarea.focus();
+ var range = document.selection.createRange();
+ range.moveStart ('character', -txtarea.value.length);
+ strPos = range.text.length;
+ }
+ else if (br == "ff") strPos = txtarea.selectionStart;
+
+ var front = (txtarea.value).substring(0,strPos);
+ var back = (txtarea.value).substring(strPos,txtarea.value.length);
+ txtarea.value=front+text+back;
+ strPos = strPos + text.length;
+ if (br == "ie") {
+ txtarea.focus();
+ var range = document.selection.createRange();
+ range.moveStart ('character', -txtarea.value.length);
+ range.moveStart ('character', strPos);
+ range.moveEnd ('character', 0);
+ range.select();
+ }
+ else if (br == "ff") {
+ txtarea.selectionStart = strPos;
+ txtarea.selectionEnd = strPos;
+ txtarea.focus();
+ }
+ txtarea.scrollTop = scrollPos;
+}
+
+var uploaderInMark = new ss.SimpleUpload({
+ button: 'mark_upload',
+ url: uploadUrl,
+ name: 'imgFile',
+ responseType: 'json',
+ allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'svg'],
+ encodeCustomHeaders: true,
+ maxSize: 2048, // kilobytes
+ onComplete: function (filename, response) {
+ if (!response) {
+ alert(filename + 'upload failed');
+ return false;
+ }
+ if (!response.success) {
+ alert('上传失败! ' + response.msg);
+ return false;
+ }
+ var markStr = '\r\n';
+ insertAtCaret('markdown', markStr)
+ }
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026830_msa-page.js b/pool/shard004/JavaScript/0026830_msa-page.js
new file mode 100644
index 0000000000000000000000000000000000000000..4344334fe4e263ac04ad1978d86eb996cb9c7f89
--- /dev/null
+++ b/pool/shard004/JavaScript/0026830_msa-page.js
@@ -0,0 +1,72 @@
+import { importHtml, importOnCall, ajax, exposeMsaBoxCtx } from "/msa/utils/msa-utils.js"
+
+const srcMsaBoxEdition = "/msa/utils/msa-utils-box-edition.js"
+const editMsaBoxes = importOnCall(srcMsaBoxEdition, "editMsaBoxes")
+const exportMsaBoxes = importOnCall(srcMsaBoxEdition, "exportMsaBoxes")
+
+importHtml(``)
+
+export class HTMLMsaPageElement extends HTMLElement {
+
+ getBaseUrl() {
+ return "/msa/page"
+ }
+ getId() {
+ return this.getAttribute("page-id")
+ }
+ isEditable() {
+ return (this.getAttribute("editable") === "true")
+ }
+ toFetch() {
+ return (this.getAttribute("fetch") !== "false")
+ }
+
+ async connectedCallback() {
+
+ exposeMsaBoxCtx(this, {
+ parent: this,
+ boxesRoute: `${this.getBaseUrl()}/${this.getId()}/_box`
+ })
+
+ this.editing = false
+ if (this.toFetch()) {
+ await this.getPage()
+ }
+
+ if(this.isEditable()) {
+ await editMsaBoxes(this, {
+ boxesRoute: `${this.getBaseUrl()}/${this.getId()}/_box`
+ })
+ this.addEventListener("msa-box-inserted", () => this.postPage())
+ this.addEventListener("msa-box-edited", () => this.postPage())
+ }
+ }
+
+ async getPage() {
+ const page = await ajax("GET", `${this.getBaseUrl()}/${this.getId()}/_page`)
+ const template = document.createElement("template")
+ template.innerHTML = page.content || ""
+ this.appendChild(template.content)
+ this.setAttribute("editable", page.editable || false)
+ }
+
+ async postPage() {
+ const exported = await exportMsaBoxes(this.children)
+ await ajax("POST", `${this.getBaseUrl()}/${this.getId()}/_page`, {
+ body: {
+ head: exported.head.innerHTML,
+ body: exported.body.innerHTML
+ }
+ })
+ }
+}
+
+// register elem
+customElements.define("msa-page", HTMLMsaPageElement)
diff --git a/pool/shard004/JavaScript/0026832_images.server.policy.js b/pool/shard004/JavaScript/0026832_images.server.policy.js
new file mode 100644
index 0000000000000000000000000000000000000000..4da8446065b2856e82caccbb92dd15c073e5234c
--- /dev/null
+++ b/pool/shard004/JavaScript/0026832_images.server.policy.js
@@ -0,0 +1,72 @@
+'use strict';
+
+/**
+ * Module dependencies
+ */
+var acl = require('acl');
+
+// Using the memory backend
+acl = new acl(new acl.memoryBackend());
+
+/**
+ * Invoke Images Permissions
+ */
+exports.invokeRolesPolicies = function () {
+ acl.allow([{
+ roles: ['admin'],
+ allows: [{
+ resources: '/api/images',
+ permissions: '*'
+ }, {
+ resources: '/api/images/:imageId',
+ permissions: '*'
+ }]
+ }, {
+ roles: ['user'],
+ allows: [{
+ resources: '/api/images',
+ permissions: ['get', 'post']
+ }, {
+ resources: '/api/images/:imageId',
+ permissions: ['get']
+ }]
+ }, {
+ roles: ['guest'],
+ allows: [{
+ resources: '/api/images',
+ permissions: ['get']
+ }, {
+ resources: '/api/images/:imageId',
+ permissions: ['get']
+ }]
+ }]);
+};
+
+/**
+ * Check If Images Policy Allows
+ */
+exports.isAllowed = function (req, res, next) {
+ var roles = (req.user) ? req.user.roles : ['guest'];
+
+ // If an Image is being processed and the current user created it then allow any manipulation
+ if (req.image && req.user && req.image.user && req.image.user.id === req.user.id) {
+ return next();
+ }
+
+ // Check for user roles
+ acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
+ if (err) {
+ // An authorization error occurred
+ return res.status(500).send('Unexpected authorization error');
+ } else {
+ if (isAllowed) {
+ // Access granted! Invoke next middleware
+ return next();
+ } else {
+ return res.status(403).json({
+ message: 'User is not authorized'
+ });
+ }
+ }
+ });
+};
diff --git a/pool/shard004/JavaScript/0026835_redirect.js b/pool/shard004/JavaScript/0026835_redirect.js
new file mode 100644
index 0000000000000000000000000000000000000000..03f7a7c06411d27bca90c0a2aafe4d23b6e7f6dc
--- /dev/null
+++ b/pool/shard004/JavaScript/0026835_redirect.js
@@ -0,0 +1,13 @@
+var actualUrl = window.location.href.toString();
+chrome.storage.sync.get("rules", function(storedRules){
+ var rules = storedRules.rules;
+ rules.forEach(function(rule){
+ if(!rule.active){
+ return;
+ }
+
+ if(actualUrl.match(new RegExp("http[s]?:\/\/" + rule.from))) {
+ window.location.href = rule.to;
+ }
+ });
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026836_Base.js b/pool/shard004/JavaScript/0026836_Base.js
new file mode 100644
index 0000000000000000000000000000000000000000..7161fef68621ebab186b436ca148e00c4dca00b8
--- /dev/null
+++ b/pool/shard004/JavaScript/0026836_Base.js
@@ -0,0 +1,262 @@
+/*global requestAnimationFrame*/
+define(['dojo/_base/declare',
+ 'dojo/_base/lang',
+ 'dojo/dom-construct',
+ 'dojo/Evented',
+ 'dojo/on',
+ 'dojo/request/xhr',
+ 'dijit/_WidgetBase'
+], function(declare, lang, domConstruct, Evented, on, xhr, WidgetBase) {
+ return declare([WidgetBase, Evented], {
+ // summary:
+ // Base class for visualizations. Handles loading data from API. Subclasses should
+ // override buildElasticsearchQuery and draw. See documentation for those methods
+ // for details.
+
+ baseClass: 'vis',
+
+ // baseQuery: Object
+ // Elasticsearch query and filters from inquiry.
+ baseQuery: null,
+
+ // dataPromise: Object
+ // Promise for data being loaded from API. Used to cancel request if loadData is
+ // called again before the previous load was finished.
+ dataPromise: null,
+
+ // datasetId: Integer
+ // ID of dataset to run inquiry against.
+ datasetId: null,
+
+ // detailsPane: Object
+ // Pane for displaying extra information about visualization content.
+ detailsPane: null,
+
+ // data: Object
+ // Data received from API for current dataset/inquiry.
+ data: null,
+
+ // isLoading: Boolean
+ // Whether or not this visualization is in the process of loading data.
+ isLoading: false,
+
+ // options: Array
+ // Array of options for a visualization.
+ // [
+ // {
+ // name: Key for option in vis class
+ // label: Label for input
+ // allowedValues: [
+ // {
+ // label: Label for option in select
+ // value: Value to set option to
+ // }
+ // ]
+ // }
+ // ]
+ //
+ // This is used to create inputs for changing visualization options. When a
+ // visualization is displayed, the options pane in the sidebar will update with
+ // inputs to change its options. If the 'allowed_values' key is specified for an
+ // option, a select box will be shown. Otherwise, a text input. When an input value
+ // changes, set(option.name, input value) will be called on the visualization object.
+ //
+ // When this.get('options') is called, another key 'value' will be mixed in
+ // with the value returned by this.get(option.name).
+ options: null,
+
+ // redrawOnResize: Boolean
+ // Whether or not to clear and redraw the visualization when this widget is resized.
+ redrawOnResize: true,
+
+ // sidebarNode: DomNode
+ // The left sidebar.
+ sidebarNode: null,
+
+ // sidebarVisible: Boolean
+ // Whether or not the left sidebar is visible.
+ sidebarVisible: false,
+
+ beforeLoad: function() {
+ this.showActivity();
+ },
+
+ buildElasticsearchQuery: function(/*Object*/baseQuery) {
+ // summary:
+ // Subclasses should override this method to provide the Elasticsearch query
+ // necessary for the visualization.
+ // baseQuery: Object
+ // Elasticsearch query with filter built from current inquiry.
+ return baseQuery;
+ },
+
+ draw: function(data) {
+ /*jshint unused:false*/
+ // summary:
+ // Subclasses should override this method to draw the visualization.
+ // data:
+ // Data returned from loadData promise.
+ },
+
+ handleData: function(data) {
+ // summary:
+ // Handle data successfully loaded from Elasticsearch.
+ this.hideActivity();
+ this.dataPromise = null;
+ this._set('data', data);
+ this.redraw(data);
+ },
+
+ handleLoadError: function(err) {
+ // summary:
+ // Handle errors loading data.
+ this.hideActivity();
+ this.dataPromise = null;
+ if (err.dojoType !== 'cancel') {
+ console.error(err);
+ }
+ },
+
+ hideActivity: function() {
+ // summary:
+ // Hide the activity indicator.
+ if (this.activityNode) {
+ domConstruct.destroy(this.activityNode);
+ this.activityNode = null;
+ }
+ },
+
+ loadData: function(baseQuery) {
+ // summary:
+ // Load data necessary for drawing. Return a promise resolved with the data which
+ // will be passed to draw.
+ // baseQuery:
+ // Base query from inquiry.
+ return this.queryDataset(this.buildElasticsearchQuery(baseQuery));
+ },
+
+ postCreate: function() {
+ this.inherited(arguments);
+ on(window, 'resize', lang.hitch(this, this.resize));
+ },
+
+ queryDataset: function(query) {
+ return xhr.post('/api/v0/datasets/' + this.datasetId + '/search', {
+ data: JSON.stringify({elasticsearch: query}),
+ handleAs: 'json',
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ });
+ },
+
+ redraw: function(data) {
+ if (data && this.domNode) {
+ domConstruct.empty(this.domNode);
+ this.draw(data);
+ }
+ },
+
+ reload: function() {
+ this.emit('display_info', '');
+
+ if (!this.datasetId) {
+ console.warn('Cannot load data without a dataset ID');
+ return;
+ }
+
+ if (this.dataPromise) {
+ this.dataPromise.cancel();
+ }
+
+ this.beforeLoad();
+ this.dataPromise = this.loadData(lang.clone(this.baseQuery));
+ this.dataPromise.then(lang.hitch(this, this.handleData), lang.hitch(this, this.handleLoadError));
+ },
+
+ resize: function() {
+ this.inherited(arguments);
+
+ if (this.redrawOnResize && this.data) {
+
+ // When resizing the window, this event will be fired many times in a row. To
+ // improve performance, only redraw on an animation frame.
+ if (this.redrawScheduled !== true) {
+ requestAnimationFrame(lang.hitch(this, function() {
+ this.redraw(this.data);
+ this.redrawScheduled = false;
+ }));
+ this.redrawScheduled = true;
+ }
+ }
+ },
+
+ showActivity: function(overlay) {
+ // summary:
+ // Show the activity indicator to note that data is being loaded.
+ // overlay: Boolean
+ // If true, dim visualization and show centered loading indicator. Use this
+ // for initially loading data and when changing filters.
+ // If false, show smaller loading indicator at the top right of the visualization.
+ // Use this for when visualizations automatically reload for streaming data.
+
+ // Default to overlay.
+ if (overlay === undefined) {
+ overlay = true;
+ }
+
+ if (this.activityNode) {
+ domConstruct.destroy(this.activityNode);
+ }
+
+ if (overlay) {
+ this.activityNode = domConstruct.toDom('');
+ domConstruct.place(this.activityNode, this.domNode);
+ }
+ else {
+ this.activityNode = domConstruct.toDom(' Loading Data');
+ domConstruct.place(this.activityNode, this.domNode);
+ }
+ },
+
+ _setBaseQueryAttr: function(/*Object*/baseQuery) {
+ // Minimal query matches all results.
+ if (!baseQuery) {
+ baseQuery = {
+ query: {
+ match_all: {}
+ },
+ };
+ }
+
+ baseQuery.size = 0;
+
+ this._set('baseQuery', baseQuery);
+ },
+
+ _setDataAttr: function(/*Object*/data) {
+ // summary:
+ // Redraw visualization with new data.
+ this._set('data', data);
+ if (data) {
+ this.redraw(data);
+ }
+ },
+
+ _getOptionsAttr: function() {
+
+ if (!this.options) {
+ return null;
+ }
+
+ return this.options.map(lang.hitch(this, function(opt) {
+ return lang.mixin(opt, { value: this.get(opt.name) });
+ }));
+ },
+
+ _setSidebarVisibleAttr: function(/*Boolean*/sidebarVisible) {
+ this._set('sidebarVisible', sidebarVisible);
+ this.emit('setSidebarVisible', sidebarVisible);
+ }
+ });
+});
diff --git a/pool/shard004/JavaScript/0026837_card_reference.js b/pool/shard004/JavaScript/0026837_card_reference.js
new file mode 100644
index 0000000000000000000000000000000000000000..6c7e5454b9fd33fb84ca7e0a364a7de1bbf39b78
--- /dev/null
+++ b/pool/shard004/JavaScript/0026837_card_reference.js
@@ -0,0 +1,72 @@
+import Oasis from "oasis";
+
+var RSVP = Oasis.RSVP,
+ Promise = RSVP.Promise;
+
+function CardReference(sandbox) {
+ this.sandbox = sandbox;
+ var card = this;
+
+ return this;
+}
+
+CardReference.prototype = {
+ waitForLoad: function() {
+ var card = this;
+ if (!this._loadPromise) {
+ this._loadPromise = this.sandbox.waitForLoad().then(function() {
+ return card;
+ }).fail(RSVP.rethrow);
+ }
+ return this._loadPromise;
+ },
+
+ metadataFor: function(name) {
+ return this.sandbox.metadataPort.request('metadataFor', name);
+ },
+
+ instruct: function(info) {
+ return this.sandbox.assertionPort.send('instruct', info);
+ },
+
+ appendTo: function(parent) {
+ if (typeof parent === 'string') {
+ var selector = parent;
+ parent = document.querySelector(selector);
+ if (!parent) { throw new Error("You are trying to append to '" + selector + "' but no element matching it was found"); }
+ }
+
+ parent.appendChild(this.sandbox.el);
+
+ return this.waitForLoad();
+ },
+
+ render: function(intent, dimensions) {
+ var card = this;
+
+ this.sandbox.activatePromise.then(function() {
+ card.sandbox.renderPort.send('render', [intent, dimensions]);
+ }).fail(RSVP.rethrow);
+ },
+
+ updateData: function(bucket, data) {
+ var sandbox = this.sandbox;
+ sandbox.activatePromise.then(function() {
+ sandbox.dataPort.send('updateData', { bucket: bucket, data: data });
+ }).fail(RSVP.rethrow);
+ },
+
+ wiretap: function(callback, binding) {
+ this.sandbox.wiretap(function() {
+ callback.apply(binding, arguments);
+ });
+ },
+
+ destroy: function() {
+ this.sandbox.conductor.unload(this);
+ }
+};
+
+Oasis.RSVP.EventTarget.mixin(CardReference.prototype);
+
+export default CardReference;
diff --git a/pool/shard004/JavaScript/0026840_verifyToken.js b/pool/shard004/JavaScript/0026840_verifyToken.js
new file mode 100644
index 0000000000000000000000000000000000000000..d487a8eb34990b90822614908bb136ffd5dd1bec
--- /dev/null
+++ b/pool/shard004/JavaScript/0026840_verifyToken.js
@@ -0,0 +1,18 @@
+
+module.exports.verify = (event, context, callback) => {
+
+ const query = event.queryStringParameters;
+
+ if(query['hub.verify_token'] === process.env.FB_VERIFY_TOKEN){
+
+ const response = {
+ statusCode: 200,
+ headers: {"content-type": "text/plain"},
+ body: query['hub.challenge'],
+ };
+ callback(null, response);
+ }
+ else{
+ callback("Failed validation. Make sure the validation tokens match", null);
+ }
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026841_live-reloaderstripped.js b/pool/shard004/JavaScript/0026841_live-reloaderstripped.js
new file mode 100644
index 0000000000000000000000000000000000000000..488abb3c5fed607aa10ae25d24b15a0c4f2e9063
--- /dev/null
+++ b/pool/shard004/JavaScript/0026841_live-reloaderstripped.js
@@ -0,0 +1,172 @@
+;(function(window) {
+
+ 0;
+
+ /**
+ * extend obj function
+ */
+ var extend = function(a, b) {
+ for (var key in b) {
+ if (b.hasOwnProperty(key)) {
+ a[key] = b[key];
+ }
+ }
+ return a;
+ };
+
+ /**
+ * Constructor
+ */
+ var LiveReloader = function(options) {
+ 0;
+ this.options = extend({}, this.options);
+ extend(this.options, options);
+ 0;
+ this._init();
+ };
+
+ /**
+ * LiveReloader options
+ */
+ LiveReloader.prototype.options = {
+ msgduration: 5000,
+ position: 'bottom-right',
+ theme: 'dark',
+ cpheight: 300,
+ cpwidth: 600
+ };
+
+ /**
+ * init function
+ * initialize and cache some vars
+ */
+ LiveReloader.prototype._init = function() {
+ // init event
+ 0;
+ //var self = this;
+ this._createControlPanel();
+ this._createButton();
+ };
+
+ /**
+ * create control panel
+ */
+ LiveReloader.prototype._createControlPanel = function() {
+ 0;
+ var bgcolor = (this.options.theme === 'dark') ? 'rgba(0, 0, 0, 0.8)' : 'rgba(255, 255, 255, 0.95)';
+ var divCP = document.createElement('div');
+ var cpMargin = 50;
+ var cpHeight = (window.innerHeight - (cpMargin * 2)) + 'px';
+ var cpWidth = (window.innerWidth - (cpMargin * 2)) + 'px';
+ divCP.id = 'reloader-cp';
+ //divCP.className = 'reloader-control-panel';
+ divCP.style.position = 'absolute';
+ divCP.style.height = cpHeight;
+ divCP.style.width = cpWidth;
+ divCP.style.top = cpMargin + 'px';
+ divCP.style.left = cpMargin + 'px';
+ divCP.style.border = '1px solid red';
+ divCP.style.zIndex = '1000';
+ divCP.style.backgroundColor = bgcolor;
+ divCP.style.display = 'none';
+
+ document.body.appendChild(divCP);
+
+
+ this.cp = divCP;
+
+ 0;
+
+
+ };
+
+
+
+ /**
+ * create button
+ */
+ LiveReloader.prototype._createButton = function() {
+ 0;
+ var cp = this.cp;
+ var bgcolor;
+ var hovercolor;
+ if (this.options.theme === 'dark') {
+ bgcolor = 'rgba(0, 0, 0, 0.8)';
+ hovercolor = 'rgba(0, 0, 0, 0.6)';
+ }
+ else {
+ bgcolor = 'rgba(255, 255, 255, 0.95)';
+ hovercolor = 'rgba(255, 255, 255, 0.85)';
+ }
+ btnOpenCP = document.createElement('div');
+ btnOpenCP.style.position = 'absolute';
+ btnOpenCP.style.height = '50px';
+ btnOpenCP.style.width = '150px';
+ btnOpenCP.style.bottom = '10px';
+ btnOpenCP.style.right = '10px';
+ btnOpenCP.style.border = '0px solid red';
+ btnOpenCP.style.zIndex = '999';
+ btnOpenCP.style.backgroundColor = bgcolor;
+ btnOpenCP.style.display = 'block';
+
+ btnOpenCP.addEventListener('click', function() {
+ 0;
+ cp.style.display = 'block';
+ });
+
+ btnOpenCP.addEventListener('mouseover', function() {
+ 0;
+ this.style.backgroundColor = hovercolor;
+ });
+
+ btnOpenCP.addEventListener('mouseout', function() {
+ 0;
+ this.style.backgroundColor = bgcolor;
+ });
+
+ document.body.appendChild(btnOpenCP);
+
+ };
+
+
+ /**
+ * show a single notification
+ */
+ LiveReloader.prototype._showMsg = function() {
+ switch (this.options.position) {
+ case 'top-right':
+ 0;
+ break;
+ case 'top-left':
+ 0;
+ break;
+ case 'bottom-left':
+ 0;
+ break;
+ default:
+ 0;
+ }
+ 0;
+ };
+
+
+
+ /**
+ * add to global namespace
+ */
+ window.LiveReloader = LiveReloader;
+
+})(window);
+
+
+var lrOptions = {
+ msgduration: 5000,
+ position: 'bottom-right',
+ theme: 'dark',
+ cpheight: 300,
+ cpwidth: 600
+};
+
+var lr = new LiveReloader(lrOptions);
+
+0;
diff --git a/pool/shard004/JavaScript/0026842_apis.js b/pool/shard004/JavaScript/0026842_apis.js
new file mode 100644
index 0000000000000000000000000000000000000000..d8cc70becdab521c5ee6aa220ca8733e406842ac
--- /dev/null
+++ b/pool/shard004/JavaScript/0026842_apis.js
@@ -0,0 +1,17 @@
+import axios from 'axios';
+import queryString from 'query-string';
+
+const productUri = '/api/products';
+export const productApi = {
+ root: productUri,
+};
+
+export const getProductsApi = (params = {}) =>
+ axios.get(`${productApi.root}?${queryString.stringify(params)}`);
+
+export const createProductApi = (categoryCode, product) =>
+ axios.post(`${productApi.root}`, {
+ product,
+ categoryCode,
+ });
+
diff --git a/pool/shard004/JavaScript/0026846_handlers.js b/pool/shard004/JavaScript/0026846_handlers.js
new file mode 100644
index 0000000000000000000000000000000000000000..497754ba0feaaba88fc78375c2502bd00531292b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026846_handlers.js
@@ -0,0 +1,164 @@
+function uploadStart(file) {
+ try {
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setStatus("Загрузка...");
+ progress.setProgress(0);
+ progress.toggleCancel(true, this);
+ }
+ catch (ex) {}
+
+ return true;
+}
+
+function fileQueued(file) {
+ try {
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setStatus("Подготовка...");
+ progress.setProgress(0);
+ progress.toggleCancel(true, this);
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function fileQueueError(file, errorCode, message) {
+ try {
+ if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
+ alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
+ return;
+ }
+
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setError();
+ progress.toggleCancel(false);
+
+ switch (errorCode) {
+ case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
+ progress.setStatus("File is too big.");
+ this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
+ break;
+ case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
+ progress.setStatus("Cannot upload Zero Byte files.");
+ this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
+ break;
+ case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
+ progress.setStatus("Invalid File Type.");
+ this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
+ break;
+ default:
+ if (file !== null) {
+ progress.setStatus("Unhandled Error");
+ }
+ this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
+ break;
+ }
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function fileDialogComplete(numFilesSelected, numFilesQueued) {
+ try {
+ if (numFilesSelected > 0) {
+ //document.getElementById(this.customSettings.cancelButtonId).disabled = false;
+ $(this.customSettings.progressTarget).show();
+ }
+
+ this.startUpload();
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function uploadProgress(file, bytesLoaded) {
+ try {
+ var percent = Math.ceil((bytesLoaded / file.size) * 100);
+
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setProgress(percent);
+ if (percent === 100) {
+ progress.setStatus("Создание thumbnail...");
+ progress.toggleCancel(false, this);
+ } else {
+ progress.setStatus("Загрузка...");
+ progress.toggleCancel(true, this);
+ }
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function uploadSuccess(file, serverData) {
+ try {
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setComplete();
+ progress.setStatus("Завершено.");
+ progress.toggleCancel(false);
+
+ progress.setThumbnail(serverData, this.customSettings.collectionTarget);
+
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function uploadComplete(file) {
+ try {
+ /* I want the next upload to continue automatically so I'll call startUpload here */
+ if (this.getStats().files_queued > 0) {
+ //this.startUpload();
+ } else {
+ var progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setComplete();
+ progress.setStatus("Все картинки успешно обработано.");
+ progress.toggleCancel(false);
+ }
+ } catch (ex) {
+ this.debug(ex);
+ }
+}
+
+function uploadError(file, errorCode, message) {
+ var progress;
+ try {
+ switch (errorCode) {
+ case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
+ try {
+ progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setCancelled();
+ progress.setStatus("Отменено");
+ progress.toggleCancel(false);
+ }
+ catch (ex1) {
+ this.debug(ex1);
+ }
+ break;
+ case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
+ try {
+ progress = new FileProgress(file, this.customSettings.progressTarget);
+ progress.setCancelled();
+ progress.setStatus("Остановлено");
+ progress.toggleCancel(true);
+ }
+ catch (ex2) {
+ this.debug(ex2);
+ }
+ case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
+ break;
+ default:
+ alert(message);
+ break;
+ }
+ } catch (ex3) {
+ this.debug(ex3);
+ }
+}
+
+// This event comes from the Queue Plugin
+function queueComplete(numFilesUploaded) {
+ var progress_bar = document.getElementById(this.customSettings.progressTarget);
+ progress_bar.style.display = 'none';
+
+ /*var status = document.getElementById("divStatus");
+ status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";*/
+}
diff --git a/pool/shard004/JavaScript/0026847_chain.js b/pool/shard004/JavaScript/0026847_chain.js
new file mode 100644
index 0000000000000000000000000000000000000000..584ddd9b4c7ec18ac7fb9272315f6f8fcca18471
--- /dev/null
+++ b/pool/shard004/JavaScript/0026847_chain.js
@@ -0,0 +1,130 @@
+
+
+function chainify(clazz) {
+ var Chain = function() {};
+
+ Chain.prototype.exec = function() {
+ return this.c_process();
+ };
+
+ Chain.prototype.c_chain = function(func, args) {
+ if (!func)
+ throw new Error('Provide a function to be chained.');
+
+ var manager;
+ if (!this.hasOwnProperty('manager')) {
+ manager = {
+ base : this,
+ timerId : null,
+ executing : false,
+ queue : []
+ };
+ } else {
+ manager = this.manager;
+ }
+
+ var f = function() {};
+ f.prototype = manager.base.constructor.prototype;
+ f.prototype.constructor = f;
+
+ var obj = function(func, args, cb, manager) {
+ this.func = func;
+ this.args = args;
+ this.cb = cb;
+ this.manager = manager;
+ };
+ obj.prototype = new f();
+ obj.prototype.constructor = obj;
+
+ var argsTmp = null;
+ var cb = null;
+ if (args) {
+ argsTmp = args;
+
+ // check if last arg is a function
+ // if so, register it as callback
+ if (args.length > 0) {
+ if (typeof args[args.length-1] === 'function') {
+ cb = args[args.length-1];
+ }
+ }
+ }
+
+ var objIns = new obj(func, argsTmp, cb, manager);
+ objIns.manager.queue.push(objIns);
+ objIns.manager.timerId = setTimeout(function() { objIns.c_process(); }, 1);
+ return objIns;
+ };
+
+ Chain.prototype.c_process = function() {
+ var self = this;
+ if (!this.manager)
+ return this;
+
+ if (this.manager.timerId)
+ clearTimeout(this.manager.timerId);
+
+ if (this.manager.queue.length > 0) {
+ var elem = this.manager.queue.shift();
+
+ var context = this;
+ context.c_next = function() {
+ if (elem.cb) {
+ var context = this;
+ context.c_next = function() {
+ self.c_process.apply(self);
+ };
+ elem.cb.apply(context);
+
+ } else {
+ self.c_process.apply(self);
+ }
+ };
+
+ elem.func.apply(context, elem.args);
+ }
+ return this;
+ };
+
+ Chain.prototype.c_clear = function() {
+ if (!this.manager)
+ return this;
+
+ if (this.manager.timerId)
+ clearTimeout(this.manager.timerId);
+ if (this.manager.queue)
+ this.manager.queue.length = 0;
+ return this;
+ };
+
+ Chain.prototype.c_delay = function() {
+ if (!this.manager)
+ return this;
+
+ if (this.manager.timerId)
+ clearTimeout(this.manager.timerId);
+ return this;
+ };
+
+ Chain.prototype.c_getSuccessors = function() {
+ if (!this.manager)
+ return [];
+
+ if (this.manager.queue)
+ return this.manager.queue;
+ return [];
+ };
+
+ Chain.prototype.c_getPredecessors = function() {
+ if (!this.manager)
+ return [];
+
+ if (this.manager.queue)
+ return this.manager.queue;
+ return [];
+ };
+
+ for (var prop in Chain.prototype)
+ clazz.prototype[prop] = Chain.prototype[prop];
+ return clazz;
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026848_index.js b/pool/shard004/JavaScript/0026848_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..c112503092cb8c75cb3e2756cd08b982c11cb3c1
--- /dev/null
+++ b/pool/shard004/JavaScript/0026848_index.js
@@ -0,0 +1,264 @@
+// Funtions to init cluster master/slave
+
+'use strict';
+
+var net = require('net');
+var tls = require('tls');
+var fs = require('fs');
+var cluster = require('cluster');
+
+var logger = require('./lib/logger');
+var common = require('./lib/common');
+var Client = require('./lib/client');
+var Parser = require('./lib/parser');
+
+
+function createServer(config, parser, tracker, log) {
+ if (!config.listen) { return null; }
+
+ var bind, server;
+
+ server = net.createServer();
+
+ server.maxConnections = +config.max_conn || 50;
+
+ bind = common.parseListenString(config.listen);
+
+ server.listen(bind.port, bind.address);
+
+ server.on('connection', function (socket) {
+ tracker.plain++;
+
+ var c = new Client(socket, parser, log);
+
+ socket.on('close', function () {
+ tracker.plain--;
+ server.emit('free');
+ });
+ });
+
+ log.info('VBNNTP Listening on', bind);
+
+ return server;
+}
+
+
+function createSecureServer(config, parser, tracker, log) {
+ if (!config.listen_ssl) { return null; }
+
+ var bind, server;
+
+ var options = {};
+ options.key = options.cert = fs.readFileSync(config.pem_file);
+
+ server = tls.createServer(options);
+
+ server.maxConnections = +config.max_conn || 50;
+
+ bind = common.parseListenString(config.listen_ssl);
+
+ server.listen(bind.port, bind.address);
+
+ server.on('connection', function (socket) {
+ tracker.secure++;
+
+ var c = new Client(socket, parser, log);
+
+ socket.on('close', function () {
+ tracker.secure--;
+ server.emit('free');
+ });
+ });
+
+ log.info('VBNNTP Listening on', bind);
+
+ return server;
+}
+
+
+// MASTER
+////////////////////////////////////////////////////////////////////////////////
+
+
+function startMaster(config) {
+ var ps_title = config.title || 'vbnntp',
+ workers_amount = +config.workers || require('os').cpus().length,
+ log = logger.create(config.logger),
+ workers = [];
+
+ // forks, configures and pushes new worker into the `workers` stack
+ function addWorker() {
+ var worker = cluster.fork();
+
+ logger.listenSlaveLogger(worker, log);
+ workers.push(worker);
+
+ log.info('VBNNTP Worker added', { idx: workers.length, pid: worker.pid });
+ worker.send({ title: ps_title + ' [worker:' + workers.length + ']' });
+ }
+
+ // --[ master events ]--------------------------------------------------------
+
+ // when one of the workers dies, master get notifications with `death` event
+ cluster.on('death', function (worker) {
+ var idx = workers.indexOf(worker);
+
+ // when existing (in the `workers` stack) worker dies - restart
+ if (idx >= 0) {
+ log.warn('VBNNTP Worker ' + worker.pid + ' died. Restarting...');
+ delete workers[idx];
+ // do not storm with worer recreation
+ setTimeout(addWorker, 1000);
+ return;
+ }
+
+ // not in the workers list (old worker) - let it go...
+ log.info('VBNNTP Worker ' + worker.pid + ' stopped.');
+ });
+
+ // soft-restart all workers
+ process.on('SIGHUP', function () {
+ var old_workers = workers;
+
+ log.info('VBNNTP Restarting workers');
+
+ // start new workers
+ workers = [];
+ while (workers.length < workers_amount) {
+ addWorker();
+ }
+
+ // request old workers to stop listen new connections
+ old_workers.forEach(function (w) {
+ w.send({ stop: true });
+ });
+ });
+
+ // kill all workers and master
+ process.once('SIGINT', function () {
+ var worker;
+ cluster.removeAllListeners('death');
+
+ while (workers.length) {
+ worker = workers.shift();
+
+ // sometimes workers dies faster than master
+ if (worker) {
+ worker.kill('SIGINT');
+ }
+
+ worker = null;
+ }
+
+ process.exit(0);
+ });
+
+ // restart logger
+ process.on('SIGUSR1', function () {
+ log.info('VBNNTP Restarting logger');
+ log.restart();
+ log.info('VBNNTP Logger restarted');
+ });
+
+ // softly stop all workers and then kill em all with master
+ process.once('SIGTERM', function () {
+ var alive = workers.length;
+
+ cluster.removeAllListeners('death');
+ cluster.on('death', function () {
+ alive--;
+
+ if (alive === 0) {
+ process.exit(0);
+ }
+ });
+
+ while (workers.length) {
+ workers.shift().send({ stop: true });
+ }
+ });
+
+ // something went wrong - report error
+ process.on('uncaughtException', function (err) {
+ log.error('Unexpected exception: ' + common.dumpError(err));
+ });
+
+ // --[ start initial workers ]------------------------------------------------
+
+ process.title = ps_title;
+ log.info('VBNNTP Master started', { pid: process.pid });
+
+ while (workers.length < workers_amount) {
+ addWorker();
+ }
+}
+
+
+// WORKER
+////////////////////////////////////////////////////////////////////////////////
+
+
+function startWorker(config) {
+ var status, clients, servers, log, database, commander;
+
+ clients = { plain: 0, secure: 0 };
+ servers = { plain: null, secure: null };
+ log = logger.createSlaveLogger(process, config.logger.severity || 'INFO');
+
+ // --[ worker events ]--------------------------------------------------------
+
+ // got message from master
+ process.on('message', function (cmd) {
+ if (cmd.title) {
+ process.title = cmd.title;
+ } else if (cmd.stop) {
+ log.debug('VBNNTP Stoppping worker', { pid: process.pid });
+ process.title += ' (stopping)';
+
+ Object.keys(servers).forEach(function (type) {
+ if (!servers[type]) { return; }
+
+ servers[type].removeAllListeners('connection');
+
+ servers[type].on('free', function () {
+ if (clients.plain === 0 && clients.secure === 0) {
+ process.exit(0);
+ }
+ });
+
+ });
+
+ if (clients.plain === 0 && clients.secure === 0) {
+ process.exit(1);
+ }
+ }
+ });
+
+ // got unhandled exception. report and terminate worker (it will be restrted
+ // by master process.
+ process.on('uncaughtException', function (err) {
+ log.error('Unexpected exception: ' + common.dumpError(err));
+ });
+
+ //
+ // Init componentes & run servers
+ //
+
+ // hardcode until single driver
+ var driver = require('./lib/drivers/vbulletin')(config, log);
+
+ driver.init(function (err) {
+ if (err) {
+ log.error('Driver init error: ' + common.dumpError(err));
+ process.exit(100);
+ }
+ var parser = new Parser(config, driver, log);
+
+ servers.plain = createServer(config, parser, clients, log);
+ servers.secure = createSecureServer(config, parser, clients, log);
+ });
+}
+
+
+exports.startMaster = startMaster;
+exports.startWorker = startWorker;
diff --git a/pool/shard004/JavaScript/0026849_UserGroup.js b/pool/shard004/JavaScript/0026849_UserGroup.js
new file mode 100644
index 0000000000000000000000000000000000000000..a761885385d0863f61c23f664f40a6e6e1c48991
--- /dev/null
+++ b/pool/shard004/JavaScript/0026849_UserGroup.js
@@ -0,0 +1,63 @@
+var kolony = require("kolony");
+var debug = kolony.common.debug;
+
+function UserGroupModel(db, module){
+ var self = new kolony.orm.model({
+ name: "UserGroup",
+ connection: "main",
+ engine: "mongoose",
+ schema: {
+ attributes: {
+ name: {
+ type: String,
+ required: true,
+ unique: true
+ },
+ creator:{
+ type: 'Reference',
+ model: 'UserProfile'
+ },
+ //namespace: {
+ // type: 'Reference,
+ // model: 'Namespace'
+ //},
+ users: [
+ {
+ type: 'Reference',
+ model: 'UserProfile'
+ }
+ ],
+ isDefault: {
+ type: Boolean,
+ default: false
+ }
+ },
+ plugins:[kolony.orm.createdModifiedPlugin],
+ hooks: {
+ findByIdAndUpdate: {
+ pre: function (id, object, callback) {
+ },
+ post: function () {
+ }
+ },
+ update: {
+ pre: function (id, object, callback) {
+ },
+ post: function () {
+ }
+ },
+ save: {
+ pre: function (next) {
+ /** @TODO: IMPLEMENT READING OF CURRENT SESSION **/
+ if (false) this.creator = currentProfile;
+ next();
+ }
+ }
+ }
+ }
+ }, db);
+
+ return self;
+}
+
+module.exports = UserGroupModel;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026851_image-coordinates.spec.js b/pool/shard004/JavaScript/0026851_image-coordinates.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..313474488b0eca4e0cc21027958db8d83c998113
--- /dev/null
+++ b/pool/shard004/JavaScript/0026851_image-coordinates.spec.js
@@ -0,0 +1,109 @@
+import { expect } from 'chai';
+import {
+ getLensModeEnlargedImageCoordinates,
+ getInPlaceEnlargedImageCoordinates
+} from '../../src/lib/imageCoordinates';
+
+describe('Image Coordinates Library', () => {
+ describe('getLensModeEnlargedImageCoordinates', () => {
+ it('returns image coordinates relative to its container', () => {
+ const enlargedImageContainerDimensions = {
+ width: 4,
+ height: 4
+ };
+ const smallImage = {
+ width: 4,
+ height: 4
+ };
+ const largeImage = {
+ width: 8,
+ height: 8
+ };
+ const position = {
+ x: 2,
+ y: 2
+ };
+ const lensCursorOffset = { x: 1, y: 1 };
+
+ const actual = getLensModeEnlargedImageCoordinates({
+ smallImage,
+ largeImage,
+ position,
+ cursorOffset: lensCursorOffset,
+ containerDimensions: enlargedImageContainerDimensions
+ });
+
+ expect(actual).to.deep.equal({ x: -2, y: -2 });
+ });
+
+ it('clamps position according to lens', () => {
+ const enlargedImageContainerDimensions = {
+ width: 4,
+ height: 4
+ };
+ const smallImage = {
+ width: 4,
+ height: 4
+ };
+ const largeImage = {
+ width: 8,
+ height: 8
+ };
+ const position = {
+ x: 1,
+ y: 3
+ };
+ const lensCursorOffset = { x: 1, y: 1 };
+
+ const actual = getLensModeEnlargedImageCoordinates({
+ smallImage,
+ largeImage,
+ position,
+ cursorOffset: lensCursorOffset,
+ containerDimensions: enlargedImageContainerDimensions
+ });
+
+ expect(actual).to.deep.equal({ x: -0, y: -4 });
+ });
+ });
+
+ describe('getInPlaceEnlargedImageCoordinates', () => {
+ it('returns image coordinates relative to its container', () => {
+ const containerDimensions = {
+ width: 4,
+ height: 4
+ };
+ const largeImage = {
+ width: 8,
+ height: 8
+ };
+ const position = {
+ x: 2,
+ y: 2
+ };
+
+ const actual = getInPlaceEnlargedImageCoordinates({ containerDimensions, largeImage, position });
+
+ expect(actual).to.deep.equal({ x: -2, y: -2 });
+ });
+
+ it('clamps coordinates to the container when position is outside', () => {
+ const containerDimensions = {
+ width: 4,
+ height: 4
+ };
+ const largeImage = {
+ width: 8,
+ height: 8
+ };
+ const position = {
+ x: 5,
+ y: -1
+ };
+
+ const actual = getInPlaceEnlargedImageCoordinates({ containerDimensions, largeImage, position });
+
+ expect(actual).to.deep.equal({ x: -4, y: 0 });
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0026852_boundsrenderingsystem.js b/pool/shard004/JavaScript/0026852_boundsrenderingsystem.js
new file mode 100644
index 0000000000000000000000000000000000000000..f822e8c5c35d96e12cbb409fe4e8ba513db6f01f
--- /dev/null
+++ b/pool/shard004/JavaScript/0026852_boundsrenderingsystem.js
@@ -0,0 +1,40 @@
+/**
+ * Display collision bounds.
+ *
+ * @param {DisplayObjectContainer} layer
+ */
+function BoundsRenderingSystem(layer) {
+ IteratingSystem.call(this, Position, Bounds);
+ this.l = layer;
+}
+
+__extend(BoundsRenderingSystem, IteratingSystem, {
+ a: function onEntityAdded(entity) {
+ var bounds = entity.g(Bounds);
+ if (bounds.w == 1 || bounds.h == 1) {
+ this.l.a(bounds.gfx = new Graphics(function(ctx, color) {
+ ctx.beginPath();
+ ctx.fillStyle = 'rgba(0,255,0,.4)';
+ ctx.fillRect(0, 0, bounds.w, bounds.h);
+ ctx.closePath();
+ }));
+ } else {
+ this.l.a(bounds.gfx = new Graphics(function(ctx, color) {
+ ctx.beginPath();
+ ctx.strokeStyle = 'rgba(0,255,0,.4)';
+ ctx.strokeRect(0.5, 0.5, bounds.w - 1, bounds.h - 1);
+ ctx.closePath();
+ }));
+ }
+ },
+ r: function onEntityRemoved(entity) {
+ this.l.r(entity.g(Bounds).gfx);
+ },
+ ue: function updateEntity(entity) {
+ var position = entity.g(Position);
+ var bounds = entity.g(Bounds);
+
+ bounds.gfx.x = (position.x | 0) - (bounds.w / 2 | 0);
+ bounds.gfx.y = (position.y | 0) - (bounds.h / 2 | 0);
+ }
+});
diff --git a/pool/shard004/JavaScript/0026856_ua.pivottable.directive.spec.js b/pool/shard004/JavaScript/0026856_ua.pivottable.directive.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..73a4b2cafb805d8bce15e9e62ce3d6a86513598d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026856_ua.pivottable.directive.spec.js
@@ -0,0 +1,73 @@
+(function () {
+ 'use strict';
+
+ describe('ua.pivottable.directive', function () {
+
+ var $rootScope, $compile, scope;
+
+ beforeEach(function () {
+ module('ua.pivottable');
+
+ inject(function (_$rootScope_, _$compile_) {
+ $rootScope = _$rootScope_;
+ $compile = _$compile_;
+ });
+
+ scope = $rootScope.$new();
+
+ // Sample Test data
+ scope.testData = [
+ {'firstName': 'Tom', lastName: 'Smith', age: 12},
+ {'firstName': 'Bob', lastName: 'Smith', age: 45},
+ {'firstName': 'Gary', lastName: 'Smith', age: 23}
+ ];
+ scope.testRows = ['firstName'];
+ scope.testCols = ['lastName'];
+ scope.testVals = ['age'];
+ scope.testAggregatorName = 'Average';
+ scope.testRendererName = 'Heatmap';
+ });
+
+ afterEach(function () {
+ scope = undefined;
+ });
+
+ function validateTableData(directiveHtml){
+ expect(directiveHtml).not.toBe('');
+ expect(directiveHtml).toContain('firstName');
+ expect(directiveHtml).toContain('lastName');
+ expect(directiveHtml).toContain('Bob');
+ expect(directiveHtml).toContain('Smith');
+ expect(directiveHtml).toContain('age');
+ expect(directiveHtml).toContain('45');
+ }
+
+ it('element is empty if no pivot-data is not specified', function () {
+ var element = $compile(' ')(scope);
+ scope.$digest();
+ expect(element.html()).toBe('');
+ });
+
+ it('element contains the data properties if pivot-data attr is specified', function () {
+ var element = $compile(' ')(scope);
+ scope.$digest();
+
+ var directiveHtml = element.html();
+ validateTableData(directiveHtml);
+ });
+
+ it('element contains correct attributes when specified', function () {
+ var htmlElement = ' ';
+
+ var element = $compile(htmlElement)(scope);
+ scope.$digest();
+
+ var directiveHtml = element.html();
+ validateTableData(directiveHtml);
+
+ expect(element[0].querySelector('.pvtRows').innerHTML).toContain('firstName');
+ expect(element[0].querySelector('.pvtCols').innerHTML).toContain('lastName');
+ });
+ });
+
+}());
diff --git a/pool/shard004/JavaScript/0026857_index.js b/pool/shard004/JavaScript/0026857_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a1f069d6c0caf71f820008e0418936d9b275582
--- /dev/null
+++ b/pool/shard004/JavaScript/0026857_index.js
@@ -0,0 +1,145 @@
+'use strict'
+
+const net = require('net')
+const mafmt = require('mafmt')
+const withIs = require('class-is')
+const errCode = require('err-code')
+const log = require('debug')('libp2p:tcp')
+const toConnection = require('./socket-to-conn')
+const createListener = require('./listener')
+const { multiaddrToNetConfig } = require('./utils')
+const { AbortError } = require('abortable-iterator')
+const { CODE_CIRCUIT, CODE_P2P } = require('./constants')
+
+/**
+ * @typedef {import('multiaddr').Multiaddr} Multiaddr
+ * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
+ */
+
+class TCP {
+ /**
+ * @class
+ * @param {object} options
+ * @param {Upgrader} options.upgrader
+ */
+ constructor ({ upgrader }) {
+ if (!upgrader) {
+ throw new Error('An upgrader must be provided. See https://github.com/libp2p/interface-transport#upgrader.')
+ }
+ this._upgrader = upgrader
+ }
+
+ /**
+ * @async
+ * @param {Multiaddr} ma
+ * @param {object} options
+ * @param {AbortSignal} options.signal - Used to abort dial requests
+ * @returns {Connection} An upgraded Connection
+ */
+ async dial (ma, options) {
+ options = options || {}
+ const socket = await this._connect(ma, options)
+ const maConn = toConnection(socket, { remoteAddr: ma, signal: options.signal })
+ log('new outbound connection %s', maConn.remoteAddr)
+ const conn = await this._upgrader.upgradeOutbound(maConn)
+ log('outbound connection %s upgraded', maConn.remoteAddr)
+ return conn
+ }
+
+ /**
+ * @private
+ * @param {Multiaddr} ma
+ * @param {object} options
+ * @param {AbortSignal} options.signal - Used to abort dial requests
+ * @returns {Promise} Resolves a TCP Socket
+ */
+ _connect (ma, options = {}) {
+ if (options.signal && options.signal.aborted) {
+ throw new AbortError()
+ }
+
+ return new Promise((resolve, reject) => {
+ const start = Date.now()
+ const cOpts = multiaddrToNetConfig(ma)
+
+ log('dialing %j', cOpts)
+ const rawSocket = net.connect(cOpts)
+
+ const onError = err => {
+ err.message = `connection error ${cOpts.host}:${cOpts.port}: ${err.message}`
+ done(err)
+ }
+
+ const onTimeout = () => {
+ log('connnection timeout %s:%s', cOpts.host, cOpts.port)
+ const err = errCode(new Error(`connection timeout after ${Date.now() - start}ms`), 'ERR_CONNECT_TIMEOUT')
+ // Note: this will result in onError() being called
+ rawSocket.emit('error', err)
+ }
+
+ const onConnect = () => {
+ log('connection opened %j', cOpts)
+ done()
+ }
+
+ const onAbort = () => {
+ log('connection aborted %j', cOpts)
+ rawSocket.destroy()
+ done(new AbortError())
+ }
+
+ const done = err => {
+ rawSocket.removeListener('error', onError)
+ rawSocket.removeListener('timeout', onTimeout)
+ rawSocket.removeListener('connect', onConnect)
+ options.signal && options.signal.removeEventListener('abort', onAbort)
+
+ if (err) return reject(err)
+ resolve(rawSocket)
+ }
+
+ rawSocket.on('error', onError)
+ rawSocket.on('timeout', onTimeout)
+ rawSocket.on('connect', onConnect)
+ options.signal && options.signal.addEventListener('abort', onAbort)
+ })
+ }
+
+ /**
+ * Creates a TCP listener. The provided `handler` function will be called
+ * anytime a new incoming Connection has been successfully upgraded via
+ * `upgrader.upgradeInbound`.
+ *
+ * @param {*} [options]
+ * @param {function(Connection)} handler
+ * @returns {Listener} A TCP listener
+ */
+ createListener (options, handler) {
+ if (typeof options === 'function') {
+ handler = options
+ options = {}
+ }
+ options = options || {}
+ return createListener({ handler, upgrader: this._upgrader }, options)
+ }
+
+ /**
+ * Takes a list of `Multiaddr`s and returns only valid TCP addresses
+ *
+ * @param {Multiaddr[]} multiaddrs
+ * @returns {Multiaddr[]} Valid TCP multiaddrs
+ */
+ filter (multiaddrs) {
+ multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]
+
+ return multiaddrs.filter(ma => {
+ if (ma.protoCodes().includes(CODE_CIRCUIT)) {
+ return false
+ }
+
+ return mafmt.TCP.matches(ma.decapsulateCode(CODE_P2P))
+ })
+ }
+}
+
+module.exports = withIs(TCP, { className: 'TCP', symbolName: '@libp2p/js-libp2p-tcp/tcp' })
diff --git a/pool/shard004/JavaScript/0026860_manage_books.js b/pool/shard004/JavaScript/0026860_manage_books.js
new file mode 100644
index 0000000000000000000000000000000000000000..80124059c577c45a3af07a38dcb6b0abb7c8ba80
--- /dev/null
+++ b/pool/shard004/JavaScript/0026860_manage_books.js
@@ -0,0 +1,111 @@
+'use strict';
+
+/**
+ * Module dependencies.
+ */
+var mongoose = require('mongoose'),
+ Schema = mongoose.Schema;
+
+/**
+ * Books Schema
+ */
+
+var BooksSchema = new Schema({
+ bookId: {
+ type: String,
+ },
+
+ bookName: {
+ type: String,
+ required: true
+ },
+
+ authorName: {
+ type: String,
+ required: true
+ },
+
+ availabilityStatus: {
+ type : Boolean,
+ default : true
+ },
+
+ quantity : {
+ type : Number,
+ required: true,
+ default : 0
+ },
+
+ createdAt: {
+ type: Date,
+ },
+
+ updatedAt: {
+ type: Date
+ },
+
+});
+
+var Books = mongoose.model('Books', BooksSchema);
+
+BooksSchema.pre('save', function(next){
+ var now = new Date();
+ var year = now.getFullYear();
+ var month = now.getMonth()+1;
+ if(month <= 9){
+ month = 0+month.toString();
+ }
+
+ var day = now.getDate();
+ if(day <= 9){
+ day = 0+day.toString();
+ }
+
+ this.updateAt = now;
+ if(!this.createdAt){
+ this.createdAt = now;
+ }
+ var doc = this;
+ Books.findOne({}).sort({ 'createdAt' : -1 }).limit(1).exec(function(error, latestBook) {
+ if(error) return next(error);
+ if(latestBook != null && latestBook != undefined && latestBook.bookId != '' && latestBook.bookId != undefined){
+ var lastDate = latestBook.createdAt
+ var lyear = lastDate.getFullYear();
+
+ var lmonth = lastDate.getMonth()+1;
+
+ if(lmonth <= 9){
+ lmonth = 0+lmonth.toString();
+ }
+
+ var lday = lastDate.getDate();
+ if(lday <= 9){
+ lday = 0+lday.toString();
+ }
+
+
+ if(year.toString() + month.toString() +day.toString() == lyear.toString() + lmonth.toString() +lday.toString()){
+ var currentUserId = latestBook.bookId.substr(11, 12)
+
+
+ if(parseInt(currentUserId) < 9){
+ var increasedCount = parseInt(currentUserId)+1;
+
+ currentUserId = '00'+increasedCount;
+ }else if(parseInt(currentUserId) < 99){
+ var increasedCount = parseInt(currentUserId)+1;
+ currentUserId = '0'+increasedCount;
+ }
+
+ var currentLastId = currentUserId;
+ doc.bookId = "BID"+year.toString() + month.toString() +day.toString()+currentLastId;
+ }else{
+ doc.bookId = "BID"+year.toString() + month.toString() +day.toString()+'001';
+ }
+ }else{
+ doc.bookId = "BID"+year.toString() + month.toString() +day.toString()+'001';
+ }
+ next();
+ });
+ //next();
+});
diff --git a/pool/shard004/JavaScript/0026864_reducer.js b/pool/shard004/JavaScript/0026864_reducer.js
new file mode 100644
index 0000000000000000000000000000000000000000..69bcb2f89edbe1d1692e93659dda1889a0ed2cd3
--- /dev/null
+++ b/pool/shard004/JavaScript/0026864_reducer.js
@@ -0,0 +1,69 @@
+import set from "lodash/fp/set";
+import { getFiles } from "./getFiles";
+
+// The Redux reducer.
+export default function (state, action){
+ state = state || {};
+ switch (action.type) {
+ case "REQUEST_INDEX":
+ return Object.assign(state, {
+ indexFetching: true
+ });
+ case "RECEIVE_INDEX":
+ return Object.assign(state, {
+ indexFetching: false,
+ index: action.data
+ });
+ case "NAVIGATE":
+ return Object.assign(state, {
+ params: action.params || {
+ unit: 1,
+ module: 1,
+ example: 1
+ }
+ });
+ case "RECEIVE_FILE":
+ case "EDIT_FILE":
+ return set([
+ "index",
+ "units", action.params.unit - 1, // Use zero-based index.
+ "modules", action.params.module - 1,
+ "examples", action.params.example - 1,
+ "files", action.filename
+ ], action.content, state);
+ case "NEXT":
+ return go(state, 1);
+ case "PREVIOUS":
+ return go(state, -1);
+ case "SAVED":
+ return set("notify", action, state);
+ case "INSERT":
+ state = set([
+ "index",
+ "units", state.params.unit - 1, // Use zero-based index.
+ "modules", state.params.module - 1,
+ "examples", state.params.example, // In the next example,
+ "files"
+ ], getFiles(state), state); // set files of the current example.
+ return go(state, 1);
+ default:
+ return state;
+ }
+};
+
+// Goes to the next or previous example.
+function go(state, increment){
+
+ // Update the example param in the state.
+ const example = state.params.example + increment;
+ state = set("params.example", example, state);
+
+ // Update the notification in the state.
+ const FORWARD = (increment === 1);
+ return set("notify", {
+ message: FORWARD ? "→" : "←",
+ position: FORWARD ? 0.75 : 0.25,
+ size: 30,
+ time: Date.now()
+ }, state);
+}
diff --git a/pool/shard004/JavaScript/0026868_dialogs.js b/pool/shard004/JavaScript/0026868_dialogs.js
new file mode 100644
index 0000000000000000000000000000000000000000..650857d3618eb55a6db3e4079edf84b5d2ab7432
--- /dev/null
+++ b/pool/shard004/JavaScript/0026868_dialogs.js
@@ -0,0 +1,163 @@
+/*
+ * Dialogs code for TigerGammonServer HTML5 Client
+ *
+ * This file is licensed under the Affero General Public License
+ * version 3 or later; see LICENSE
+ *
+ * @author Andreas Hausmann
+ * @copyright Andreas Hausmann 2013 - 2015
+ *
+*/
+
+var dlgHtml = {
+ invite: "hallo",
+};
+
+function loadDialogs() {
+ var dlg = (function() {
+ var signal_colors = {1: "green", 3: "red", 0: "orange"};
+ return {
+ dialogResign: function () {
+ $("#resignDialog").load('resign.html').show();
+ },
+ sendResign: function () {
+ var value = $("#cResign input:checked").attr('value');
+ tgc.cc.sendCmd("resign " + value);
+ this.cancelResign();
+ },
+ cancelResign: function () {
+ $("#resignDialog").hide();
+ },
+ dialogWatch: function (player) {
+ $("#invitation #wPlayerName").html(player);
+ $("#invitationSection").hide();
+ $("#send_invite").hide();
+ $("#inviteDialog").show();
+ },
+ dialogInvite: function (player) {
+ var toggle = function (id, value) {
+ if (value) {
+ $(id).show();
+ } else {
+ $(id).hide();
+ }
+ };
+ $("#standardBGvariant").prop("checked", true);
+ this.displayBackgammonVariation();
+ $("#useClockToggle").prop("checked", false);
+ this.displayUseClock();
+ $("#inviteSavedGames").hide();
+ tgc.blackBoard['savedGamesFocusOld'] = tgc.blackBoard['savedGamesFocus']
+ tgc.blackBoard['savedGamesFocus'] = '#inviteSavedGames';
+ tgc.blackBoard['invitationHrSemaphore'] = 0;
+ tgc.cc.sendCmd("savedgame " + player);
+ toggle("#xlockInvitationSection", tgc.action.playersList.features(player, 'xlock'));
+ toggle("#clockInvitationSection", tgc.action.playersList.features(player, 'clock'));
+ toggle(".tavliVariants", tgc.action.playersList.features(player, 'tavli'));
+ $("#invitation #iPlayerName").html(player);
+ $("#invitation #wPlayerName").html(player);
+ $("#invitation #iResumeName").html(player);
+ $("#invitationHr").hide();
+ $("#inviteDialog").show();
+ },
+ watch: function (player) {
+ return function(event) {
+ dlg.dialogWatch(player);
+ return false;
+ };
+ },
+ invite: function (player) {
+ return function(event) {
+ dlg.dialogInvite(player);
+ return false;
+ };
+ },
+ hideInvite: function () {
+ $("#inviteDialog").hide();
+ $("#invitationSection").show();
+ $("#send_invite").show();
+ $('#inviteSavedGames .gaContent table').remove()
+ tgc.blackBoard['savedGamesFocus'] = tgc.blackBoard['savedGamesFocusOld'];
+ },
+ hideClockInvitation: function () {
+ $("#iCLabel").show();
+ $("#iCData").hide();
+ if (tgc.blackBoard['invitationHrSemaphore'] == 1) {
+ $("#invitationHr").hide();
+ }
+ tgc.blackBoard['invitationHrSemaphore']--;
+ },
+ showClockInvitation: function () {
+ $("#iCData").show();
+ $("#iCLabel").hide();
+ if (tgc.blackBoard['invitationHrSemaphore'] == 0) {
+ $("#invitationHr").show();
+ }
+ tgc.blackBoard['invitationHrSemaphore']++;
+ },
+ hideBackgammonVariation: function () {
+ $("#bVLabel").show();
+ $("#backgammonVariation").hide();
+ if (tgc.blackBoard['invitationHrSemaphore'] == 1) {
+ $("#invitationHr").hide();
+ }
+ tgc.blackBoard['invitationHrSemaphore']--;
+ },
+ showBackgammonVariation: function () {
+ $("#backgammonVariation").show();
+ $("#bVLabel").hide();
+ if (tgc.blackBoard['invitationHrSemaphore'] == 0) {
+ $("#invitationHr").show();
+ }
+ tgc.blackBoard['invitationHrSemaphore']++;
+ },
+ displayBackgammonVariation: function () {
+ var element = $("#backgammonVariation input:checked"),
+ variation = element.attr('value'),
+ label = element.parent().text();
+ if (variation == 'standard') {
+ $("#bgVariant").hide();
+ } else {
+ $("#bgVariant").html('of '+label+' ');
+ $("#bgVariant").show();
+ }
+ },
+ displayUseClock: function () {
+ var element = $("#useClockToggle");
+ if (element.prop("checked")) {
+ $("#usingClock").show();
+ } else {
+ $("#usingClock").hide();
+ }
+ },
+ sendUnwatch: function () {
+ tgc.cc.sendCmd("unwatch");
+ $(".watching").hide();
+ $(".playing").show();
+ },
+ sendWatch: function () {
+ var watch = "watch "+$("#invitation #wPlayerName").html();
+ tgc.cc.sendCmd(watch);
+ this.hideInvite();
+ $(".playing").hide();
+ $(".watching").show();
+ },
+ sendInvite: function () {
+ var variation = $("#backgammonVariation input:checked").attr('value'),
+ matchLength = document.getElementById("iMatchLength"),
+ ML = matchLength.value == "" ? "1" : matchLength.value,
+ invitation = "invite "+$("#invitation #iPlayerName").html()+" "+ML;
+ if (variation != 'standard') {
+ invitation += ' ' + variation;
+ }
+ if ($("#useClockToggle").prop("checked")) {
+ invitation += ' clock_' + $("#iCBronstein").prop('value')
+ + '_' + $("#iCReserve").prop('value');
+ }
+ tgc.cc.sendCmd(invitation);
+ this.hideInvite();
+ },
+ }
+ }());
+ return dlg;
+}
diff --git a/pool/shard004/JavaScript/0026869_test-retry-operation.js b/pool/shard004/JavaScript/0026869_test-retry-operation.js
new file mode 100644
index 0000000000000000000000000000000000000000..cecfa3b731001341ec6bc99cae3c6fe87053102a
--- /dev/null
+++ b/pool/shard004/JavaScript/0026869_test-retry-operation.js
@@ -0,0 +1,106 @@
+var common = require('../common');
+var assert = common.assert;
+var fake = common.fake.create();
+var retry = require(common.dir.lib + '/retry');
+
+(function testErrors() {
+ var operation = retry.operation();
+
+ var error = new Error('some error');
+ var error2 = new Error('some other error');
+ operation._errors.push(error);
+ operation._errors.push(error2);
+
+ assert.deepEqual(operation.errors(), [error, error2]);
+})();
+
+(function testMainErrorReturnsMostFrequentError() {
+ var operation = retry.operation();
+ var error = new Error('some error');
+ var error2 = new Error('some other error');
+
+ operation._errors.push(error);
+ operation._errors.push(error2);
+ operation._errors.push(error);
+
+ assert.strictEqual(operation.mainError(), error);
+})();
+
+(function testMainErrorReturnsLastErrorOnEqualCount() {
+ var operation = retry.operation();
+ var error = new Error('some error');
+ var error2 = new Error('some other error');
+
+ operation._errors.push(error);
+ operation._errors.push(error2);
+
+ assert.strictEqual(operation.mainError(), error2);
+})();
+
+(function testAttempt() {
+ var operation = retry.operation();
+ var fn = new Function();
+
+ var timeoutOpts = {
+ timeout: 1,
+ cb: function() {}
+ };
+ operation.attempt(fn, timeoutOpts);
+
+ assert.strictEqual(fn, operation._fn);
+ assert.strictEqual(timeoutOpts.timeout, operation._operationTimeout);
+ assert.strictEqual(timeoutOpts.cb, operation._operationTimeoutCb);
+})();
+
+(function testRetry() {
+ var times = 3;
+ var error = new Error('some error');
+ var operation = retry.operation([1, 2, 3]);
+ var attempts = 0;
+
+ var finalCallback = fake.callback('finalCallback');
+ fake.expectAnytime(finalCallback);
+
+ var fn = function() {
+ operation.attempt(function(currentAttempt) {
+ attempts++;
+ assert.equal(currentAttempt, attempts);
+ if (operation.retry(error)) {
+ return;
+ }
+
+ assert.strictEqual(attempts, 4);
+ assert.strictEqual(operation.attempts(), attempts);
+ assert.strictEqual(operation.mainError(), error);
+ finalCallback();
+ });
+ };
+
+ fn();
+})();
+
+(function testRetryForever() {
+ var error = new Error('some error');
+ var operation = retry.operation({ retries: 3, forever: true });
+ var attempts = 0;
+
+ var finalCallback = fake.callback('finalCallback');
+ fake.expectAnytime(finalCallback);
+
+ var fn = function() {
+ operation.attempt(function(currentAttempt) {
+ attempts++;
+ assert.equal(currentAttempt, attempts);
+ if (attempts !== 6 && operation.retry(error)) {
+ return;
+ }
+
+ assert.strictEqual(attempts, 6);
+ assert.strictEqual(operation.attempts(), attempts);
+ assert.strictEqual(operation.mainError(), error);
+ finalCallback();
+ });
+ };
+
+ fn();
+})();
diff --git a/pool/shard004/JavaScript/0026874_board.js b/pool/shard004/JavaScript/0026874_board.js
new file mode 100644
index 0000000000000000000000000000000000000000..776a31c04b49b8b4979af81dd5be57028489f457
--- /dev/null
+++ b/pool/shard004/JavaScript/0026874_board.js
@@ -0,0 +1,96 @@
+var boardSize = 0;
+var theCanvas = document.getElementById('canvas');
+var theContext = theCanvas.getContext('2d');
+
+var winHeight;
+var winWidth;
+var eachHeight;
+var eachWidth;
+
+function boardInit() {
+ if (boardSize > 0) {
+ boardResizeCanvas();
+ boardDraw();
+ }
+}
+
+function boardResizeCanvas() {
+ theCanvas.width = window.innerWidth;
+ theCanvas.height = window.innerHeight;
+ winWidth = window.innerWidth;
+ winHeight = window.innerHeight;
+ eachHeight = winHeight / boardSize;
+ eachWidth = winWidth / boardSize;
+}
+
+function boardDraw() {
+ for (var x = 0; x <= boardSize; x++) {
+ var lineheight = eachHeight * x;
+ var lineWidth = eachWidth * x;
+
+ theContext.moveTo(0, lineheight);
+ theContext.lineTo(winWidth, lineheight);
+ theContext.moveTo(lineWidth, 0);
+ theContext.lineTo(lineWidth, winHeight);
+
+ }
+ theContext.lineWidth = 1;
+ theContext.strokeStyle = "#d3d3d3";
+ theContext.stroke();
+
+}
+
+function drawPlayer(x, y) {
+ theContext.fillStyle = "#FF0000";
+ theContext.fillRect(x * eachWidth + 2, y * eachHeight + 2, eachWidth - 4, eachHeight - 4);
+}
+
+function deletePlayer(x, y) {
+ var eachHeight = winHeight / boardSize;
+ var eachWidth = winWidth / boardSize;
+
+
+ theContext.fillStyle = "#eee";
+ theContext.fillRect(x * eachWidth + 1, y * eachHeight + 1, eachWidth - 2, eachHeight - 2);
+}
+
+var players = new Array();
+
+
+function movePlayer(player) {
+ console.log("move");
+ var found = false;
+ var i = players.length;
+ while (i--) {
+ if (players[i].UserName === player.UserName){
+ found = true;
+ break;
+ }
+
+ }
+ console.log(found);
+ console.log(i);
+
+
+ if (found) {
+ deletePlayer(players[i].x, players[i].y);
+ players[i] = player;
+ drawPlayer(player.x, player.y);
+ } else {
+ players.push(player);
+ drawPlayer(player.x, player.y);
+ }
+
+}
+
+
+function containsName(a, obj) {
+ var i = a.length;
+ while (i--) {
+ if (a[i] === obj) {
+ return true;
+ }
+ }
+ return false;
+}
+
diff --git a/pool/shard004/JavaScript/0026875_dialogs.js b/pool/shard004/JavaScript/0026875_dialogs.js
new file mode 100644
index 0000000000000000000000000000000000000000..90abae206f574b9f5ed4bc60a6cac39fd089e693
--- /dev/null
+++ b/pool/shard004/JavaScript/0026875_dialogs.js
@@ -0,0 +1,33 @@
+$(document).foundation({
+ reveal: {
+ animation: 'none' ,
+ animation_speed: 0,
+ close_on_background_click: true,
+ close_on_esc: true,
+ dismiss_modal_class: "reveal-modal-close"
+ }
+});
+
+// Honour any html autofocus attributes on inputs inside a modal dialog
+$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
+ var modal = $(this);
+ modal.find('[autofocus]').focus();
+ $('form[data-client-side-validations]').enableClientSideValidations();
+ $('.searchable_select', modal).select2();
+ // If a modal is launched again, ensure the submit button is re-enabled.
+ if ($('input[data-disable-with]').length > 0) {
+ Rails.enableElement($('input[data-disable-with]')[0]);
+ };
+ // Refresh layout of foundation widgets
+ $(document).foundation('reflow');
+ initClockpickersIn("body");
+
+ var resizeSelect2DropDownsToFitModal = function(){
+ $('.select2', modal).css('width', "100%");
+ };
+});
+
+// If there was an error submitting a modal form, be sure to re-enable the submit button
+$(document).on('ajax:error', function(event) {
+ Rails.enableElement($('input[data-disable-with]')[0]);
+});
diff --git a/pool/shard004/JavaScript/0026876_index.js b/pool/shard004/JavaScript/0026876_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..8c9ac6455dcf70f8b7a83feaa34a2af1bbbf52f4
--- /dev/null
+++ b/pool/shard004/JavaScript/0026876_index.js
@@ -0,0 +1,172 @@
+'use strict';
+
+// Core packages
+const fs = require('fs');
+const util = require('util');
+const ejs = require('ejs');
+const pjson = require('../../package.json');
+
+// Third-party packages
+const Generator = require('yeoman-generator');
+
+module.exports = class extends Generator {
+ prompting() {
+ let prompts = []
+
+ if (fs.existsSync(this.destinationPath('.gitignore'))) {
+ prompts.push(
+ {
+ type : 'confirm',
+ name : 'updateGitignore',
+ message : 'Should we update .gitignore?'
+ }
+ );
+ }
+
+ if (fs.existsSync(this.destinationPath('package.json'))) {
+ prompts.push(
+ {
+ type : 'confirm',
+ name : 'updateDependencies',
+ message : 'Should we update "dependencies" in package.json?'
+ }
+ );
+ prompts.push(
+ {
+ type : 'confirm',
+ name : 'updateScripts',
+ message : 'Should we update "scripts" in package.json?'
+ }
+ );
+ }
+
+ return this.prompt(prompts).then(
+ (answers) => {
+ this.answers = answers;
+ }
+ );
+ }
+
+ writing() {
+ // Defaults
+ let options = {
+ 'version': pjson.version
+ };
+
+ // Overrides
+ Object.assign(options, this.options);
+
+ // The run script itself
+ this.fs.copyTpl(
+ this.templatePath('run'),
+ this.destinationPath('run'),
+ options
+ );
+
+ // .gitignore
+ if (! fs.existsSync(this.destinationPath('.gitignore'))) {
+ this.fs.copyTpl(
+ this.templatePath('gitignore'),
+ this.destinationPath('.gitignore'),
+ options
+ );
+ } else {
+ if (this.answers.updateGitignore) {
+ const currentContents = this.fs.read(this.destinationPath('.gitignore'));
+ const incomingContents = this.fs.read(this.templatePath('gitignore'));
+ const contextualisedContents = ejs.render(incomingContents, options)
+ const currentBlocks = currentContents.split(/\r?\n\r?\n/);
+ const incomingBlocks = contextualisedContents.split(/\r?\n\r?\n/);
+
+ let addedBlocks = [];
+ let newBlocks = [];
+
+ incomingBlocks.forEach(
+ function(block) {
+ const match = block.trim().match(/^# \[([^\]]+)\] (.*)\n([\s\S]*)/);
+
+ if (match) {
+ const id = match[1]
+ const title = match[2]
+ const ignores = match[3]
+
+ newBlocks.push("# [" + id + "] " + title + "\n" + ignores.trim())
+
+ addedBlocks.push(id)
+ }
+ }
+ );
+
+ currentBlocks.forEach(
+ function(block) {
+ const match = block.trim().match(/^# \[([^\]]+)\] (.*)\n([\s\S]*)/);
+
+ if (match) {
+ const id = match[1]
+
+ // Keep blocks that haven't already been added
+ if (addedBlocks.indexOf(id) == -1) {
+ newBlocks.push(block.trim())
+ }
+ } else {
+ newBlocks.push(block.trim())
+ }
+ }
+ )
+
+ fs.writeFileSync(
+ this.destinationPath('.gitignore'),
+ newBlocks.join("\n\n"),
+ 'utf8'
+ );
+ }
+ }
+
+ // package,json
+ if (! fs.existsSync(this.destinationPath('package.json'))) {
+ // Copy default package.json
+ this.fs.copyTpl(
+ this.templatePath('package.json'),
+ this.destinationPath('package.json'),
+ options
+ );
+ } else if (this.answers.updateDependencies || this.answers.updateScripts) {
+ // We're updating package.json, so parse contents of both new and old package.json
+ const currentJson = this.fs.read(this.destinationPath('package.json'));
+ const incomingJson = this.fs.read(this.templatePath('package.json'));
+ const contextualisedJson = ejs.render(incomingJson, options)
+ const packageContents = JSON.parse(currentJson);
+ const incomingPackageContents = JSON.parse(contextualisedJson);
+
+ // Update dependencies if requested
+ if (this.answers.updateDependencies) {
+ const currentDependencies = packageContents['dependencies'] || {};
+ const incomingDependencies = incomingPackageContents['dependencies'];
+ const updatedDependencies = util._extend(currentDependencies, incomingDependencies);
+ packageContents['dependencies'] = updatedDependencies;
+ }
+
+ // Update scripts if requested
+ if (this.answers.updateScripts) {
+ const currentScripts = packageContents['scripts'] || {};
+ const incomingScripts = incomingPackageContents['scripts'];
+ const updatedScripts = util._extend(currentScripts, incomingScripts);
+ packageContents['scripts'] = updatedScripts;
+ }
+
+ // .sass-lint.yaml
+ this.fs.copyTpl(
+ this.templatePath('sass-lint.yml'),
+ this.destinationPath('.sass-lint.yml'),
+ options
+ );
+
+ const updatedJson = JSON.stringify(packageContents, null, 2);
+ fs.writeFileSync(
+ this.destinationPath('package.json'),
+ updatedJson,
+ 'utf8'
+ );
+ }
+ }
+};
diff --git a/pool/shard004/JavaScript/0026877_index.js b/pool/shard004/JavaScript/0026877_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..e850aa3fca03f1ebf641a2cafae00734bad40511
--- /dev/null
+++ b/pool/shard004/JavaScript/0026877_index.js
@@ -0,0 +1,69 @@
+/*
+ * moleculer
+ * Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer)
+ * MIT Licensed
+ */
+
+"use strict";
+
+const { isObject, isString } = require("../utils");
+const { BrokerOptionsError } = require("../errors");
+
+const Cachers = {
+ Base: require("./base"),
+ Memory: require("./memory"),
+ MemoryLRU: require("./memory-lru"),
+ Redis: require("./redis")
+};
+
+function getByName(name) {
+ /* istanbul ignore next */
+ if (!name)
+ return null;
+
+ let n = Object.keys(Cachers).find(n => n.toLowerCase() == name.toLowerCase());
+ if (n)
+ return Cachers[n];
+}
+
+/**
+ * Resolve cacher by name
+ *
+ * @param {object|string} opt
+ * @returns {Cacher}
+ */
+function resolve(opt) {
+ if (opt instanceof Cachers.Base) {
+ return opt;
+ } else if (opt === true) {
+ return new Cachers.Memory();
+ } else if (isString(opt)) {
+ let CacherClass = getByName(opt);
+ if (CacherClass)
+ return new CacherClass();
+
+ if (opt.startsWith("redis://") || opt.startsWith("rediss://"))
+ CacherClass = Cachers.Redis;
+
+ if (CacherClass)
+ return new CacherClass(opt);
+ else
+ throw new BrokerOptionsError(`Invalid cacher type '${opt}'.`, { type: opt });
+
+ } else if (isObject(opt)) {
+ let CacherClass = getByName(opt.type || "Memory");
+ if (CacherClass)
+ return new CacherClass(opt.options);
+ else
+ throw new BrokerOptionsError(`Invalid cacher type '${opt.type}'.`, { type: opt.type });
+ }
+
+ return null;
+}
+
+function register(name, value) {
+ Cachers[name] = value;
+}
+
+module.exports = Object.assign(Cachers, { resolve, register });
+
diff --git a/pool/shard004/JavaScript/0026879_index.js b/pool/shard004/JavaScript/0026879_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..f50652869f8df057f6814b5b59615b78bd89f117
--- /dev/null
+++ b/pool/shard004/JavaScript/0026879_index.js
@@ -0,0 +1,68 @@
+'use strict';
+
+var path = require('path');
+var through = require('through');
+var falafel = require('falafel');
+var fs = require('fs');
+
+var prefix = /^text!/;
+
+function create(config) {
+ return function(file) {
+ var source = '';
+ if (!(/\.js$/).test(file)) return through();
+
+ var rootDirectory = path.resolve(path.normalize(config.rootDirectory || './bower_components/'));
+
+ var tr = through(function(buf){source += buf;}, function(){
+ try {
+ tr.queue(parse(source));
+ } catch(err) {
+ err.debowerifyFile = file;
+ err.sourcecode = source;
+ tr.emit('error', err);
+ }
+ tr.queue(null);
+ });
+ return tr;
+
+ function parse() {
+ return String(falafel(source, { locations: true, ecmaVersion: 6 }, function(node) {
+
+ // Find require() calls
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
+ var requirePath;
+
+ if(node.callee.name === 'requireText') { // requireText("file.txt")
+ requirePath = node.arguments[0].value;
+ } else if(node.callee.name === 'require' && prefix.test(node.arguments[0].value)) { // require("text!file.txt")
+ requirePath = node.arguments[0].value.replace(prefix, '');
+ } else {// none of the above, skip
+ return;
+ }
+
+ var fsPath;
+ if (/^\.+\//.test(requirePath)) {
+ fsPath = path.resolve(path.dirname(file), requirePath); // relative paths are relative to the current file
+ } else if (rootDirectory) {
+ fsPath = path.resolve(rootDirectory, requirePath); // absolute paths require rootDirectory setting
+ }
+
+ if (fsPath.substring(0, rootDirectory.length) !== rootDirectory) {
+ throw new Error("Can't require '" + requirePath + "' in '" + file + ":" + node.loc.start.line + "', because the path points outside the root directory (too many '../'?)");
+ }
+
+ if (!fs.existsSync(fsPath)) {
+ throw new Error("Can't require '" + requirePath + "' in '" + file + ":" + node.loc.start.line + "', because the file '" + fsPath + "' doesn't exist");
+ }
+
+ // JSON.stringify escapes the text as a JS string literal
+ node.update(JSON.stringify(fs.readFileSync(fsPath, {encoding:'utf-8'})));
+ }
+ }));
+ }
+ };
+}
+
+module.exports = create({});
+module.exports.create = create;
diff --git a/pool/shard004/JavaScript/0026881_commit.js b/pool/shard004/JavaScript/0026881_commit.js
new file mode 100644
index 0000000000000000000000000000000000000000..592b555e2030b8c27dc3ff0c2f50158c4531a8ae
--- /dev/null
+++ b/pool/shard004/JavaScript/0026881_commit.js
@@ -0,0 +1,51 @@
+'use strict';
+
+/* global angular, app */
+
+angular.module(app.name)
+.directive('commit',[function(){
+ return {
+ restrict: 'A',
+ templateUrl: 'app/directives/commit.html',
+ controller: 'commitCtrl',
+ scope: {
+ commit: '=commit'
+ }
+ };
+}])
+.controller('commitCtrl',['$scope','Github',function($scope,Github){
+
+ // parse patch blob from github and determine which lines need added/removed styles
+ function prettyDiff(input) {
+ var arr, i, css,
+ added = /^\+/,
+ removed = /^-/;
+
+ arr = input.split('\n');
+ for(i=0;i {
+ return createOrganization(_, args, req);
+ },
+};
+
+export default createOrganizationMutation;
diff --git a/pool/shard004/JavaScript/0026883_bonusRecordSingle.js b/pool/shard004/JavaScript/0026883_bonusRecordSingle.js
new file mode 100644
index 0000000000000000000000000000000000000000..74f94a1531434f4766a2e7af3d01cd20866f8677
--- /dev/null
+++ b/pool/shard004/JavaScript/0026883_bonusRecordSingle.js
@@ -0,0 +1,209 @@
+/**
+ *
+ */
+
+define( function() {
+ /**
+ * 在逻辑代码中,一定要先绑定事件,然后再加载jqm
+ */
+ var vm = avalon.define({
+ $id : "bonusRecordSingle",
+ datas:{
+ currentClientId:"",
+ nickname:"",
+ domainnameId : "",
+ domainname : "",
+ description:"",
+ domainPhoto : "",
+ sharenumber : 0,
+ sharetotal : 0,
+ shareList:[],
+ sharedSize:0,
+ secondBonusData:"",
+ shareCommissionData:"",
+ },
+ // 分享
+ share : function(){
+ if (vm.datas.currentClientId == "" || vm.datas.currentClientId == null) {
+ $.tips({
+ content : "请先关注公共号再进行域名分享",
+ stayTime : 2000,
+ type : "error"
+ });
+ return false;
+ }
+
+ var url = utils.shareHref(window.location.href,"singleDomainname.html")+"?singleDomainId=" + vm.datas.domainnameId + "&shareClientId=" + vm.datas.currentClientId;
+ var self = $(this);
+ //分享按钮操作
+ $("#directiveDivBonusOrCommission").addClass("show").click(function(){
+ $(this).removeClass("show");
+ });
+ wx.onMenuShareAppMessage({
+ title: '【' + vm.datas.nickname + '】分享的域名' + vm.datas.domainname, // 分享标题
+ desc: vm.datas.description, // 分享描述
+ link: url, // 分享链接
+ imgUrl: "http://" + window.location.host + vm.datas.domainPhoto, // 分享图标
+ type: '', // 分享类型,music、video或link,不填默认为link
+ dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
+ success: function () {
+ // 用户确认分享后执行的回调函数
+ shareSuccessCallback();
+ },
+ cancel: function () {
+ // 用户取消分享后执行的回调函数
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ }
+ });
+
+ //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
+ wx.onMenuShareTimeline({
+ title : '【' + vm.datas.nickname + '】分享的域名' + vm.datas.domainname, // 分享标题
+ link : url, // 分享链接
+ imgUrl : "http://" + window.location.host + vm.datas.domainPhoto, // 分享图标
+ success : function() {
+ // 用户确认分享后执行的回调函数
+ shareSuccessCallback();
+ },
+ cancel : function() {
+ // 用户取消分享后执行的回调函数
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ }
+ });
+
+ //获取“分享到QQ”按钮点击状态及自定义分享内容接口
+ wx.onMenuShareQQ({
+ title: '【' + vm.datas.nickname + '】分享的域名' + vm.datas.domainname, // 分享标题
+ desc: vm.datas.description, // 分享描述
+ link : url, // 分享链接
+ imgUrl : "http://" + window.location.host + vm.datas.domainPhoto, // 分享图标
+ success : function() {
+ // 用户确认分享后执行的回调函数
+ shareSuccessCallback();
+ },
+ cancel : function() {
+ // 用户取消分享后执行的回调函数
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ }
+ });
+
+ //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
+ wx.onMenuShareWeibo({
+ title: '【' + vm.datas.nickname + '】分享的域名' + vm.datas.domainname, // 分享标题
+ desc: vm.datas.description, // 分享描述
+ link : url, // 分享链接
+ imgUrl : "http://" + window.location.host + vm.datas.domainPhoto, // 分享图标
+ success : function() {
+ // 用户确认分享后执行的回调函数
+ shareSuccessCallback();
+ },
+ cancel : function() {
+ // 用户取消分享后执行的回调函数
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ }
+ });
+
+ //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
+ wx.onMenuShareQZone({
+ title: '【' + vm.datas.nickname + '】分享的域名' + vm.datas.domainname, // 分享标题
+ desc: vm.datas.description, // 分享描述
+ link : url, // 分享链接
+ imgUrl : "http://" + window.location.host + vm.datas.domainPhoto, // 分享图标
+ success : function() {
+ // 用户确认分享后执行的回调函数
+ shareSuccessCallback();
+ },
+ cancel : function() {
+ // 用户取消分享后执行的回调函数
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ }
+ });
+ return false;
+ }
+ });
+
+ $("#bonusRecordSingle").on("pageloaded", function() {
+ // 获取jsticket
+ $.get("jsapiTicket.json", {href:window.location.href},function(res) {
+ wx.config({
+ debug : false,
+ appId : res.data.appId,
+ timestamp : res.data.timestamp,
+ nonceStr : res.data.nonceStr,
+ signature : res.data.signature, // 签名
+ jsApiList :[
+ 'onMenuShareTimeline',
+ 'onMenuShareAppMessage',
+ 'onMenuShareQQ',
+ 'onMenuShareWeibo',
+ 'onMenuShareQZone',
+ 'chooseWXPay'
+ ]
+ });
+ });
+ });
+
+ // 下面是获取个人领红包记录,页面和js加载的时候就要初始化,所以不需要监听任何事件
+ $("#bonusRecordSingle").on("pageshow", function(e, d){
+ vm.datas.domainnameId = $.m.getParam().domainnameId;
+ $.get("bonusRecordSingleInfo.json", {domainnameId:vm.datas.domainnameId}, function(res) {
+ vm.datas.domainname = res.data.domainname;
+ vm.datas.domainPhoto = res.data.domainPhoto;
+ vm.datas.sharenumber = res.data.sharenumber;
+ vm.datas.sharetotal = res.data.sharetotal;
+ vm.datas.currentClientId = res.data.currentClientId;
+ vm.datas.nickname = res.data.nickname;
+ vm.datas.description = res.data.description;
+ if(res.type=="warn"){
+ $.tips({
+ content : res.msg,
+ stayTime:2000,
+ type : res.type
+ })
+ }else{
+ vm.datas.sharedSize = res.data.sharedSize;
+ if(vm.datas.sharedSize>0){
+ vm.datas.shareList.pushArray(res.data.shareList);
+ }else{
+ vm.datas.shareList = "";
+ }
+ vm.datas.secondBonusData = res.data.secondBonusData;
+ vm.datas.shareCommissionData = res.data.shareCommissionData;
+ }
+ });
+ });
+ $("#bonusRecordSingle").on("pagehide", function(e, d){
+ vm.datas.currentClientId="";
+ vm.datas.nickname="";
+ vm.datas.domainnameId = "";
+ vm.datas.domainname = "";
+ vm.datas.description = "";
+ vm.datas.domainPhoto = "";
+ vm.datas.sharenumber = 0;
+ vm.datas.sharetotal =0,
+ vm.datas.shareList.clear();
+ vm.datas.sharedSize = 0;
+ vm.datas.secondBonusData = "";
+ vm.datas.shareCommissionData = "";
+ });
+
+ function shareSuccessCallback() {
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ var hasmore = vm.datas.sharenumber > vm.datas.sharedSize ? true : false;
+ $.post('share', {domainId : vm.datas.domainnameId, hasRedBag : hasmore},
+ function (res) {
+ if (res.type === 'success') {
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ } else {
+ $("#directiveDivBonusOrCommission").removeClass("show");
+ $.tips({
+ content : res.msg,
+ stayTime : 2000,
+ type : res.type
+ });
+ }
+ });
+ }
+
+ return vm;
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026885_ajax.js b/pool/shard004/JavaScript/0026885_ajax.js
new file mode 100644
index 0000000000000000000000000000000000000000..1bd759005a15432526e87a648f16b03574921859
--- /dev/null
+++ b/pool/shard004/JavaScript/0026885_ajax.js
@@ -0,0 +1,89 @@
+ $(document).ready(function (){
+ /*** main tea list ***/
+ $(".tea-list").find("li").each(function(){
+
+ var teaIndex= $(this).index();
+ $(this).click(function(){
+ $(".overlay-slideup").stop().animate({top: 0},1800,"easeOutQuart");
+ $(".ss-des-wrapper").fadeOut()
+ $.getJSON( "result.json", function( data ) {
+
+ $(".overlay-slideup").attr("id",(data.flowers[teaIndex].flowerpPosition))
+ $(".overlay-slideup").find(".background").css("background-color",(data.flowers[teaIndex].mainColor))
+ $(".flower-name").html((data.flowers[teaIndex].flowerChinese))
+ $(".flower-name-en").html((data.flowers[teaIndex].flowerName))
+ $(".chinese-content").find("p").html((data.flowers[teaIndex].contentChinese))
+ $(".eng-content").find("p").html((data.flowers[teaIndex].contentEnglish))
+ $(".pattern-top").css("background-image", "url(../img/ss1/pat"+(teaIndex+1)+".svg)");
+ $(".supporting-tea-list").find("li").each(function(){
+ var thisIndexli = $(this).index();
+ var thisIndexlip = data.flowers[teaIndex].maxID[thisIndexli];
+ $(this).find(".top-block").css("background-image", "url(../img/ss1/icon"+(data.flowers[teaIndex].maxID[thisIndexli])+".svg)");
+ $(this).find(".bottom-block").find("h6.tc").html((data.flowers[thisIndexlip-1].flowerChinese))
+ $(this).find(".bottom-block").find("h6.en").html((data.flowers[thisIndexlip-1].flowerName))
+ $(this).click(function(){
+ $(".bottom-background").css("background-image", "url(../img/ss1/pat"+(data.flowers[teaIndex].maxID[thisIndexli])+".svg)");
+ $(".max-content").find("h3.tc").html(data.flowers[teaIndex].maxtitle[thisIndexli])
+ $(".max-content").find("h4.en").html(data.flowers[teaIndex].maxtitleen[thisIndexli])
+ });
+
+
+ })
+ });
+ })
+ })
+ /*** support tea list ***/
+ $(".supporting-tea-list").find("li").each(function(){
+ $(this).click( function() {
+ var thisID = $(this).parent().parent().parent().parent().parent().attr("id");
+ $(".max-overlay").attr("data-src",thisID);
+ $(".icon-wrapper").fadeOut()
+ $(".overlay-slideup").find(".pattern-top").stop().animate({height:"50%"},1600,"easeOutQuart");
+ $(".overlay-slideup").find(".pattern-bottom").stop().animate({height:"50%",top:"50%"},1000,"easeOutQuart");
+
+ $(".pattern-bottom").find(".bottom-conten-wrapper").fadeOut("slow", function() {
+ $(".overlay-slideup").find(".pattern-top").addClass("leftright");
+ $(".pattern-bottom").find(".bottom-background").delay(400).fadeIn("slow")
+ $(".max-overlay").delay(1600).fadeIn("slow");
+ $.getJSON( "result.json", function( data ) {
+ $(".max-overlay-background").css("background","#FFF")
+ });
+ });
+
+ })
+ })
+ /*** support tea list ***/
+
+ $(".close-about-btn").click(function(){
+ $(".overlay-slideup").stop().animate({top: "100%"},1800,"easeOutQuart");
+ })
+
+
+ /*** support tea list back ***/
+ $(".back-main-btn").click(function(){
+ var parentId = ($(this).parent().parent().attr("data-src"))-1;
+ $(".max-overlay").fadeOut("slow");
+
+ $(".pattern-bottom").find(".bottom-background").delay(800).fadeOut("slow",function(){
+ $(".overlay-slideup").find(".pattern-top").delay(400).stop().animate({height:"45%"},1000,"easeInQuart");
+ $(".overlay-slideup").find(".pattern-bottom").delay(400).stop().animate({height:"40%",top:"48%"},1000,"easeInQuart");
+ $(".pattern-bottom").find(".bottom-conten-wrapper").delay(1200).fadeIn("slow", function() {
+ $(".icon-wrapper").delay(400).fadeIn("slow")
+ $(".overlay-slideup").find(".pattern-top").removeClass("leftright");
+
+ })
+
+
+ })
+
+
+ $.getJSON( "result.json", function( data ) {
+
+
+ });
+ })
+
+
+
+
+ })
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026887_page-controller.js b/pool/shard004/JavaScript/0026887_page-controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..09096c32cfd5df105e5a27990545c18cbbb780b2
--- /dev/null
+++ b/pool/shard004/JavaScript/0026887_page-controller.js
@@ -0,0 +1,33 @@
+/**
+ * Created by sridharrajs on 6/30/16.
+ */
+
+'use strict';
+
+let urlUtils = require('../utils/url-utils');
+let pageUtil = require('../utils/page-utils');
+let networkUtils = require('../utils/network-utils');
+
+class PageController {
+
+ static fetchPage(rawURL) {
+ let url = '';
+ return urlUtils.sanitizeWithPromise(rawURL).then((readableURL) => {
+ url = readableURL;
+ return networkUtils.makeGET(readableURL);
+ }).then((html) => {
+ return pageUtil.parse(html);
+ }).then((article) => {
+ article.url = url;
+ let host = urlUtils.getHostName(url);
+ article.host = host;
+ article.isVideo = urlUtils.isVideo(host);
+ return Promise.resolve(article);
+ }).catch((err) => {
+ return Promise.reject(err);
+ });
+ }
+
+}
+
+module.exports = PageController;
diff --git a/pool/shard004/JavaScript/0026888_echo-base64.js b/pool/shard004/JavaScript/0026888_echo-base64.js
new file mode 100644
index 0000000000000000000000000000000000000000..435cc1f4615a79541995c6a786a4f4a830e94e62
--- /dev/null
+++ b/pool/shard004/JavaScript/0026888_echo-base64.js
@@ -0,0 +1,22 @@
+var util = require('util');
+
+var decode = function(base64) { return new Buffer(base64, 'base64').toString('utf8'); };
+var encode = function(utf8) { return new Buffer(utf8, 'utf8').toString('base64'); };
+
+console.error('process started');
+console.error('current directory is ' + process.cwd());
+
+var stdin = process.openStdin();
+stdin.setEncoding('utf8');
+
+stdin.on('data', function(data) {
+ console.error('received: ' + data);
+
+ var in_msg = decode(data.slice(0, -1));
+ console.error('decoded as ' + in_msg);
+
+ console.log(encode(in_msg));
+});
+
+console.log(encode("multi-line\nscript\nstarted"));
+
diff --git a/pool/shard004/JavaScript/0026891_synacormediaBidAdapter.js b/pool/shard004/JavaScript/0026891_synacormediaBidAdapter.js
new file mode 100644
index 0000000000000000000000000000000000000000..ae2fd91cb6fa1e4860749264fb6f216bf53f1037
--- /dev/null
+++ b/pool/shard004/JavaScript/0026891_synacormediaBidAdapter.js
@@ -0,0 +1,182 @@
+'use strict';
+
+import { getAdUnitSizes, logWarn } from '../src/utils.js';
+import { registerBidder } from '../src/adapters/bidderFactory.js';
+import { BANNER, VIDEO } from '../src/mediaTypes.js';
+import includes from 'core-js/library/fn/array/includes.js';
+
+const BID_HOST = 'https://prebid.technoratimedia.com';
+const USER_SYNC_HOST = 'https://ad-cdn.technoratimedia.com';
+const VIDEO_PARAMS = [ 'minduration', 'maxduration', 'startdelay', 'placement', 'linearity', 'mimes', 'protocols', 'api' ];
+const BLOCKED_AD_SIZES = [
+ '1x1',
+ '1x2'
+];
+export const spec = {
+ code: 'synacormedia',
+ supportedMediaTypes: [ BANNER, VIDEO ],
+ sizeMap: {},
+
+ isVideoBid: function(bid) {
+ return bid.mediaTypes !== undefined &&
+ bid.mediaTypes.hasOwnProperty('video');
+ },
+ isBidRequestValid: function(bid) {
+ const hasRequiredParams = bid && bid.params && bid.params.hasOwnProperty('placementId') && bid.params.hasOwnProperty('seatId');
+ const hasAdSizes = bid && getAdUnitSizes(bid).filter(size => BLOCKED_AD_SIZES.indexOf(size.join('x')) === -1).length > 0
+ return !!(hasRequiredParams && hasAdSizes);
+ },
+
+ buildRequests: function(validBidReqs, bidderRequest) {
+ if (!validBidReqs || !validBidReqs.length || !bidderRequest) {
+ return;
+ }
+ const refererInfo = bidderRequest.refererInfo;
+ const openRtbBidRequest = {
+ id: bidderRequest.auctionId,
+ site: {
+ domain: location.hostname,
+ page: refererInfo.referer,
+ ref: document.referrer
+ },
+ device: {
+ ua: navigator.userAgent
+ },
+ imp: []
+ };
+
+ const schain = validBidReqs[0].schain;
+ if (schain) {
+ openRtbBidRequest.source = { ext: { schain } };
+ }
+
+ let seatId = null;
+
+ validBidReqs.forEach((bid, i) => {
+ if (seatId && seatId !== bid.params.seatId) {
+ logWarn(`Synacormedia: there is an inconsistent seatId: ${bid.params.seatId} but only sending bid requests for ${seatId}, you should double check your configuration`);
+ return;
+ } else {
+ seatId = bid.params.seatId;
+ }
+ const placementId = bid.params.placementId;
+ const bidFloor = bid.params.bidfloor ? parseFloat(bid.params.bidfloor) : null;
+ if (isNaN(bidFloor)) {
+ logWarn(`Synacormedia: there is an invalid bid floor: ${bid.params.bidfloor}`);
+ }
+ let pos = parseInt(bid.params.pos, 10);
+ if (isNaN(pos)) {
+ logWarn(`Synacormedia: there is an invalid POS: ${bid.params.pos}`);
+ pos = 0;
+ }
+ const videoOrBannerKey = this.isVideoBid(bid) ? 'video' : 'banner';
+ getAdUnitSizes(bid)
+ .filter(size => BLOCKED_AD_SIZES.indexOf(size.join('x')) === -1)
+ .forEach((size, i) => {
+ if (!size || size.length != 2) {
+ return;
+ }
+ const size0 = size[0];
+ const size1 = size[1];
+ const imp = {
+ id: `${videoOrBannerKey.substring(0, 1)}${bid.bidId}-${size0}x${size1}`,
+ tagid: placementId
+ };
+ if (bidFloor !== null && !isNaN(bidFloor)) {
+ imp.bidfloor = bidFloor;
+ }
+
+ const videoOrBannerValue = {
+ w: size0,
+ h: size1,
+ pos
+ };
+ if (videoOrBannerKey === 'video') {
+ if (bid.mediaTypes.video) {
+ this.setValidVideoParams(bid.mediaTypes.video, bid.params.video);
+ }
+ if (bid.params.video) {
+ this.setValidVideoParams(bid.params.video, videoOrBannerValue);
+ }
+ }
+ imp[videoOrBannerKey] = videoOrBannerValue;
+ openRtbBidRequest.imp.push(imp);
+ });
+ });
+
+ if (openRtbBidRequest.imp.length && seatId) {
+ return {
+ method: 'POST',
+ url: `${BID_HOST}/openrtb/bids/${seatId}?src=$$REPO_AND_VERSION$$`,
+ data: openRtbBidRequest,
+ options: {
+ contentType: 'application/json',
+ withCredentials: true
+ }
+ };
+ }
+ },
+
+ setValidVideoParams: function (sourceObj, destObj) {
+ Object.keys(sourceObj)
+ .filter(param => includes(VIDEO_PARAMS, param) && sourceObj[param] !== null && (!isNaN(parseInt(sourceObj[param], 10)) || !(sourceObj[param].length < 1)))
+ .forEach(param => destObj[param] = Array.isArray(sourceObj[param]) ? sourceObj[param] : parseInt(sourceObj[param], 10));
+ },
+ interpretResponse: function(serverResponse) {
+ const updateMacros = (bid, r) => {
+ return r ? r.replace(/\${AUCTION_PRICE}/g, bid.price) : r;
+ };
+
+ if (!serverResponse.body || typeof serverResponse.body != 'object') {
+ logWarn('Synacormedia: server returned empty/non-json response: ' + JSON.stringify(serverResponse.body));
+ return;
+ }
+
+ const {id, seatbid: seatbids} = serverResponse.body;
+ let bids = [];
+ if (id && seatbids) {
+ seatbids.forEach(seatbid => {
+ seatbid.bid.forEach(bid => {
+ const creative = updateMacros(bid, bid.adm);
+ const nurl = updateMacros(bid, bid.nurl);
+ const [, impType, impid, width, height] = bid.impid.match(/^([vb])(.*)-(.*)x(.*)$/);
+ const isVideo = impType == 'v';
+ const bidObj = {
+ requestId: impid,
+ adId: bid.id.replace(/~/g, '-'),
+ cpm: parseFloat(bid.price),
+ width: parseInt(width, 10),
+ height: parseInt(height, 10),
+ creativeId: `${seatbid.seat}_${bid.crid}`,
+ currency: 'USD',
+ netRevenue: true,
+ mediaType: isVideo ? VIDEO : BANNER,
+ ad: creative,
+ ttl: 60
+ };
+ if (isVideo) {
+ const [, uuid] = nurl.match(/ID=([^&]*)&?/);
+ bidObj.videoCacheKey = encodeURIComponent(uuid);
+ bidObj.vastUrl = nurl;
+ }
+ bids.push(bidObj);
+ });
+ });
+ }
+ return bids;
+ },
+ getUserSyncs: function (syncOptions, serverResponses) {
+ const syncs = [];
+ if (syncOptions.iframeEnabled) {
+ syncs.push({
+ type: 'iframe',
+ url: `${USER_SYNC_HOST}/html/usersync.html?src=$$REPO_AND_VERSION$$`
+ });
+ } else {
+ logWarn('Synacormedia: Please enable iframe based user sync.');
+ }
+ return syncs;
+ }
+};
+
+registerBidder(spec);
diff --git a/pool/shard004/JavaScript/0026893_workitemCell.js b/pool/shard004/JavaScript/0026893_workitemCell.js
new file mode 100644
index 0000000000000000000000000000000000000000..cdb031165922ee991f4618837003cace4dcb64db
--- /dev/null
+++ b/pool/shard004/JavaScript/0026893_workitemCell.js
@@ -0,0 +1,99 @@
+Ti.include('ISO8601Date.js');
+
+function fillZero(/* Number */n, length) {
+ return ("0000" + n).slice(-length);
+}
+function formatHHMM(/* Date */d) {
+ return fillZero(d.getHours(), 2) + ':' + fillZero(d.getMinutes(), 2);
+}
+function formatYYYYMMDD(/* Date */d) {
+ return fillZero(d.getFullYear(), 4) + '/' + fillZero(d.getMonth() + 1, 2)
+ + '/' + fillZero(d.getDate(), 2);
+}
+
+var WorkitemCell = {};
+WorkitemCell.HEIGHT = 60;
+
+WorkitemCell.createWorkitemCell = function(/* Object */workitem) {
+ var row = Ti.UI.createTableViewRow({
+ height : WorkitemCell.HEIGHT
+ });
+ if (workitem.processInstanceTitle === null
+ || workitem.processInstanceTitle == "") {
+ workitem.processInstanceTitle = '(件名なし)';
+ }
+ var offerDatetime = new Date();
+ offerDatetime.setISO8601(workitem.offerDatetime);
+ var now = new Date();
+ var offerDateString = '';
+ if (now.getTime() - offerDatetime.getTime() < 1000 * 60 * 60 * 24
+ && now.getDate() == offerDatetime.getDate()) {
+ offerDateString = formatHHMM(offerDatetime);
+ } else {
+ offerDateString = formatYYYYMMDD(offerDatetime);
+ }
+ var processModelNameLabel = Ti.UI.createLabel({
+ text : workitem.processModelInfoName,
+ left : 10,
+ right : 60,
+ top : 4,
+ height : 12,
+ font : {
+ fontSize : 12
+ }
+ });
+ var nodeNameLabel = Ti.UI.createLabel({
+ text : workitem.nodeName,
+ left : 10,
+ right : 50,
+ top : 18,
+ height : 12,
+ font : {
+ fontSize : 12
+ }
+ });
+ var titleLabel = Ti.UI.createLabel({
+ text : workitem.processInstanceTitle,
+ left : 20,
+ right : 50,
+ top : 32,
+ height : 21,
+ font : {
+ fontSize : 14,
+ fontWeight : 'bold'
+ }
+ });
+ var dateLabel = Ti.UI.createLabel({
+ text : offerDateString,
+ right : 10,
+ top : 0,
+ height : 21,
+ textAlign : 'right',
+ color : '#0000DD',
+ font : {
+ fontSize : 12
+ }
+ });
+ row.add(processModelNameLabel);
+ row.add(nodeNameLabel);
+ row.add(titleLabel);
+ row.add(dateLabel);
+ return row;
+};
+
+WorkitemCell.createMessageCell = function(message) {
+ var row = Ti.UI.createTableViewRow({
+ height : WorkitemCell.HEIGHT
+ });
+ var label = Ti.UI.createLabel({
+ text : message,
+ textAlign: 'center',
+ left : 20,
+ right : 20,
+ font : {
+ fontSize : 12
+ }
+ });
+ row.add(label);
+ return row;
+};
diff --git a/pool/shard004/JavaScript/0026894_render.js b/pool/shard004/JavaScript/0026894_render.js
new file mode 100644
index 0000000000000000000000000000000000000000..f50d51196e9e71fad581af3e5f11044efcde4f64
--- /dev/null
+++ b/pool/shard004/JavaScript/0026894_render.js
@@ -0,0 +1,30 @@
+function renderHtmlBy(data, templateJs, targetElement) {
+
+ if (!targetElement)
+ targetElement = '#data';
+
+ $.when($.get(templateJs))
+ .done(function(template) {
+ $.templates({ renderTemplate: template });
+ var html = $.render.renderTemplate(data,
+ {
+ formatDate: function formatDate(s) {
+
+ function pad(num, size) {
+ var s = num + "";
+ while (s.length < size) s = "0" + s;
+ return s;
+ }
+
+
+ var d = new Date(s);
+ return (1900 + d.getYear()) + "-" + pad((1 + d.getMonth()), 2) + "-" + pad(d.getDate(), 2) + " " +
+ pad(d.getHours(), 2) + ":" + pad(d.getMinutes(), 2) + ":" + pad(d.getSeconds(), 2);
+ }
+ }
+ );
+ console.log(html);
+ $(targetElement).html(html);
+
+ });
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026895_functions.es6.js b/pool/shard004/JavaScript/0026895_functions.es6.js
new file mode 100644
index 0000000000000000000000000000000000000000..5966fc1b6bfcfe669fa620235962e6a59f89f96c
--- /dev/null
+++ b/pool/shard004/JavaScript/0026895_functions.es6.js
@@ -0,0 +1,71 @@
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+var functions = {
+ // Convert to percentage
+
+ percentage: function percentage() {
+ var value = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
+
+ value = +value;
+ return (value <= 1 ? (value * 100).toFixed(8) : value) + '%';
+ },
+
+
+ // Simple clearfix
+ clearfix: function clearfix() {
+ return {
+ '*zoom': 1,
+ '&:before, &:after': {
+ 'content': '" "',
+ 'display': 'table'
+ },
+ '&:after': {
+ 'clear': 'both'
+ }
+ };
+ }
+};
+
+functions = Object.assign(functions, {
+ // Sets layout direction and layout opposite direction to `@direction`
+ // and `@opposite-direction` accordingly.
+
+ getDirection: function getDirection(layout) {
+ return {
+ direction: layout === 'LTR' ? 'right' : 'left',
+ oppositeDirection: layout === 'LTR' ? 'left' : 'right'
+ };
+ },
+
+
+ // Sets neat grid column's width to `@column-width`.
+ flexWidth: function flexWidth(columns, containerColumns, column, gutter) {
+ columns = +columns;
+ containerColumns = +containerColumns;
+ column = +column.replace('em', '').replace('px', '');
+ gutter = +gutter.replace('em', '').replace('px', '');
+
+ var tmpWidth = columns * column + (columns - 1) * gutter;
+ var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;
+
+ return tmpWidth / tmpContainerWidth; // columnWidth
+ },
+
+
+ // Sets neat grid column's gutter (the white space between two columns) to `@column-gutter`.
+ flexGutter: function flexGutter(containerColumns, column, gutter) {
+ containerColumns = +containerColumns;
+ column = +column.replace('em', '').replace('px', '');
+ gutter = +gutter.replace('em', '').replace('px', '');
+
+ var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;
+
+ return gutter / tmpContainerWidth; // columnGutter
+ }
+});
+
+exports.default = functions;
+//# sourceMappingURL=functions.es6.js.map
diff --git a/pool/shard004/JavaScript/0026896_RTCPeerConnection-Helpers.js b/pool/shard004/JavaScript/0026896_RTCPeerConnection-Helpers.js
new file mode 100644
index 0000000000000000000000000000000000000000..1d38e8d0491cc366d21d92889c3a7d13af599d0b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026896_RTCPeerConnection-Helpers.js
@@ -0,0 +1,111 @@
+var codecs = {};
+
+/* this function credit goes to Google Chrome WebRTC team! */
+codecs.opus = function (sessionDescription) {
+
+ /* no opus? use other codec! */
+ if (!isopus) return sessionDescription;
+
+ var sdp = sessionDescription.sdp;
+
+ /* Opus? use it! */
+ function preferOpus() {
+ var sdpLines = sdp.split('\r\n');
+
+ // Search for m line.
+ for (var i = 0; i < sdpLines.length; i++) {
+ if (sdpLines[i].search('m=audio') !== -1) {
+ var mLineIndex = i;
+ break;
+ }
+ }
+ if (mLineIndex === null)
+ return sdp;
+
+ // If Opus is available, set it as the default in m line.
+ for (var i = 0; i < sdpLines.length; i++) {
+ if (sdpLines[i].search('opus/48000') !== -1) {
+ var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
+ if (opusPayload)
+ sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
+ break;
+ }
+ }
+
+ // Remove CN in m line and sdp.
+ sdpLines = removeCN(sdpLines, mLineIndex);
+
+ sdp = sdpLines.join('\r\n');
+ return sdp;
+ }
+
+ function extractSdp(sdpLine, pattern) {
+ var _result = sdpLine.match(pattern);
+ return (_result && _result.length == 2) ? _result[1] : null;
+ }
+
+ // Set the selected codec to the first in m line.
+ function setDefaultCodec(mLine, payload) {
+ var elements = mLine.split(' ');
+ var newLine = new Array();
+ var index = 0;
+ for (var i = 0; i < elements.length; i++) {
+ if (index === 3) // Format of media starts from the fourth.
+ newLine[index++] = payload; // Put target payload to the first.
+ if (elements[i] !== payload)
+ newLine[index++] = elements[i];
+ }
+ return newLine.join(' ');
+ }
+
+ // Strip CN from sdp before CN constraints is ready.
+ function removeCN(sdpLines, mLineIndex) {
+ var mLineElements = sdpLines[mLineIndex].split(' ');
+ // Scan from end for the convenience of removing an item.
+ for (var i = sdpLines.length - 1; i >= 0; i--) {
+ var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
+ if (payload) {
+ var cnPos = mLineElements.indexOf(payload);
+ if (cnPos !== -1) {
+ // Remove CN payload from m line.
+ mLineElements.splice(cnPos, 1);
+ }
+ // Remove CN line in sdp
+ sdpLines.splice(i, 1);
+ }
+ }
+
+ sdpLines[mLineIndex] = mLineElements.join(' ');
+ return sdpLines;
+ }
+
+
+ var result;
+
+ /* in case of error; use default codec; otherwise use opus */
+ try {
+ result = preferOpus();
+ console.log('using opus codec!');
+ }
+ catch (e) {
+ console.error(e);
+ result = sessionDescription.sdp;
+ }
+
+ return new SessionDescription({
+ sdp: result,
+ type: sessionDescription.type
+ });
+};
+
+/* check support of opus codec */
+codecs.isopus = function () {
+ var result = true;
+ new PeerConnection(defaults.iceServers).createOffer(function (sessionDescription) {
+ result = sessionDescription.sdp.indexOf('opus') !== -1;
+ }, null, defaults.constraints);
+ return result;
+};
+
+/* used to know opus codec support */
+var isopus = !!codecs.isopus();
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026898_seed.js b/pool/shard004/JavaScript/0026898_seed.js
new file mode 100644
index 0000000000000000000000000000000000000000..b5c28e359412bed445a7e3389217b70c539f1863
--- /dev/null
+++ b/pool/shard004/JavaScript/0026898_seed.js
@@ -0,0 +1,127 @@
+var mongoose = require('mongoose');
+var config = require('./config');
+var seeder = require('mongoose-seeder');
+var slugify = require('speakingurl');
+var fs = require('fs');
+
+var modelDir = './src/backend/model';
+
+fs.readdirSync(modelDir).forEach((modelPath) => {
+ console.log(modelDir + '/' + modelPath);
+ require('../model/' + modelPath);
+});
+var roles = require('../controller/auth').Roles;
+
+mongoose.connect(config.db, function(err) {
+ // Load Mongoose models
+ seeder.seed(data).then(() => {
+ process.exit();
+ }).catch((error) => {
+ console.error(error);
+ });
+});
+
+// Data array containing seed data - documents organized by Model
+var data = {
+ categories: {
+ '_model': 'Categories',
+ 'c1': { description:"Learn abute a new framework or language", name: 'Tech talk' },
+ 'c2': { description:"Hear the storys from great entrepreneurs", name: 'Startup talk' },
+ 'c3': { description:"Startups explains what they do", name: 'Show and tell' },
+ 'c4': { description:"Meet and build some thing cool", name: 'Hackathons' },
+ 'c5': { description:"Who writes abute what", name: 'In the spotligth' },
+ 'c6': { description:"Party?", name: 'After hours' },
+ 'c7': { description:"Meet new perssons", name: 'Network' }
+ },
+ users: {
+ '_model': 'Users',
+ 'admin': { email: 'admin@gbgtech.co', provider: 'email', role: roles.admin},
+ 'bark': { email: 'erikaxelsson1@gmail.com', provider: 'email', role: roles.admin, subscribedCategories: ['->categories.c7', '->categories.c4']},
+ 'tejp': { email: 'andresamuelsson94@gmail.com', provider: 'email', role: roles.admin, subscribedCategories: ['->categories.c1', '->categories.c5']},
+ 'ndushi': { email: 'johan.lindskogen@gmail.com', provider: 'email', role: roles.admin}
+ },
+ posts: {
+ '_model': 'Posts',
+ 'p1': {
+ slug: slugify('Startup Ping pong tournament'),
+ title: 'Startup Ping pong tournament',
+ organizer: 'StartupPingPong AB',
+ accepted: 'APPROVED',
+ author: '->users.admin',
+ body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
+ url: 'https://google.com',
+ categories: ['->categories.c1', '->categories.c5'],
+ eventData: {
+ from: '=new Date(2016, 4, 6, 13, 37)',
+ to: '=new Date(2016, 4, 6, 17, 0)',
+ rsvp: 'http://splashthat.com',
+ location: {
+ lat: '57.7166056',
+ lng: '12.0061702',
+ name: 'Hubben 2.1'
+ }
+ }
+ }
+ },
+ feeds:{
+ '_model': 'Feeds',
+ 'f1':{
+ userId: '->users.bark',
+ categories: ['->categories.c1'],
+ name:"Javaforum",
+ acceptedDefault:'WAITING',
+ uniqueId:'Javaforum-Goteborg',
+ vendor:"meetup"
+ },
+ 'f2':{
+ userId: '->users.bark',
+ categories: ['->categories.c2', '->categories.c3'],
+ name:"gbgtartup",
+ acceptedDefault:'WAITING',
+ uniqueId:'gbgtartup',
+ vendor:"meetup"
+ },
+ 'f3':{
+ userId: '->users.bark',
+ categories: ['->categories.c2', '->categories.c6'],
+ name:"Startup-Grind",
+ acceptedDefault:'WAITING',
+ uniqueId:'Startup-Grind-Gothenburg',
+ vendor:"meetup"
+ },
+ 'f4':{
+ userId: '->users.bark',
+ categories: ['->categories.c2', '->categories.c6'],
+ name:"HUBGothenburg",
+ acceptedDefault:'WAITING',
+ uniqueId:'HUBGothenburg',
+ vendor:"meetup",
+ defaultBlockedOutlets:['reddit','email']
+ },
+ 'f5':{
+ userId: '->users.bark',
+ categories: ['->categories.c4'],
+ name:"Hackathons-Goteborg",
+ acceptedDefault:'WAITING',
+ uniqueId:'Hackathons-Goteborg',
+ vendor:"meetup"
+ },
+
+ 'f6':{
+ userId: '->users.bark',
+ categories: ['->categories.c4'],
+ name:"Entrepreneurial hive",
+ acceptedDefault:'WAITING',
+ uniqueId:'Entrepreneurial-Hive',
+ vendor:"meetup"
+ },
+ 'f7':{
+ userId: '->users.bark',
+ categories: ['->categories.c4'],
+ name:"Goteborg Startup Founder 101",
+ acceptedDefault:'WAITING',
+ uniqueId:'Goteborg-Startup-Founder-101',
+ vendor:"meetup"
+ }
+ },
+};
diff --git a/pool/shard004/JavaScript/0026900_jquery.jeditable.ui-datepicker.js b/pool/shard004/JavaScript/0026900_jquery.jeditable.ui-datepicker.js
new file mode 100644
index 0000000000000000000000000000000000000000..f4a33777458b32c876277b42e190d1dac92b7170
--- /dev/null
+++ b/pool/shard004/JavaScript/0026900_jquery.jeditable.ui-datepicker.js
@@ -0,0 +1,28 @@
+/* Create an inline datepicker which leverages the
+ jQuery UI datepicker
+*/
+jQuery.editable.addInputType('datepicker', {
+ element: function(settings, original) {
+ var input = jQuery('');
+ // Catch the blur event on month change
+
+ settings.onblur = function(e) {
+ };
+
+ input.datepicker({
+ dateFormat: 'dd-mm-yy',
+ onSelect: function(dateText, inst) {
+ // you may want to remove this or
+ // change it to
+ // jQuery(this).submit();
+ // see GamB's comments below
+ jQuery(this).parents("form").submit();
+ }
+ });
+
+ input.datepicker('option', 'showAnim', 'slide');
+
+ jQuery(this).append(input);
+ return (input);
+ }
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026901_security.js b/pool/shard004/JavaScript/0026901_security.js
new file mode 100644
index 0000000000000000000000000000000000000000..5181be649f78a9713042320ae8a43ec4c376e1b0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026901_security.js
@@ -0,0 +1,59 @@
+/**
+ * Copyright 2007-2008 Axiom Software Inc.
+ * This file is part of the Axiom Inspector Application.
+ *
+ * The Axiom Manage Application 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.
+ *
+ * The Axiom Manage Application 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 the Axiom Manage Application. If not, see
+ * .
+ */
+
+/**
+ * Unauthorized handler
+ */
+function unauthorized(){
+ var error = '';
+ var came_from = req.get('http_referer');
+ if(came_from && came_from.match(/login$/)){ error='?error=true';}
+ res.redirect(this.getURI('login'+error));
+}
+
+/**
+ * If an admin account has been created, return the login screen,
+ * otherwise return the admin account creation screen.
+ */
+function login(){
+ var action = (app.getHits('AXSuperUser', {}).length == 0) ? 'create_user' : 'login_screen';
+ return this.wrap({content: action});
+}
+
+/**
+ * Validates username and password, logs in user if correct.
+ */
+function authenticate(){
+ var user_hits = app.getHits('AXSuperUser', {username: req.data.username, password: req.data.password.md5()});
+ if(user_hits.length == 0){
+ this.unauthorized();
+ } else {
+ session.login(user_hits.objects(0,1)[0]);
+ res.redirect(this.getURI());
+ }
+
+}
+
+/**
+ * Logout the current user.
+ */
+function logout(){
+ session.logout();
+ res.redirect(this.getURI('login'));
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026902_PausingAndResuming.js b/pool/shard004/JavaScript/0026902_PausingAndResuming.js
new file mode 100644
index 0000000000000000000000000000000000000000..7abb9aef45a4c27ec03f27613a169b89298a4bce
--- /dev/null
+++ b/pool/shard004/JavaScript/0026902_PausingAndResuming.js
@@ -0,0 +1,51 @@
+/**
+* This script is a demonstration of how you can go to the pause and resume an animation.
+**/
+var PausingAndResuming = new Kiwi.State('PausingAndResuming');
+
+PausingAndResuming.preload = function () {
+
+ //Resize
+ this.game.stage.resize(800, 250);
+
+ this.addSpriteSheet('zombie', 'assets/spritesheets/zombie.png', 150, 117);
+}
+
+PausingAndResuming.create = function () {
+ //The text
+ var text = new Kiwi.GameObjects.Textfield(this, 'Click anywhere to start or stop the zombie!', this.game.stage.width / 2, 10, '#000', 12);
+ text.textAlign = 'center';
+ this.addChild(text);
+
+ //Create the zombag
+ this.zombie = new Kiwi.GameObjects.Sprite(this, this.textures.zombie, 300, 30);
+ this.addChild(this.zombie);
+
+ //Run zombag RUN!
+ this.zombie.animation.add('running!', [0, 1, 2, 3, 4, 5, 6], 0.1, true);
+ this.zombie.animation.play('running!');
+
+ //When someone clicks on the screen then either pause or resume the animation based off what the animation was doing.
+ this.game.input.onUp.add(this.released, this);
+}
+
+//Callback for when someone clicks on the screen.
+PausingAndResuming.released = function () {
+ if (this.zombie.animation.isPlaying) {
+ this.zombie.animation.pause();
+ } else {
+ this.zombie.animation.resume();
+ }
+}
+
+
+//Create's a new Kiwi.Game.
+/*
+* Param One - DOMID - String - ID of a DOMElement that the game will reside in.
+* Param Two - GameName - String - Name that the game will be given.
+* Param Three - State - Object - The state that is to be loaded by default.
+* Param Four - Options - Object - Optional options that the game will use whilst playing. Currently this is used to to choose the renderer/debugmode/device to target
+*/
+if(typeof gameOptions == "undefined") gameOptions = {};
+
+var game = new Kiwi.Game('game', 'KiwiExample', PausingAndResuming, gameOptions);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026903_popuper.js b/pool/shard004/JavaScript/0026903_popuper.js
new file mode 100644
index 0000000000000000000000000000000000000000..c381471fe46b41c168e054ad8f075c0357bae5dc
--- /dev/null
+++ b/pool/shard004/JavaScript/0026903_popuper.js
@@ -0,0 +1,40 @@
+(function(){
+window.popuper = {
+init: function(id, shift, scroll, noclose){
+ var self = this;
+ $('.popuper').off().click(function(e){
+ e.preventDefault();
+ self.open($(this).data('target'));
+ });
+ $('.popup-closer').off().click(function(e){
+ e.preventDefault();
+ self.close();
+ });
+ if(id) self.open(id, shift, scroll, noclose);
+},
+close: function(){
+ $('.popup-layout').fadeOut(100, function(){ $(this).remove(); });
+ $('.popup').fadeOut(100);
+ this.opened = false;
+},
+open: function(id, shift, scroll, noclose){
+ var self = this,
+ el = $('#' + id);
+ if(shift == undefined) shift = el.data('shift');
+ if(noclose == undefined) noclose = el.data('noclose');
+ if(scroll == undefined) scroll = el.data('scroll');
+ if(!(self.opened && noclose)){
+ self.close();
+ $('').click(function(){
+ self.close();
+ }).appendTo('body').fadeIn(100);
+ }
+ if(shift != false) el.css('margin-top', Math.ceil(el.height()/2)*-1);
+ if(!(self.opened && noclose)) el.fadeIn(100);
+ if(scroll == true) $('html, body').animate({scrollTop: el.offset().top-100}, 300);
+ self.opened = true;
+},
+opened: false,
+version: 5
+}
+})();
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026905_index.js b/pool/shard004/JavaScript/0026905_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..da249fddf890a5e149d82a1aca712b9dd1758d38
--- /dev/null
+++ b/pool/shard004/JavaScript/0026905_index.js
@@ -0,0 +1,102 @@
+import React from 'react';
+import {
+ arrayOf,
+ oneOfType,
+ string,
+ func,
+ node,
+ bool,
+ shape,
+ objectOf,
+ any
+} from 'prop-types';
+import { connect } from 'react-redux';
+import { isPlainObject, isEqual, toLower } from 'lodash';
+import { shortcutKeyPressed } from 'modules/keyBindings';
+
+@connect(null, { shortcutKeyPressed })
+export default class KeyBindings extends React.Component {
+ static propTypes = {
+ codes: arrayOf(
+ oneOfType([
+ string,
+ shape({
+ key: string.isRequired,
+ shiftKey: bool,
+ altKey: bool,
+ ctrlKey: bool
+ })
+ ])
+ ),
+ shortcutKeyPressed: func.isRequired,
+ stopPropagation: bool,
+ className: string,
+ style: objectOf(any),
+ children: node
+ };
+
+ static defaultProps = {
+ codes: [],
+ stopPropagation: false
+ };
+
+ handleKey = e => {
+ const { key, shiftKey, altKey, ctrlKey } = e;
+ const pressedModifiers = { shiftKey, altKey, ctrlKey };
+ const pressedKey = toLower(key);
+
+ const shouldHandleKey = this.props.codes.some(code => {
+ if (isPlainObject(code)) {
+ // handle key + modifier
+ const { key, shiftKey, altKey, ctrlKey } = code;
+
+ const testKey = toLower(key);
+ const testModifiers = {
+ shiftKey: shiftKey || false,
+ altKey: altKey || false,
+ ctrlKey: ctrlKey || false
+ };
+
+ return (
+ // key itself was pressed
+ testKey === pressedKey &&
+ // correct modifiers were held
+ isEqual(testModifiers, pressedModifiers)
+ );
+ }
+
+ // handle plain key
+ return toLower(pressedKey) === toLower(code);
+ });
+
+ if (shouldHandleKey) {
+ this.props.shortcutKeyPressed(pressedKey, pressedModifiers);
+ this.props.stopPropagation && e.stopPropagation();
+ }
+ };
+
+ render() {
+ return (
+
+ {this.props.children}
+
+ );
+ }
+}
+
+export const withKeyBindings = options => WrappedComponent => {
+ return class WrappedWithKeyBindings extends React.Component {
+ render() {
+ return (
+
+
+
+ );
+ }
+ };
+};
diff --git a/pool/shard004/JavaScript/0026906_editor_plugin_src.js b/pool/shard004/JavaScript/0026906_editor_plugin_src.js
new file mode 100644
index 0000000000000000000000000000000000000000..7c897380c68cada2741534d731dfa3a6306961f5
--- /dev/null
+++ b/pool/shard004/JavaScript/0026906_editor_plugin_src.js
@@ -0,0 +1,90 @@
+/**
+ * $Id$
+ *
+ * @author Moxiecode
+ * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
+ */
+
+/* Import plugin specific language pack */
+tinyMCE.importPluginLanguagePack('insertdatetime');
+
+var TinyMCE_InsertDateTimePlugin = {
+ getInfo : function() {
+ return {
+ longname : 'Insert date/time',
+ author : 'Moxiecode Systems AB',
+ authorurl : 'http://tinymce.moxiecode.com',
+ infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/insertdatetime',
+ version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
+ };
+ },
+
+ /**
+ * Returns the HTML contents of the insertdate, inserttime controls.
+ */
+ getControlHTML : function(cn) {
+ switch (cn) {
+ case "insertdate":
+ return tinyMCE.getButtonHTML(cn, 'lang_insertdate_desc', '{$pluginurl}/images/insertdate.gif', 'mceInsertDate');
+
+ case "inserttime":
+ return tinyMCE.getButtonHTML(cn, 'lang_inserttime_desc', '{$pluginurl}/images/inserttime.gif', 'mceInsertTime');
+ }
+
+ return "";
+ },
+
+ /**
+ * Executes the mceInsertDate command.
+ */
+ execCommand : function(editor_id, element, command, user_interface, value) {
+ /* Adds zeros infront of value */
+ function addZeros(value, len) {
+ value = "" + value;
+
+ if (value.length < len) {
+ for (var i=0; i<(len-value.length); i++)
+ value = "0" + value;
+ }
+
+ return value;
+ }
+
+ function getDateTime(d, fmt) {
+ fmt = fmt.replace("%D", "%m/%d/%y");
+ fmt = fmt.replace("%r", "%I:%M:%S %p");
+ fmt = fmt.replace("%Y", "" + d.getFullYear());
+ fmt = fmt.replace("%y", "" + d.getYear());
+ fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2));
+ fmt = fmt.replace("%d", addZeros(d.getDate(), 2));
+ fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2));
+ fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2));
+ fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2));
+ fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1));
+ fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM"));
+ fmt = fmt.replace("%B", "" + tinyMCE.getLang("lang_inserttime_months_long")[d.getMonth()]);
+ fmt = fmt.replace("%b", "" + tinyMCE.getLang("lang_inserttime_months_short")[d.getMonth()]);
+ fmt = fmt.replace("%A", "" + tinyMCE.getLang("lang_inserttime_day_long")[d.getDay()]);
+ fmt = fmt.replace("%a", "" + tinyMCE.getLang("lang_inserttime_day_short")[d.getDay()]);
+ fmt = fmt.replace("%%", "%");
+
+ return fmt;
+ }
+
+ // Handle commands
+ switch (command) {
+ case "mceInsertDate":
+ tinyMCE.execInstanceCommand(editor_id, 'mceInsertContent', false, getDateTime(new Date(), tinyMCE.getParam("plugin_insertdate_dateFormat", tinyMCE.getLang('lang_insertdate_def_fmt'))));
+ return true;
+
+ case "mceInsertTime":
+ tinyMCE.execInstanceCommand(editor_id, 'mceInsertContent', false, getDateTime(new Date(), tinyMCE.getParam("plugin_insertdate_timeFormat", tinyMCE.getLang('lang_inserttime_def_fmt'))));
+ return true;
+ }
+
+ // Pass to next handler in chain
+ return false;
+ }
+};
+
+tinyMCE.addPlugin("insertdatetime", TinyMCE_InsertDateTimePlugin);
diff --git a/pool/shard004/JavaScript/0026907_traverse.js b/pool/shard004/JavaScript/0026907_traverse.js
new file mode 100644
index 0000000000000000000000000000000000000000..37c71e9cf984f70c2491fd1a32b0c78a6bd6e0e8
--- /dev/null
+++ b/pool/shard004/JavaScript/0026907_traverse.js
@@ -0,0 +1,39 @@
+/* @flow */
+
+import { _Set as Set, isObject } from '../util/index'
+import type { SimpleSet } from '../util/index'
+
+const seenObjects = new Set()
+
+/**
+ * Recursively traverse an object to evoke all converted
+ * getters, so that every nested property inside the object
+ * is collected as a "deep" dependency.
+ */
+export function traverse (val: any) {
+ _traverse(val, seenObjects)
+ seenObjects.clear()
+}
+
+function _traverse (val: any, seen: SimpleSet) {
+ let i, keys
+ const isA = Array.isArray(val)
+ if ((!isA && !isObject(val)) || Object.isFrozen(val)) {
+ return
+ }
+ if (val.__ob__) {
+ const depId = val.__ob__.dep.id
+ if (seen.has(depId)) {
+ return
+ }
+ seen.add(depId)
+ }
+ if (isA) {
+ i = val.length
+ while (i--) _traverse(val[i], seen)
+ } else {
+ keys = Object.keys(val)
+ i = keys.length
+ while (i--) _traverse(val[keys[i]], seen)
+ }
+}
diff --git a/pool/shard004/JavaScript/0026909_array-int.js b/pool/shard004/JavaScript/0026909_array-int.js
new file mode 100644
index 0000000000000000000000000000000000000000..08d410a0132e39606afaf597b378d121149b5b41
--- /dev/null
+++ b/pool/shard004/JavaScript/0026909_array-int.js
@@ -0,0 +1,53 @@
+/************************************************************************
+ * This file is part of EspoCRM.
+ *
+ * EspoCRM - Open Source CRM application.
+ * Copyright (C) 2014-2017 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
+ * Website: http://www.espocrm.com
+ *
+ * EspoCRM is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * EspoCRM is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
+ *
+ * The interactive user interfaces in modified source and object code versions
+ * of this program must display Appropriate Legal Notices, as required under
+ * Section 5 of the GNU General Public License version 3.
+ *
+ * In accordance with Section 7(b) of the GNU General Public License version 3,
+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
+ ************************************************************************/
+
+Espo.define('views/fields/array-int', 'views/fields/array', function (Dep) {
+
+ return Dep.extend({
+
+ type: 'arrayInt',
+
+ addValue: function (value) {
+ value = parseInt(value);
+ if (isNaN(value)) {
+ return;
+ }
+ Dep.prototype.addValue.call(this, value);
+ },
+
+ removeValue: function (value) {
+ value = parseInt(value);
+ if (isNaN(value)) {
+ return;
+ }
+ Dep.prototype.removeValue.call(this, value);
+ }
+
+ });
+});
+
diff --git a/pool/shard004/JavaScript/0026910_share-bar.js b/pool/shard004/JavaScript/0026910_share-bar.js
new file mode 100644
index 0000000000000000000000000000000000000000..ec74c620cb216a6afa70ebf3ae9a4dd89770f6f0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026910_share-bar.js
@@ -0,0 +1,104 @@
+import Component from '@ember/component';
+import $ from 'jquery';
+import coughDropExtras from '../utils/extras';
+import app_state from '../utils/app_state';
+import modal from '../utils/modal';
+import capabilities from '../utils/capabilities';
+import i18n from '../utils/i18n';
+import { computed } from '@ember/object';
+
+export default Component.extend({
+ tagName: 'span',
+ didInsertElement: function() {
+ if(this.get('utterance') && this.get('utterance').check_for_large_image_url) {
+ this.get('utterance').check_for_large_image_url();
+ }
+ this.check_native_shares();
+ },
+ check_native_shares: function() {
+ var _this = this;
+ _this.set('native', {});
+ capabilities.sharing.available().then(function(list) {
+ if(list.indexOf('facebook') != -1) { _this.set('native.facebook', true); }
+ if(list.indexOf('twitter') != -1) { _this.set('native.twitter', true); }
+ if(list.indexOf('instagram') != -1) { _this.set('native.instagram', true); }
+ if(list.indexOf('email') != -1) { _this.set('native.email', true); }
+ if(list.indexOf('clipboard') != -1) { _this.set('native.clipboard', true); }
+ if(list.indexOf('generic') != -1) { _this.set('native.generic', true); }
+ });
+ },
+ facebook_enabled: computed('url', 'native.generic', 'native.facebook', function() {
+ return !!(this.get('url') && (!this.get('native.generic') || this.get('native.facebook')));
+ }),
+ twitter_enabled: computed('url', 'native.generic', 'native.twitter', function() {
+ return !!(this.get('url') && (!this.get('native.generic') || this.get('native.twitter')));
+ }),
+ email_enabled: computed('text', function() {
+ return !!this.get('text');
+ }),
+ instagram_enabled: computed('url', 'native.instagram', 'utterance.best_image_url', function() {
+ return !!(this.get('url') && this.get('native.instagram') && this.get('utterance.best_image_url'));
+ }),
+ clipboard_enabled: computed('native.clipboard', function() {
+ if(document.queryCommandSupported && document.queryCommandSupported('copy')) {
+ return true;
+ } else {
+ return !!this.get('native.clipboard');
+ }
+ }),
+ generic_enabled: computed('url', 'native.generic', function() {
+ return !!(this.get('url') && this.get('native.generic'));
+ }),
+ facebook_url: computed('url', function() {
+ return 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(this.get('url'));
+ }),
+ twitter_url: computed('url', 'text', function() {
+ var res = 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(this.get('url')) + '&text=' + encodeURIComponent(this.get('text'));
+ if(app_state.get('domain_settings.twitter_handle')) {
+ res = res + '&related=' + encodeURIComponent(app_state.get('domain_settings.twitter_handle'));
+ }
+ return res;
+ }),
+ actions: {
+ message: function(supervisor) {
+ modal.open('confirm-notify-user', {user: supervisor, utterance: this.get('utterance'), sentence: this.get('utterance.sentence')});
+ },
+ share_via: function(medium) {
+ if(this.get('native.' + medium)) {
+ // TODO: download the image locally first??
+ capabilities.sharing.share(medium, this.get('text'), this.get('url'), this.get('utterance.best_image_url'));
+ } else if(medium == 'facebook') {
+ capabilities.window_open(this.get('facebook_url'));
+ } else if(medium == 'twitter') {
+ capabilities.window_open(this.get('twitter_url'));
+ } else if(medium == 'email') {
+ modal.open('share-email', {url: this.get('url'), text: this.get('text'), utterance_id: this.get('utterance.id') });
+ } else if(medium == 'clipboard' && this.get('clipboard_enabled')) {
+ var res = false
+ if(this.get('native.clipboard')) {
+ capabilities.sharing.share('clipboard', this.get('text'));
+ res = true;
+ }
+ if(!res) {
+ var $elem = $("#" + this.get('element_id'));
+ window.getSelection().removeAllRanges();
+ var text = $elem[0].innerText;
+ if($elem[0].tagName == 'INPUT') {
+ $elem.focus().select();
+ text = $elem.val();
+ } else {
+ var range = document.createRange();
+ range.selectNode($elem[0]);
+ window.getSelection().addRange(range);
+ }
+ res = document.execCommand('copy');
+ if(!res) {
+ capabilities.sharing.copy_text(text);
+ }
+ window.getSelection().removeAllRanges();
+ }
+ this.sendAction('copy_event', !!res);
+ }
+ }
+ }
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026912_complex-numbers.js b/pool/shard004/JavaScript/0026912_complex-numbers.js
new file mode 100644
index 0000000000000000000000000000000000000000..c0067036ad052b4501e59a105123dee744a56536
--- /dev/null
+++ b/pool/shard004/JavaScript/0026912_complex-numbers.js
@@ -0,0 +1,41 @@
+//complex numbers
+
+function Complex(a,b){
+ //complex number a + bi
+ this.a = a;
+ this.b = b;
+}
+Complex.prototype.clone = function () {
+ //clone this and return a new complex number
+ return new Complex(this.a, this.b);
+}
+Complex.prototype.add = function (other) {
+ //add another complex number
+ this.a = this.a + other.a;
+ this.b = this.b + other.b;
+}
+Complex.prototype.addComponent = function (a,b) {
+ //add another complex number
+ this.a = this.a + a;
+ this.b = this.b + b;
+}
+Complex.prototype.multiply = function(other) {
+ //multiply with another complex number
+ var a = this.a;
+ var b = this.b;
+ var c = other.a;
+ var d = other.b;
+ var x = (a * c - b * d);
+ var y = (a * d + b * c);
+ this.a = x;
+ this.b = y;
+}
+Complex.prototype.multiplyComponent = function (c,d) {
+ //multiply with another complex number
+ var a = this.a;
+ var b = this.b;
+ var x = (a * c - b * d);
+ var y = (a * d + b * c);
+ this.a = x;
+ this.b = y;
+}
diff --git a/pool/shard004/JavaScript/0026916_directtransport_test.js b/pool/shard004/JavaScript/0026916_directtransport_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..940537767481eb51415e87efcd0a77a3d0aac302
--- /dev/null
+++ b/pool/shard004/JavaScript/0026916_directtransport_test.js
@@ -0,0 +1,264 @@
+// Copyright 2013 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 Tests the direct transport.
+ */
+
+goog.provide('goog.net.xpc.DirectTransportTest');
+
+goog.require('goog.Promise');
+goog.require('goog.dom');
+goog.require('goog.dom.TagName');
+goog.require('goog.labs.userAgent.browser');
+goog.require('goog.log');
+goog.require('goog.log.Level');
+goog.require('goog.net.xpc');
+goog.require('goog.net.xpc.CfgFields');
+goog.require('goog.net.xpc.CrossPageChannel');
+goog.require('goog.net.xpc.CrossPageChannelRole');
+goog.require('goog.net.xpc.TransportTypes');
+goog.require('goog.testing.TestCase');
+goog.require('goog.testing.jsunit');
+goog.setTestOnly('goog.net.xpc.DirectTransportTest');
+
+
+/**
+ * Echo service name.
+ * @type {string}
+ * @const
+ */
+var ECHO_SERVICE_NAME = 'echo';
+
+
+/**
+ * Response service name.
+ * @type {string}
+ * @const
+ */
+var RESPONSE_SERVICE_NAME = 'response';
+
+
+/**
+ * Test Payload.
+ * @type {string}
+ * @const
+ */
+var MESSAGE_PAYLOAD_1 = 'This is message payload 1.';
+
+
+/**
+ * The name id of the peer iframe.
+ * @type {string}
+ * @const
+ */
+var PEER_IFRAME_ID = 'peer-iframe';
+
+
+// Class aliases.
+var CfgFields = goog.net.xpc.CfgFields;
+var CrossPageChannel = goog.net.xpc.CrossPageChannel;
+var CrossPageChannelRole = goog.net.xpc.CrossPageChannelRole;
+var TransportTypes = goog.net.xpc.TransportTypes;
+
+var outerXpc;
+var innerXpc;
+var peerIframe;
+var channelName;
+var messageIsSync = false;
+var savedHtml;
+var debugDiv;
+
+function setUpPage() {
+ // Show debug log
+ debugDiv = goog.dom.createElement(goog.dom.TagName.DIV);
+ var logger = goog.log.getLogger('goog.net.xpc');
+ logger.setLevel(goog.log.Level.ALL);
+ goog.log.addHandler(logger, function(logRecord) {
+ var msgElm = goog.dom.createDom(goog.dom.TagName.DIV);
+ msgElm.innerHTML = logRecord.getMessage();
+ goog.dom.appendChild(debugDiv, msgElm);
+ });
+ goog.testing.TestCase.getActiveTestCase().promiseTimeout = 10000; // 10s
+}
+
+function setUp() {
+ savedHtml = document.body.innerHTML;
+ document.body.appendChild(debugDiv);
+}
+
+
+function tearDown() {
+ if (peerIframe) {
+ document.body.removeChild(peerIframe);
+ peerIframe = null;
+ }
+ if (outerXpc) {
+ outerXpc.dispose();
+ outerXpc = null;
+ }
+ if (innerXpc) {
+ innerXpc.dispose();
+ innerXpc = null;
+ }
+ window.iframeLoadHandler = null;
+ channelName = null;
+ messageIsSync = false;
+ document.body.innerHTML = savedHtml;
+}
+
+
+function createIframe() {
+ peerIframe = goog.dom.createElement(goog.dom.TagName.IFRAME);
+ peerIframe.id = PEER_IFRAME_ID;
+ document.body.insertBefore(peerIframe, document.body.firstChild);
+}
+
+
+/**
+ * Tests 2 same domain frames using direct transport.
+ */
+function testDirectTransport() {
+ // This test has been flaky on IE.
+ // For now, disable.
+ // Flakiness is tracked in http://b/18595666
+ if (goog.labs.userAgent.browser.isIE()) {
+ return;
+ }
+
+ createIframe();
+ channelName = goog.net.xpc.getRandomString(10);
+ outerXpc = new CrossPageChannel(
+ getConfiguration(CrossPageChannelRole.OUTER, PEER_IFRAME_ID));
+ // Outgoing service.
+ outerXpc.registerService(ECHO_SERVICE_NAME, goog.nullFunction);
+ // Incoming service.
+ var resolver = goog.Promise.withResolver();
+ outerXpc.registerService(RESPONSE_SERVICE_NAME, function(message) {
+ assertEquals(
+ 'Received payload is equal to sent payload.', message,
+ MESSAGE_PAYLOAD_1);
+ resolver.resolve();
+ });
+
+ outerXpc.connect(function() {
+ assertTrue('XPC over direct channel is connected', outerXpc.isConnected());
+ outerXpc.send(ECHO_SERVICE_NAME, MESSAGE_PAYLOAD_1);
+ });
+ // inner_peer.html calls this method at end of html.
+ window.iframeLoadHandler = function() {
+ peerIframe.contentWindow.instantiateChannel(
+ getConfiguration(CrossPageChannelRole.INNER));
+ };
+ peerIframe.src = 'testdata/inner_peer.html';
+
+ return resolver.promise;
+}
+
+
+/**
+ * Tests 2 xpc's communicating with each other in the same window.
+ */
+function testSameWindowDirectTransport() {
+ channelName = goog.net.xpc.getRandomString(10);
+
+ outerXpc = new CrossPageChannel(getConfiguration(CrossPageChannelRole.OUTER));
+ outerXpc.setPeerWindowObject(self);
+
+ // Outgoing service.
+ outerXpc.registerService(ECHO_SERVICE_NAME, goog.nullFunction);
+
+ var resolver = goog.Promise.withResolver();
+ // Incoming service.
+ outerXpc.registerService(RESPONSE_SERVICE_NAME, function(message) {
+ assertEquals(
+ 'Received payload is equal to sent payload.', message,
+ MESSAGE_PAYLOAD_1);
+ resolver.resolve();
+ });
+ outerXpc.connect(function() {
+ assertTrue(
+ 'XPC over direct channel, same window, is connected',
+ outerXpc.isConnected());
+ outerXpc.send(ECHO_SERVICE_NAME, MESSAGE_PAYLOAD_1);
+ });
+
+ innerXpc = new CrossPageChannel(getConfiguration(CrossPageChannelRole.INNER));
+ innerXpc.setPeerWindowObject(self);
+ // Incoming service.
+ innerXpc.registerService(ECHO_SERVICE_NAME, function(message) {
+ innerXpc.send(RESPONSE_SERVICE_NAME, message);
+ });
+ // Outgoing service.
+ innerXpc.registerService(RESPONSE_SERVICE_NAME, goog.nullFunction);
+ innerXpc.connect();
+ return resolver.promise;
+}
+
+function getConfiguration(role, opt_peerFrameId) {
+ var cfg = {};
+ cfg[CfgFields.TRANSPORT] = TransportTypes.DIRECT;
+ if (goog.isDefAndNotNull(opt_peerFrameId)) {
+ cfg[CfgFields.IFRAME_ID] = opt_peerFrameId;
+ }
+ cfg[CfgFields.CHANNEL_NAME] = channelName;
+ cfg[CfgFields.ROLE] = role;
+ return cfg;
+}
+
+
+/**
+ * Tests 2 same domain frames using direct transport using sync mode.
+ */
+function testSyncMode() {
+ // This test has been flaky on IE.
+ // For now, disable.
+ // Flakiness is tracked in http://b/18595666
+ if (goog.labs.userAgent.browser.isIE()) {
+ return;
+ }
+
+ createIframe();
+ channelName = goog.net.xpc.getRandomString(10);
+
+ var cfg = getConfiguration(CrossPageChannelRole.OUTER, PEER_IFRAME_ID);
+ cfg[CfgFields.DIRECT_TRANSPORT_SYNC_MODE] = true;
+
+ outerXpc = new CrossPageChannel(cfg);
+ // Outgoing service.
+ outerXpc.registerService(ECHO_SERVICE_NAME, goog.nullFunction);
+ var resolver = goog.Promise.withResolver();
+ // Incoming service.
+ outerXpc.registerService(RESPONSE_SERVICE_NAME, function(message) {
+ assertTrue('The message response was syncronous', messageIsSync);
+ assertEquals(
+ 'Received payload is equal to sent payload.', message,
+ MESSAGE_PAYLOAD_1);
+ resolver.resolve();
+ });
+ outerXpc.connect(function() {
+ assertTrue('XPC over direct channel is connected', outerXpc.isConnected());
+ messageIsSync = true;
+ outerXpc.send(ECHO_SERVICE_NAME, MESSAGE_PAYLOAD_1);
+ messageIsSync = false;
+ });
+ // inner_peer.html calls this method at end of html.
+ window.iframeLoadHandler = function() {
+ var cfg = getConfiguration(CrossPageChannelRole.INNER);
+ cfg[CfgFields.DIRECT_TRANSPORT_SYNC_MODE] = true;
+ peerIframe.contentWindow.instantiateChannel(cfg);
+ };
+ peerIframe.src = 'testdata/inner_peer.html';
+ return resolver.promise;
+}
diff --git a/pool/shard004/JavaScript/0026917_pathUtils.js b/pool/shard004/JavaScript/0026917_pathUtils.js
new file mode 100644
index 0000000000000000000000000000000000000000..d4f628869ede99592c1cd206b626355fe810907d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026917_pathUtils.js
@@ -0,0 +1,44 @@
+
+import path from 'path'
+
+export let parseFileUri = function(fileUri) {
+ var fileName, pathInfo, storeName, url;
+ url = require('url');
+ pathInfo = url.parse(fileUri);
+ storeName = pathInfo.protocol;
+ fileName = pathInfo.host + pathInfo.pathname;
+ storeName = storeName.replace(":", "");
+ if (storeName === null) {
+ if (pathInfo.path[0] === "/") {
+ storeName = "local";
+ } else {
+
+ }
+ } else if (storeName === "http" || storeName === "https") {
+ storeName = "xhr";
+ fileName = pathInfo.href;
+ }
+ return [storeName, fileName];
+};
+
+export let toAbsoluteUri = function(fileName, parentUri, store) {
+ var fullPath, isXHr, rootUri, segments;
+ path = require('path');
+ segments = fileName.split("/");
+ if (segments[0] !== '.' && segments[0] !== '..') {
+ return fileName;
+ }
+ rootUri = parentUri || store.rootUri || "";
+ fileName = path.normalize(fileName);
+ isXHr = rootUri.indexOf("http") !== -1;
+ if (isXHr) {
+ fullPath = rootUri + fileName;
+ } else {
+ rootUri = rootUri[rootUri.length - 1] === "/" ? rootUri += "a" : rootUri;
+ rootUri = path.normalize(rootUri);
+ rootUri = path.dirname(rootUri);
+ fullPath = path.join(rootUri, fileName);
+ }
+ return fullPath;
+};
+
diff --git a/pool/shard004/JavaScript/0026921_childVariant.js b/pool/shard004/JavaScript/0026921_childVariant.js
new file mode 100644
index 0000000000000000000000000000000000000000..bc0d2ad1ca7f0d2399120980540a7a611a31fa46
--- /dev/null
+++ b/pool/shard004/JavaScript/0026921_childVariant.js
@@ -0,0 +1,46 @@
+/**
+ * childVariantForm helpers
+ */
+
+Template.childVariantForm.helpers({
+ childVariantFormId: function () {
+ return "child-variant-form-" + this._id;
+ }
+});
+
+/**
+ * childVariantForm events
+ */
+
+Template.childVariantForm.events({
+ "click .child-variant-form :input, click li": function (event, template) {
+ return setCurrentVariant(template.data._id);
+ },
+ "change .child-variant-form :input": function (event, template) {
+ let variant = template.data;
+ let value = $(event.currentTarget).val();
+ let field = $(event.currentTarget).attr("name");
+
+ variant[field] = value;
+ Meteor.call("products/updateVariant", variant, function (error) {
+ if (error) {
+ throw new Meteor.Error("error updating variant", error);
+ }
+ });
+ return setCurrentVariant(template.data._id);
+ },
+ "click #remove-child-variant": function (event) {
+ event.stopPropagation();
+ event.preventDefault();
+ let optionTitle = this.optionTitle || "this option";
+ if (confirm("Are you sure you want to delete " + optionTitle)) {
+ let id = this._id;
+ return Meteor.call("products/deleteVariant", id, function (error,
+ result) {
+ if (result && selectedVariantId() === id) {
+ return setCurrentVariant(null);
+ }
+ });
+ }
+ }
+});
diff --git a/pool/shard004/JavaScript/0026922_spawn-libp2p-node.js b/pool/shard004/JavaScript/0026922_spawn-libp2p-node.js
new file mode 100644
index 0000000000000000000000000000000000000000..2976586488624823c5bd7f9c2140cd8834baab62
--- /dev/null
+++ b/pool/shard004/JavaScript/0026922_spawn-libp2p-node.js
@@ -0,0 +1,41 @@
+'use strict'
+
+const libp2p = require('libp2p-ipfs')
+const isNode = require('detect-node')
+const _random = require('lodash.random')
+const PeerId = require('peer-id')
+const PeerInfo = require('peer-info')
+const multiaddr = require('multiaddr')
+
+module.exports = spawnNode
+
+function spawnNode (peerInfo, callback) {
+ if (typeof peerInfo === 'function') {
+ callback = peerInfo
+ peerInfo = undefined
+ }
+
+ if (!peerInfo) {
+ const id = PeerId.create()
+ peerInfo = new PeerInfo(id)
+
+ if (isNode) {
+ peerInfo.multiaddr.add(multiaddr('/ip4/0.0.0.0/tcp/0'))
+ // until libp2p-websockets supports port 0
+ const wsPort = _random(10000, 19000)
+ peerInfo.multiaddr.add(multiaddr(`/ip4/127.0.0.1/tcp/${wsPort}/ws`))
+ } else {
+ const sig = multiaddr('/libp2p-webrtc-star/ip4/127.0.0.1/tcp/20000/ws')
+ peerInfo.multiaddr.add(sig.encapsulate(`/ipfs/${id.toB58String()}`))
+ }
+ }
+
+ const node = new libp2p.Node(peerInfo)
+
+ node.start((err) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, node)
+ })
+}
diff --git a/pool/shard004/JavaScript/0026924_home.js b/pool/shard004/JavaScript/0026924_home.js
new file mode 100644
index 0000000000000000000000000000000000000000..72d807db05a20f798538248e842783fe1c65ef83
--- /dev/null
+++ b/pool/shard004/JavaScript/0026924_home.js
@@ -0,0 +1,72 @@
+var home = angular.module('home',['services']);
+
+home.controller('header', function($scope) {
+ $scope.contextItems = [
+ {url: "player.html#/players", label: "My Players"},
+ {url: "team.html", label: "My Teams"},
+ {url: "league.html", label: "My Leagues"}
+ ];
+});
+home.controller('color', function($scope) {
+
+});
+home.controller('feed', function($scope, Events, League, LeagueTables, TeamView, LeagueTableResult, TeamView) {
+ TeamView.get().$promise.then(function(resp){
+ $scope.teamList = resp.teams;
+ });
+ var startDate = moment().format(serviceDateFormat);
+ var endDate = moment().add(3,'M').format(serviceDateFormat);
+ Events.get({start: startDate, end: endDate}).$promise.then(function(resp) {
+ var sortevents = resp.events.slice(0);
+ sortevents.sort(function(a,b){
+ if(moment(a.start).isBefore(moment(b.start)))
+ return -1;
+ else
+ return 1;
+ });
+ var events = sortevents.slice(0,10);
+ angular.forEach(events, function(value, key){
+ events[key].startday = moment(value.start).format("D");
+ events[key].startmonth = moment(value.start).format("MMM");
+ events[key].start = moment(value.start).format("h:mm A");
+ events[key].end = moment(value.end).format("h:mm A");
+ });
+ if(events.length == 0)
+ $scope.noevents = "No Upcoming Events";
+ else
+ $scope.events = events;
+ });
+
+ $scope.loadTournament = function(leagueId, tableId) {
+ TeamView.get().$promise.then(function(resp) {
+ if(resp.status.code == 200) {
+ var teamviews = resp.teams
+ LeagueTableResult.get({id: leagueId, tableID: tableId, showError: false}).$promise.then(function(resp){
+ var table = resp.tournamentResults;
+
+ angular.forEach(table, function(teamResults, key){
+ angular.forEach(teamviews, function(team, key){
+ if(teamResults.teamID == team.id)
+ teamResults.name = team.name;
+ });
+ });
+
+ $scope.tournamentResults = table;
+ });
+ }
+ });
+ }
+
+
+ // Get first league and league table we find, and display it.
+ League.get().$promise.then(function(resp) {
+ if(resp.leagues.length != 0) {
+ var leagueid = resp.leagues[0].id;
+ LeagueTables.get({id: leagueid}).$promise.then(function(resp){
+ if(resp.tables.length != 0) {
+ $scope.loadTournament(leagueid, resp.tables[0].tournamentId);
+ }
+ });
+ }
+ });
+});
diff --git a/pool/shard004/JavaScript/0026926_BingMap.js b/pool/shard004/JavaScript/0026926_BingMap.js
new file mode 100644
index 0000000000000000000000000000000000000000..a68b350332bc6a20dff8ae7a9b8ca0d242abee7d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026926_BingMap.js
@@ -0,0 +1,109 @@
+/*jslint plusplus: true */
+/*globals VELatLong,VEMap,VEShape,VEShapeType,VEShapeLayer,VERouteOptions,VERouteDistanceUnit,watermarktext_blur*/
+var map = null;
+var pushPinLayer = null;
+try {
+ function addPushPin(latLong) {
+ "use strict";
+ var marker = new VEShape(VEShapeType.Pushpin, latLong);
+ marker.SetTitle("MAQ Software");
+ marker.SetDescription("15446 Bel-Red Road,
Suite 201 Redmond,
WA 98052(425) 526 5399");
+ pushPinLayer.AddShape(marker);
+ }
+
+ function getMap() {
+ "use strict";
+ var LAtitiude_Longitude = new VELatLong(47.633082999999985, -122.13328600000006);
+ map = new VEMap('mapviewer');
+ map.LoadMap();
+ map.SetCenterAndZoom(LAtitiude_Longitude, 15);
+ pushPinLayer = new VEShapeLayer();
+ map.DeleteAllShapeLayers();
+ addPushPin(LAtitiude_Longitude);
+ map.AddShapeLayer(pushPinLayer);
+ }
+ getMap();
+
+ /*changes for the get directions functionality*/
+ function resetFields() {
+ "use strict";
+ getMap();
+ document.getElementById('directionInput').value = '';
+ document.getElementById("directions").innerHTML = '';
+ watermarktext_blur(document.getElementById('directionInput'));
+ }
+
+ function ShowTurns(route) {
+ "use strict";
+ if (route) {
+ // Unroll route and populate DIV
+ var legs = route.RouteLegs,
+ turns = "Turn-by-Turn Directions
",
+ leg = null,
+ i,
+ j,
+ turnNum = 0, // The turn #
+ totalDistance = 0, // The sum of all leg distances
+ turn,
+ legDistance;
+
+ // Get intermediate legs
+ for (i = 0; i < legs.length; i++) {
+ // Get this leg so we don't have to derefernce multiple times
+ leg = legs[i]; // Leg is a VERouteLeg object
+
+ // Unroll each intermediate leg
+ turn = null; // The itinerary leg
+ legDistance = null; // The distance for this leg
+
+ for (j = 0; j < leg.Itinerary.Items.length; j++) {
+ turnNum++;
+ turn = leg.Itinerary.Items[j]; // turn is a VERouteItineraryItem object
+ turns += "" + turnNum + "." + turn.Text;
+ legDistance = turn.Distance;
+ totalDistance += legDistance;
+
+ // Round distances to 1/10ths
+ turns += " (" + legDistance.toFixed(1) + " miles)
";
+ }
+ }
+ turns += "
Total distance: " + totalDistance.toFixed(1) + " miles";
+
+ // Populate DIV with directions
+ document.getElementById("directions").innerHTML = turns;
+ }
+ }
+
+ //var mileDist = new VERouteDistanceUnit.Mile();
+ function getRouteMap(locations) {
+ "use strict";
+ var options = new VERouteOptions();
+ // Otherwise what's the point?
+ options.DrawRoute = true;
+ // So the map repositions:
+ options.SetBestMapView = true;
+ // Call this function when map route is determined:
+ options.RouteCallback = ShowTurns;
+ // Show as miles
+ options.DistanceUnit = VERouteDistanceUnit.Mile;
+ // Show the disambiguation dialog if unable to locate a location
+ options.ShowDisambiguation = true;
+ map.GetDirections(locations, options);
+ // map.GetRoute(start, end, units, route_type, callback);
+ }
+
+ function getRouteTo(latitude, longitude, input) {
+ "use strict";
+ if ($('#input').hasClass("maqwatermark")) {
+ return;
+ }
+
+ var MAQSoftwareLocation = new VELatLong(latitude, longitude); //47.633087, -122.133202);
+ if (input && input !== "") {
+ getRouteMap([input, MAQSoftwareLocation]);
+ }
+ $('#directions').css({
+ "display": "block"
+ });
+ }
+} catch (ignore) { }
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026927_serve.js b/pool/shard004/JavaScript/0026927_serve.js
new file mode 100644
index 0000000000000000000000000000000000000000..a7f792d51b62a80d6f84badc7c6d3fc2faa5c836
--- /dev/null
+++ b/pool/shard004/JavaScript/0026927_serve.js
@@ -0,0 +1,100 @@
+/**
+ * This task starts a dev server that provides a script loader for OpenLayers
+ * and Closure Library. In addition, a static server hosts all files in the
+ * repository.
+ */
+
+var path = require('path');
+var url = require('url');
+
+var closure = require('closure-util');
+var nomnom = require('nomnom');
+
+var log = closure.log;
+
+
+/**
+ * Create a debug server for ol and Closure Library sources.
+ * @param {function(Error, closure.Server)} callback Callback.
+ */
+var createServer = exports.createServer = function(callback) {
+ var server;
+ var manager = new closure.Manager({
+ lib: [
+ 'src/**/*.js',
+ 'build/ol.ext/*.js',
+ 'test/spec/**/*.test.js'
+ ],
+ main: 'examples/*.js'
+ });
+ manager.on('error', function(err) {
+ if (server) {
+ log.error('serve', err.message);
+ } else {
+ callback(err);
+ }
+ });
+ manager.on('ready', function() {
+ server = new closure.Server({
+ manager: manager,
+ loader: /^\/\w+\/loader.js/,
+ getMain: function(req) {
+ var main;
+ var query = url.parse(req.url, true).query;
+ if (query.id) {
+ var referer = req.headers.referer;
+ if (referer) {
+ var from = path.join(process.cwd(),
+ path.dirname(url.parse(referer).pathname));
+ main = path.resolve(from, query.id + '.js');
+ }
+ }
+ return main;
+ }
+ });
+ callback(null, server);
+ });
+};
+
+
+/**
+ * If running this module directly start the server.
+ */
+if (require.main === module) {
+ var options = nomnom.options({
+ port: {
+ abbr: 'p',
+ default: 3000,
+ help: 'Port for incoming connections',
+ metavar: 'PORT'
+ },
+ loglevel: {
+ abbr: 'l',
+ choices: ['silly', 'verbose', 'info', 'warn', 'error'],
+ default: 'info',
+ help: 'Log level',
+ metavar: 'LEVEL'
+ }
+ }).parse();
+
+ /** @type {string} */
+ log.level = options.loglevel;
+
+ log.info('serve', 'Parsing dependencies ...');
+ createServer(function(err, server) {
+ if (err) {
+ log.error('serve', 'Parsing failed');
+ log.error('serve', err.message);
+ process.exit(1);
+ }
+ server.listen(options.port, function() {
+ log.info('serve', 'Listening on http://localhost:' +
+ options.port + '/ (Ctrl+C to stop)');
+ });
+ server.on('error', function(err) {
+ log.error('serve', 'Server failed to start: ' + err.message);
+ process.exit(1);
+ });
+
+ });
+}
diff --git a/pool/shard004/JavaScript/0026928_AppSpec.js b/pool/shard004/JavaScript/0026928_AppSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..3cd9bc6aa0467332f277bc4c8ffd3a94a7aa5811
--- /dev/null
+++ b/pool/shard004/JavaScript/0026928_AppSpec.js
@@ -0,0 +1,13 @@
+/* global window: false */
+
+var App = require('../../../src/browser/App.coffee');
+var HelloWorld = require('../../../src/common/HelloWorld.coffee');
+
+describe("HelloJQuery", function() {
+ it("running App.main() should create an element with 'hello' id, with text set to helloUnderscore()", function() {
+ App.main();
+ var expected = HelloWorld.helloUnderscore();
+ var actual = window.document.getElementById('hello').innerHTML;
+ expect(actual).toEqual(expected);
+ });
+});
diff --git a/pool/shard004/JavaScript/0026932_links-alliances.js b/pool/shard004/JavaScript/0026932_links-alliances.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a2f6c6988bbbe5c9b1f01c1c2260138c79ecc84
--- /dev/null
+++ b/pool/shard004/JavaScript/0026932_links-alliances.js
@@ -0,0 +1,33 @@
+'use strict';
+/**
+ * linksyouthoverview.js
+ * Foxtrick add links to arena pages
+ * @author larsw84, LA-MJ
+ */
+
+Foxtrick.modules['LinksAlliances'] = {
+ MODULE_CATEGORY: Foxtrick.moduleCategories.LINKS,
+ PAGES: ['federation'],
+ LINK_TYPES: 'federationlink',
+ /**
+ * return HTML for FT prefs
+ * @param {document} doc
+ * @param {function} cb
+ * @return {HTMLUListElement}
+ */
+ OPTION_FUNC: function(doc, cb) {
+ return Foxtrick.util.links.getPrefs(doc, this, cb);
+ },
+
+ run: function(doc) {
+ Foxtrick.util.links.run(doc, this);
+ },
+
+ links: function(doc) {
+ var federationId = Foxtrick.Pages.All.getId(doc);
+ var info = {
+ federationId: federationId,
+ };
+ return { info: info };
+ }
+};
diff --git a/pool/shard004/JavaScript/0026933_token.js b/pool/shard004/JavaScript/0026933_token.js
new file mode 100644
index 0000000000000000000000000000000000000000..49449d359f0003b9a6aa752ce7cd27e7cd8f331d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026933_token.js
@@ -0,0 +1,122 @@
+'use strict';
+var site = require( './site' );
+var charmap = require( './charmap' );
+var error = require( './error' );
+
+/*
+ lexer token types
+*/
+
+// lexer token type enumeration
+const type_ids = {
+ trm : 1,
+ tag : 2,
+ lpr : 3,
+ rpr : 5,
+ neg : 7,
+ oro : 11,
+ wts : 13,
+ quo : 17
+};
+
+// base, abstract token type
+class tok {
+ constructor ( tok_site ) {
+ if ( !( tok_site instanceof site ) )
+ throw new Error( "tok accepts only one site" );
+ this._site = tok_site;
+ }
+
+ getType () {
+ return this._type;
+ }
+
+ getSite () {
+ return this._site;
+ }
+
+ getText () {
+ return this.getSite().getText();
+ }
+
+ error ( msg ) {
+ return new error( this.getSite(), msg );
+ }
+};
+
+// term
+class trm extends tok {
+ constructor ( trm_site ) {
+ super( trm_site );
+ this._type = type_ids.trm;
+ }
+};
+
+// quote
+class quo extends tok {
+ constructor ( site ) {
+ super( site );
+ this._type = type_ids.quo;
+ }
+}
+
+// tag identifier (':')
+class tag extends tok {
+ constructor( tag_site ) {
+ super( tag_site );
+ this._type = type_ids.tag;
+ }
+};
+
+// left parenthesis
+class lpr extends tok {
+ constructor ( lpr_site ) {
+ super( lpr_site );
+ this._type = type_ids.lpr;
+ }
+};
+
+// right parenthesis
+class rpr extends tok {
+ constructor ( rpr_site ) {
+ super( rpr_site );
+ this._type = type_ids.rpr;
+ }
+};
+
+// negation operator ('!', '-')
+class neg extends tok {
+ constructor ( neg_site ) {
+ super( neg_site );
+ this._type = type_ids.neg;
+ }
+};
+
+// disjunctive operator ('|')
+class oro extends tok {
+ constructor ( oro_site ) {
+ super( oro_site );
+ this._type = type_ids.oro;
+ }
+};
+
+// whitespace
+class wts extends tok {
+ constructor ( wts_site ) {
+ super( wts_site );
+ this._type = type_ids.wts;
+ }
+};
+
+module.exports = {
+ tok : tok,
+ trm : trm,
+ quo : quo,
+ tag : tag,
+ lpr : lpr,
+ rpr : rpr,
+ neg : neg,
+ oro : oro,
+ wts : wts,
+ type_ids : type_ids
+};
diff --git a/pool/shard004/JavaScript/0026934_index.js b/pool/shard004/JavaScript/0026934_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..110fdebddaf3df10357757f4563d6bcb6721d92c
--- /dev/null
+++ b/pool/shard004/JavaScript/0026934_index.js
@@ -0,0 +1,49 @@
+/*globals $, d3, geo */
+
+$(function () {
+ "use strict";
+
+ var map = $("#content").geojsMap(),
+ data = [
+ [ "NEW YORK", "NY", "40.757929", "-73.985506"],
+ [ "LOS ANGELES", "CA", "34.052187", "-118.243425"],
+ [ "DENVER", "CO", "39.755092", "-104.988123"],
+ [ "PORTLAND", "OR", "45.523104", "-122.670132"],
+ [ "HONOLULU", "HI", "21.291982", "-157.821856"],
+ [ "ANCHORAGE", "AK", "61.216583", "-149.899597"],
+ [ "DALLAS", "TX", "32.781078", "-96.797111"],
+ [ "SALT LAKE CITY", "UT", "40.771592", "-111.888189"],
+ [ "MIAMI", "FL", "25.774252", "-80.190262"],
+ [ "PHOENIX", "AZ", "33.448263", "-112.073821"],
+ [ "CHICAGO", "IL", "41.879535", "-87.624333"],
+ [ "WASHINGTON", "DC", "38.892091", "-77.024055"],
+ [ "SEATTLE", "WA", "47.620716", "-122.347533"],
+ [ "NEW ORLEANS", "LA", "30.042487", "-90.025126"],
+ [ "SAN FRANCISCO", "CA", "37.775196", "-122.419204"],
+ [ "ATLANTA", "GA", "33.754487", "-84.389663"]
+ ],
+ svg = map.geojsMap("svg"),
+ points = d3.select(svg).selectAll(".points").data(data);
+
+ points.enter()
+ .append("circle")
+ .attr("class", "points")
+ .attr("r", 5)
+ .style("fill", "steelblue");
+
+ function draw() {
+ var pts = [];
+ data.forEach(function (d) {
+ var pt = map.geojsMap("latlng2display", geo.latlng(parseFloat(d[2]), parseFloat(d[3])));
+ pts.push(pt);
+ });
+ points
+ .attr("cx", function (d, i) {
+ return pts[i].x;
+ })
+ .attr("cy", function (d, i) {
+ return pts[i].y;
+ });
+ }
+ draw();
+});
diff --git a/pool/shard004/JavaScript/0026936_while-3.js b/pool/shard004/JavaScript/0026936_while-3.js
new file mode 100644
index 0000000000000000000000000000000000000000..8a453192e9aaf8fbb2cdad502e64baa053830629
--- /dev/null
+++ b/pool/shard004/JavaScript/0026936_while-3.js
@@ -0,0 +1,22 @@
+module.exports = flatten
+
+function flatten (array) {
+ return flattenWithResult(array, [])
+}
+
+function flattenWithResult (array, result) {
+ var len = array.length
+ var num = 0
+
+ while (len--) {
+ var i = num++
+
+ if (Array.isArray(array[i])) {
+ flattenWithResult(array[i], result)
+ } else {
+ result.push(array[i])
+ }
+ }
+
+ return result
+}
diff --git a/pool/shard004/JavaScript/0026938_gr-patch-range-select.js b/pool/shard004/JavaScript/0026938_gr-patch-range-select.js
new file mode 100644
index 0000000000000000000000000000000000000000..4e7fa385db586a7c09ba368f785e6cd7242e7d22
--- /dev/null
+++ b/pool/shard004/JavaScript/0026938_gr-patch-range-select.js
@@ -0,0 +1,246 @@
+// Copyright (C) 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+(function() {
+ 'use strict';
+
+ // Maximum length for patch set descriptions.
+ const PATCH_DESC_MAX_LENGTH = 500;
+
+ /**
+ * Fired when the patch range changes
+ *
+ * @event patch-range-change
+ *
+ * @property {string} patchNum
+ * @property {string} basePatchNum
+ */
+
+ Polymer({
+ is: 'gr-patch-range-select',
+
+ properties: {
+ availablePatches: Array,
+ _baseDropdownContent: {
+ type: Object,
+ computed: '_computeBaseDropdownContent(availablePatches, patchNum,' +
+ '_sortedRevisions, comments)',
+ },
+ _patchDropdownContent: {
+ type: Object,
+ computed: '_computePatchDropdownContent(availablePatches,' +
+ 'basePatchNum, _sortedRevisions, comments)',
+ },
+ changeNum: String,
+ // In the case of a patch range select (like diff view) comments should
+ // be an empty array, so that the patch and base content computed values
+ // get triggered.
+ comments: {
+ type: Object,
+ value: () => { return {}; },
+ },
+ /** @type {{ meta_a: !Array, meta_b: !Array}} */
+ filesWeblinks: Object,
+ patchNum: String,
+ basePatchNum: String,
+ revisions: Object,
+ _sortedRevisions: Array,
+ },
+
+ observers: [
+ '_updateSortedRevisions(revisions.*)',
+ ],
+
+ behaviors: [Gerrit.PatchSetBehavior],
+
+ _computeBaseDropdownContent(availablePatches, patchNum, _sortedRevisions,
+ comments) {
+ const dropdownContent = [];
+ for (const basePatch of availablePatches) {
+ const basePatchNum = basePatch.num;
+ dropdownContent.push({
+ disabled: this._computeLeftDisabled(
+ basePatch.num, patchNum, _sortedRevisions),
+ triggerText: `Patchset ${basePatchNum}`,
+ text: `Patchset ${basePatchNum}` +
+ this._computePatchSetCommentsString(this.comments, basePatchNum),
+ mobileText: this._computeMobileText(basePatchNum, comments,
+ _sortedRevisions),
+ bottomText: `${this._computePatchSetDescription(
+ _sortedRevisions, basePatchNum)}`,
+ value: basePatch.num,
+ });
+ }
+ dropdownContent.push({
+ text: 'Base',
+ value: 'PARENT',
+ });
+ return dropdownContent;
+ },
+
+ _computeMobileText(patchNum, comments, revisions) {
+ return `${patchNum}` +
+ `${this._computePatchSetCommentsString(this.comments, patchNum)}` +
+ `${this._computePatchSetDescription(revisions, patchNum, true)}`;
+ },
+
+ _computePatchDropdownContent(availablePatches, basePatchNum,
+ _sortedRevisions, comments) {
+ const dropdownContent = [];
+ for (const patch of availablePatches) {
+ const patchNum = patch.num;
+ dropdownContent.push({
+ disabled: this._computeRightDisabled(basePatchNum, patchNum,
+ _sortedRevisions),
+ triggerText: `${patchNum === 'edit' ? '': 'Patchset '}` +
+ patchNum,
+ text: `${patchNum === 'edit' ? '': 'Patchset '}${patchNum}` +
+ `${this._computePatchSetCommentsString(
+ this.comments, patchNum)}`,
+ mobileText: this._computeMobileText(patchNum, comments,
+ _sortedRevisions),
+ bottomText: `${this._computePatchSetDescription(
+ _sortedRevisions, patchNum)}`,
+ value: patchNum,
+ });
+ }
+ return dropdownContent;
+ },
+
+ _updateSortedRevisions(revisionsRecord) {
+ const revisions = revisionsRecord.base;
+ this._sortedRevisions = this.sortRevisions(Object.values(revisions));
+ },
+
+ /**
+ * The basePatchNum should always be <= patchNum -- because sortedRevisions
+ * is sorted in reverse order (higher patchset nums first), invalid base
+ * patch nums have an index greater than the index of patchNum.
+ * @param {number|string} basePatchNum The possible base patch num.
+ * @param {number|string} patchNum The current selected patch num.
+ * @param {!Array} sortedRevisions
+ */
+ _computeLeftDisabled(basePatchNum, patchNum, sortedRevisions) {
+ return this.findSortedIndex(basePatchNum, sortedRevisions) <=
+ this.findSortedIndex(patchNum, sortedRevisions);
+ },
+
+ /**
+ * The basePatchNum should always be <= patchNum -- because sortedRevisions
+ * is sorted in reverse order (higher patchset nums first), invalid patch
+ * nums have an index greater than the index of basePatchNum.
+ * In addition, if the current basePatchNum is 'PARENT', all patchNums are
+ * valid.
+ * @param {number|string} basePatchNum The current selected base patch num.
+ * @param {number|string} patchNum The possible patch num.
+ * @param {!Array} sortedRevisions
+ */
+ _computeRightDisabled(basePatchNum, patchNum, sortedRevisions) {
+ if (basePatchNum === 'PARENT') { return false; }
+ return this.findSortedIndex(basePatchNum, sortedRevisions) <=
+ this.findSortedIndex(patchNum, sortedRevisions);
+ },
+
+ // Copied from gr-file-list
+ // @todo(beckysiegel) clean up.
+ _getCommentsForPath(comments, patchNum, path) {
+ return (comments[path] || []).filter(c => {
+ return this.patchNumEquals(c.patch_set, patchNum);
+ });
+ },
+
+ // Copied from gr-file-list
+ // @todo(beckysiegel) clean up.
+ _computeUnresolvedNum(comments, drafts, patchNum, path) {
+ comments = this._getCommentsForPath(comments, patchNum, path);
+ drafts = this._getCommentsForPath(drafts, patchNum, path);
+ comments = comments.concat(drafts);
+
+ // Create an object where every comment ID is the key of an unresolved
+ // comment.
+
+ const idMap = comments.reduce((acc, comment) => {
+ if (comment.unresolved) {
+ acc[comment.id] = true;
+ }
+ return acc;
+ }, {});
+
+ // Set false for the comments that are marked as parents.
+ for (const comment of comments) {
+ idMap[comment.in_reply_to] = false;
+ }
+
+ // The unresolved comments are the comments that still have true.
+ const unresolvedLeaves = Object.keys(idMap).filter(key => {
+ return idMap[key];
+ });
+
+ return unresolvedLeaves.length;
+ },
+
+ _computePatchSetCommentsString(allComments, patchNum) {
+ // todo (beckysiegel) get comment strings for diff view also.
+ if (!allComments) { return ''; }
+ let numComments = 0;
+ let numUnresolved = 0;
+ for (const file in allComments) {
+ if (allComments.hasOwnProperty(file)) {
+ numComments += this._getCommentsForPath(
+ allComments, patchNum, file).length;
+ numUnresolved += this._computeUnresolvedNum(
+ allComments, {}, patchNum, file);
+ }
+ }
+ let commentsStr = '';
+ if (numComments > 0) {
+ commentsStr = ' (' + numComments + ' comments';
+ if (numUnresolved > 0) {
+ commentsStr += ', ' + numUnresolved + ' unresolved';
+ }
+ commentsStr += ')';
+ }
+ return commentsStr;
+ },
+
+ /**
+ * @param {!Array} revisions
+ * @param {number|string} patchNum
+ * @param {boolean=} opt_addFrontSpace
+ */
+ _computePatchSetDescription(revisions, patchNum, opt_addFrontSpace) {
+ const rev = this.getRevisionByPatchNum(revisions, patchNum);
+ return (rev && rev.description) ?
+ (opt_addFrontSpace ? ' ' : '') +
+ rev.description.substring(0, PATCH_DESC_MAX_LENGTH) : '';
+ },
+
+ /**
+ * Catches value-change events from the patchset dropdowns and determines
+ * whether or not a patch change event should be fired.
+ */
+ _handlePatchChange(e) {
+ const detail = {patchNum: this.patchNum, basePatchNum: this.basePatchNum};
+ const target = Polymer.dom(e).localTarget;
+
+ if (target === this.$.patchNumDropdown) {
+ detail.patchNum = e.detail.value;
+ } else {
+ detail.basePatchNum = e.detail.value;
+ }
+
+ this.dispatchEvent(
+ new CustomEvent('patch-range-change', {detail, bubbles: false}));
+ },
+ });
+})();
diff --git a/pool/shard004/JavaScript/0026942_index.js b/pool/shard004/JavaScript/0026942_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..6507107e52dd937b16d29d7fb95185472b992ba0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026942_index.js
@@ -0,0 +1,142 @@
+const path = require('path');
+const classifyImportLocation = 'ember-css-composer/classify';
+const classifyMacroImportLocation = 'ember-css-composer/classify-macro';
+
+function ClassifyPlugin(babel) {
+ const { types: t, traverse } = babel;
+
+ const ImportDeclarationFinder = {
+ ImportDefaultSpecifier(path, parent, scope, state) {
+ let importPath = parent.source.value;
+
+ if (importPath === classifyImportLocation) {
+ state.classifyIdentifier = path.local;
+ } else if(importPath === classifyMacroImportLocation) {
+ state.classifyMacroIdentifier = path.local;
+ }
+ }
+ };
+
+ const ClassNamesMacroFinder = {
+ Literal(path, parent, scope, state) {
+ let value = path.value;
+ let parentIdentifier = state.parentIdentifier;
+
+ if (!(typeof value === 'string') || value.charAt(0) !== '@') {
+ return;
+ }
+
+ // Mark that we need the classify macro
+ state.classifyImportNeeded = true;
+
+ // Replace the string with the function to classify.
+ this.replaceWith(classifyString(state.classifyIdentifier, value));
+ }
+ };
+
+ const ClassNameBindingsMacroFinder = {
+ Literal(path, parent, scope, state) {
+ let value = path.value;
+ let parentIdentifier = state.parentIdentifier;
+
+ // If no :@ symbol, skip.
+ if (!(typeof value === 'string') || value.indexOf('@') === -1) {
+ return;
+ }
+
+ // Mark that we need the various classify imports.
+ state.classifyMacroImportNeeded = true;
+ state.classifyImportNeeded = true;
+
+ // Get the various bits from the value.
+ let [objectKey, truthy = '', falsey = ''] = value.split(':');
+
+ let macroArgs = [];
+
+ // Add the first arg as a string declaration.
+ macroArgs.push(t.literal(objectKey));
+ macroArgs.push(classifyString(state.classifyIdentifier, truthy));
+ macroArgs.push(classifyString(state.classifyIdentifier, falsey));
+
+ // Create a new UID key for the object.
+ let macroKey = scope.generateUidIdentifierBasedOnNode(parentIdentifier.parent, objectKey || 'classifyMacro');
+
+ this.replaceWith(t.literal(macroKey.name));
+
+ // Create the new Object expression.
+ let prop = t.property('object', macroKey, t.callExpression(state.classifyMacroIdentifier, macroArgs));
+ state.parentIdentifierScope.insertAfter([prop]);
+ }
+ };
+
+ return new babel.Transformer('ember-css-composer-babel-transform', {
+ Property(path, parent, scope, state) {
+ let attr = path.key.name;
+
+ // Make the current property available to sub-traversal
+ state.parentIdentifier = path;
+ state.parentIdentifierScope = this;
+
+ if (attr === 'classNames') {
+ traverse(path, ClassNamesMacroFinder, scope, state);
+ } else if (attr === 'classNameBindings') {
+ traverse(path, ClassNameBindingsMacroFinder, scope, state);
+ }
+
+ // Remove parent Identifier from state
+ delete state.parentIdentifier;
+ },
+ Program: {
+ enter(path, parent, scope, state) {
+ traverse(path, ImportDeclarationFinder, scope, state);
+
+ if (!state.classifyIdentifier) {
+ state.doesNotHaveClassifyImport = true;
+ state.classifyIdentifier = scope.generateUidIdentifier('classify');
+ }
+
+ if (!state.classifyMacroIdentifier) {
+ state.doesNotHaveClassifyMacroImport = true;
+ state.classifyMacroIdentifier = scope.generateUidIdentifier('classifyMacro');
+ }
+ },
+ exit(path, parent, scope, state) {
+ if (state.classifyImportNeeded && state.doesNotHaveClassifyImport) {
+ makeImportStatement.call(this, path, state.classifyIdentifier, classifyImportLocation);
+ }
+
+ if (state.classifyMacroImportNeeded && state.doesNotHaveClassifyMacroImport) {
+ makeImportStatement.call(this, path, state.classifyMacroIdentifier, classifyMacroImportLocation);
+ }
+ }
+ }
+ });
+
+ function classifyString(classifyIdentifier, string) {
+ if (string.charAt(0) === '@') {
+ return t.callExpression(classifyIdentifier, [
+ t.literal(string.slice(1))
+ ]);
+ } else {
+ return t.literal(string);
+ }
+ }
+
+ function makeImportStatement(path, identifier, importPath) {
+ let specifier = t.importDefaultSpecifier(identifier);
+ let importsFrom = t.literal(importPath);
+ let declaration = t.importDeclaration([specifier], importsFrom);
+ this.unshiftContainer('body', declaration);
+ }
+};
+
+// Make sure broccoli-babel-transpiler can cache this.
+ClassifyPlugin.baseDir = function() {
+ return path.join(__dirname, '../../');
+};
+
+ClassifyPlugin.cacheKey = function() {
+ return '{}';
+};
+
+module.exports = ClassifyPlugin;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026943_MultiInputRenderer-dbg.js b/pool/shard004/JavaScript/0026943_MultiInputRenderer-dbg.js
new file mode 100644
index 0000000000000000000000000000000000000000..5aa0561223a0fcd16dbd77ccf92b2ae6e86d4376
--- /dev/null
+++ b/pool/shard004/JavaScript/0026943_MultiInputRenderer-dbg.js
@@ -0,0 +1,96 @@
+/*!
+ * UI development toolkit for HTML5 (OpenUI5)
+ * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
+ * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
+ */
+sap.ui.define(['jquery.sap.global', './InputRenderer', 'sap/ui/core/Renderer'],
+ function(jQuery, InputRenderer, Renderer) {
+ "use strict";
+
+
+ /**
+ * MultiInput renderer.
+ * @namespace
+ */
+ var MultiInputRenderer = Renderer.extend(InputRenderer);
+
+ MultiInputRenderer.getAriaDescribedBy = function(oControl) {
+
+ var sAriaDescribedBy = InputRenderer.getAriaDescribedBy.apply(this, arguments);
+
+ if (oControl.getTokens().length > 0) {
+ if (sAriaDescribedBy) {
+ sAriaDescribedBy = sAriaDescribedBy + " " + oControl._sAriaMultiInputContainTokenId;
+ } else {
+ sAriaDescribedBy = oControl._sAriaMultiInputContainTokenId;
+ }
+ }
+
+ return sAriaDescribedBy;
+
+ };
+
+
+ MultiInputRenderer.openInputTag = function(oRm, oControl) {
+
+ if (oControl.getEnableMultiLineMode() || oControl._bUseDialog){
+
+ oControl._isMultiLineMode = true;
+
+ // add multi-line css to the boarder if the multi-line mode is on
+ if ( !oControl._bUseDialog && oControl._bShowIndicator === false ) {
+ oRm.write("");
+ } else {
+ oControl._showIndicator();
+
+ //render the single line
+ oRm.write("");
+ }
+
+ } else {
+ oRm.write("");
+
+ }
+
+ MultiInputRenderer._renderTokens(oRm, oControl);
+ MultiInputRenderer._renderInput(oRm, oControl);
+ };
+
+ MultiInputRenderer._renderTokens = function(oRm, oControl) {
+ oRm.renderControl(oControl._tokenizer);
+ };
+
+ MultiInputRenderer._renderInput = function(oRm, oControl) {
+
+ if ( oControl._isMultiLineMode && oControl._bShowIndicator === false ) {
+ oRm.write("");
+ } else {
+ if ( oControl._isMultiLineMode && oControl._bShowIndicator === true) {
+ var iTokens = oControl.getTokens().length;
+ oRm.write("");
+ if (iTokens > 1) {
+ var oMessageBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
+ oRm.write( oMessageBundle.getText("MULTIINPUT_SHOW_MORE_TOKENS", iTokens - 1) );
+ }
+ oRm.write("");
+ }
+ oRm.write("");
+ }
+
+ InputRenderer.openInputTag.call(this, oRm, oControl);
+
+ };
+
+
+ MultiInputRenderer.closeInputTag = function(oRm, oControl) {
+ InputRenderer.closeInputTag.call(this, oRm, oControl);
+
+ oRm.write("");
+ oRm.write("");
+ oRm.write("");
+ };
+
+
+ return MultiInputRenderer;
+
+}, /* bExport= */ true);
diff --git a/pool/shard004/JavaScript/0026945_gulpfile.js b/pool/shard004/JavaScript/0026945_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..bb2b8cc04b26e22fa542d59aa1fb46ffa1cc163c
--- /dev/null
+++ b/pool/shard004/JavaScript/0026945_gulpfile.js
@@ -0,0 +1,17 @@
+'use strict';
+
+var gulp = require('gulp');
+var electron = require('electron-connect').server.create();
+
+gulp.task('serve', function () {
+ // Start browser process
+ electron.start();
+
+ // Restart browser process
+ gulp.watch('app/index.js', electron.restart);
+
+ // Reload renderer process
+ gulp.watch(['renderer/**/*.*'], electron.reload);
+
+ electron.on('quit', () => {process.exit(0)})
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026949_fa-animation.js b/pool/shard004/JavaScript/0026949_fa-animation.js
new file mode 100644
index 0000000000000000000000000000000000000000..b65144af032f4c8a1842476e2eb1d912282a8cb8
--- /dev/null
+++ b/pool/shard004/JavaScript/0026949_fa-animation.js
@@ -0,0 +1,318 @@
+/**
+ * @ngdoc directive
+ * @name faAnimation
+ * @module famous.angular
+ * @restrict EA
+ * @description
+ * This directive is used to animate an element in conjunction with an {@link api/directive/animate animate} directive
+ *
+ * @usage
+ * ```html
+ *
+ *
+ *
+ * ```
+ */
+
+angular.module('famous.angular')
+ .directive('faAnimation', ['$famous', '$famousDecorator', function ($famous, famousDecorator) {
+ return {
+ restrict: 'EA',
+ scope: true,
+ compile: function(tElement, tAttrs, transclude){
+ var Transform = $famous['famous/core/Transform'];
+ var Transitionable = $famous['famous/transitions/Transitionable'];
+ var Easing = $famous['famous/transitions/Easing'];
+ return {
+ pre: function(scope, element, attrs){
+ var isolate = famousDecorator.ensureIsolate(scope);
+ },
+ post: function(scope, element, attrs){
+ var isolate = famousDecorator.ensureIsolate(scope);
+
+ setTimeout(function(){
+ isolate.timeline = scope.$eval(attrs.timeline);
+ isolate._trans = new Transitionable(0);
+
+ isolate.play = function(callback){
+ var transition = {
+ duration: scope.$eval(attrs.duration),
+ curve: scope.$eval(attrs.curve) || 'linear'
+ };
+ isolate._trans.set(1, transition, function(){
+ if(callback)
+ callback();
+ if(attrs.loop){
+ //Famo.us silently breaks its transitionable if this runs in
+ //the same execution context. Maybe a suppressed SO error somewhere?
+ setTimeout(function(){isolate.replay(callback)}, 0);
+ }
+ });
+ //TODO: handle $animate with a callback
+ }
+ isolate.reset = function(){
+ isolate._trans.set(0);
+ }
+ isolate.replay = function(callback){
+ isolate.reset();
+ isolate.play(callback);
+ }
+
+ //disengage is a function that
+ //can unassign the event listener
+ var _disengage = undefined;
+ if(attrs.event){
+ if(_disengage)
+ _disengage();
+ _disengage = scope.$on(attrs.event, function(evt, data){
+ var callback = data && data.callback ? data.callback : undefined;
+ isolate.replay(callback)
+ })
+ }
+
+ var id = attrs.id;
+
+ if(isolate.timeline === undefined){
+ isolate.timeline = isolate._trans.get.bind(isolate._trans);
+ if(attrs.autoplay)
+ isolate.play();
+ }
+ if(!isolate.timeline instanceof Function)
+ throw 'timeline must be a reference to a function or duration must be provided';
+
+ /**
+ * @ngdoc directive
+ * @name animate
+ * @module famous.angular
+ * @restrict E
+ * @description
+ * This directive is used to specify the animation of an element in a {@link api/directive/faAnimation faAnimation} directive
+ *
+ * @usage
+ * ```html
+ *
+ *
+ *
+ * ```
+ */
+
+ var animates = element.find('animate');
+ var declarations = {};
+
+ for(var i = 0; i < animates.length; i++){
+ (function(){
+ var animate = animates[i];
+
+ //DOM selector string that points to our mod of interest
+ if(animate.attributes['targetmodselector']){
+ //dig out the reference to our modifier
+ //TODO: support passing a direct reference to a modifier
+ // instead of performing a DOM lookup
+ var modElements = element.parent().find(
+ animate.attributes['targetmodselector'].value
+ );
+
+
+ _.each(modElements, function(modElement){
+ var modScope = angular.element(modElement).scope();
+ var modifier = modScope.isolate[modScope.$id].modifier;
+ var getTransform = modScope.isolate[modScope.$id].getTransform;
+
+ //TODO: won't need to special-case curve type 'linear'
+ // once/if it exists in Easing.js
+ var curve =
+ animate.attributes['curve'] &&
+ animate.attributes['curve'].value !== 'linear'
+ ? Easing[animate.attributes['curve'].value]
+ : function(j) {return j;}; //linear
+
+ //assign the modifier functions
+ if(animate.attributes['field']){
+ var field = animate.attributes['field'].value;
+
+ var lowerBound =
+ animate.attributes['timelinelowerbound']
+ ? parseFloat(animate.attributes['timelinelowerbound'].value)
+ : 0;
+
+ var upperBound =
+ animate.attributes['timelineupperbound']
+ ? parseFloat(animate.attributes['timelineupperbound'].value)
+ : 1;
+
+ if(!animate.attributes['startvalue'])
+ throw 'you must provide a start value for the animation'
+ var startValue = scope.$eval(animate.attributes['startvalue'].value);
+
+ if(!animate.attributes['endvalue'])
+ throw 'you must provide an end value for the animation'
+ var endValue = scope.$eval(animate.attributes['endValue'].value);
+
+ //Keep arrays of all declarations so that transformFunctions
+ //can handle all of the appropriate segments
+
+ var modDecs =
+ declarations[modScope.$id] =
+ declarations[modScope.$id] || {};
+ var segments = modDecs[field] = modDecs[field] || [];
+ segments.push({
+ field: field,
+ lowerBound: lowerBound,
+ upperBound: upperBound,
+ startValue: startValue,
+ endValue: endValue,
+ curve: curve
+ });
+
+ //Keep modDecs[field] sorted
+ segments.sort(function(a, b){
+ return a.lowerBound - b.lowerBound;
+ });
+
+ //Check domain overlap:
+ //after sorting by lowerBounds, if any segment's lower bound
+ //is lower than the lower bound of any item before it, domains are
+ //overlapping
+ for(var j = 1; j < segments.length; j++){
+ var lower = segments[j].lowerBound;
+ for(var k = 0; k < j; k++){
+ if(lower < segments[k].upperBound){
+ throw "Animate segments have overlapping \
+ domains for the same field (" + field + "). \
+ At any point in the timeline, only one \
+ can affect a given field on the same modifier."
+ }
+ }
+ }
+
+
+ //Domain: timeline function bounded [0,1]
+ //Subdomains (between pipes): specified subdomains of timeline segments
+ //Range: output value, determined by interpolating startValue and
+ // endValue through the easing curves.
+ // | | | |
+ // | | | |
+ // | | | |
+ // | | | |
+ // | (ease) | | (ease) |
+ // | -/|-----------------------|-\ |
+ // | -/ | | -\ |
+ // | -/ | | -\ |
+ // | -/ | | -\ |
+ // ----|-/ | | -\|-------
+ // | | | |
+ //_____|__________|_______________________|__________|_______
+ // |x(0,0) |x(0,1) |x(1,0) |x(1,1)
+
+ //TODO: in order to support nested fa-animation directives,
+ // this function needs to be exposed somehow. (pass a reference into the directive;
+ // and then assign this function to that reference?)
+ //TODO: if needed: make this more efficient. This is a hot-running
+ // function and we should be able to optimize.
+ var transformFunction = function(){
+ var x = isolate.timeline() || 0;
+ var relevantIndex = 0;
+ var relevantSegment = segments[relevantIndex];
+
+ for(var j = 0; j < segments.length; j++){
+ //this is the relevant segment if x is in the subdomain
+ if(x >= segments[j].lowerBound && x <= segments[j].upperBound){
+ relevantSegment = segments[j];
+ break;
+ }
+ //this is the relevant segment if it is the last one
+ if(j === segments.length - 1){
+ relevantSegment = segments[j];
+ break;
+ }
+ //this is the relevant segment if x is greater than its upper
+ //bound but less than the next segment's lower bound
+ if(x >= segments[j].upperBound && x < segments[j + 1].lowerBound){
+ relevantSegment = segments[j];
+ break;
+ }
+ }
+
+ if(x <= relevantSegment.lowerBound)
+ return relevantSegment.startValue;
+ if(x >= relevantSegment.upperBound)
+ return relevantSegment.endValue;
+ //normalize our domain to [0, 1]
+ var subDomain = (relevantSegment.upperBound - relevantSegment.lowerBound)
+ var normalizedX = (x - relevantSegment.lowerBound) / subDomain;
+
+ //Support interpolating multiple values, e.g. for a Scale array [x,y,z]
+ if(Array.isArray(relevantSegment.startValue)){
+ var ret = [];
+ for(var j = 0; j < relevantSegment.startValue.length; j++){
+ ret.push(
+ relevantSegment.startValue[j] + relevantSegment.curve(normalizedX)
+ *
+ (relevantSegment.endValue[j] - relevantSegment.startValue[j])
+ );
+ }
+ return ret;
+ }else{
+ return relevantSegment.startValue
+ + relevantSegment.curve(normalizedX)
+ * (relevantSegment.endValue
+ - relevantSegment.startValue);
+ }
+ };
+
+ var transformComponents = modDecs.transformComponents = modDecs.transformComponents || [];
+
+ if(field === 'opacity'){
+ modifier.opacityFrom(function(){
+ return transformFunction();
+ });
+ }else if (field === 'origin'){
+ modifier.originFrom(function(){
+ return transformFunction();
+ });
+ }else if (field === 'size'){
+ modifier.sizeFrom(function(){
+ return transformFunction();
+ });
+ }else{ //transform field
+ transformComponents.push({
+ field: field,
+ fn: transformFunction
+ })
+
+ modifier.transformFrom(function(){
+
+ var mult = getTransform && getTransform() ? [getTransform()] : [];
+ for(var j = 0; j < transformComponents.length; j++){
+ ((function(){
+ var transVal = transformComponents[j].fn();
+ var f = transformComponents[j].field;
+ if(Array.isArray(transVal))
+ mult.push(Transform[f].apply(this, transVal));
+ else
+ mult.push(Transform[f](transVal));
+ })());
+ }
+
+ //Transform.multiply fails on arrays of <=1 matricies
+ if(mult.length === 1)
+ return mult[0]
+ else
+ return Transform.multiply.apply(this, mult);
+ });
+ }
+ }
+ });
+ }
+
+ })();
+
+ }
+ }, 1)//end setTimeout
+ }
+
+ }
+
+ }
+ };
+ }]);
diff --git a/pool/shard004/JavaScript/0026950_core.js b/pool/shard004/JavaScript/0026950_core.js
new file mode 100644
index 0000000000000000000000000000000000000000..d5ec973d57f5e0359777c84adb6022684e0c88b6
--- /dev/null
+++ b/pool/shard004/JavaScript/0026950_core.js
@@ -0,0 +1,235 @@
+/*
+* printThis v1.3
+* @desc Printing plug-in for jQuery
+* @author Jason Day
+*
+* Resources (based on) :
+* jPrintArea: http://plugins.jquery.com/project/jPrintArea
+* jqPrint: https://github.com/permanenttourist/jquery.jqprint
+* Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
+*
+* Dual licensed under the MIT and GPL licenses:
+* http://www.opensource.org/licenses/mit-license.php
+* http://www.gnu.org/licenses/gpl.html
+*
+* (c) Jason Day 2013
+*
+* Usage:
+*
+* $("#mySelector").printThis({
+* debug: false, * show the iframe for debugging
+* importCSS: true, * import page CSS
+* printContainer: true, * grab outer container as well as the contents of the selector
+* loadCSS: "path/to/my.css", * path to additional css file
+* pageTitle: "", * add title to print page
+* removeInline: false, * remove all inline styles from print elements
+* printDelay: 333, * variable print delay
+* header: null * prefix to html
+* });
+*
+* Notes:
+* - the loadCSS will load additional css (with or without @media print) into the iframe, adjusting layout
+*/
+;(function ($) {
+ var opt;
+ $.fn.printThis = function (options) {
+ opt = $.extend({}, $.fn.printThis.defaults, options);
+ var $element = this instanceof jQuery ? this : $(this);
+
+ var strFrameName = "printThis-" + (new Date()).getTime();
+
+ if(window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)){
+ // Ugly IE hacks due to IE not inheriting document.domain from parent
+ // checks if document.domain is set by comparing the host name against document.domain
+ var iframeSrc = "javascript:document.write(\"\")";
+ var printI= document.createElement('iframe');
+ printI.name = "printIframe";
+ printI.id = strFrameName;
+ printI.className = "MSIE";
+ document.body.appendChild(printI);
+ printI.src = iframeSrc;
+
+ } else {
+ // other browsers inherit document.domain, and IE works if document.domain is not explicitly set
+ var $frame = $("");
+ $frame.appendTo("body");
+ }
+
+
+ var $iframe = $("#" + strFrameName);
+
+ // show frame if in debug mode
+ if (!opt.debug) $iframe.css({
+ position: "absolute",
+ width: "0px",
+ height: "0px",
+ left: "-600px",
+ top: "-600px"
+ });
+
+
+ // $iframe.ready() and $iframe.load were inconsistent between browsers
+ setTimeout ( function () {
+
+ var $doc = $iframe.contents();
+
+ // import page stylesheets
+ if (opt.importCSS) $("link[rel=stylesheet]").each(function () {
+ var href = $(this).attr("href");
+ if (href) {
+ var media = $(this).attr("media") || "all";
+ $doc.find("head").append("")
+ }
+ });
+
+ //add title of the page
+ if (opt.pageTitle) $doc.find("head").append("" + opt.pageTitle + " ");
+
+ // import additional stylesheet
+ if (opt.loadCSS) $doc.find("head").append("");
+
+ // print header
+ if (opt.header) $doc.find("body").append(opt.header);
+
+ // grab $.selector as container
+ if (opt.printContainer) $doc.find("body").append($element.outer());
+
+ // otherwise just print interior elements of container
+ else $element.each(function () {
+ $doc.find("body").append($(this).html());
+ });
+
+ // remove inline styles
+ if (opt.removeInline) {
+ // $.removeAttr available jQuery 1.7+
+ if ($.isFunction($.removeAttr)) {
+ $doc.find("body *").removeAttr("style");
+ } else {
+ $doc.find("body *").attr("style", "");
+ }
+ }
+
+ setTimeout(function () {
+ if($iframe.hasClass("MSIE")){
+ // check if the iframe was created with the ugly hack
+ // and perform another ugly hack out of neccessity
+ window.frames["printIframe"].focus();
+ $doc.find("head").append("");
+ } else {
+ // proper method
+ $iframe[0].contentWindow.focus();
+ $iframe[0].contentWindow.print();
+ }
+
+ $element.trigger( "done");
+ //remove iframe after print
+ if (!opt.debug) {
+ setTimeout(function () {
+ $iframe.remove();
+ }, 1000);
+ }
+
+ }, opt.printDelay);
+
+ }, 333 );
+
+ };
+
+ // defaults
+ $.fn.printThis.defaults = {
+ debug: false, // show the iframe for debugging
+ importCSS: true, // import parent page css
+ printContainer: true, // print outer container/$.selector
+ loadCSS: "", // load an additional css file
+ pageTitle: "", // add title to print page
+ removeInline: false, // remove all inline styles
+ printDelay: 333, // variable print delay
+ header: null // prefix to html
+ };
+
+ // $.selector container
+ jQuery.fn.outer = function () {
+ return $($("").html(this.clone())).html()
+ }
+})(jQuery);
+
+
+/*jshint eqnull:true */
+/*!
+* jQuery Cookie Plugin v1.1
+* https://github.com/carhartl/jquery-cookie
+*
+ * Copyright 2011, Klaus Hartl
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.opensource.org/licenses/GPL-2.0
+ */
+(function($, document) {
+
+var pluses = /\+/g;
+function raw(s) {
+ return s;
+}
+function decoded(s) {
+ return decodeURIComponent(s.replace(pluses, ' '));
+}
+
+$.cookie = function(key, value, options) {
+
+ // key and at least value given, set cookie...
+ if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
+ options = $.extend({}, $.cookie.defaults, options);
+
+ if (value == null) {
+ options.expires = -1;
+ }
+
+ if (typeof options.expires === 'number') {
+ var days = options.expires, t = options.expires = new Date();
+ t.setDate(t.getDate() + days);
+ }
+
+ value = String(value);
+
+ return (document.cookie = [
+ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
+ options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
+ options.path ? '; path=' + options.path : '',
+ options.domain ? '; domain=' + options.domain : '',
+ options.secure ? '; secure' : ''
+ ].join(''));
+ }
+
+ // key and possibly options given, get cookie...
+ options = value || $.cookie.defaults || {};
+ var decode = options.raw ? raw : decoded;
+ var cookies = document.cookie.split('; ');
+ for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
+ if (decode(parts.shift()) === key) {
+ return decode(parts.join('='));
+ }
+ }
+ return null;
+};
+
+ $.cookie.defaults = {};
+
+ })(jQuery, document);
+
+
+jQuery(document).ready(function($) {
+ jQuery(".fontSizeSmall").click(function(){
+ jQuery(".post p").css("font-size","13px")
+ });
+
+ jQuery(".fontSizeMedium").click(function(){
+ jQuery(".post p").css("font-size","15px")
+ });
+
+ jQuery(".fontSizeLarge").click(function(){
+ jQuery(".post p").css("font-size","17px")
+ });
+
+
+});
+
diff --git a/pool/shard004/JavaScript/0026953_CandlestickSeries.js b/pool/shard004/JavaScript/0026953_CandlestickSeries.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e0f10cb988a39d64a31f1de5d6cea456109cc5c
--- /dev/null
+++ b/pool/shard004/JavaScript/0026953_CandlestickSeries.js
@@ -0,0 +1,156 @@
+/* ****************************************************************************
+ * Start Candlestick series code *
+ *****************************************************************************/
+
+// 1 - set default options
+defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, {
+ lineColor: 'black',
+ lineWidth: 1,
+ states: {
+ hover: {
+ lineWidth: 2
+ }
+ },
+ tooltip: defaultPlotOptions.ohlc.tooltip,
+ threshold: null,
+ upColor: 'white'
+ // upLineColor: null
+});
+
+// 2 - Create the CandlestickSeries object
+var CandlestickSeries = extendClass(OHLCSeries, {
+ type: 'candlestick',
+
+ /**
+ * One-to-one mapping from options to SVG attributes
+ */
+ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
+ fill: 'color',
+ stroke: 'lineColor',
+ 'stroke-width': 'lineWidth'
+ },
+ upColorProp: 'fill',
+
+ /**
+ * Postprocess mapping between options and SVG attributes
+ */
+ getAttribs: function () {
+ seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments);
+ var series = this,
+ options = series.options,
+ stateOptions = options.states,
+ upLineColor = options.upLineColor || options.lineColor,
+ hoverStroke = stateOptions.hover.upLineColor || upLineColor,
+ selectStroke = stateOptions.select.upLineColor || upLineColor;
+
+ // Add custom line color for points going up (close > open).
+ // Fill is handled by OHLCSeries' getAttribs.
+ each(series.points, function (point) {
+ if (point.open < point.close) {
+
+ // If an individual line color is set, we need to merge the
+ // point attributes, because they are shared between all up
+ // points by inheritance from OHCLSeries.
+ if (point.lineColor) {
+ point.pointAttr = merge(point.pointAttr);
+ upLineColor = point.lineColor;
+ }
+
+ point.pointAttr[''].stroke = upLineColor;
+ point.pointAttr.hover.stroke = hoverStroke;
+ point.pointAttr.select.stroke = selectStroke;
+ }
+ });
+ },
+
+ /**
+ * Draw the data points
+ */
+ drawPoints: function () {
+ var series = this, //state = series.state,
+ points = series.points,
+ chart = series.chart,
+ pointAttr,
+ seriesPointAttr = series.pointAttr[''],
+ plotOpen,
+ plotClose,
+ topBox,
+ bottomBox,
+ hasTopWhisker,
+ hasBottomWhisker,
+ crispCorr,
+ crispX,
+ graphic,
+ path,
+ halfWidth;
+
+
+ each(points, function (point) {
+
+ graphic = point.graphic;
+ if (point.plotY !== UNDEFINED) {
+
+ pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || seriesPointAttr;
+
+ // crisp vector coordinates
+ crispCorr = (pointAttr['stroke-width'] % 2) / 2;
+ crispX = mathRound(point.plotX) - crispCorr; // #2596
+ plotOpen = point.plotOpen;
+ plotClose = point.plotClose;
+ topBox = math.min(plotOpen, plotClose);
+ bottomBox = math.max(plotOpen, plotClose);
+ halfWidth = mathRound(point.shapeArgs.width / 2);
+ hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY);
+ hasBottomWhisker = bottomBox !== point.yBottom;
+ topBox = mathRound(topBox) + crispCorr;
+ bottomBox = mathRound(bottomBox) + crispCorr;
+
+ // Create the path. Due to a bug in Chrome 49, the path is first instanciated
+ // with no values, then the values pushed. For unknown reasons, instanciated
+ // the path array with all the values would lead to a crash when updating
+ // frequently (#5193).
+ path = [];
+ path.push(
+ 'M',
+ crispX - halfWidth, bottomBox,
+ 'L',
+ crispX - halfWidth, topBox,
+ 'L',
+ crispX + halfWidth, topBox,
+ 'L',
+ crispX + halfWidth, bottomBox,
+ 'Z', // Use a close statement to ensure a nice rectangle #2602
+ 'M',
+ crispX, topBox,
+ 'L',
+ crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094
+ 'M',
+ crispX, bottomBox,
+ 'L',
+ crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox // #460, #2094
+ );
+
+ if (graphic) {
+ graphic
+ .attr(pointAttr) // #3897
+ .animate({ d: path });
+ } else {
+ point.graphic = chart.renderer.path(path)
+ .attr(pointAttr)
+ .add(series.group)
+ .shadow(series.options.shadow);
+ }
+
+ }
+ });
+
+ }
+
+
+});
+
+seriesTypes.candlestick = CandlestickSeries;
+
+/* ****************************************************************************
+ * End Candlestick series code *
+ *****************************************************************************/
diff --git a/pool/shard004/JavaScript/0026954_vp-api-key.directive.js b/pool/shard004/JavaScript/0026954_vp-api-key.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..c39128579a5775d4d872c1635e1d491b8cb98c86
--- /dev/null
+++ b/pool/shard004/JavaScript/0026954_vp-api-key.directive.js
@@ -0,0 +1,20 @@
+(function () {
+ angular
+ .module("viewpoint.directives")
+ .directive("vpApiKey", vpApiKey);
+
+ vpApiKey.$inject = ["userService"];
+
+ function vpApiKey (userService) {
+ var directive = {
+ "restrict": "A",
+ "link": linkFunction
+ }
+
+ return directive;
+
+ function linkFunction (scope, element, attributes) {
+ element[0].value = userService.getApiKey();
+ }
+ }
+})();
diff --git a/pool/shard004/JavaScript/0026958_index.js b/pool/shard004/JavaScript/0026958_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..6f380a934248834165d74c75852ebd26c6f88edc
--- /dev/null
+++ b/pool/shard004/JavaScript/0026958_index.js
@@ -0,0 +1,72 @@
+'use strict';
+/**
+ * System
+ */
+var path = require('path');
+
+/**
+ * Framework
+ */
+var documentation = require('gulp-documentation'),
+ debug = require('debug')('gastropod/addons/tasks/docjs'),
+ plumber = require('gulp-plumber'),
+ named = require('vinyl-named'),
+ accept = require('check-args');
+
+/**
+ * Project
+ * @params filename string output filename
+ * @params format string 'html', 'md', 'json' or 'docset'
+ */
+var DEFAULT_OPTIONS = {
+ format: 'md'
+};
+var buildPath = accept(String, String)
+ .to(function(root, part){
+ return path.join(root, part);
+ });
+/**
+ * Exportable
+ */
+module.exports = function (gulp, gastro){
+ /**
+ * Constants
+ */
+
+ var Config = gastro.Config,
+
+ target = buildPath(Config.target.root,
+ Config.target.docs),
+
+ sources = [],
+
+ DocumentationConfig = (Config.plugins.documentation && Config.plugins.documentation.docjs) || DEFAULT_OPTIONS;
+
+ var pattern;
+ for(var index=0; index < Config.source.documentation.length; index++) {
+ pattern = Config.source.documentation[index];
+ sources.push(buildPath(Config.source.root, pattern));
+ }
+
+ debug('config:', DocumentationConfig);
+
+ gulp.task('docjs', function(done){
+
+ debug('Starting');
+ debug(' > source', sources);
+ debug(' > target', target);
+
+ return gulp.src(sources)
+ .on('error', function(err){
+ this.emit('end');
+ })
+ .on('end', function(){
+ debug('Finished: documentation');
+ })
+ .pipe(documentation(DocumentationConfig))
+ .pipe(gulp.dest(target));
+
+ });
+
+ debug('task registered');
+}
diff --git a/pool/shard004/JavaScript/0026960_hash.js b/pool/shard004/JavaScript/0026960_hash.js
new file mode 100644
index 0000000000000000000000000000000000000000..fc07b36460ed859d4eed69e0d5251de6e1a5d934
--- /dev/null
+++ b/pool/shard004/JavaScript/0026960_hash.js
@@ -0,0 +1,82 @@
+var hashMe = function (file, callbackFunction) {
+
+ var thisObj = this,
+ _binStart = "",
+ _binEnd = "",
+ callback = "",
+ fileManager1 = new FileReader,
+ fileManager2 = new FileReader;
+
+ this.setBinAndHash = function (startOrEnd, binData) {
+
+ switch (startOrEnd) {
+ case 0:
+ this._binStart = binData;
+ break;
+ case 1:
+ this._binEnd = binData;
+ }
+
+ if (this._binStart && this._binEnd) {
+ this.md5sum(startOrEnd, this._binStart, this._binEnd);
+ }
+ };
+
+ this.md5sum = function (startOrEnd, start, end) {
+ this._hash = rstr2hex(rstr_md5(start + end));
+ if (startOrEnd) {
+ callback(this._hash);
+ }
+ };
+
+ this.getHash = function() {
+ return this._hash;
+ };
+
+ this.calculateHashOfFile = function (file) {
+
+// var start = file.slice(0, 65536);
+// var end = file.slice(file.size - 65536, file.size);
+ blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
+ var start = blobSlice.call(file, 0, 65536);
+ var end = blobSlice.call(file, file.size - 65536, file.size);
+
+ //extend FileReader
+ if (!FileReader.prototype.readAsBinaryString) {
+ FileReader.prototype.readAsBinaryString = function (fileData) {
+ var binary = "";
+ var pt = this;
+ var reader = new FileReader();
+ reader.onload = function (e) {
+ var bytes = new Uint8Array(reader.result);
+ var length = bytes.byteLength;
+ for (var i = 0; i < length; i++) {
+ binary += String.fromCharCode(bytes[i]);
+ }
+ pt.content = binary;
+ $(pt).trigger('onload');
+ }
+ reader.readAsArrayBuffer(fileData);
+ }
+ }
+ //
+ fileManager1.onload = function (f) {
+ if (fileManager1.result) fileManager1.content = fileManager1.result;
+ var base64Data = btoa(fileManager1.content);
+ thisObj.setBinAndHash(0, base64Data);
+ };
+
+ fileManager2.onload = function (f) {
+ if (fileManager2.result) fileManager2.content = fileManager2.result;
+ var base64Data = btoa(fileManager2.content);
+ thisObj.setBinAndHash(1, base64Data);
+ };
+
+ fileManager1.readAsBinaryString(start);
+ fileManager2.readAsBinaryString(end);
+ };
+
+ this.calculateHashOfFile(file);
+ callback = callbackFunction;
+
+};
diff --git a/pool/shard004/JavaScript/0026962_coEditor.js b/pool/shard004/JavaScript/0026962_coEditor.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b9f81e6584fb7af6d6cbb6369228d3c958256d5
--- /dev/null
+++ b/pool/shard004/JavaScript/0026962_coEditor.js
@@ -0,0 +1,56 @@
+(function (app){
+ app
+ .directive('coEditor', ['$http', '$parse', '$timeout', function ($http, $parse, $timeout) {
+ return {
+ restrict: 'A',
+ link: function (scope, element, attribs){
+
+ var id = element.id;
+ if (!id){
+ id = (new Date()).getTime() + '';
+ }
+ element.attr('id', id);
+ var editor = CKEDITOR.replace(id, {
+ filebrowserBrowseUrl: '/dashboard/browse-media',
+ filebrowserUploadUrl: '/api/v1/media/editor'
+ });
+
+ var modelAccessor = $parse(attribs['ngModel']);
+ editor.on( 'change', function( evt ) {
+ if (!CKEDITOR.instances[id]){
+ return modelAccessor.assign($scope, null);
+ }
+ modelAccessor.assign(scope, CKEDITOR.instances[id].getData());
+ });
+
+ var timeout = null;
+ editor.on( 'key', function( evt ) {
+ if (timeout){
+ $timeout.cancel(timeout);
+ }
+ timeout = $timeout(function (){
+ if (!CKEDITOR.instances[id]){
+ return modelAccessor.assign($scope, null);
+ }
+ modelAccessor.assign(scope, CKEDITOR.instances[id].getData());
+ }, 500);
+ });
+
+ scope.$watch(modelAccessor, function (val) {
+ if (!CKEDITOR.instances[id]){
+ return;
+ }
+ if (CKEDITOR.instances[id].getData() == val){
+ return;
+ }
+ CKEDITOR.instances[id].setData(val);
+ element.val(val);
+ });
+
+ scope.$on('$destroyed', function (v){
+ });
+
+ }
+ };
+ }]);
+}(app));
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026964_DebugUtil.js.uncompressed.js b/pool/shard004/JavaScript/0026964_DebugUtil.js.uncompressed.js
new file mode 100644
index 0000000000000000000000000000000000000000..acbd1269af9e5edbc89a92d86711319c8582f13d
--- /dev/null
+++ b/pool/shard004/JavaScript/0026964_DebugUtil.js.uncompressed.js
@@ -0,0 +1,64 @@
+// wrapped by build app
+define("gridx/tests/support/DebugUtil", ["dijit","dojo","dojox"], function(dijit,dojo,dojox){
+
+dojo.setObject('DebugUtil',{
+ timer:{
+ _cache:{}
+ ,_data: []
+ ,start:function(id){
+ if(!id)this.defaultTimer = (new Date()).getTime();
+ else this._cache[id] = (new Date()).getTime();
+ }
+ ,end:function(id, msg, noConsole, callback){
+ if(id && !this._cache[id]){
+ msg = id;
+ id = null;
+ }
+ var t = this.getTime(id);
+ var startTime = id ? this._cache[id] : this.defaultTimer;
+ if(!noConsole)console.debug((msg||'') + ': ' + t + 'ms');
+ if(callback)callback(t);
+ return t;
+ }
+ ,getTime:function(id){
+ return (new Date()).getTime() - (id ? this._cache[id] : this.defaultTimer);
+ }
+ ,trackFunction: function(obj, funcName, msg){
+ console.debug(obj, funcName);
+ obj = obj || window;
+
+ var data = dojo.filter(this._data, function(d){
+ return d.obj == obj && d.funcName == funcName;
+ })[0];
+ if(!data){
+ data = {obj: obj, funcName: funcName, count: 0, time: 0};
+ this._data.push(data);
+ }
+ var func = obj[funcName];
+ var self = this;
+ obj[funcName] = function(){
+ var _id = (new Date()).getTime()+'';
+ self.start(_id);
+ var re = func.apply(obj, arguments);
+ var arr = [];
+ for(var i=0; i {
+ // set the derived MasterPassKey globally
+ global.MasterPassKey = new MasterPassKey(mpkey)
+ return
+ })
+ .then(() => {
+ // save the credentials used to derive the MasterPassKey
+ return global.mdb.saveGlobalObj('creds')
+ })
+ .then(() => {
+ // Inform user that the MasterPass has successfully been set
+ webContents.send('setMasterPassResult', null)
+ })
+ .catch((err) => {
+ // Inform user of the error that occured while setting the MasterPass
+ logger.error(err)
+ webContents.send('setMasterPassResult', err.message)
+ error = err
+ })
+ })
+
+ ipcMain.on('done', function (event, masterpass) {
+ // Dond event emotted from render process
+ logger.info('IPCMAIN: done emitted setup complete. Closing...')
+ // Setup successfully finished
+ // therefore set error to nothing
+ error = null
+ // Relaunch Crypter
+ app.emit('app:relaunch')
+ })
+
+ win.on('closed', function () {
+ logger.verbose('IPCMAIN: win.closed event emitted for setupWindow.')
+ // close window by setting it to nothing (null)
+ win = null
+ // if error occured then send error back to callee else send null
+ callback((error) ? error : null)
+ })
+}
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026966_oauth.strava.js b/pool/shard004/JavaScript/0026966_oauth.strava.js
new file mode 100644
index 0000000000000000000000000000000000000000..fd6a8e4e019ad19a201478d67ca58461159be836
--- /dev/null
+++ b/pool/shard004/JavaScript/0026966_oauth.strava.js
@@ -0,0 +1,59 @@
+angular.module('oauth.strava', ['oauth.utils'])
+ .factory('$strava', strava);
+
+function strava($q, $http, $cordovaOauthUtility) {
+ return { signin: oauthStrava };
+
+ /*
+ * Sign into the Strava service
+ *
+ * @param string clientId
+ * @param string clientSecret
+ * @param array appScope
+ * @param object options
+ * @return promise
+ */
+ function oauthStrava(clientId, clientSecret, appScope, options) {
+ var deferred = $q.defer();
+ if(window.cordova) {
+ if($cordovaOauthUtility.isInAppBrowserInstalled()) {
+ var redirect_uri = "http://localhost/callback";
+ if(options !== undefined) {
+ if(options.hasOwnProperty("redirect_uri")) {
+ redirect_uri = options.redirect_uri;
+ }
+ }
+ var browserRef = window.cordova.InAppBrowser.open('https://www.strava.com/oauth/authorize?client_id=' + clientId + '&redirect_uri=' + redirect_uri + '&scope=' + appScope.join(",") + '&response_type=code&approval_prompt=force', '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');
+ browserRef.addEventListener('loadstart', function(event) {
+ if((event.url).indexOf(redirect_uri) === 0) {
+ requestToken = (event.url).split("code=")[1];
+ $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
+ $http({method: "post", url: "https://www.strava.com/oauth/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken })
+ .success(function(data) {
+ deferred.resolve(data);
+ })
+ .error(function(data, status) {
+ deferred.reject("Problem authenticating");
+ })
+ .finally(function() {
+ setTimeout(function() {
+ browserRef.close();
+ }, 10);
+ });
+ }
+ });
+ browserRef.addEventListener('exit', function(event) {
+ deferred.reject("The sign in flow was canceled");
+ });
+ } else {
+ deferred.reject("Could not find InAppBrowser plugin");
+ }
+ } else {
+ deferred.reject("Cannot authenticate via a web browser");
+ }
+
+ return deferred.promise;
+ }
+}
+
+strava.$inject = ['$q', '$http', '$cordovaOauthUtility'];
diff --git a/pool/shard004/JavaScript/0026969_ResourceLoader.js b/pool/shard004/JavaScript/0026969_ResourceLoader.js
new file mode 100644
index 0000000000000000000000000000000000000000..bdb66563f209da3b1b914ca38029a9d43ae8fcec
--- /dev/null
+++ b/pool/shard004/JavaScript/0026969_ResourceLoader.js
@@ -0,0 +1,43 @@
+/* jshint newcap:false */
+/* global Class, Kanji, console, LI, $, Image */
+
+/**
+ * ResourceLoader loads stylesheets, scripts, and images declared in data-cfg.
+ *
+ * @author Tan Nhu, http://lnkd.in/tnhu
+ * @licence MIT
+ * @dependency jsface, Kanji, jQuery
+ */
+Class(Kanji, {
+ id : 'ResourceLoader',
+ type: 'shared', /* one shared instance */
+ lazy: false,
+
+ init: function(element, config) {
+ var type, i, len, items, url,
+ head = $('head');
+
+ // TODO cache urls to make sure there's no duplication
+ for (type in config) {
+ items = config[type];
+
+ for (i = 0, len = items.length; i < len; i++) {
+ url = items[i];
+
+ switch (type) {
+ case 'js':
+ $.getScript(url);
+ break;
+
+ case 'css':
+ head.append("");
+ break;
+
+ case 'img':
+ new Image().src = url;
+ break;
+ }
+ }
+ }
+ }
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026971_config.js b/pool/shard004/JavaScript/0026971_config.js
new file mode 100644
index 0000000000000000000000000000000000000000..ba5a77a54ebcfaa4787b6494095735de5fdc1eb5
--- /dev/null
+++ b/pool/shard004/JavaScript/0026971_config.js
@@ -0,0 +1,142 @@
+var inquirer = require('inquirer')
+ , helper = require('../helpers/promise')
+ , i18n = require('i18n')
+ , Promise = require('bluebird')
+ , logger = require('ezseed-logger')('config')
+ , p = require('path')
+ , HOME = require('../../constants').HOME
+
+module.exports = function() {
+ //Array that contains all the commands that'd be executed as root
+ //this one is the main configuration directory
+ //using mkdir -p to add logs directory
+ var runasroot = [
+ '[ -d "/usr/local/opt/ezseed/logs" ] || mkdir -p /usr/local/opt/ezseed/logs',
+ 'chmod -R 777 /usr/local/opt/ezseed'
+ ]
+
+ return new Promise(function(resolve, reject) {
+
+ require('local-port').findOpen(3000, 9000, function(err, open_port) {
+ if(err) {
+ logger.error('We could not find any open port')
+ open_port = 8970
+ }
+
+ inquirer.prompt([
+ {
+ type : "input",
+ name : "home",
+ message : i18n.__("Ezseed home directory"),
+ default : '/home',
+ validate : function(directory) {
+ runasroot.push('[ -d "'+directory+'" ] || mkdir -p '+directory)
+
+ return true
+ }
+ },
+ {
+ type : 'input',
+ name : 'tmp',
+ message : i18n.__('Temporary directory'),
+ default : '/usr/local/opt/ezseed/tmp',
+ validate : function(directory) {
+ runasroot.push('[ -d "'+directory+'" ] || mkdir -p '+directory, 'chmod -R 777 /usr/local/opt/ezseed/tmp')
+
+ return true
+ }
+ },
+ //to add this feature we would need to update shells to add the values
+ // in vhosts
+
+ // {
+ // type: 'input',
+ // name: 'tmp',
+ // message: i18n.__('Installation folder'),
+ // default: '/usr/local/opt/ezseed',
+ // validate : function(directory) {
+ // if(!fs.existsSync(directory)) {
+ // mkdirp.sync(directory)
+ // }
+ //
+ // return true
+ // }
+ // },
+ {
+ type : 'input',
+ name : 'port',
+ message : i18n.__('Listening on'),
+ default : open_port,
+ validate : function(port) {
+ return !isNaN(parseInt(port)) && parseInt(port) > 1024
+ }
+ },
+ {
+ type : 'input',
+ name : 'basepath',
+ message : i18n.__('Base path'),
+ default : '/',
+ validate : function(basepath) {
+ return basepath.charAt(0) == '/'
+ },
+ filter: function (basepath) {
+ basepath += basepath.charAt(basepath.length - 1) == '/' ? '' : '/'
+
+ return basepath
+ }
+ },
+ {
+
+ type : 'input',
+ name : 'sslkeys',
+ message : i18n.__("Want to add ssl keys? (ie: './ssl.pem ./ssl.key')"),
+ default : ' ',
+ validate : function(ssl) {
+
+ if(ssl === ' ') {
+ // return require('../helpers/ssl').create(done)
+ runasroot.push("openssl req -new -x509 -days 365 -nodes -out /usr/local/opt/ezseed/ezseed.pem -keyout /usr/local/opt/ezseed/ezseed.key -subj '/CN=ezseed/O=EzSeed/C=FR' 2>/dev/null")
+ return true
+ }
+
+ ssl = ssl.split(' ')
+
+ function ok(val) { return val.indexOf('.pem') !== -1 || val.indexOf('.key') !== -1}
+
+ if(ok(ssl[0]) && ok(ssl[1])) {
+ for(var i in ssl) {
+ var k = {path: ssl[i], ext: p.extname(ssl[i])}
+
+ runasroot.push("mv " + k.path + " " + "/usr/local/opt/ezseed/" + k.ext)
+ }
+
+ return true
+ } else {
+ return false
+ }
+
+ }
+ }], function (answers) {
+ answers.lang = i18n.getLocale()
+
+ require('../helpers/which_stream.js')(function(converter) {
+
+ if(converter === false) {
+ logger.warn(i18n.__('avconv is not installed'))
+ } else {
+ logger.info(i18n.__('using %s to encode'), converter)
+ }
+
+ answers.converter = converter
+
+ helper.runasroot(runasroot)
+ .then(function() {
+ resolve(answers)
+ })
+ .catch(helper.exit('Configuration'))
+ })
+ })
+
+ })
+ })
+}
diff --git a/pool/shard004/JavaScript/0026972_answer-encoder-service.js b/pool/shard004/JavaScript/0026972_answer-encoder-service.js
new file mode 100644
index 0000000000000000000000000000000000000000..f83bb7d2354992f389f222d7da378e954f336ca0
--- /dev/null
+++ b/pool/shard004/JavaScript/0026972_answer-encoder-service.js
@@ -0,0 +1,236 @@
+/*
+ * Encodes/Decodes the answer to a question given the question type.
+ *
+ * The encoder function always receives answer as a list of answer ids.
+ *
+ * Usage:
+ * var answer = [1, 5];
+ * var codec = AnswerEncoderService("MEEK-STV", 7);
+ * asser(codec.sanityCheck()).toBe(true);
+ * var encoded = codec.encode([1, 5], );
+ * var decoded = codec.decode(encoded);
+ * assert(DeterministicJsonStringifyService(decoded) ==
+ * DeterministicJsonStringifyService(answer)).toBe(true);
+ */
+
+angular.module('avCrypto')
+ .service('AnswerEncoderService', function(DeterministicJsonStringifyService) {
+ var stringify = DeterministicJsonStringifyService;
+
+
+ /**
+ * Converts a number to a string. For example if number=23 and numCharts=3,
+ * result="023"
+ */
+ function numberToString(number, numChars) {
+ var numStr = number.toString(10);
+ var ret = numStr;
+ for (var i = 0; i < numChars - numStr.length; i++) {
+ ret = "0" + ret;
+ }
+ return ret;
+ }
+
+ return function (requestedCodec, numAvailableOptions) {
+ var multi = {
+ validCodecs: ["plurality-at-large", "borda-nauru", "borda"],
+ numAvailableOptions: numAvailableOptions,
+
+ /**
+ * Converts a vote into a number. A vote in this case is a list of
+ * answer ids (which must always be positive integers),
+ * for example [0, 2].
+ *
+ * Note that answer ids cannot be zero because it would cause encoding
+ * problems. Next step is converting those number to strings of fixed
+ * size:
+ *
+ * [0, 2] -> ['01', '03']
+ *
+ * We need to be sure that each option will always be encoded using the
+ * the same number of characters so that decoding the options is
+ * possible in a deterministic way. So if we have 24 options, we know
+ * that we can codify any of those options with 2 characters, but if we
+ * have 110 options we need three chars per option.
+ *
+ * Next step is to concatenate the ordered list of option strings:
+ *
+ * [0, 2] -> ['01', '03'] -> '0103' -> 103
+ *
+ * NOTE: the zeros at the left of the final number are removed, because
+ * a number representation never has any zeros at the left. When
+ * doing decoding of the result you should take this into account.
+ */
+ encode: function(answer) {
+ var numChars = (numAvailableOptions + 2).toString(10).length;
+ var encodedAnswer = _.reduceRight(answer, function (memo, answerId) {
+ return numberToString(answerId + 1, numChars) + memo;
+ }, "");
+
+ // blank vote --> make it not count numAvailableOptions + 2;
+ if (encodedAnswer.length === 0) {
+ encodedAnswer = numberToString(numAvailableOptions + 2, numChars);
+ }
+ return encodedAnswer;
+ },
+
+ /**
+ * Returns extracted answers from a question.
+ *
+ * The question objects needs to have an "answers" key, and each
+ * selected asnwer will be marked by a "selected" attribute. We will
+ * order by this attribute, and return an ordered array with all the
+ * answers' ids. An answer id is set by its "id" attribute.
+ */
+ extractAnswers: function(question) {
+ // first, convert the question answers into a list of selected options
+ // get only selected
+ var filtered = _.filter(question.answers, function (option) {
+ return option.selected > -1;
+ });
+
+ // sort by selected
+ var sorted = _.sortBy(filtered, function (option) {
+ return option.selected;
+ });
+
+ // get the selected sorted options as a list of int ids
+ var answers = _.pluck(sorted, "id");
+
+ var forceAllowBlankVote = (angular.isDefined(question.extra_options) &&
+ question.extra_options.force_allow_blank_vote === "TRUE");
+
+ if (answers.length > question.max ||
+ (answers.length < question.min &&
+ (!forceAllowBlankVote || answers.length > 0))
+ ) {
+ throw "error in the number of selected answers";
+ }
+
+ return answers;
+ },
+
+ /**
+ * Does exactly the reverse of of encodeQuestionAnswer. It should be
+ * such as the following statement is always true:
+ *
+ * data == codec.decode(codec.encode(answer))
+ *
+ * This function is very useful for sanity checks.
+ */
+ decode: function(encodedAnswer) {
+ var encodedStr = encodedAnswer;
+ var length = encodedStr.length;
+ var tabNumChars = (numAvailableOptions + 2).toString(10).length;
+ var missingZeros = (tabNumChars - (length % tabNumChars)) % tabNumChars;
+ var i;
+ var decodedAnswer = [];
+
+ // check if it's a blank vote
+ if (parseInt(encodedStr, 10) === numAvailableOptions + 2) {
+ return [];
+ }
+
+ // add zeros to the left for tabulation
+ for (i = 0; i < missingZeros; i++) {
+ encodedStr = "0" + encodedStr;
+ }
+
+ // decode each option
+ for (i = 0; i < (encodedStr.length / tabNumChars); i++) {
+ var optionStr = encodedStr.substr(i*tabNumChars, tabNumChars);
+ var optionId = parseInt(optionStr, 10);
+ decodedAnswer.push(optionId - 1);
+ }
+ return decodedAnswer;
+ },
+
+ // question is optional
+ sanityCheck: function(question) {
+ try {
+ var possibleAnswers = _.times(numAvailableOptions, function(n) {
+ return n + 1; });
+
+ if (question !== undefined) {
+ possibleAnswers = _.pluck(question.answers, "id");
+ }
+
+ // TODO do a test with specific input and output values
+
+ // test 10 random ballots. Note, we won't honor the limits of number
+ // of options for this question for simplicity, we'll just do some
+ // tests to assure everything is fine.
+ for (var i = 0; i < 10; i++) {
+ // generate answer
+ var answer = [];
+ var randomNumOptions = Math.ceil(Math.random() * 10000) % possibleAnswers.length;
+ for (var j = 0; j < randomNumOptions; j++) {
+ var rnd = Math.ceil(Math.random() * 10000) % possibleAnswers.length;
+ var opt = possibleAnswers[rnd];
+ // do not duplicate options
+ if (_.indexOf(answer, opt) === -1) {
+ answer.push(opt);
+ }
+ }
+ // check encode -> decode pipe doesn't modify the ballot
+ var encodedAnswer = multi.encode(answer);
+ var decodedAnswer = stringify(multi.decode(encodedAnswer));
+ if (stringify(answer) !== decodedAnswer) {
+ return false;
+ }
+ }
+
+ // test blank vote
+ var encoded = multi.encode([]);
+ var decoded = stringify(multi.decode(encoded));
+ if (stringify([]) !== decoded) {
+ return false;
+ }
+ // if any any exception is thrown --> sanity check didnt pass
+ } catch (e) {
+ return false;
+ }
+
+ // if everything whent right
+ return true;
+ }
+ };
+
+
+ var pairwise = _.extend(_.clone(multi), {
+ validCodecs: ["pairwise-beta"],
+
+ /**
+ * Returns extracted answers from a question.
+ *
+ * The question objects needs to have an "answers" key, and each
+ * selected asnwer will be marked by a "selected" attribute. We will
+ * order by this attribute, and return an ordered array with all the
+ * answers' ids. An answer id is set by its "id" attribute.
+ */
+ extractAnswers: function(question) {
+ // get the selected sorted options as a list of int ids
+ var answers = _.pluck(_.flatten(question.selection), "id");
+
+ if (answers.length > question.max*2 || answers.length < question.min*2) {
+ throw "error in the number of selected answers";
+ }
+
+ return answers;
+ }
+ });
+
+
+ var codecs = [multi, pairwise];
+
+ var foundCodec = _.find(codecs, function (codec) {
+ return _.contains(codec.validCodecs, requestedCodec);
+ });
+
+ if (!foundCodec) {
+ throw "unknown answer encoding service requested: " + requestedCodec;
+ }
+
+ return foundCodec;
+ };
+ });
diff --git a/pool/shard004/JavaScript/0026976_templateSettings.js b/pool/shard004/JavaScript/0026976_templateSettings.js
new file mode 100644
index 0000000000000000000000000000000000000000..0afcb768607dbe78a8f86df047ee5d3321bd6286
--- /dev/null
+++ b/pool/shard004/JavaScript/0026976_templateSettings.js
@@ -0,0 +1,69 @@
+(function(){var escape = require('./escape'),
+ reEscape = require('../internal/reEscape'),
+ reEvaluate = require('../internal/reEvaluate'),
+ reInterpolate = require('../internal/reInterpolate');
+
+/**
+ * By default, the template delimiters used by lodash are like those in
+ * embedded Ruby (ERB). Change the following template settings to use
+ * alternative delimiters.
+ *
+ * @static
+ * @memberOf _
+ * @type Object
+ */
+var templateSettings = {
+
+ /**
+ * Used to detect `data` property values to be HTML-escaped.
+ *
+ * @memberOf _.templateSettings
+ * @type RegExp
+ */
+ 'escape': reEscape,
+
+ /**
+ * Used to detect code to be evaluated.
+ *
+ * @memberOf _.templateSettings
+ * @type RegExp
+ */
+ 'evaluate': reEvaluate,
+
+ /**
+ * Used to detect `data` property values to inject.
+ *
+ * @memberOf _.templateSettings
+ * @type RegExp
+ */
+ 'interpolate': reInterpolate,
+
+ /**
+ * Used to reference the data object in the template text.
+ *
+ * @memberOf _.templateSettings
+ * @type string
+ */
+ 'variable': '',
+
+ /**
+ * Used to import variables into the compiled template.
+ *
+ * @memberOf _.templateSettings
+ * @type Object
+ */
+ 'imports': {
+
+ /**
+ * A reference to the `lodash` function.
+ *
+ * @memberOf _.templateSettings.imports
+ * @type Function
+ */
+ '_': { 'escape': escape }
+ }
+};
+
+module.exports = templateSettings;
+
+})();
diff --git a/pool/shard004/JavaScript/0026977_Canvas.js b/pool/shard004/JavaScript/0026977_Canvas.js
new file mode 100644
index 0000000000000000000000000000000000000000..403c2d775051044ff65cfef0f677db5e45ca7c43
--- /dev/null
+++ b/pool/shard004/JavaScript/0026977_Canvas.js
@@ -0,0 +1,113 @@
+import { Component, createRef } from 'inferno';
+import { useBackend } from '../backend';
+import { Box, Button } from '../components';
+import { Window } from '../layouts';
+
+const PX_PER_UNIT = 24;
+
+class PaintCanvas extends Component {
+ constructor(props) {
+ super(props);
+ this.canvasRef = createRef();
+ this.onCVClick = props.onCanvasClick;
+ }
+
+ componentDidMount() {
+ this.drawCanvas(this.props);
+ }
+
+ componentDidUpdate() {
+ this.drawCanvas(this.props);
+ }
+
+ drawCanvas(propSource) {
+ const ctx = this.canvasRef.current.getContext("2d");
+ const grid = propSource.value;
+ const x_size = grid.length;
+ if (!x_size) {
+ return;
+ }
+ const y_size = grid[0].length;
+ const x_scale = Math.round(this.canvasRef.current.width / x_size);
+ const y_scale = Math.round(this.canvasRef.current.height / y_size);
+ ctx.save();
+ ctx.scale(x_scale, y_scale);
+ for (let x = 0; x < grid.length; x++) {
+ const element = grid[x];
+ for (let y = 0; y < element.length; y++) {
+ const color = element[y];
+ ctx.fillStyle = color;
+ ctx.fillRect(x, y, 1, 1);
+ }
+ }
+ ctx.restore();
+ }
+
+ clickwrapper(event) {
+ const x_size = this.props.value.length;
+ if (!x_size) {
+ return;
+ }
+ const y_size = this.props.value[0].length;
+ const x_scale = this.canvasRef.current.width / x_size;
+ const y_scale = this.canvasRef.current.height / y_size;
+ const x = Math.floor(event.offsetX / x_scale)+1;
+ const y = Math.floor(event.offsetY / y_scale)+1;
+ this.onCVClick(x, y);
+ }
+
+ render() {
+ const {
+ res = 1,
+ value,
+ dotsize = PX_PER_UNIT,
+ ...rest
+ } = this.props;
+ const [width, height] = getImageSize(value);
+ return (
+
+ );
+ }
+}
+
+const getImageSize = value => {
+ const width = value.length;
+ const height = width !== 0 ? value[0].length : 0;
+ return [width, height];
+};
+
+export const Canvas = (props, context) => {
+ const { act, data } = useBackend(context);
+ const dotsize = PX_PER_UNIT;
+ const [width, height] = getImageSize(data.grid);
+ return (
+
+
+
+ act("paint", { x, y })} />
+
+ {!data.finalized && (
+ act("finalize")}
+ content="Finalize" />
+ )}
+ {data.name}
+
+
+
+
+ );
+};
diff --git a/pool/shard004/JavaScript/0026981_binarySearch.js b/pool/shard004/JavaScript/0026981_binarySearch.js
new file mode 100644
index 0000000000000000000000000000000000000000..94a6c600c73b3bd05303950db9eddaba36b63877
--- /dev/null
+++ b/pool/shard004/JavaScript/0026981_binarySearch.js
@@ -0,0 +1,26 @@
+function indexOf(arr, toBeSearched){
+ let minimumIndex = 0;
+ let maximumIndex = arr.length - 1;
+ let currentIndex, currentElement;
+
+ while (minimumIndex <= maximumIndex) {
+ currentIndex = Math.floor((minimumIndex + maximumIndex)/2);
+ currentElement = arr[currentIndex];
+
+ if (currentElement < toBeSearched) {
+ minimumIndex = currentIndex + 1;
+ }
+ else if (currentElement > toBeSearched) {
+ maximumIndex = currentIndex - 1;
+ }
+ else {
+ return currentIndex;
+ }
+ }
+
+ return -1;
+}
+//assuming a sorted array A, one can calculate the index of an element
+let A = [1,2,4,6,75,667];
+let indexOf4 = indexOf(A, 4);
+console.log(indexOf4);
diff --git a/pool/shard004/JavaScript/0026985_all_bool.js b/pool/shard004/JavaScript/0026985_all_bool.js
new file mode 100644
index 0000000000000000000000000000000000000000..00dc9815482f09d0749f2ea17bba72267112f5e7
--- /dev/null
+++ b/pool/shard004/JavaScript/0026985_all_bool.js
@@ -0,0 +1,32 @@
+var parse = require('../');
+var test = require('tape');
+
+test('flag boolean true (default all --args to boolean)', function (t) {
+ var argv = parse(['moo', '--honk', 'cow'], {
+ boolean: true
+ });
+
+ t.deepEqual(argv, {
+ honk: true,
+ _: ['moo', 'cow']
+ });
+
+ t.deepEqual(typeof argv.honk, 'boolean');
+ t.end();
+});
+
+test('flag boolean true only affects double hyphen arguments without equals signs', function (t) {
+ var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], {
+ boolean: true
+ });
+
+ t.deepEqual(argv, {
+ honk: true,
+ tacos: 'good',
+ p: '55',
+ _: ['moo', 'cow']
+ });
+
+ t.deepEqual(typeof argv.honk, 'boolean');
+ t.end();
+});
diff --git a/pool/shard004/JavaScript/0026986_test-browser.js b/pool/shard004/JavaScript/0026986_test-browser.js
new file mode 100644
index 0000000000000000000000000000000000000000..208a5170e814ad84c59d7b8b4132e1e44a13c3e9
--- /dev/null
+++ b/pool/shard004/JavaScript/0026986_test-browser.js
@@ -0,0 +1,213 @@
+#!/usr/bin/env node
+'use strict';
+
+var wd = require('wd');
+wd.configureHttp({timeout: 180000}); // 3 minutes
+
+var sauceConnectLauncher = require('sauce-connect-launcher');
+var selenium = require('selenium-standalone');
+var querystring = require("querystring");
+var request = require('request').defaults({json: true});
+
+var devserver = require('./dev-server.js');
+
+var testTimeout = 30 * 60 * 1000;
+
+var username = process.env.SAUCE_USERNAME;
+var accessKey = process.env.SAUCE_ACCESS_KEY;
+
+var SELENIUM_VERSION = process.env.SELENIUM_VERSION || '2.45.0';
+
+// BAIL=0 to disable bailing
+var bail = process.env.BAIL !== '0';
+
+// process.env.CLIENT is a colon seperated list of
+// (saucelabs|selenium):browserName:browserVerion:platform
+var tmp = (process.env.CLIENT || 'selenium:firefox').split(':');
+var client = {
+ runner: tmp[0] || 'selenium',
+ browser: tmp[1] || 'firefox',
+ version: tmp[2] || null, // Latest
+ platform: tmp[3] || null
+};
+
+var testRoot = 'http://127.0.0.1:8000/tests/';
+var testUrl;
+if (process.env.PERF) {
+ testUrl = testRoot + 'performance/index.html';
+} else if (process.env.TYPE === 'fuzzy') {
+ testUrl = testRoot + 'fuzzy/index.html';
+} else if (process.env.TYPE === 'mapreduce') {
+ testUrl = testRoot + 'mapreduce/index.html';
+} else {
+ testUrl = testRoot + 'integration/index.html';
+}
+
+var qs = {};
+
+var sauceClient;
+var sauceConnectProcess;
+var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now();
+
+if (client.runner === 'saucelabs') {
+ qs.saucelabs = true;
+}
+if (process.env.INVERT) {
+ qs.invert = process.env.INVERT;
+}
+if (process.env.GREP) {
+ qs.grep = process.env.GREP;
+}
+if (process.env.ADAPTERS) {
+ qs.adapters = process.env.ADAPTERS;
+}
+if (process.env.AUTO_COMPACTION) {
+ qs.autoCompaction = true;
+}
+if (process.env.SERVER) {
+ qs.SERVER = process.env.SERVER;
+}
+if (process.env.SKIP_MIGRATION) {
+ qs.SKIP_MIGRATION = process.env.SKIP_MIGRATION;
+}
+if (process.env.POUCHDB_SRC) {
+ qs.src = process.env.POUCHDB_SRC;
+}
+if (process.env.COUCH_HOST) {
+ qs.couchHost = process.env.COUCH_HOST;
+}
+
+testUrl += '?';
+testUrl += querystring.stringify(qs);
+
+if (process.env.TRAVIS &&
+ client.runner === 'saucelabs' &&
+ process.env.TRAVIS_SECURE_ENV_VARS === 'false') {
+ console.error('Not running test, cannot connect to saucelabs');
+ process.exit(0);
+}
+
+function testError(e) {
+ console.error(e);
+ console.error('Doh, tests failed');
+ sauceClient.quit();
+ process.exit(3);
+}
+
+function postResult(result) {
+ if (process.env.PERF && process.env.DASHBOARD_HOST) {
+ result.branch = process.env.TRAVIS_BRANCH || process.env.BRANCH || false;
+ result.commit = process.env.TRAVIS_COMMIT || process.env.COMMIT || false;
+ result.pull_request = process.env.TRAVIS_PULL_REQUEST;
+ var commits = 'https://api.github.com/repos/pouchdb/pouchdb/git/commits/';
+ request({
+ method: 'GET',
+ uri: commits + result.commit,
+ headers: {'User-Agent': 'request'}
+ }, function (error, response, body) {
+ result._id = result.date = body.committer.date;
+ request({
+ method: 'POST',
+ uri: process.env.DASHBOARD_HOST + '/performance_results',
+ json: result
+ }, function (error) {
+ console.log(result);
+ process.exit(!!error);
+ });
+ });
+ return;
+ }
+ process.exit(!process.env.PERF && result.failed ? 1 : 0);
+}
+
+function testComplete(result) {
+ console.log(result);
+
+ sauceClient.quit().then(function () {
+ if (sauceConnectProcess) {
+ sauceConnectProcess.close(function () {
+ postResult(result);
+ });
+ } else {
+ postResult(result);
+ }
+ });
+}
+
+function startSelenium(callback) {
+ // Start selenium
+ var opts = {version: SELENIUM_VERSION};
+ selenium.install(opts, function (err) {
+ if (err) {
+ console.error('Failed to install selenium');
+ process.exit(1);
+ }
+ selenium.start(opts, function () {
+ sauceClient = wd.promiseChainRemote();
+ callback();
+ });
+ });
+}
+
+function startSauceConnect(callback) {
+
+ var options = {
+ username: username,
+ accessKey: accessKey,
+ tunnelIdentifier: tunnelId
+ };
+
+ sauceConnectLauncher(options, function (err, process) {
+ if (err) {
+ console.error('Failed to connect to saucelabs');
+ console.error(err);
+ return process.exit(1);
+ }
+ sauceConnectProcess = process;
+ sauceClient = wd.promiseChainRemote("localhost", 4445, username, accessKey);
+ callback();
+ });
+}
+
+function startTest() {
+
+ console.log('Starting', client);
+
+ var opts = {
+ browserName: client.browser,
+ version: client.version,
+ platform: client.platform,
+ tunnelTimeout: testTimeout,
+ name: client.browser + ' - ' + tunnelId,
+ 'max-duration': 60 * 45,
+ 'command-timeout': 599,
+ 'idle-timeout': 599,
+ 'tunnel-identifier': tunnelId
+ };
+
+ sauceClient.init(opts).get(testUrl, function () {
+
+ /* jshint evil: true */
+ var interval = setInterval(function () {
+ sauceClient.eval('window.results', function (err, results) {
+ if (err) {
+ clearInterval(interval);
+ testError(err);
+ } else if (results.completed || (results.failures.length && bail)) {
+ clearInterval(interval);
+ testComplete(results);
+ } else {
+ console.log('=> ', results);
+ }
+ });
+ }, 10 * 1000);
+ });
+}
+
+devserver.start(function () {
+ if (client.runner === 'saucelabs') {
+ startSauceConnect(startTest);
+ } else {
+ startSelenium(startTest);
+ }
+});
diff --git a/pool/shard004/JavaScript/0026987_user.js b/pool/shard004/JavaScript/0026987_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..6d5ca5574a31bbc31e48e848f6bd77f431fd4450
--- /dev/null
+++ b/pool/shard004/JavaScript/0026987_user.js
@@ -0,0 +1,22 @@
+'use strict';
+
+describe('Controller: UserCtrl', function () {
+
+ // load the controller's module
+ beforeEach(module('jodomaxApp'));
+
+ var UserCtrl,
+ scope;
+
+ // Initialize the controller and a mock scope
+ beforeEach(inject(function ($controller, $rootScope) {
+ scope = $rootScope.$new();
+ UserCtrl = $controller('UserCtrl', {
+ $scope: scope
+ });
+ }));
+
+ it('should attach a list of awesomeThings to the scope', function () {
+ expect(scope.awesomeThings.length).toBe(3);
+ });
+});
diff --git a/pool/shard004/JavaScript/0026989_app.js b/pool/shard004/JavaScript/0026989_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..004852b413e28527d7bd549ea8e942f8cb06877b
--- /dev/null
+++ b/pool/shard004/JavaScript/0026989_app.js
@@ -0,0 +1,86 @@
+var express = require('express'),
+ bodyParser = require('body-parser'),
+ methodOverride = require('method-override'),
+ compress = require('compression'),
+ errorhandler = require('errorhandler'),
+ passport = require('passport'),
+ mongoose = require('mongoose'),
+ ECT = require('ect'),
+ expressJwt = require('express-jwt'),
+ sanitizer = require('sanitize-html'),
+ _ = require('underscore'),
+ secret = require('./config/secret');
+
+var app = module.exports = express();
+
+// this should be used in prod evn so we don't get a bunch of time outs
+// var toobusy = require('toobusy');
+// app.use(function(req, res, next) {
+// if (toobusy()) {
+// res.send(503, "I'm busy right now, sorry.");
+// } else {
+// next();
+// }
+// });
+
+if (app.get('env') === 'prod') {
+ app.use(compress());
+ app.set('views', __dirname + '/dist/app/views');
+ var ectRenderer = ECT({ watch: true, root: __dirname + '/dist/app/views', ext : '.html' });
+ app.use(express.static(__dirname + '/dist', { maxAge: 345600000 })); // four days
+ app.use(errorhandler());
+} else {
+ app.set('views', __dirname + '/client/app/views');
+ var ectRenderer = ECT({ watch: true, root: __dirname + '/client/app/views', ext : '.html' });
+ app.use(express.static(__dirname + '/client'));
+ app.use(errorhandler({dumpExceptions: true, showStack: true}));
+}
+
+mongoose.connect(secret.mongoPath, function onMongooseError(err) {
+ if (err) { throw err; } // Log This
+});
+
+// All routes need to be protected by JWT
+app.use('/api/s/', expressJwt({secret: secret.jwtSecret}));
+
+app.set('port', process.env.PORT || 8080);
+app.engine('.html', ectRenderer.render);
+app.set('view engine', 'html');
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({extended: true}));
+app.use(methodOverride());
+
+require('./config/passport')(passport);
+app.use(passport.initialize());
+app.use(passport.session());
+
+app.use(function (err, req, res, next) {
+ if (err.constructor.name === 'UnauthorizedError') {
+ return res.send(401, 'Unauthorized');
+ }
+ next();
+});
+
+app.use(function (req, res, next) {
+ if (req.body) {
+ _.each(req.body, function(value, key) {
+ if(!parseInt(value,10) && value !== null) {
+ if (typeof value === 'string') {
+ value = value.replace(/>/gi, '>');
+ value = value.replace(/</gi, '<');
+ value = value.replace(/(©|"|&)/gi, '');
+ }
+ req.body[key] = sanitizer(value, {
+ allowedTags: []
+ });
+ }
+ });
+ }
+ next();
+});
+
+require('./server/routes.js')(app);
+
+app.listen(app.get('port'), function() {
+ console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
+});
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0026991_validate.js b/pool/shard004/JavaScript/0026991_validate.js
new file mode 100644
index 0000000000000000000000000000000000000000..68121dc854abcb0ac3c910b397b8bc27140a00f4
--- /dev/null
+++ b/pool/shard004/JavaScript/0026991_validate.js
@@ -0,0 +1,110 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Do some validation.
+
+define([
+ 'lib/constants'
+], function (Constants) {
+ 'use strict';
+
+ // taken from the fxa-auth-server
+ var HEX_STRING = /^(?:[a-fA-F0-9]{2})+$/;
+
+ return {
+ /**
+ * Check if an email address is valid
+ *
+ * @return true if email is valid, false otw.
+ */
+ isEmailValid: function (email) {
+ if (typeof email !== 'string') {
+ return false;
+ }
+
+ var parts = email.split('@');
+
+ var localLength = parts[0] && parts[0].length;
+ var domainLength = parts[1] && parts[1].length;
+
+ // Original regexp from:
+ // http://blog.gerv.net/2011/05/html5_email_address_regexp/
+ // Modified to remove the length checks, which are done later.
+ // IETF spec: http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
+ // NOTE: this does *NOT* allow internationalized domain names.
+ return (/^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d][a-z\d\-]*(?:\.[a-z\d][a-z\d\-]*)*$/i).test(email) &&
+ // total email allwed to be 256 bytes long
+ email.length <= 256 &&
+ // local side only allowed to be 64 bytes long
+ 1 <= localLength && localLength <= 64 &&
+ // domain side allowed to be up to 255 bytes long which
+ // doesn't make much sense unless the local side has 0 length;
+ 1 <= domainLength && domainLength <= 255;
+ },
+
+ /**
+ * Check if an email verification code is valid
+ */
+ isCodeValid: function (code) {
+ if (typeof code !== 'string') {
+ return false;
+ }
+
+ // codes are fixed length hex strings.
+ return code.length === Constants.CODE_LENGTH &&
+ HEX_STRING.test(code);
+ },
+
+ /**
+ * Check if an OAuth code is valid
+ */
+ isOAuthCodeValid: function (code) {
+ if (typeof code !== 'string') {
+ return false;
+ }
+
+ // codes are fixed length hex strings.
+ return code.length === Constants.OAUTH_CODE_LENGTH &&
+ HEX_STRING.test(code);
+ },
+
+ /**
+ * Check if a verification token is valid
+ */
+ isTokenValid: function (token) {
+ if (typeof token !== 'string') {
+ return false;
+ }
+
+ // tokens are variable length hex strings.
+ return HEX_STRING.test(token);
+ },
+
+ /**
+ * Check if a verification uid is valid
+ */
+ isUidValid: function (uid) {
+ if (typeof uid !== 'string') {
+ return false;
+ }
+
+ // uids are fixed length hex strings.
+ return uid.length === Constants.UID_LENGTH &&
+ HEX_STRING.test(uid);
+ },
+
+ /**
+ * Check if a password is valid
+ */
+ isPasswordValid: function (password) {
+ if (typeof password !== 'string') {
+ return false;
+ }
+
+ return password.length >= Constants.PASSWORD_MIN_LENGTH;
+ }
+ };
+});
+
+
diff --git a/pool/shard004/JavaScript/0026995_map-context.test.js b/pool/shard004/JavaScript/0026995_map-context.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..4d5d4a3e112238fbf48c039c206e0605598592bb
--- /dev/null
+++ b/pool/shard004/JavaScript/0026995_map-context.test.js
@@ -0,0 +1,93 @@
+/* global it, describe, expect */
+
+import React from 'react';
+import {mount, configure} from 'enzyme';
+import Adapter from 'enzyme-adapter-react-16';
+import createSagaMiddleware from 'redux-saga';
+import TileLayer from 'ol/layer/Tile';
+import TileWMSSource from 'ol/source/TileWMS';
+import XYZSource from 'ol/source/XYZ';
+
+import {createStore, combineReducers, applyMiddleware} from 'redux';
+import {Provider} from 'react-redux';
+
+import ConnectedMap from '@boundlessgeo/sdk/components/map';
+import MapReducer from '@boundlessgeo/sdk/reducers/map';
+import * as MapActions from '@boundlessgeo/sdk/actions/map';
+import * as ContextSagas from '@boundlessgeo/sdk/sagas/context';
+
+configure({adapter: new Adapter()});
+
+const sagaMiddleware = createSagaMiddleware();
+
+describe('Map component context documents', () => {
+ it('should correctly reload context documents', (done) => {
+ const store = createStore(combineReducers({
+ map: MapReducer,
+ }), applyMiddleware(sagaMiddleware));
+
+ sagaMiddleware.run(ContextSagas.handleContext);
+
+ const ref = React.createRef();
+ mount( );
+ const map = ref.current;
+
+ const wmsJson = {
+ version: 8,
+ name: 'states-wms',
+ center: [-98.78906130124426, 37.92686191312036],
+ zoom: 4,
+ sources: {
+ states: {
+ type: 'raster',
+ maxzoom: 12,
+ tileSize: 256,
+ tiles: ['https://ahocevar.com/geoserver/gwc/service/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&SRS=EPSG:900913&LAYERS=topp:states&STYLES=&WIDTH=256&HEIGHT=256&BBOX={bbox-epsg-3857}'],
+ },
+ },
+ layers: [
+ {
+ id: 'states-wms',
+ source: 'states',
+ },
+ ],
+ };
+ store.dispatch(MapActions.fetchContext({json: wmsJson}));
+ window.setTimeout(() => {
+ let layers = map.map.getLayers().getArray();
+ expect(layers[0]).toBeInstanceOf(TileLayer);
+ expect(layers[0].getSource()).toBeInstanceOf(TileWMSSource);
+ const osmJson = {
+ version: 8,
+ name: 'osm',
+ center: [-98.78906130124426, 37.92686191312036],
+ zoom: 4,
+ sources: {
+ osm: {
+ type: 'raster',
+ attribution: '© OpenStreetMap contributors.',
+ tileSize: 256,
+ tiles: [
+ 'https://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
+ 'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
+ 'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png',
+ ],
+ },
+ },
+ layers: [
+ {
+ id: 'osm',
+ source: 'osm',
+ },
+ ],
+ };
+ store.dispatch(MapActions.fetchContext({json: osmJson}));
+ window.setTimeout(() => {
+ layers = map.map.getLayers().getArray();
+ expect(layers[0]).toBeInstanceOf(TileLayer);
+ expect(layers[0].getSource()).toBeInstanceOf(XYZSource);
+ done();
+ }, 0);
+ }, 0);
+ });
+});
diff --git a/pool/shard004/JavaScript/0026996_Date.js b/pool/shard004/JavaScript/0026996_Date.js
new file mode 100644
index 0000000000000000000000000000000000000000..e3b6a61053b0e9c3e816288332445353fb969bd7
--- /dev/null
+++ b/pool/shard004/JavaScript/0026996_Date.js
@@ -0,0 +1,151 @@
+/* eslint quotes: 0 */
+/* eslint max-len: 0 */
+import React, { Component } from 'react';
+import PropTypes from 'prop-types';
+import Const from '../Const';
+
+const legalComparators = [ '=', '>', '>=', '<', '<=', '!=' ];
+
+function dateParser(d) {
+ return `${d.getFullYear()}-${("0" + (d.getMonth() + 1)).slice(-2)}-${("0" + d.getDate()).slice(-2)}`;
+}
+
+class DateFilter extends Component {
+ constructor(props) {
+ super(props);
+ this.dateComparators = this.props.dateComparators || legalComparators;
+ this.filter = this.filter.bind(this);
+ this.onChangeComparator = this.onChangeComparator.bind(this);
+ }
+
+ setDefaultDate() {
+ let defaultDate = '';
+ const { defaultValue } = this.props;
+ if (defaultValue && defaultValue.date) {
+ // Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
+ defaultDate = dateParser(new Date(defaultValue.date));
+ }
+ return defaultDate;
+ }
+
+ onChangeComparator(event) {
+ let date = this.inputDate.value;
+ const comparator = event.target.value;
+ if (date === '') {
+ return;
+ }
+ date = new Date(date);
+ this.props.filterHandler({ date, comparator }, Const.FILTER_TYPE.DATE);
+ }
+
+ getComparatorOptions() {
+ const optionTags = [];
+ optionTags.push();
+ for (let i = 0; i < this.dateComparators.length; i++) {
+ optionTags.push(
+
+ );
+ }
+ return optionTags;
+ }
+
+ filter(event) {
+ const comparator = this.dateFilterComparator.value;
+ const dateValue = event.target.value;
+ if (dateValue) {
+ this.props.filterHandler({ date: new Date(dateValue), comparator }, Const.FILTER_TYPE.DATE);
+ } else {
+ this.props.filterHandler(null, Const.FILTER_TYPE.DATE);
+ }
+ }
+
+ cleanFiltered() {
+ const value = this.setDefaultDate();
+ const comparator = (this.props.defaultValue) ? this.props.defaultValue.comparator : '';
+ this.setState(() => { return { isPlaceholderSelected: (value === '') }; });
+ this.dateFilterComparator.value = comparator;
+ this.inputDate.value = value;
+ this.props.filterHandler({ date: new Date(value), comparator }, Const.FILTER_TYPE.DATE);
+ }
+
+ applyFilter(filterDateObj) {
+ const { date, comparator } = filterDateObj;
+ this.setState(() => { return { isPlaceholderSelected: (date === '') }; });
+ this.dateFilterComparator.value = comparator;
+ this.inputDate.value = dateParser(date);
+ this.props.filterHandler({ date, comparator }, Const.FILTER_TYPE.DATE);
+ }
+
+ componentDidMount() {
+ const comparator = this.dateFilterComparator.value;
+ const dateValue = this.inputDate.value;
+ if (comparator && dateValue) {
+ this.props.filterHandler({ date: new Date(dateValue), comparator }, Const.FILTER_TYPE.DATE);
+ }
+ }
+
+ render() {
+ const { defaultValue, style: { date, comparator } } = this.props;
+ return (
+
+
+ this.inputDate = n }
+ className='filter date-filter-input form-control'
+ style={ date }
+ type='date'
+ onChange={ this.filter }
+ defaultValue={ this.setDefaultDate() } />
+
+ );
+ }
+}
+
+DateFilter.propTypes = {
+ filterHandler: PropTypes.func.isRequired,
+ defaultValue: PropTypes.shape({
+ date: PropTypes.object,
+ comparator: PropTypes.oneOf(legalComparators)
+ }),
+ style: PropTypes.shape({
+ date: PropTypes.oneOfType([ PropTypes.object ]),
+ comparator: PropTypes.oneOfType([ PropTypes.object ])
+ }),
+ /* eslint consistent-return: 0 */
+ dateComparators: function(props, propName) {
+ if (!props[propName]) {
+ return;
+ }
+ for (let i = 0; i < props[propName].length; i++) {
+ let comparatorIsValid = false;
+ for (let j = 0; j < legalComparators.length; j++) {
+ if (legalComparators[j] === props[propName][i]) {
+ comparatorIsValid = true;
+ break;
+ }
+ }
+ if (!comparatorIsValid) {
+ return new Error(`Date comparator provided is not supported.
+ Use only ${legalComparators}`);
+ }
+ }
+ },
+ columnName: PropTypes.any
+};
+
+DateFilter.defaultProps = {
+ style: {
+ date: null,
+ comparator: null
+ }
+};
+
+
+export default DateFilter;
diff --git a/pool/shard004/JavaScript/0026997_qweb_pos_ticket.js b/pool/shard004/JavaScript/0026997_qweb_pos_ticket.js
new file mode 100644
index 0000000000000000000000000000000000000000..8c7f0ac54667d73eaa3959c46fed7451fba4b4ca
--- /dev/null
+++ b/pool/shard004/JavaScript/0026997_qweb_pos_ticket.js
@@ -0,0 +1,28 @@
+function openerp.qweb_pos_ticket(instance){ //module is instance.point_of_sale
+ module=instance.point_of_sale;
+ _t = instance.web._t;
+
+ console.log("qweb pos ticket");
+ module.PaymentScreenWidget=module.ScreenWidget.extend({
+
+ show: function () {
+
+ console.log("Click on back_buton");
+ this._super();
+ var self = this;
+
+ this.back_button = this.add_action_button({
+ label: _t('Back'),
+ icon: '/point_of_sale/static/src/img/icons/png48/go-previous.png',
+ click: function(){
+ self.pos_widget.screen_selector.set_current_screen(self.back_screen);
+ $('#numpad-return').removeAttr('disabled');
+ },
+ });
+ },
+
+});
+
+}
+
+
diff --git a/pool/shard004/JavaScript/0026998_router.js b/pool/shard004/JavaScript/0026998_router.js
new file mode 100644
index 0000000000000000000000000000000000000000..1990e56b08fff9df87176c8ff69a83b76226ffe6
--- /dev/null
+++ b/pool/shard004/JavaScript/0026998_router.js
@@ -0,0 +1,75 @@
+import Vue from "vue";
+import VueRouter from "vue-router";
+
+Vue.use(VueRouter);
+
+const Main = () => import("../webapp/pages/Main.vue");
+const Index = () => import("../webapp/components/Index.vue");
+const Dataset = () => import("../webapp/components/Dataset.vue");
+const Visualizations = () => import("../webapp/pages/Visualizations.vue");
+
+export const tabs = ['resumen', 'editor', 'consultas', 'visualizaciones', 'descarga', 'mapa']
+export const ROUTE_NAMES = {
+ Visualizations: 'Visualizations',
+ Index: 'Index',
+ Dataset: 'Dataset',
+ Query: 'Query',
+ Visualization: 'Visualization',
+ Map: 'Map',
+}
+
+// https://router.vuejs.org/guide/essentials/nested-routes.html
+export const router = new VueRouter({
+ mode: 'history',
+ routes: [
+ {
+ path: '/datos/v/visualizaciones',
+ component: Visualizations,
+ name: ROUTE_NAMES.Visualizations
+ },
+ {
+ path: '/datos/',
+ alias: "/",
+ component: Main,
+ children: [
+ {
+ path: '',
+ name: ROUTE_NAMES.Index,
+ component: Index
+ },
+ {
+ path: ':id/:tab?',
+ component: Dataset,
+ name: ROUTE_NAMES.Dataset,
+ // send props as a function, default to tab[0], otherwise take the index
+ props: ({ params: { tab = tabs[0] } }) => ({
+ activeDatasetTab: tabs.indexOf(tab)
+ })
+ },
+ {
+ path: ':id/q/:queryId?',
+ component: Dataset,
+ name: ROUTE_NAMES.Query,
+ props: { activeDatasetTab: 1 }
+ },
+ {
+ path: ':id/v/:queryId?',
+ component: Dataset,
+ name: ROUTE_NAMES.Visualization,
+ props: { activeDatasetTab: 3 }
+ }
+ ]
+ }
+ ],
+ scrollBehavior() {
+ const element = document.getElementById('gobierto-datos-app');
+ const elementBounding = element.getBoundingClientRect();
+ const { y } = elementBounding
+ if (window.pageYOffset > (y + window.scrollY)) {
+ window.scrollTo({
+ top: element.offsetTop,
+ behavior: 'smooth'
+ });
+ }
+ }
+ });
diff --git a/pool/shard004/JavaScript/0027000_licenseController.js b/pool/shard004/JavaScript/0027000_licenseController.js
new file mode 100644
index 0000000000000000000000000000000000000000..08ebe60d03fc3fab07e8a6e71f85b06f613359f0
--- /dev/null
+++ b/pool/shard004/JavaScript/0027000_licenseController.js
@@ -0,0 +1,180 @@
+/*
+ * ***************************************************
+ *
+ * cismet GmbH, Saarbruecken, Germany
+ *
+ * ... and it just works.
+ *
+ * ***************************************************
+ */
+
+/*jshint sub:true*/
+/*jshint camelcase: false */
+
+angular.module(
+ 'de.cismet.sip-html5-resource-registration.controllers'
+).controller(
+ 'de.cismet.sip-html5-resource-registration.controllers.licenseController',
+ [
+ '$scope',
+ 'AppConfig',
+ 'de.cismet.sip-html5-resource-registration.services.dataset',
+ 'de.cismet.sip-html5-resource-registration.services.TagGroupService',
+ // Controller Constructor Function
+ function (
+ $scope,
+ AppConfig,
+ dataset,
+ tagGroupService
+ ) {
+ 'use strict';
+ var _this = this;
+ _this.dataset = dataset;
+ _this.config = AppConfig;
+ _this.generateDOI = false;
+ if(dataset.$deposition && dataset.$deposition !== null) {
+ dataset.$deposition.$promise.then(
+ function success(deposition) {
+ if(deposition.metadata.prereserve_doi.doi !== null) {
+ _this.generateDOI = true;
+ } else {
+ _this.generateDOI = false;
+ }
+ }, function error() {
+ _this.generateDOI = false;
+ });
+ }
+
+ // load taglist
+ $scope.tags['accessconditions'] = tagGroupService.getTagList('access conditions', 'Creative Commons (CC BY),Creative Commons (CC BY-NC),Creative Commons (CC BY-NC-ND),Creative Commons (CC BY-NC-SA),Creative Commons (CC BY-ND),Creative Commons (CC BY-SA),for research only,no limitations,other');
+
+ // validation functions
+ $scope.wizard.enterValidators['License and Conditions'] = function(context) {
+
+ if(context.valid === true){
+ $scope.message.text='Please select a predefined license for regulating the conditions for access and use of the dataset and / or provide a brief statement or URL to the license which applies to the usage of the dataset. This statement should provide additional information.';
+ $scope.message.icon='fa-info-circle';
+ $scope.message.type = 'success';
+ }
+
+ if(_this.config.developmentMode === true) {
+ context.valid = true;
+ }
+
+ return context.valid;
+ };
+
+ $scope.wizard.exitValidators['License and Conditions'] = function(context){
+ context.valid = true;
+
+ // ACCESS CONDITIONS
+ var isInvalidAccessconditions = $scope.tags['accessconditions'].every(function(element) {
+ if (_this.dataset.accessconditions && _this.dataset.accessconditions.name &&
+ (element.name === _this.dataset.accessconditions.name)) {
+ _this.dataset.accessconditions = element;
+ return false;
+ } else {
+ return true;
+ }
+ });
+
+ if(isInvalidAccessconditions) {
+ $scope.message.text='Please select a valid access condition (e.g. no limitations).';
+ $scope.message.icon='fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetAccessconditions';
+ context.valid = false;
+ } else if($scope.licenseForm.datasetLicensestatement.$error.required) {
+ // NAME
+ $scope.message.text='Please provide a description of the license of type other or select another license from the list.';
+ $scope.message.icon='fa-warning';
+ $scope.message.type='warning';
+
+ $scope.wizard.hasError = 'datasetLicensestatement';
+ context.valid = false;
+ } else if (dataset.licensestatement && dataset.licensestatement !== null && dataset.licensestatement.length > 0 && dataset.licensestatement.length < 6) {
+ $scope.message.text = 'Statement or URL to the license which applies to the usage of the dataset is too short.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetLicensestatement';
+ context.valid = false;
+ } else if (dataset.contact.name && dataset.contact.name !== null && dataset.contact.name.length > 0 && dataset.contact.name.length < 3) {
+ $scope.message.text = 'Name of the contact person is too short.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetContactperson';
+ context.valid = false;
+ }
+ else if (dataset.contact.organisation && dataset.contact.organisation !== null && dataset.contact.organisation.length > 0 && dataset.contact.organisation.length < 3) {
+ $scope.message.text = 'Name of the organisation is too short.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetOrganisation';
+ context.valid = false;
+ }
+ else if (dataset.contact.description && dataset.contact.description !== null && dataset.contact.description.length > 0 && dataset.contact.description.length < 6) {
+ $scope.message.text = 'Optional citation information is too short.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetCitation';
+ context.valid = false;
+ }
+ else if ($scope.licenseForm.datasetOrganisation.$error.required) {
+ // CONTENT LOCATION
+ $scope.message.text = 'Please provide a name of the organisation responsible for the establishment, management, maintenance and distribution of dataset or publication to be associated with the DOI.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetOrganisation';
+ context.valid = false;
+ } else if ($scope.licenseForm.datasetContactperson.$error.required) {
+ // CONTENT LOCATION
+ $scope.message.text = 'Please provide a name of the contact person (Family name, Given name) responsible for the establishment, management, maintenance and distribution of dataset or publication to be associated with the DOI.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetContactperson';
+ context.valid = false;
+ } else if ($scope.licenseForm.datasetContactemail.$error.email) {
+ // CONTENT LOCATION
+ $scope.message.text = 'The email address of the contact person is not a valid.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetContactperson';
+ context.valid = false;
+ } else if ($scope.licenseForm.datasetOrganisationurl.$error.url) {
+ // CONTENT LOCATION
+ $scope.message.text = 'The website url of the organisation is not a valid URL.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetOrganisation';
+ context.valid = false;
+ } else if (dataset.metadata[1].description && dataset.metadata[1].description !== null && dataset.metadata[1].description.length > 0 && dataset.metadata[1].description.length < 10) {
+ $scope.message.text = 'Optional data lineage / data provenance information is too short.';
+ $scope.message.icon = 'fa-warning';
+ $scope.message.type = 'warning';
+
+ $scope.wizard.hasError = 'datasetLineage';
+ context.valid = false;
+ }
+
+ if(context.valid === true) {
+ $scope.wizard.hasError = null;
+ }
+
+ if(_this.config.developmentMode === true) {
+ context.valid = true;
+ }
+
+ return context.valid;
+ };
+ }
+ ]
+);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027003_rolesController.js b/pool/shard004/JavaScript/0027003_rolesController.js
new file mode 100644
index 0000000000000000000000000000000000000000..332a42a9f18d2c91dbb8efddbcbb423249c3a4e5
--- /dev/null
+++ b/pool/shard004/JavaScript/0027003_rolesController.js
@@ -0,0 +1,124 @@
+angular.module('Sentinel.rolesController', [])
+.controller('RoleController', ['$scope', '$state', '$window', 'Role', function($scope, $state, $window, Role){
+ $scope.main = {
+ offset: 1,
+ limit: 1,
+ sort: 'name ASC',
+ rowsArray: [
+ {id:1, label:'1 Per Page'},
+ {id:2, label:'2 Per Page'},
+ {id:3, label:'3 Per Page'}
+ ],
+ sortArray: [
+ {id:'name ASC', label:'Name (A-Z)'},
+ {id:'name DESC',label:'Name (Z-A)'},
+ ]
+ };
+
+ $scope.loadPage = function(page){
+ $scope.main.offset = page;
+ Role.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){
+ //var orgs = JSON.parse(data);
+ // users from your api
+ $scope.roles = data.roles;
+
+ // total number of rows
+ $scope.count = data.count;
+
+ // number of pages of orgs
+ $scope.pagesCount = data.count/$scope.main.limit;
+
+ // build pages array
+ var pagesArray = [];
+ for(var p = 1; p < $scope.pagesCount+1; p++){
+ pagesArray.push(p);
+ }
+ $scope.pages = pagesArray;
+ });
+ }
+
+ $scope.loadPerPage = function(option){
+ $scope.main.limit = option;
+ $scope.loadPage($scope.main.offset);
+ }
+
+ $scope.loadSortPage = function(option){
+ $scope.main.sort = option;
+ $scope.loadPage($scope.main.offset);
+ }
+
+ $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs
+
+ $scope.deleteRole = function(role) { // Delete a org. Issues a DELETE to /api/org/:id
+ role.$delete(function(response) {
+ $scope.message = response;
+
+ if(response.status == 'ok'){
+ $state.go('orgs'); //redirect to home
+ }
+ });
+ };
+ }]
+)
+.controller('RoleViewController', ['$scope', '$stateParams' ,'Role', function($scope,$stateParams,Role){
+ $scope.role=Role.get({id:$stateParams.id});
+}])
+.controller('RoleCreateController',['$scope', '$state', '$stateParams', 'Role', function($scope,$state,$stateParams,Role){
+ $scope.activities = ['user:show', 'user:create', 'user:update', 'user:destroy'];
+
+ $scope.role=new Role();
+
+ $scope.addRole=function(){
+ $scope.role.$save(function(response){
+ $scope.message = response;
+
+ if(response.status == 'ok'){
+ $state.go('roles'); //redirect to home
+ }
+ });
+ }
+}]).controller('RoleEditController',['$scope', '$state', '$stateParams', 'Role', function($scope,$state,$stateParams,Role){
+ $scope.acties = ['user:show', 'user:create', 'user:update', 'user:destroy'];
+
+ $scope.updateRole=function(){
+ var roleForm = jQuery('#roleForm').serialize();
+ jQuery.ajax({
+ url: '/roles/update',
+ method: 'post',
+ data: roleForm,
+ dataType: 'json',
+ success:function(response){
+ $scope.message = response.message;
+
+ if(response.status == 'ok'){
+ $state.go('roles'); //redirect to home
+ }
+ }
+ })
+ };
+
+ $scope.activities = [];
+ var array = [];
+ $scope.loadRole=function(){
+ Role.get({id:$stateParams.id}, function(response){
+ $scope.role = response;
+ array = response.activities;
+ $scope.activities = JSON.parse(array);
+ //console.log(Object.prototype.toString.call($scope.activities));
+ });
+
+ };
+
+ $scope.loadRole();
+
+ $scope.toggleSelection = function toggleSelection(id) {
+ var idx = $scope.activities.indexOf(id);
+ if (idx > -1) {
+ $scope.activities.splice(idx, 1);
+ }
+ else {
+ $scope.activities.push(id);
+ }
+ console.log($scope.activities)
+ };
+}]);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027005_space-before-closing-brace.js b/pool/shard004/JavaScript/0027005_space-before-closing-brace.js
new file mode 100644
index 0000000000000000000000000000000000000000..0ce9f23049df928309435a5fd96ede974880730b
--- /dev/null
+++ b/pool/shard004/JavaScript/0027005_space-before-closing-brace.js
@@ -0,0 +1,102 @@
+'use strict';
+
+var gonzales = require('gonzales-pe');
+
+module.exports = function () {
+ var valueFromSettings;
+ var blockIndent;
+
+ function getLastWhitespaceNode(node) {
+ var lastNode = node.last();
+
+ if (!lastNode || !lastNode.content) return null;
+
+ if (lastNode.is('block')) return null;
+ if (lastNode.is('space')) return lastNode;
+
+ return getLastWhitespaceNode(lastNode);
+ }
+
+ function processBlock(x, level) {
+ level = level || 0;
+
+ x.forEach(function (node) {
+ if (!node.is('block') && !node.is('atrulers')) return processBlock(node, level);
+
+ level++;
+
+ var value = valueFromSettings;
+ if (value.indexOf('\n') > -1) {
+ // TODO: Check that it works for '' block indent value
+ if (blockIndent) {
+ value += new Array(level).join(blockIndent);
+ }
+ }
+
+ // If found block node stop at the next one for space check
+ // For the pre-block node, find its last (the deepest) child
+ var whitespaceNode = getLastWhitespaceNode(node);
+
+ // If it's spaces, modify this node
+ // If it's something different from spaces, add a space node
+ // to the end
+ if (whitespaceNode) {
+ whitespaceNode.content = value;
+ } else if (value !== '') {
+ var space = gonzales.createNode({
+ type: 'space',
+ content: value
+ });
+ node.content.push(space);
+ }
+
+ processBlock(node, level);
+ });
+ }
+
+ return {
+ name: 'space-before-closing-brace',
+
+ runBefore: 'tab-size',
+
+ syntax: ['css', 'less', 'scss'],
+
+ accepts: {
+ number: true,
+ string: /^[ \t\n]*$/
+ },
+
+ /**
+ * Processes tree node.
+ * @param {node} ast
+ * @param {Object} config
+ */
+ process: function (ast, config) {
+ valueFromSettings = this.value;
+ blockIndent = config['block-indent'];
+
+ processBlock(ast);
+ },
+
+ /**
+ * Detects the value of an option at the tree node.
+ *
+ * @param {node} ast
+ */
+ detect: function (ast) {
+ let detected = [];
+
+ ast.traverseByTypes(['block', 'atrulers'], function (node) {
+ // For the block node, find its last (the deepest) child
+ var whitespaceNode = getLastWhitespaceNode(node);
+ if (whitespaceNode) {
+ detected.push(whitespaceNode.content);
+ } else {
+ detected.push('');
+ }
+ });
+
+ return detected;
+ }
+ };
+}();
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027007_index.js b/pool/shard004/JavaScript/0027007_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..505df9644d1a4b9a9764b8e99825da9e442a3ac9
--- /dev/null
+++ b/pool/shard004/JavaScript/0027007_index.js
@@ -0,0 +1,43 @@
+process.env.NODE_ENV = process.env.NODE_ENV || 'development';
+
+const resolve = require('path').resolve,
+ yargs = require('yargs').argv,
+ _slice = [].slice;
+
+const SRC_DIRNAME = 'src',
+ DIST_DIRNAME = 'dist',
+ PROJECT_PATH = resolve(__dirname, '../');
+
+function inProject () {
+ return resolve.apply(resolve, [PROJECT_PATH].concat(_slice.apply(arguments)));
+}
+
+module.exports = exports = {
+
+ // environment
+ NODE_ENV : process.env.NODE_ENV,
+ __DEBUG__ : !!yargs.debug,
+ __DEV__ : process.env.NODE_ENV === 'development',
+ __PROD__ : process.env.NODE_ENV === 'production',
+
+ // path helpers
+ SRC_DIRNAME : SRC_DIRNAME,
+ DIST_DIRNAME : DIST_DIRNAME,
+ PROJECT_PATH : PROJECT_PATH,
+ inProject : inProject,
+ inSrc : inProject.bind(undefined, SRC_DIRNAME),
+ inDist : inProject.bind(undefined, DIST_DIRNAME),
+
+ // build system
+ // these will be bundled separately from the core app
+ VENDOR_DEPENDENCIES : [
+ 'react',
+ 'react-router',
+ 'redux'
+ ],
+
+ // server configuration
+ WEBPACK_PORT : 3000,
+ WEBPACK_HOST: '0.0.0.0',
+ SERVER_PORT : process.env.PORT || 4000
+};
diff --git a/pool/shard004/JavaScript/0027010_gulpfile.js b/pool/shard004/JavaScript/0027010_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..38ea9bcc3cd160cde099cd3c2f9ba19bb8776e3f
--- /dev/null
+++ b/pool/shard004/JavaScript/0027010_gulpfile.js
@@ -0,0 +1,201 @@
+'use strict';
+
+var gulp = require('gulp');
+var del = require('del');
+var eslint = require('gulp-eslint');
+var sass = require('gulp-sass');
+var ngHtml2Js = require("gulp-ng-html2js");
+var minifyHtml = require("gulp-minify-html");
+var concat = require("gulp-concat");
+var uglify = require("gulp-uglify");
+var runSequence = require('run-sequence');
+var fs = require('fs');
+var sourcemaps = require('gulp-sourcemaps');
+var rename = require('gulp-rename');
+var inject = require('gulp-inject');
+var bowerFiles = require('main-bower-files');
+var cleanCSS = require('gulp-clean-css');
+var gulpNgConfig = require('gulp-ng-config');
+
+//////////////////////////////////
+// utility tasks
+//////////////////////////////////
+
+var packageJson = JSON.parse(fs.readFileSync('./package.json'));
+
+//clean distribution directory
+gulp.task('clean', function () {
+ return del(['dist', 'build']);
+});
+
+//test the quality of the code with ESLint
+gulp.task('lint', function () {
+ return gulp.src(['./app/**/*.js'])
+ .pipe(eslint())
+ .pipe(eslint.formatEach())
+ .pipe(eslint.failAfterError());
+});
+
+//////////////////////////////////
+// build tasks
+//////////////////////////////////
+
+//switch configuration based on the build profile
+gulp.task('build-config-dev', function () {
+ return gulp.src('./app/config.json')
+ .pipe(gulpNgConfig('MainModule.configuration', {
+ environment: 'development'
+ }))
+ .pipe(gulp.dest('./build/scripts'))
+});
+
+//switch configuration based on the build profile
+gulp.task('build-config-prod', function () {
+ return gulp.src('./app/config.json')
+ .pipe(gulpNgConfig('MainModule.configuration', {
+ environment: 'production'
+ }))
+ .pipe(gulp.dest('./build/scripts'))
+});
+
+//create template cache from html files
+//it creates 'templates' module and adds the cache to it
+//keys are formed as component_name/file_name.html
+gulp.task('build-template-cache', function () {
+ return gulp.src("./app/**/*.html")
+ .pipe(minifyHtml({
+ empty: true,
+ spare: true,
+ quotes: true
+ }))
+ .pipe(ngHtml2Js({
+ moduleName: 'MainModule.templates',
+ rename: function (templateUrl) {
+ var url = templateUrl.substring(templateUrl.indexOf('/') + 1);
+ return url;
+ }
+ }))
+ .pipe(concat("partials.min.js"))
+ .pipe(gulp.dest("./build/scripts"));
+});
+
+//build css from sass and compress
+gulp.task('build-sass', function () {
+ return gulp.src('./assets/sass/**/*.scss')
+ .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
+ .pipe(gulp.dest('./build/stylesheets'))
+ .pipe(sourcemaps.init())
+ .pipe(cleanCSS())
+ .pipe(rename({extname: '.min.css'}))
+ .pipe(sourcemaps.write('.'))
+ .pipe(gulp.dest('./dist/stylesheets'));
+});
+
+//build css from sass and compress for production
+//does not create map files
+gulp.task('build-sass-prod', function () {
+ return gulp.src('./assets/sass/**/*.scss')
+ .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
+ .pipe(gulp.dest('./dist/stylesheets'))
+ .pipe(cleanCSS())
+ .pipe(rename({extname: '.min.css'}))
+ .pipe(gulp.dest('./dist/stylesheets'));
+});
+
+//copy index.html to dist directory
+gulp.task('build-index', function () {
+ return gulp.src(['./index.html'])
+ .pipe(gulp.dest('dist/'))
+ .pipe(inject(gulp.src(['./scripts/*.js', './stylesheets/*.css'], {
+ read: false,
+ cwd: __dirname + '/dist'
+ }), {relative: true, addRootSlash: false}))
+ .pipe(inject(gulp.src(bowerFiles({
+ paths: {
+ bowerDirectory: 'dist/bower_components'
+ }
+ }), {read: false, cwd: __dirname + '/dist'}), {name: 'bower', relative: true}))
+ .pipe(gulp.dest('dist/'));
+});
+
+//copy assets to dist directory
+gulp.task('build-assets', function () {
+ return gulp.src(['./assets/img/**/*'])
+ .pipe(gulp.dest('dist/'));
+});
+
+//copy bower components to dist directory
+gulp.task('build-bower', function () {
+ return gulp.src(['./bower_components/**/*'])
+ .pipe(gulp.dest('dist/bower_components/'));
+});
+
+
+//build js files for development
+gulp.task('build-js-dev', function () {
+ var concatName = packageJson.name + '-' + packageJson.version + '.js';
+ return gulp.src(['./app/**/*.js', './build/scripts/*.js'])
+ .pipe(sourcemaps.init())
+ .pipe(concat(concatName))
+ .pipe(gulp.dest('build/scripts'))
+ .pipe(uglify({mangle: false}))
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(sourcemaps.write('.'))
+ .pipe(gulp.dest('dist/scripts'));
+});
+
+//build js files for production
+gulp.task('build-js-prod', function () {
+ var concatName = packageJson.name + '-' + packageJson.version + '.js';
+ return gulp.src(['./app/**/*.js', './build/scripts/*.js'])
+ .pipe(concat(concatName))
+ .pipe(gulp.dest('build/scripts'))
+ .pipe(uglify())
+ .pipe(rename({extname: '.min.js'}))
+ .pipe(gulp.dest('dist/scripts'));
+});
+
+
+//////////////////////////////////
+// watch tasks
+//////////////////////////////////
+//watch changes in the app code (html and js files)
+gulp.task('watch', function () {
+ return gulp.watch([
+ './app/**/*.js',
+ './app/**/*.html',
+ 'index.html'
+ ], ['build-dev']);
+});
+
+//watch changes in the design domain
+gulp.task('watch-des', function () {
+ return gulp.watch([
+ './app/**/*.html',
+ './assets/sass/*.less',
+ './assets/sass/*.scss',
+ './assets/sass/*.css',
+ './assets/img/*.*'
+ ], ['build-dev']);
+});
+
+//////////////////////////////////
+// global tasks
+//////////////////////////////////
+//build app for development
+gulp.task('build-dev', function (callback) {
+ runSequence('clean', 'lint', ['build-template-cache', 'build-config-dev'],
+ ['build-assets', 'build-bower', 'build-sass', 'build-js-dev'],
+ 'build-index', callback);
+});
+
+//build app for production
+gulp.task('build-prod', function (callback) {
+ runSequence('clean', 'lint', ['build-template-cache', 'build-config-prod'],
+ ['build-assets', 'build-bower', 'build-sass-prod', 'build-js-prod'],
+ 'build-index', callback);
+});
+
+//default task specification
+gulp.task('default', ['build-dev']);
+
diff --git a/pool/shard004/JavaScript/0027012_labels.test.js b/pool/shard004/JavaScript/0027012_labels.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e63232118a46f27e1ae611244162481ebfbaf96
--- /dev/null
+++ b/pool/shard004/JavaScript/0027012_labels.test.js
@@ -0,0 +1,64 @@
+const path = require('path');
+const should = require('should');
+const supertest = require('supertest');
+const sinon = require('sinon');
+const testUtils = require('../../../../utils');
+const localUtils = require('./utils');
+const config = require('../../../../../core/shared/config');
+
+let request;
+
+describe('Labels API', function () {
+ after(function () {
+ sinon.restore();
+ });
+
+ before(async function () {
+ await localUtils.startGhost();
+ request = supertest.agent(config.get('url'));
+ await localUtils.doAuth(request);
+ });
+
+ it('Errors when adding label with the same name', function () {
+ const label = {
+ name: 'test'
+ };
+
+ return request
+ .post(localUtils.API.getApiQuery(`labels/`))
+ .send({labels: [label]})
+ .set('Origin', config.get('url'))
+ .expect('Content-Type', /json/)
+ .expect('Cache-Control', testUtils.cacheRules.private)
+ .expect(201)
+ .then((res) => {
+ should.not.exist(res.headers['x-cache-invalidate']);
+ const jsonResponse = res.body;
+ should.exist(jsonResponse);
+ should.exist(jsonResponse.labels);
+ jsonResponse.labels.should.have.length(1);
+
+ jsonResponse.labels[0].name.should.equal(label.name);
+ jsonResponse.labels[0].slug.should.equal(label.name);
+ })
+ .then(() => {
+ return request
+ .post(localUtils.API.getApiQuery(`labels/`))
+ .send({labels: [label]})
+ .set('Origin', config.get('url'))
+ .expect('Content-Type', /json/)
+ .expect('Cache-Control', testUtils.cacheRules.private)
+ .expect(422);
+ })
+ .then((res) => {
+ should.not.exist(res.headers['x-cache-invalidate']);
+ const jsonResponse = res.body;
+ should.exist(jsonResponse);
+ should.exist(jsonResponse.errors);
+ jsonResponse.errors.should.have.length(1);
+
+ jsonResponse.errors[0].type.should.equal('ValidationError');
+ jsonResponse.errors[0].context.should.equal('Label already exists');
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0027013_PolylineGraphicsSpec.js b/pool/shard004/JavaScript/0027013_PolylineGraphicsSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..44088e111c0ef290853f541ec955c16dae6a5a5f
--- /dev/null
+++ b/pool/shard004/JavaScript/0027013_PolylineGraphicsSpec.js
@@ -0,0 +1,130 @@
+/*global defineSuite*/
+defineSuite([
+ 'DataSources/PolylineGraphics',
+ 'Core/Color',
+ 'DataSources/ColorMaterialProperty',
+ 'DataSources/ConstantProperty',
+ 'Specs/testDefinitionChanged',
+ 'Specs/testMaterialDefinitionChanged'
+ ], function(
+ PolylineGraphics,
+ Color,
+ ColorMaterialProperty,
+ ConstantProperty,
+ testDefinitionChanged,
+ testMaterialDefinitionChanged) {
+ 'use strict';
+
+ it('creates expected instance from raw assignment and construction', function() {
+ var options = {
+ material : Color.BLUE,
+ positions : [],
+ show : true,
+ width : 1,
+ followSurface : false,
+ granularity : 2
+ };
+
+ var polyline = new PolylineGraphics(options);
+ expect(polyline.material).toBeInstanceOf(ColorMaterialProperty);
+ expect(polyline.positions).toBeInstanceOf(ConstantProperty);
+ expect(polyline.show).toBeInstanceOf(ConstantProperty);
+ expect(polyline.width).toBeInstanceOf(ConstantProperty);
+ expect(polyline.followSurface).toBeInstanceOf(ConstantProperty);
+ expect(polyline.granularity).toBeInstanceOf(ConstantProperty);
+
+ expect(polyline.material.color.getValue()).toEqual(options.material);
+ expect(polyline.positions.getValue()).toEqual(options.positions);
+ expect(polyline.show.getValue()).toEqual(options.show);
+ expect(polyline.width.getValue()).toEqual(options.width);
+ expect(polyline.followSurface.getValue()).toEqual(options.followSurface);
+ expect(polyline.granularity.getValue()).toEqual(options.granularity);
+ });
+
+ it('merge assigns unassigned properties', function() {
+ var source = new PolylineGraphics();
+ source.material = new ColorMaterialProperty();
+ source.positions = new ConstantProperty();
+ source.width = new ConstantProperty();
+ source.show = new ConstantProperty();
+ source.followSurface = new ConstantProperty();
+ source.granularity = new ConstantProperty();
+
+ var target = new PolylineGraphics();
+ target.merge(source);
+ expect(target.material).toBe(source.material);
+ expect(target.positions).toBe(source.positions);
+ expect(target.width).toBe(source.width);
+ expect(target.show).toBe(source.show);
+ expect(target.followSurface).toBe(source.followSurface);
+ expect(target.granularity).toBe(source.granularity);
+ });
+
+ it('merge does not assign assigned properties', function() {
+ var source = new PolylineGraphics();
+ source.material = new ColorMaterialProperty();
+ source.positions = new ConstantProperty();
+ source.width = new ConstantProperty();
+ source.show = new ConstantProperty();
+ source.followSurface = new ConstantProperty();
+ source.granularity = new ConstantProperty();
+
+ var color = new ColorMaterialProperty();
+ var positions = new ConstantProperty();
+ var width = new ConstantProperty();
+ var show = new ConstantProperty();
+ var followSurface = new ConstantProperty();
+ var granularity = new ConstantProperty();
+
+ var target = new PolylineGraphics();
+ target.material = color;
+ target.positions = positions;
+ target.width = width;
+ target.show = show;
+ target.followSurface = followSurface;
+ target.granularity = granularity;
+
+ target.merge(source);
+ expect(target.material).toBe(color);
+ expect(target.positions).toBe(positions);
+ expect(target.width).toBe(width);
+ expect(target.show).toBe(show);
+ expect(target.followSurface).toBe(followSurface);
+ expect(target.granularity).toBe(granularity);
+ });
+
+ it('clone works', function() {
+ var source = new PolylineGraphics();
+ source.material = new ColorMaterialProperty();
+ source.width = new ConstantProperty();
+ source.positions = new ConstantProperty();
+ source.show = new ConstantProperty();
+ source.followSurface = new ConstantProperty();
+ source.granularity = new ConstantProperty();
+
+ var result = source.clone();
+ expect(result.material).toBe(source.material);
+ expect(result.positions).toBe(source.positions);
+ expect(result.width).toBe(source.width);
+ expect(result.show).toBe(source.show);
+ expect(result.followSurface).toBe(source.followSurface);
+ expect(result.granularity).toBe(source.granularity);
+ });
+
+ it('merge throws if source undefined', function() {
+ var target = new PolylineGraphics();
+ expect(function() {
+ target.merge(undefined);
+ }).toThrowDeveloperError();
+ });
+
+ it('raises definitionChanged when a property is assigned or modified', function() {
+ var property = new PolylineGraphics();
+ testMaterialDefinitionChanged(property, 'material', Color.RED, Color.BLUE);
+ testDefinitionChanged(property, 'show', true, false);
+ testDefinitionChanged(property, 'positions', [], []);
+ testDefinitionChanged(property, 'width', 3, 4);
+ testDefinitionChanged(property, 'followSurface', false, true);
+ testDefinitionChanged(property, 'granularity', 2, 1);
+ });
+});
diff --git a/pool/shard004/JavaScript/0027014_main.js b/pool/shard004/JavaScript/0027014_main.js
new file mode 100644
index 0000000000000000000000000000000000000000..2e28b22ca4711b6b508340d9c217f782d9b34725
--- /dev/null
+++ b/pool/shard004/JavaScript/0027014_main.js
@@ -0,0 +1,25 @@
+require(['d3', 'barChart'], function (d3, BarChart) {
+ var barChart = BarChart();
+
+ d3.tsv("../../exampleData/letterByFrequency.tsv", type, function(error, data) {
+ barChart.set({
+ xAttribute: "letter",
+ yAttribute: "frequency",
+ yAxisLabel: "Frequency",
+ data: data,
+ box: { width: 960, height: 500 }
+ });
+ setInterval(function () {
+ barChart.data = data.filter(function(){ return Math.random() < 0.5 });
+ }, 1000);
+ setInterval(function () {
+ var i = Math.floor(Math.random() * 3);
+ barChart.yAxisLabel = ["A", "B", "C"][i];
+ }, 1500);
+ });
+
+ function type(d) {
+ d.frequency = +d.frequency;
+ return d;
+ }
+});
diff --git a/pool/shard004/JavaScript/0027015_lite.js b/pool/shard004/JavaScript/0027015_lite.js
new file mode 100644
index 0000000000000000000000000000000000000000..a7b252fa43bda91e9afaf93c98512a9066b7adbe
--- /dev/null
+++ b/pool/shard004/JavaScript/0027015_lite.js
@@ -0,0 +1,27 @@
+/*
+ * Lite - a simple & light javascript template engine
+ *
+ * @version 2.0
+ * @author Mohammed Al Ashaal
+ * @copyright (c) 2015, lite.js
+ * @License MIT License
+ */
+function lite(str, args)
+{
+ // convert anything between ?> to =''?>
+ // convert anything between = ?> to "o += ;"
+ // convert anything before "" from the start to "o += ;"
+ // convert anything after "?>" from the end to "o += ;"
+ str = "var o = ''; " + str
+ .replace(/\?>([^<\?]+)<\?/g, "?> = '" + "$1" + "' ?> ")
+ .replace(/<\?=([^<\?=]+)\?>/g, "o += $1;")
+ .replace(/^([^<\?]+)<\?/g, "o += '$1'; ")
+ .replace(/([^\?>\s]+)\?>$/g, "o += '$1'; ?>")
+ .replace(/<\?|\?>/g, '') + " return o;"
+
+ for ( var k in args ) {
+ str = "var " + k + " = '" + args[k] + "'; " + str
+ }
+
+ return new Function(str)().trim();
+}
diff --git a/pool/shard004/JavaScript/0027019_global-nav-search.js b/pool/shard004/JavaScript/0027019_global-nav-search.js
new file mode 100644
index 0000000000000000000000000000000000000000..6e09db5690688f20ee4280c972d3cce1e4bc31c9
--- /dev/null
+++ b/pool/shard004/JavaScript/0027019_global-nav-search.js
@@ -0,0 +1,84 @@
+import Backbone from 'backbone';
+import React from 'react';
+import SearchView from './search-view';
+
+function contains (root, node) {
+ while (node) {
+ if (node === root) {
+ return true;
+ }
+ node = node.parentNode;
+ }
+ return false;
+}
+
+export default React.createClass({
+ getInitialState() {
+ return { open: false };
+ },
+
+ componentDidMount() {
+ key('s', () => {
+ this.openSearch();
+ return false;
+ });
+ },
+
+ componentWillUnmount() {
+ this.closeSearch();
+ key.unbind('s');
+ },
+
+ openSearch() {
+ window.addEventListener('click', this.onClickOutside);
+ this.setState({ open: true }, this.renderSearchView);
+ },
+
+ closeSearch() {
+ window.removeEventListener('click', this.onClickOutside);
+ this.resetSearchView();
+ this.setState({ open: false });
+ },
+
+ renderSearchView() {
+ let searchContainer = this.refs.container;
+ this.searchView = new SearchView({
+ model: new Backbone.Model(this.props),
+ hide: this.closeSearch
+ });
+ this.searchView.render().$el.appendTo(searchContainer);
+ },
+
+ resetSearchView() {
+ if (this.searchView) {
+ this.searchView.destroy();
+ }
+ },
+
+ onClick(e) {
+ e.preventDefault();
+ if (this.state.open) {
+ this.closeSearch();
+ } else {
+ this.openSearch();
+ }
+ },
+
+ onClickOutside(e) {
+ if (!contains(this.refs.dropdown, e.target)) {
+ this.closeSearch();
+ }
+ },
+
+ render() {
+ const dropdownClassName = 'dropdown' + (this.state.open ? ' open' : '');
+ return (
+
+
+
+
+
+
+ );
+ }
+});
diff --git a/pool/shard004/JavaScript/0027024_temperatureDeviceNodeParser_test.js b/pool/shard004/JavaScript/0027024_temperatureDeviceNodeParser_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..600482d3b5452c6be13f1e07c26b32b96d68e691
--- /dev/null
+++ b/pool/shard004/JavaScript/0027024_temperatureDeviceNodeParser_test.js
@@ -0,0 +1,44 @@
+(function() {
+ 'use strict';
+
+ describe('opentele.parserServices.temperatureDeviceNodeParser', function() {
+ var nodesParser, parserUtils, nodeMap, parseNode, node;
+
+ beforeEach(module('opentele.parserServices'));
+
+ beforeEach(inject(function(_nodesParser_, _parserUtils_) {
+ nodesParser = _nodesParser_;
+ parserUtils = _parserUtils_;
+
+ spyOn(parserUtils, 'parseSimpleInputNode').andReturn({});
+
+ node = {
+ "TemperatureDeviceNode": {
+ "nodeName": "144",
+ "next": "ANSEV_143_D142",
+ "nextFail": "AN_142_CANCEL",
+ "text": "Mål din temperatur og indtast resultatet i feltet nedenfor",
+ "temperature": {
+ "name": "144.TEMPERATURE",
+ "type": "Float"
+ }
+ }
+ };
+ nodeMap = {
+ '144': node
+ };
+
+ parseNode = function() {
+ return nodesParser.parse('144', nodeMap, {});
+ };
+ }));
+
+ it('should parse node as simple input node', function() {
+ parseNode();
+
+ expect(parserUtils.parseSimpleInputNode).toHaveBeenCalledWith(node.TemperatureDeviceNode,
+ node.TemperatureDeviceNode.temperature,
+ 'TEMPERATURE');
+ });
+ });
+}());
diff --git a/pool/shard004/JavaScript/0027026_app.js b/pool/shard004/JavaScript/0027026_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..6932b259fc78fd83d4870c55a3fa37c8d1b18468
--- /dev/null
+++ b/pool/shard004/JavaScript/0027026_app.js
@@ -0,0 +1,72 @@
+var reader = new FileReader();
+
+// Closure to capture the file information.
+// Closure to capture the file information.
+// reader.onload = (function(theFile) {
+// return function(e) {
+// console.console.log(theFile,'aaaaaaaaaa');
+// // Render thumbnail.
+// // var span = document.createElement('span');
+// // span.innerHTML = ['
'].join('');
+// // document.getElementById('list').insertBefore(span, null);
+// };
+// })("../source/test.md");
+
+// uploadData is a form element
+// fileChooser is input element of type 'file'
+var file = new File([1,11,1],"../sourece/test.md");
+
+// alternative syntax can be
+// var file = document.forms['uploadData']['fileChooser'].files.item(0);
+
+if(file)
+{
+ // Perform file ops
+ console.log(file,"ddddddddddd");
+}
+
+// var blod = new Blod();
+// console.log(blod);
+
+// Read in the image file as a data URL.
+reader.readAsText(new Blod());
+
+
+hljs.initHighlightingOnLoad();
+var articleStr;
+new Vue({
+ el: '#md-viewer',
+ data: {
+ input: '',
+ article: "### aaaa"
+ },
+ computed: {
+ compiledMarkdown: function () {
+ return marked(this.article, {
+ renderer: new marked.Renderer(),
+ gfm: true,
+ tables: true,
+ breaks: false,
+ pedantic: false,
+ sanitize: true,
+ smartLists: true,
+ smartypants: false,
+ highlight: function(code){
+ var result = hljs.highlightAuto(code,["c++"]).value;
+ console.log(result,aaaaaaaaaaaaaa);
+ return result;
+ }})
+ }
+ },
+ methods: {
+ update: _.debounce(function (e) {
+ this.input = e.target.value
+ }, 300)
+ }
+})
+
+
+function laodArticle(art){
+ articleStr = art;
+}
diff --git a/pool/shard004/JavaScript/0027027_index.js b/pool/shard004/JavaScript/0027027_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..00c0395ece547e281216fad6ffa788191459a2c3
--- /dev/null
+++ b/pool/shard004/JavaScript/0027027_index.js
@@ -0,0 +1,227 @@
+var React = require('react'),
+ StatsSection = require('./stats'),
+ UploadButton = require('./upload'),
+ Settings = require('../settings');
+
+import { OverlayTrigger, Tooltip } from 'react-bootstrap'
+
+require('./style.css')
+
+var PropertiesPane = React.createClass({
+
+ onFileChanged: function(e) {
+ var p = this.props.parent;
+
+ var i = e.target.value;
+
+ var cue = p.state.cue;
+ if(p.state.availableFiles[i].breakpoints.indexOf(cue) < 0) {
+ cue = 0;
+ }
+
+ Settings.set('file.name', p.state.availableFiles[i].fileName);
+ p.setState({filenameI: i, cue: cue});
+
+ },
+
+ onCueChange: function(e) {
+ var p = this.props.parent;
+
+ var c = e.target.value;
+ Settings.set('file.cue', c);
+ p.setState({cue: c});
+ },
+
+ render: function() {
+
+ var p = this.props.parent;
+
+ var cues = [];
+ if(p.state.filenameI < p.state.availableFiles.length) {
+ cues = p.state.availableFiles[p.state.filenameI].breakpoints;
+ }
+
+ return (
+
+
+
+ Input
+
+
+
+
+
+
+
+
+ File
+
+
+
+
+
+
+
+
+
+
+ Breakpoint
+
+
+
+
+
+ Scale
+ p.setState({scale: e.target.value*1})} />
+
+
+
+
+
+
+
+
+
+
+ {/* TODO: Hide this if the regular mode has already started */}
+
+ Preview} placement="right">
+
+
+
+
+
+
+
+
+
+ {p.state.stats? : null}
+
+
+ );
+ }
+
+});
+
+
+var Controls = React.createClass({
+
+ render: function() {
+
+ var p = this.props.parent;
+
+
+ var state = '';
+ var playing = false;
+ var allConnected = false;
+ if(p.state.stats && p.state.stats.vehicles.length >= 1) {
+ // TODO: Consider the state of all drones
+ state = p.state.stats.vehicles[0].state;
+ playing = p.state.stats.global.playing;
+
+
+ var vs = p.state.stats.vehicles;
+ allConnected = true;
+ for(var i = 0; i < vs.length; i++) {
+ if(!vs[i].connected || !vs[i].tracking) {
+ allConnected = false;
+ break;
+ }
+ }
+
+ }
+
+
+ var btns = [];
+
+ var msg = null;
+ if(state == 'init') {
+ if(!allConnected) {
+ msg = "Some vehicles not synced"
+ }
+ else {
+ btns.push(
+
+ );
+ }
+ }
+ else if(state == 'holding') {
+ btns.push(
+
+ );
+ btns.push(
+
+ );
+ }
+ else if(playing) {
+ btns.push(
+
+ );
+ btns.push(
+
+ )
+ }
+
+
+ var preButtons = null;
+ if(state == 'init' && p.state.stats.vehicles.length >= 1) {
+ preButtons = (
+
+
+ {/*
+
+
+ */}
+
+ );
+ }
+
+
+
+ return (
+
+
+ Controls
+
+
+
+ {btns.map((b, i) => React.cloneElement(b, {key: i, style: {width: (100 / btns.length) + '%'}}))}
+ {btns.length == 0? (
+
+ {msg || 'Pending...'}
+
+ ) : null}
+
+
+ {preButtons}
+
+
+
+
+ )
+
+ }
+
+
+});
+
+module.exports = PropertiesPane;
diff --git a/pool/shard004/JavaScript/0027028_regpack_test.js b/pool/shard004/JavaScript/0027028_regpack_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..ccbc1400f4eed02b35570f40f7e228baefe96747
--- /dev/null
+++ b/pool/shard004/JavaScript/0027028_regpack_test.js
@@ -0,0 +1,48 @@
+'use strict';
+
+var grunt = require('grunt');
+
+/*
+ ======== A Handy Little Nodeunit Reference ========
+ https://github.com/caolan/nodeunit
+
+ Test methods:
+ test.expect(numAssertions)
+ test.done()
+ Test assertions:
+ test.ok(value, [message])
+ test.equal(actual, expected, [message])
+ test.notEqual(actual, expected, [message])
+ test.deepEqual(actual, expected, [message])
+ test.notDeepEqual(actual, expected, [message])
+ test.strictEqual(actual, expected, [message])
+ test.notStrictEqual(actual, expected, [message])
+ test.throws(block, [error], [message])
+ test.doesNotThrow(block, [error], [message])
+ test.ifError(value)
+*/
+
+exports.regpack = {
+ setUp: function(done) {
+ // setup here if necessary
+ done();
+ },
+ default_options: function(test) {
+ test.expect(1);
+
+ var actual = grunt.file.read('tmp/default_options');
+ var expected = grunt.file.read('test/expected/default_options');
+ test.equal(actual, expected, 'should describe what the default behavior is.');
+
+ test.done();
+ },
+ custom_options: function(test) {
+ test.expect(1);
+
+ var actual = grunt.file.read('tmp/custom_options');
+ var expected = grunt.file.read('test/expected/custom_options');
+ test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');
+
+ test.done();
+ },
+};
diff --git a/pool/shard004/JavaScript/0027029_child-logger.js b/pool/shard004/JavaScript/0027029_child-logger.js
new file mode 100644
index 0000000000000000000000000000000000000000..5e3e97f2bdd1e321a99fe8d0738c7ad3beb532ce
--- /dev/null
+++ b/pool/shard004/JavaScript/0027029_child-logger.js
@@ -0,0 +1,84 @@
+
+var test = require('tape');
+
+var captureStdio = require('./lib/capture-stdio.js');
+
+var Logger = require('../logger.js');
+var ConsoleBackend = require('../backends/console.js');
+
+function createLogger() {
+ return Logger({
+ meta: {},
+ backends: {
+ console: ConsoleBackend()
+ },
+ transforms: [
+ pathPrefixTransform
+ ]
+ });
+}
+
+function pathPrefixTransform(entry) {
+ return new entry.constructor(
+ entry.level,
+ (entry.path ? entry.path + ': ' : '') + entry.message,
+ entry.meta,
+ entry.path
+ );
+}
+
+test('root logger paths', function t(assert) {
+ var logger = createLogger();
+
+ assert.ok(captureStdio('info: hello who=world', function capture() {
+ logger.info('hello', { who: 'world' });
+ }));
+
+ assert.end();
+});
+
+test('child logger path', function t(assert) {
+ var logger = createLogger();
+ var childLogger = logger.createChild('child', {info: true});
+
+ assert.ok(captureStdio('info: child: hello who=world', function t() {
+ childLogger.info('hello', { who: 'world' });
+ }));
+
+ assert.end();
+});
+
+test('child logger path', function t(assert) {
+ var logger = createLogger();
+ var childLogger = logger.createChild('child');
+ var grandchildLogger = childLogger.createChild('child');
+
+ assert.ok(captureStdio('info: child.child: hello who=world', function t() {
+ grandchildLogger.info('hello', { who: 'world' });
+ }));
+
+ assert.end();
+});
+
+test('child logger can not be constructed ' +
+ 'with duplicate path', function t(assert) {
+
+ var logger = createLogger();
+ logger.createChild('child');
+ assert.throws(function () {
+ logger.createChild('child');
+ });
+ assert.end();
+});
+
+test('child logger can not be constructed ' +
+ 'with duplicate path indirectly', function t(assert) {
+
+ var logger = createLogger();
+ logger.createChild('child.child');
+ var child = logger.createChild('child');
+ assert.throws(function () {
+ child.createChild('child');
+ });
+ assert.end();
+});
diff --git a/pool/shard004/JavaScript/0027030_index-201611022200.js b/pool/shard004/JavaScript/0027030_index-201611022200.js
new file mode 100644
index 0000000000000000000000000000000000000000..bad101fa02635938573a3111e839c821b987b415
--- /dev/null
+++ b/pool/shard004/JavaScript/0027030_index-201611022200.js
@@ -0,0 +1,147 @@
+// BART Departure Information
+
+// func to convert an XML data blob response to some query,
+// call directly from other processes as needed.
+var parseXML = function(responseXML) {
+ var response = xml2json(responseXML);
+ response = response.replace("undefined", "");
+ return JSON.parse(response).root;
+};
+
+// func for taking a data blob response for a specific station from a $.get,
+// call directly from a $.get funtion as needed.
+var processData = function(responseXML) {
+ // setTimeout(10000);
+ var response = parseXML(responseXML);
+ // console.log(response);
+ showData(response);
+ //instead of using the function I wrote, I pulled the time from the BART query.
+ // showDateTime();
+};
+
+// processStations converts the station XML data and sets showStations to the array of station information buried in the stations object.
+
+var processStations = function(responseXML) {
+ // setTimeout(5000);
+ var stations = parseXML(responseXML);
+ var stationList = stations.stations.station;
+ showStations(stationList);
+};
+
+var showData = function(response) {
+ var $departureTime = $("#departureTime");
+ var station = response.station.name;
+ console.log(response);
+ $("#station").html("Departures from " + station + " station");
+ var departures = response.station.etd;
+ console.log(departures.length);
+ var departureList = "";
+ //testing to see if departures is an array
+ var toClass = {}.toString; // (1)
+// alert( toClass.call( departures) );
+ var isArray = toClass.call(departures );
+
+
+ //test to see if variable departures is an array. If it is, step through all destinations.
+ if (isArray == "[object Array]") {
+ for (var i = 0; i < departures.length; i++) {
+ // console.log("in the loop");
+ departureList = departureList.concat("Destination: ", departures[i].destination, "
");
+ var estimateTime = departures[i].estimate;
+ // alert(toClass.call(estimateTime));
+ var estimateArray = toClass.call(estimateTime);
+ if (estimateArray=="[object Array]") {
+
+ for (var y = 0; y < estimateTime.length; y++) {
+ // console.log("estimate for loop" + estimateTime.length);
+// console.log(estimateTime[y].minutes);
+ // departureList = departureList.concat("   ", estimate[y].minutes, "  minutes
");
+ departureList = departureList.concat("   ", estimateTime[y].minutes, "  minutes
");
+// console.log("done");
+ }
+ } else {
+ departureList = departureList.concat("   ", estimateTime.minutes, "  minutes
");
+ }
+ departureList = departureList.concat("
");
+ }
+ //else is for stations that only have one destination - not an array
+ } else {
+// console.log("in else");
+ departureList = departureList.concat("Destination: ", departures.destination, "
");
+ var estimateTime = departures.estimate;
+ var estimateArray = toClass.call(estimateTime);
+ if (estimateArray=="[object Array]") {
+// console.log("estimate length T");
+ for (var y = 0; y < estimateTime.length; y++) {
+ departureList = departureList.concat("   ", estimateTime[y].minutes, "  minutes
");
+ }
+ } else {
+// console.log("estimate length null");
+ departureList = departureList.concat("   ", estimateTime.minutes, "  minutes
");
+ }
+ departureList = departureList.concat("
");
+ }
+// console.log("out");
+// console.log(departureList);
+ $("#departureTime").html(departureList);
+ $("#datetime").html(response.time);
+}; //showData
+
+var showDateTime = function() {
+ var dateTime = Date();
+ $("#datetime").html(dateTime);
+};
+
+//populate control "pick-station" with BART station names
+var showStations = function(response) {
+ var $select = $("#pick-station");
+ for (var i = 0; i < response.length; i++) {
+ var $option = $("");
+ var abbr = response[i].abbr;
+ var name = response[i].name;
+ $option.html(name);
+ $option.val(abbr);
+ //add option to select menu
+ $select.append($option);
+ // console.log(response[i].abbr);
+
+ }
+};
+
+var findDepartures = function() {
+ $("#departureTime").html("");
+ var $select = $("#pick-station");
+ var stationAbbr = $(this).val();
+ $.get({
+ url: "http://api.bart.gov/api/etd.aspx",
+ dataFormat: "xml",
+ data: {
+ cmd: "etd",
+ orig: stationAbbr,
+ key: "MW9S-E7SL-26DU-VV8V"
+ },
+ timeout: 10000,
+ success: processData
+ // success: processData.setTimeout(logConsoleA,10000)
+ // success: setTimeout(processData, 10000)
+ });
+};
+
+var logConsoleA = function() {
+ console.log("A delay");
+
+}
+
+$.get({
+ url: "http://api.bart.gov/api/stn.aspx",
+ dataFormat: "xml",
+ data: {
+ cmd: "stns",
+ key: "MW9S-E7SL-26DU-VV8V",
+ },
+ timeout: 3000,
+ success: processStations
+ // success: setTimeout(processStations, 3000)
+});
+
+$("#pick-station").change(findDepartures);
diff --git a/pool/shard004/JavaScript/0027031_casper.js b/pool/shard004/JavaScript/0027031_casper.js
new file mode 100644
index 0000000000000000000000000000000000000000..56fba29c4c7227fd358f054e82568142aa466c03
--- /dev/null
+++ b/pool/shard004/JavaScript/0027031_casper.js
@@ -0,0 +1,94 @@
+'use strict';
+
+var werker = require('werker');
+var Spooky = require('spooky');
+var URI = require('URIjs');
+
+var scan = function (target, options, done) {
+ console.log('Scanning:', target.url);
+ var spooky = new Spooky({
+ child: {
+ transport: 'http'
+ },
+ casper: {
+ logLevel: 'debug',
+ verbose: false
+ }
+ }, function (error) {
+ if (error) {
+ return;
+ }
+
+ spooky.on('error', function (error) {
+ var url = target.url;
+ var status = 0;
+ done({
+ error: {
+ code: error.code,
+ message: error.message
+ },
+ url: (new URI(url)).toString(),
+ status: status
+ });
+ });
+
+ // spooky.on('console', function (line) {
+ // console.log(line);
+ // });
+
+ // spooky.on('log', function (log) {
+ // if (log.space === 'phantom') {
+ // console.log(log.message.replace(/ \- .*/, ''));
+ // }
+ // });
+
+ // spooky.on('log', function (log) {
+ // if (log.space === 'remote') {
+ // console.log(log.message.replace(/ \- .*/, ''));
+ // }
+ // });
+
+ var timer = Date.now();
+ spooky.start(target.url);
+
+ // spooky.thenEvaluate(function () {
+ // console.log('Hello, from', document.title);
+ // });
+
+ // spooky.then(function () {
+ // // this.echo('Now, let me write something');
+ // // done(null, {
+ // // // url: url.toString(),
+ // // // status: browser.statusCode,
+ // // warnings: [],
+ // // // links: links,
+ // // // assets: assets,
+ // // // timing: Date.now() - timer
+ // // });
+ // });
+
+ spooky.on('run.complete', function () {
+ var url = target.url;
+ var status = 0;
+ var links = [];
+ var assets = [];
+ done(null, {
+ url: url,
+ status: status,
+ warnings: [],
+ links: links,
+ assets: assets,
+ timing: Date.now() - timer
+ });
+ });
+
+ spooky.on('exit', function () {
+ console.log('On exit', this === spooky);
+ });
+
+ spooky.run();
+
+ });
+};
+
+module.exports = werker.worker().method('scan', scan, true).start();
diff --git a/pool/shard004/JavaScript/0027032_index.js b/pool/shard004/JavaScript/0027032_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..8c5d8ac5c182c62d3887d0382a620ca4102a15fa
--- /dev/null
+++ b/pool/shard004/JavaScript/0027032_index.js
@@ -0,0 +1,129 @@
+/*
+ 参考文档:http://rongcloud.cn/docs/server.html#group_user_gag
+*/
+const config = require('./api.json');
+const verify = require('../verify.json');
+
+const request = require('../../request').request;
+const utils = require('../../utils');
+
+const _ = utils.underscore;
+const logger = utils.logger;
+const getError = utils.getError;
+
+const check = utils.check;
+
+let add = (group) => {
+ let conf = config.add;
+
+ let muteVerify = _.extend(_.pick(verify.group, 'groups'));
+ let error = check({
+ api: conf,
+ model: 'group',
+ data: group,
+ verify: muteVerify
+ });
+ if (error) {
+ return Promise.reject(error);
+ }
+
+ let groupIds = _.map(group.groups, (group) => {
+ return group.id;
+ });
+ return request({
+ url: conf.url,
+ data: {
+ groupId: groupIds
+ }
+ }).then(result => {
+ return result.text;
+ }).catch(error => {
+ error = getError({
+ code: error,
+ errors: conf.response.fail
+ });
+ logger.log({
+ content: error,
+ level: 'error',
+ pos: 'Group.MuteAll.add'
+ });
+ return error;
+ });
+};
+
+let remove = (group) => {
+ let conf = config.remove;
+
+ let muteVerify = _.extend(_.pick(verify.group, 'groups'));
+ let error = check({
+ api: conf,
+ model: 'group',
+ data: group,
+ verify: muteVerify
+ });
+ if (error) {
+ return Promise.reject(error);
+ }
+
+ let groupIds = _.map(group.groups, (group) => {
+ return group.id;
+ });
+
+ return request({
+ url: conf.url,
+ data: {
+ groupId: groupIds
+ }
+ }).then(result => {
+ return result.text;
+ }).catch(error => {
+ error = getError({
+ code: error,
+ errors: conf.response.fail
+ });
+ logger.log({
+ content: error,
+ level: 'error',
+ pos: 'Group.MuteAll.remove'
+ });
+ return error;
+ });
+};
+
+let getList = () => {
+ let conf = config.getList;
+ return request({
+ url: conf.url,
+ data: {}
+ }).then(result => {
+ result = utils.rename(result.text, {
+ groupinfo: 'groups'
+ });
+ let groups = result.groups || [];
+ return _.extend(result, {
+ groups: _.map(groups, (group) => {
+ return utils.rename(group, {
+ groupId: 'id',
+ stat: 'isMuted'
+ });
+ })
+ });
+ }).catch(error => {
+ error = getError({
+ code: error,
+ errors: conf.response.fail
+ });
+ logger.log({
+ content: error,
+ level: 'error',
+ pos: 'Group.MuteAll.getList'
+ });
+ return error;
+ });
+};
+
+module.exports = {
+ add: add,
+ remove: remove,
+ getList: getList
+};
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027033_learningitem.js b/pool/shard004/JavaScript/0027033_learningitem.js
new file mode 100644
index 0000000000000000000000000000000000000000..95ac977eeaf955bf058dd6f435ef484f842af227
--- /dev/null
+++ b/pool/shard004/JavaScript/0027033_learningitem.js
@@ -0,0 +1,195 @@
+/*
+ * This file is part of Totara LMS
+ *
+ * Copyright (C) 2010 onwards Totara Learning Solutions LTD
+ *
+ * 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 .
+ *
+ * @author Aaron Wells
+ * @author Eugene Venter
+ * @package totara
+ * @subpackage cohort
+ */
+/**
+ * This file contains the Javascript for the dialog that lets you add courses & programs
+ * to a cohort's enrolled learning
+ */
+
+M.totara_cohortlearning = M.totara_cohortlearning || {
+
+ Y: null,
+
+ // optional php params and defaults defined here, args passed to init method
+ // below will override these values
+ config: {},
+
+ /**
+ * module initialisation method called by php js_init_call()
+ *
+ * @param object YUI instance
+ * @param string args supplied in JSON format
+ */
+ init: function(Y, args) {
+ // save a reference to the Y instance (all of its dependencies included)
+ this.Y = Y;
+
+ // if defined, parse args into this module's config object
+ if (args) {
+ var jargs = Y.JSON.parse(args);
+ for (var a in jargs) {
+ if (Y.Object.owns(jargs, a)) {
+ this.config[a] = jargs[a];
+ }
+ }
+ }
+
+ // check jQuery dependency is available
+ if (typeof $ === 'undefined') {
+ throw new Error('M.totara_cohortlearning.init()-> jQuery dependency required for this module.');
+ }
+
+ var url = M.cfg.wwwroot + '/totara/cohort/dialog/';
+ var assgnval = this.config.assign_value ? this.config.assign_value : this.config.COHORT_ASSN_VALUE_ENROLLED;
+ var assgnstring = this.config.assign_string ? this.config.assign_string : 'enrolled';
+
+ // Init courses dialog.
+ var csaveurl = url + 'updatelearning.php?type=' + this.config.COHORT_ASSN_ITEMTYPE_COURSE + '&cohortid=' + this.config.cohortid + '&sesskey=' +
+ M.cfg.sesskey + '&v=' + assgnval + '&u=';
+ var chandler = new totaraDialog_handler_cohortlearning();
+ chandler.baseurl = url;
+ var cbuttons = {};
+ cbuttons[M.util.get_string('cancel','moodle')] = function() { chandler._cancel() }
+ cbuttons[M.util.get_string('save','totara_core')] = function() { chandler._save(csaveurl) }
+
+ totaraDialogs['learningitemcourses'] = new totaraDialog(
+ 'learningitemcourses',
+ 'add-course-learningitem-dialog',
+ {
+ buttons: cbuttons,
+ title: '' + M.util.get_string('assign'+assgnstring+'learning', 'totara_cohort') + '
'
+ },
+ url+'browselearning.php?cohortid=' + this.config.cohortid + '&v=' + assgnval + '&type=' + this.config.COHORT_ASSN_ITEMTYPE_COURSE,
+ chandler
+ );
+
+ // Init programs dialog.
+ var psaveurl = url + 'updatelearning.php?type=' + this.config.COHORT_ASSN_ITEMTYPE_PROGRAM + '&cohortid=' + this.config.cohortid + '&sesskey=' +
+ M.cfg.sesskey + '&v=' + assgnval + '&u=';
+ var phandler = new totaraDialog_handler_cohortlearning();
+ phandler.baseurl = url;
+ var pbuttons = {};
+ pbuttons[M.util.get_string('cancel','moodle')] = function() { phandler._cancel() }
+ pbuttons[M.util.get_string('save','totara_core')] = function() { phandler._save(psaveurl) }
+
+ totaraDialogs['learningitemprograms'] = new totaraDialog(
+ 'learningitemprograms',
+ 'add-program-learningitem-dialog',
+ {
+ buttons: pbuttons,
+ title: '' + M.util.get_string('assign'+assgnstring+'learning', 'totara_cohort') + '
'
+ },
+ url+'browselearning.php?cohortid=' + this.config.cohortid + '&v=' + assgnval + '&type=' + this.config.COHORT_ASSN_ITEMTYPE_PROGRAM,
+ phandler
+ );
+
+ // Init certifications dialog.
+ var pcsaveurl = url + 'updatelearning.php?type=' + this.config.COHORT_ASSN_ITEMTYPE_CERTIF + '&cohortid=' + this.config.cohortid + '&sesskey=' +
+ M.cfg.sesskey + '&v=' + assgnval + '&u=';
+ var pchandler = new totaraDialog_handler_cohortlearning();
+ pchandler.baseurl = url;
+ var pcbuttons = {};
+ pcbuttons[M.util.get_string('cancel','moodle')] = function() { pchandler._cancel() }
+ pcbuttons[M.util.get_string('save','totara_core')] = function() { pchandler._save(pcsaveurl) }
+
+ totaraDialogs['learningitemcertifications'] = new totaraDialog(
+ 'learningitemcertifications',
+ 'add-certification-learningitem-dialog',
+ {
+ buttons: pcbuttons,
+ title: '' + M.util.get_string('assign'+assgnstring+'learning', 'totara_cohort') + '
'
+ },
+ url+'browselearning.php?cohortid=' + this.config.cohortid + '&v=' + assgnval + '&type=' + this.config.COHORT_ASSN_ITEMTYPE_CERTIF,
+ pchandler
+ );
+
+ this.init_deletelisteners();
+ }, // init
+
+ init_deletelisteners: function() {
+ $('a.learning-delete').unbind('click');
+ $('a.learning-delete').bind('click', function(e, postdeletecallback) {
+ e.preventDefault();
+
+ var link = $(this);
+ var row = link.closest('tr');
+ var confirmed = confirm(M.util.get_string('deletelearningconfirm', 'totara_cohort'));
+
+ if (!confirmed) {
+ return;
+ }
+
+ $.ajax({
+ url: link.attr('href'),
+ type: "GET",
+ data: ({}),
+ beforeSend: function() {
+ var loadingimg = '
';
+ link.replaceWith(loadingimg);
+ },
+ success: function(o) {
+ row.remove();
+ },
+ error: function(h, t, e) {
+ alert(M.util.get_string('error:badresponsefromajax', 'totara_cohort'));
+ //Reload the broken page
+ location.reload();
+ }
+ }); // ajax
+
+ // Call the postdeletecallback method, if provided
+ if (postdeletecallback != undefined && postdeletecallback.object != undefined) {
+ postdeletecallback.object[postdeletecallback.method]();
+ }
+ });
+ } // init_deletelisteners
+}
+
+
+// Create handler for the dialog
+totaraDialog_handler_cohortlearning = function() {
+ // Base url
+ var baseurl = '';
+}
+
+totaraDialog_handler_cohortlearning.prototype = new totaraDialog_handler_treeview_multiselect();
+
+/**
+ * Add a row to a table on the calling page
+ * Also hides the dialog and any no item notice
+ *
+ * @param string HTML response
+ * @return void
+ */
+totaraDialog_handler_cohortlearning.prototype._update = function(response) {
+
+ // Hide dialog
+ this._dialog.hide();
+
+ //TODO: the stuff to add table rows :-P
+ if (M.totara_cohortlearning.config.saveurl) {
+ location.replace(M.cfg.wwwroot + M.totara_cohortlearning.config.saveurl + '?id=' + M.totara_cohortlearning.config.cohortid);
+ } else {
+ location.replace(M.cfg.wwwroot + '/totara/cohort/enrolledlearning.php?id=' + M.totara_cohortlearning.config.cohortid);
+ }
+}
diff --git a/pool/shard004/JavaScript/0027041_strategy.js b/pool/shard004/JavaScript/0027041_strategy.js
new file mode 100644
index 0000000000000000000000000000000000000000..f4da3cd26d6cda31c19d3098335a53003d8f4857
--- /dev/null
+++ b/pool/shard004/JavaScript/0027041_strategy.js
@@ -0,0 +1,166 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.adjustMinifyCSSOptions = exports.defaultStrategy = exports.defaultMinifyOptions = exports.defaultMinifyCSSOptions = void 0;
+///
+// Reference needed for d.ts distribution files in rollup-plugin-minify-html-literals
+const CleanCSS = require("clean-css");
+const optimization_level_1 = require("clean-css/lib/options/optimization-level");
+const html_minifier_1 = require("html-minifier");
+/**
+ * The default clean-css options, optimized for production
+ * minification.
+ */
+exports.defaultMinifyCSSOptions = {};
+/**
+ * The default html-minifier options, optimized for production
+ * minification.
+ */
+exports.defaultMinifyOptions = {
+ caseSensitive: true,
+ collapseWhitespace: true,
+ decodeEntities: true,
+ minifyCSS: exports.defaultMinifyCSSOptions,
+ minifyJS: true,
+ processConditionalComments: true,
+ removeAttributeQuotes: false,
+ removeComments: true,
+ removeEmptyAttributes: true,
+ removeScriptTypeAttributes: true,
+ removeStyleLinkTypeAttributes: true,
+ useShortDoctype: true
+};
+/**
+ * The default strategy. This uses html-minifier to minify HTML and
+ * clean-css to minify CSS.
+ */
+exports.defaultStrategy = {
+ getPlaceholder(parts) {
+ // Using @ and (); will cause the expression not to be removed in CSS.
+ // However, sometimes the semicolon can be removed (ex: inline styles).
+ // In those cases, we want to make sure that the HTML splitting also
+ // accounts for the missing semicolon.
+ const suffix = '();';
+ let placeholder = '@TEMPLATE_EXPRESSION';
+ while (parts.some(part => part.text.includes(placeholder + suffix))) {
+ placeholder += '_';
+ }
+ return placeholder + suffix;
+ },
+ combineHTMLStrings(parts, placeholder) {
+ return parts.map(part => part.text).join(placeholder);
+ },
+ minifyHTML(html, options = {}) {
+ let minifyCSSOptions;
+ if (options.minifyCSS) {
+ if (options.minifyCSS !== true &&
+ typeof options.minifyCSS !== 'function') {
+ minifyCSSOptions = { ...options.minifyCSS };
+ }
+ else {
+ minifyCSSOptions = {};
+ }
+ }
+ else {
+ minifyCSSOptions = false;
+ }
+ let adjustedMinifyCSSOptions = false;
+ if (minifyCSSOptions) {
+ adjustedMinifyCSSOptions = adjustMinifyCSSOptions(minifyCSSOptions);
+ }
+ let result = html_minifier_1.minify(html, {
+ ...options,
+ minifyCSS: adjustedMinifyCSSOptions
+ });
+ if (options.collapseWhitespace) {
+ // html-minifier does not support removing newlines inside ')
+ .css({
+ position: 'absolute',
+ visibility: 'visible',
+ left: -j*(width/cells),
+ top: -i*(height/rows)
+ })
+ .parent()
+ .addClass('ui-effects-explode')
+ .css({
+ position: 'absolute',
+ overflow: 'hidden',
+ width: width/cells,
+ height: height/rows,
+ left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0),
+ top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0),
+ opacity: o.options.mode == 'show' ? 0 : 1
+ }).animate({
+ left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)),
+ top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)),
+ opacity: o.options.mode == 'show' ? 1 : 0
+ }, o.duration || 500);
+ }
+ }
+
+ // Set a timeout, to call the callback approx. when the other animations have finished
+ setTimeout(function() {
+
+ o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide();
+ if(o.callback) o.callback.apply(el[0]); // Callback
+ el.dequeue();
+
+ $('div.ui-effects-explode').remove();
+
+ }, o.duration || 500);
+
+
+ });
+
+};
+
+})(jQuery);
diff --git a/pool/shard004/JavaScript/0027309_displayName.js b/pool/shard004/JavaScript/0027309_displayName.js
new file mode 100644
index 0000000000000000000000000000000000000000..0438e4ac1ad1232f1263fa453ba517ae3535160c
--- /dev/null
+++ b/pool/shard004/JavaScript/0027309_displayName.js
@@ -0,0 +1,32 @@
+define(function(require) {
+
+ 'use strict';
+
+
+ var forOwn = require('mout/object/forOwn');
+ var isFunction = require('mout/lang/isFunction');
+
+
+ var makeDebug = function(constructor) {
+
+ var meta = constructor._meta;
+ var proto = constructor.prototype;
+
+ forOwn(proto, function(val, key) {
+ if (isFunction(val)) {
+ val.displayName = meta.name + '#' + key;
+ }
+ });
+
+ forOwn(constructor, function(val, key) {
+ if (isFunction(val)) {
+ val.displayName = meta.name + '.' + key;
+ }
+ });
+
+ };
+
+
+ return makeDebug;
+
+});
diff --git a/pool/shard004/JavaScript/0027311_UISpec.js b/pool/shard004/JavaScript/0027311_UISpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf92e56c249667dcd631bce73b9ba487145fd0cf
--- /dev/null
+++ b/pool/shard004/JavaScript/0027311_UISpec.js
@@ -0,0 +1,51 @@
+describe( 'phoneItIn', function () {
+
+ describe( '.UI', function () {
+ var ui, domAdapter, telInput1, telInput2, actsAsLiveChangeSource;
+
+ beforeEach(function () {
+ function TelInput() {
+ this.addFocusListener = jasmine.createSpy( 'addFocusListener' );
+ this.addBlurListener = jasmine.createSpy( 'addBlurListener' );
+ this.addLiveChangeListener = jasmine.createSpy( 'addLiveChangeListener' );
+ }
+ telInput1 = new TelInput();
+ telInput2 = new TelInput();
+
+ domAdapter = {
+ inputsOfType : function () { } ,
+ newElementAdapterFor : function () { }
+ };
+
+ actsAsLiveChangeSource = {
+ extendElementAdapter: jasmine.createSpy('extendElementAdapter')
+ };
+ ui = phoneItIn.UI.create( domAdapter, actsAsLiveChangeSource );
+ });
+
+ describe( '#bindToInput', function () {
+ it( "binds to the given input element", function () {
+ var domTelInput1 = {};
+ spyOn( domAdapter, 'newElementAdapterFor' ).andReturn( telInput1 );
+ ui.bindToInput( domTelInput1 );
+ expect( actsAsLiveChangeSource.extendElementAdapter ).toHaveBeenCalledWith( telInput1 );
+ expect( telInput1.addLiveChangeListener ).toHaveBeenCalledWith( jasmine.any(Function) );
+ expect( domAdapter.newElementAdapterFor ).toHaveBeenCalledWith( domTelInput1 );
+ });
+ });
+
+ describe( '#bindToTelInputs', function () {
+ it( "binds to all 'tel' inputs on the page", function () {
+ spyOn( domAdapter, 'inputsOfType' ).andReturn([ telInput1, telInput2 ]);
+ ui.bindToTelInputs();
+ expect( domAdapter.inputsOfType ).toHaveBeenCalledWith( 'tel' );
+ // TODO: Stop redundantly testing shared functionality. Extract
+ // implementation to somewhere we can test it in isolation.
+ expect( actsAsLiveChangeSource.extendElementAdapter ).toHaveBeenCalledWith( telInput1 );
+ expect( actsAsLiveChangeSource.extendElementAdapter ).toHaveBeenCalledWith( telInput2 );
+ expect( telInput1.addFocusListener ).toHaveBeenCalledWith( jasmine.any(Function) );
+ expect( telInput2.addFocusListener ).toHaveBeenCalledWith( jasmine.any(Function) );
+ });
+ });
+ });
+});
diff --git a/pool/shard004/JavaScript/0027313_results.js b/pool/shard004/JavaScript/0027313_results.js
new file mode 100644
index 0000000000000000000000000000000000000000..63c7791832db88cda9459b71df29d1c99816a4e6
--- /dev/null
+++ b/pool/shard004/JavaScript/0027313_results.js
@@ -0,0 +1,100 @@
+angular.module('app.search.results', ['services.storage', 'services.workbench'])
+
+.config(['$routeProvider', function ($routeProvider) {
+ $routeProvider.when('/search/:query', {
+ templateUrl: 'search/results/results.tpl.html',
+ controller: 'ResultsCtrl'
+ });
+
+ $routeProvider.when('/search/bindings', {
+ templateUrl: 'search/results/results.tpl.html',
+ controller: 'ResultsCtrl'
+ });
+}])
+
+.controller('ResultsCtrl', ['$rootScope', '$scope', '$location', '$routeParams', 'entityService', 'workbenchService',
+ function ($rootScope, $scope, $location, $routeParams, entityService, workbenchService) {
+ $scope.result = [];
+
+ $scope.showCompounds = true;
+ $scope.showTargets = true;
+
+ $scope.selectedAll = false;
+
+ $scope.totalPages = 0;
+ $scope.totalElements = 0;
+ $scope.currentPage = 0;
+
+ $scope.showDetails = function(item) {
+ $location.path((item.type === 'TARGET' ? 'targets/' : 'compounds/') + item.id);
+ };
+
+ $scope.showTypes = function(item){
+ return (item.type === 'COMPOUND' && $scope.showCompounds) ||
+ (item.type === 'TARGET' && $scope.showTargets);
+ };
+
+ $scope.pageSelected = function(page) {
+ $scope.currentPage = page;
+ $scope.search($routeParams.query, page - 1);
+ };
+
+ $scope.search = function(query, page) {
+ entityService.getList({q: query, page: page}).then(function(list) {
+ angular.forEach(list, function (entity) {
+ entity.isSelected = false;
+ });
+
+ $scope.result = list;
+ $scope.totalPages = list.page.totalPages;
+ $scope.totalElements = list.page.totalElements;
+ });
+ };
+
+ $scope.allEntitiesSelected = function() {
+ var allEntitiesSelected = true;
+
+ if ($scope.result.length < 1) {
+ return false;
+ }
+
+ angular.forEach($scope.result, function(entity) {
+ allEntitiesSelected &= entity.isSelected;
+ });
+
+ return allEntitiesSelected;
+ };
+
+ $scope.selectAllChanged = function() {
+ var isSelected = !$scope.allEntitiesSelected();
+ angular.forEach($scope.result, function(entity) {
+ entity.isSelected = isSelected;
+ });
+ };
+
+ $scope.selectedEntities = function() {
+ var selectedEntities = [];
+
+ angular.forEach($scope.result, function(entity) {
+ if (entity.isSelected) {
+ selectedEntities.push(entity);
+ }
+ });
+ return selectedEntities;
+ };
+
+ $scope.addSelectionToWorkbench = function() {
+ workbenchService.add($scope.selectedEntities()).then(function() {
+ _($scope.result).each(function(entity) {
+ entity.isSelected = false;
+ });
+ });
+ };
+
+ if (!angular.isUndefined($routeParams.query) && $routeParams.query.length > 0) {
+ $rootScope.$broadcast('queryChanged', { query: $routeParams.query });
+ }
+
+ $scope.search($routeParams.query, 0);
+
+}]);
diff --git a/pool/shard004/JavaScript/0027316_clean.js b/pool/shard004/JavaScript/0027316_clean.js
new file mode 100644
index 0000000000000000000000000000000000000000..2f17a2d91f820520daa90470cc11bf992cee0391
--- /dev/null
+++ b/pool/shard004/JavaScript/0027316_clean.js
@@ -0,0 +1,13 @@
+var gulp = require('gulp');
+var del = require('del');
+var config = require('../config');
+var htmlConfig = require('../config/html');
+var iconFontConfig = require('../config/iconFont');
+
+gulp.task('clean', function(cb) {
+ del([
+ config.publicAssets,
+ htmlConfig.dest,
+ iconFontConfig.sassDest
+ ], cb);
+});
diff --git a/pool/shard004/JavaScript/0027322_Cache.platform.service.js b/pool/shard004/JavaScript/0027322_Cache.platform.service.js
new file mode 100644
index 0000000000000000000000000000000000000000..eeac3a03f7901990012cf6a0b969e2a4d91afe9a
--- /dev/null
+++ b/pool/shard004/JavaScript/0027322_Cache.platform.service.js
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import _ from 'lodash';
+
+const enumValueMapper = (val) => _.capitalize(val);
+
+const DFLT_CACHE = {
+ cacheMode: {
+ clsName: 'Apache.Ignite.Core.Cache.Configuration.CacheMode',
+ mapper: enumValueMapper
+ },
+ atomicityMode: {
+ clsName: 'Apache.Ignite.Core.Cache.Configuration.CacheAtomicityMode',
+ mapper: enumValueMapper
+ },
+ memoryMode: {
+ clsName: 'Apache.Ignite.Core.Cache.Configuration.CacheMemoryMode',
+ value: 'ONHEAP_TIERED',
+ mapper: enumValueMapper
+ },
+ atomicWriteOrderMode: {
+ clsName: 'org.apache.ignite.cache.CacheAtomicWriteOrderMode',
+ mapper: enumValueMapper
+ },
+ writeSynchronizationMode: {
+ clsName: 'org.apache.ignite.cache.CacheWriteSynchronizationMode',
+ value: 'PRIMARY_SYNC',
+ mapper: enumValueMapper
+ },
+ rebalanceMode: {
+ clsName: 'org.apache.ignite.cache.CacheRebalanceMode',
+ value: 'ASYNC',
+ mapper: enumValueMapper
+ }
+};
+
+export default class IgniteCachePlatformDefaults {
+ constructor() {
+ Object.assign(this, DFLT_CACHE);
+ }
+}
diff --git a/pool/shard004/JavaScript/0027329_app.services.js b/pool/shard004/JavaScript/0027329_app.services.js
new file mode 100644
index 0000000000000000000000000000000000000000..01cb747f19db598746574d3aa349f6f56829ad8c
--- /dev/null
+++ b/pool/shard004/JavaScript/0027329_app.services.js
@@ -0,0 +1,49 @@
+'use strict';
+
+(function (angular, buildfire) {
+ angular.module('smoochChatPluginWidget')
+ .provider('Buildfire', [function () {
+ var Buildfire = this;
+ Buildfire.$get = function () {
+ return buildfire
+ };
+ return Buildfire;
+ }])
+ .factory("DataStore", ['Buildfire', '$q', 'STATUS_CODE', 'STATUS_MESSAGES', function (Buildfire, $q, STATUS_CODE, STATUS_MESSAGES) {
+ var onUpdateListeners = [];
+ return {
+ get: function (_tagName) {
+ var deferred = $q.defer();
+ Buildfire.datastore.get(_tagName, function (err, result) {
+ if (err) {
+ return deferred.reject(err);
+ } else if (result) {
+ return deferred.resolve(result);
+ }
+ });
+ return deferred.promise;
+ },
+ onUpdate: function () {
+ var deferred = $q.defer();
+ var onUpdateFn = Buildfire.datastore.onUpdate(function (event) {
+ if (!event) {
+ return deferred.notify(new Error({
+ code: STATUS_CODE.UNDEFINED_EVENT,
+ message: STATUS_MESSAGES.UNDEFINED_EVENT
+ }), true);
+ } else {
+ return deferred.notify(event);
+ }
+ });
+ onUpdateListeners.push(onUpdateFn);
+ return deferred.promise;
+ },
+ clearListener: function () {
+ onUpdateListeners.forEach(function (listner) {
+ listner.clear();
+ });
+ onUpdateListeners = [];
+ }
+ }
+ }])
+})(window.angular, window.buildfire);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027333_form.js b/pool/shard004/JavaScript/0027333_form.js
new file mode 100644
index 0000000000000000000000000000000000000000..0adedc577924db17e502eeab4cce4746e170ec94
--- /dev/null
+++ b/pool/shard004/JavaScript/0027333_form.js
@@ -0,0 +1,251 @@
+import React from 'react';
+import validator from 'validator';
+
+import Button from '@material-ui/core/Button';
+
+export default class Form extends React.Component {
+ constructor(props, context) {
+ super(props, context);
+ this.state = { children: {}, isValid: false };
+ this.model = {};
+ this.inputs = {}; // We create a map of traversed inputs
+ }
+
+ componentDidMount() {
+ this.registerInputs(); // We register inputs from the children
+ }
+
+ componentDidUpdate(prevProps) {
+ const self = this;
+ // Use nextprops for registering components cwu
+ if (prevProps.children !== self.props.children) {
+ self.registerInputs();
+ }
+ }
+
+ registerInputs() {
+ const self = this;
+ self.setState({ newChildren: React.Children.map(self.props.children, child => self._cloneChild(child, self)) });
+ }
+
+ // eslint-disable-next-line consistent-this
+ _cloneChild(child, self) {
+ // If we use the required prop we add a validation rule
+ // that ensures there is a value. The input
+ // should not be valid with empty value
+ if (typeof child?.type === 'undefined') {
+ return child;
+ }
+ var props = child.props || {};
+ var validations = props.validations || '';
+ if (props.required && validations.indexOf('isLength') == -1) {
+ validations = validations ? `${validations}, ` : validations;
+ validations += 'isLength:1';
+ }
+ return React.cloneElement(child, {
+ validations: validations,
+ attachToForm: self.attachToForm.bind(self),
+ detachFromForm: self.detachFromForm.bind(self),
+ updateModel: self.updateModel.bind(self),
+ validate: self.validate.bind(self),
+ hideHelp: self.props.hideHelp,
+ handleKeyPress: self._handleKeyPress.bind(self)
+ });
+ }
+
+ tryApplyValidations(value, validations, initialValidationResult) {
+ return validations.split(',').reduce((accu, validation) => {
+ if (!accu.isValid) {
+ return accu;
+ }
+ var args = validation.split(':');
+ var validateMethod = args.shift();
+ // We use JSON.parse to convert the string values passed to the
+ // correct type. Ex. 'isLength:1' will make '1' actually a number
+ args = args.map(arg => JSON.parse(JSON.stringify(arg)));
+
+ var tmpArgs = args;
+ // We then merge two arrays, ending up with the value
+ // to pass first, then options, if any. ['valueFromInput', 5]
+ args = [value].concat(args);
+ try {
+ // So the next line of code is actually:
+ // validator.isLength('valueFromInput', 5)
+ if (!validator[validateMethod].apply(validator, args)) {
+ return { errortext: this.getErrorMsg(validateMethod, tmpArgs), isValid: false };
+ }
+ } catch {
+ const errortext = this.getErrorMsg(validateMethod, args) || '';
+ return { errortext, isValid: !errortext };
+ }
+ return accu;
+ }, initialValidationResult);
+ }
+
+ validate(component, value) {
+ if (!component.props.validations) {
+ return;
+ }
+
+ var isValid = true;
+ var errortext = '';
+
+ if (component.props.file) {
+ if (component.props.required && !value) {
+ isValid = false;
+ errortext = 'You must choose a file to upload';
+ }
+ } else if (component.props.id && component.props.id.substr(0, 8) === 'password') {
+ if (component.props.required && !value) {
+ isValid = false;
+ errortext = 'Password is required';
+ } else {
+ isValid = this.tryApplyValidations(value, component.props.validations, { isValid, errortext }).isValid;
+ errortext = !isValid ? 'Password too weak' : errortext;
+ }
+ } else {
+ if (value || component.props.required) {
+ const { isValid: appliedValid, errortext: appliedError } = this.tryApplyValidations(value, component.props.validations, { isValid, errortext });
+ isValid = appliedValid;
+ errortext = appliedError;
+ }
+ }
+
+ // Now we set the state of the input based on the validation
+ component.setState(
+ {
+ isValid: isValid,
+ errortext: errortext
+ // We use the callback of setState to wait for the state
+ // change being propagated, then we validate the form itself
+ },
+ this.validateForm.bind(this)
+ );
+ }
+
+ getErrorMsg(validateMethod, args) {
+ switch (validateMethod) {
+ case 'isLength':
+ if (args[0] === 1) {
+ return 'This field is required';
+ } else if (args[0] > 1) {
+ return `Must be at least ${args[0]} characters long`;
+ }
+ break;
+ case 'isAlpha':
+ return 'This field must contain only letters';
+ case 'isAlphanumeric':
+ return 'This field must contain only letters or numbers';
+ case 'isNumeric':
+ return 'Please enter a valid code';
+ case 'isEmail':
+ return 'Please enter a valid email address';
+ case 'isNot':
+ if (args[0] === args[1]) {
+ return `This field should have a value other than ${args[0]}`;
+ }
+ break;
+ default:
+ return 'There is an error with this field';
+ }
+ }
+
+ validateForm() {
+ // We set allIsValid to true and flip it if we find any
+ // invalid input components
+ var allIsValid = true;
+
+ // Now we run through the inputs registered and flip our state
+ // if we find an invalid input component
+ var inputs = this.inputs;
+ Object.keys(inputs).forEach(name => {
+ if (!inputs[name].state.isValid || (inputs[name].props.required && !inputs[name].state.value)) {
+ allIsValid = false;
+ }
+ });
+
+ // And last, but not least, we set the valid state of the
+ // form itself
+ this.setState({
+ isValid: allIsValid
+ });
+ }
+
+ // All methods defined are bound to the component by React JS, so it is safe to use "this"
+ // even though we did not bind it. We add the input component to our inputs map
+ attachToForm(component) {
+ this.inputs[component.props.id] = component;
+ this.model[component.props.id] = component.state.value || component.state.checked;
+
+ // We have to validate the input when it is attached to put the
+ // form in its correct state
+ //this.validate(component);
+ }
+
+ // We want to remove the input component from the inputs map
+ detachFromForm(component) {
+ delete this.inputs[component.props.id];
+ delete this.model[component.props.id];
+ }
+ updateModel() {
+ Object.keys(this.inputs).forEach(name => {
+ // re validate each input in case submit button pressed too soon
+ this.validate(this.inputs[name], this.inputs[name].state.value);
+ });
+
+ this.validateForm();
+ Object.keys(this.inputs).forEach(id => {
+ this.model[id] = this.inputs[id].state.value || this.inputs[id].state.checked;
+ });
+ if (this.state.isValid) {
+ this.props.onSubmit(this.model);
+ }
+ }
+ _handleKeyPress(event) {
+ event.stopPropagation();
+ if (event.key === 'Enter' && this.state.isValid) {
+ this.updateModel();
+ }
+ }
+
+ onSubmit(event) {
+ event.preventDefault();
+ }
+
+ render() {
+ var uploadActions = !!this.props.showButtons && (
+
+ {!!this.props.handleCancel && (
+
+ )}
+
+
+ );
+
+ return (
+
+ );
+ }
+}
diff --git a/pool/shard004/JavaScript/0027334_User.js b/pool/shard004/JavaScript/0027334_User.js
new file mode 100644
index 0000000000000000000000000000000000000000..2666f73f9f089cd46ccf0b008ea0665ece599b6e
--- /dev/null
+++ b/pool/shard004/JavaScript/0027334_User.js
@@ -0,0 +1,35 @@
+export default class User {
+
+ constructor(user) {
+ this.token = user.token;
+ this.uid = user.uid;
+ this.name = user.name || user.displayName || user.email;
+ this.photoURL = user.photoURL || '/static/img/user_icon.svg';
+ this.email = user.email;
+ this.phoneNumber = user.phoneNumber;
+ this.birthDate = user.birthDate;
+ this.cpf = user.cpf;
+ this.providerId = user.providerId;
+ }
+
+ clone() {
+ return new User(this);
+ }
+
+ static n(mod) {
+ return Math.floor(Math.random() * 1984 * 12 * 6 * 4) % (mod);
+ }
+
+ static sample(commingFrom) {
+ const token = `${this.n(9999)}-${commingFrom}-${this.n(99999)}`;
+ return new User({
+ token,
+ name: 'Gabriel Lucas de Toledo Ribeiro',
+ photoURL: '/static/img/user.jpg',
+ email: 'gltr@pluralsolutions.com.br',
+ phoneNumber: '(11) 98181-5555',
+ birthDate: '06/12/1984',
+ cpf: '11111111111',
+ });
+ }
+}
diff --git a/pool/shard004/JavaScript/0027335_index.js b/pool/shard004/JavaScript/0027335_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..cda3cb1cc20a92a3b8b94b693702e4932f814b8e
--- /dev/null
+++ b/pool/shard004/JavaScript/0027335_index.js
@@ -0,0 +1,26 @@
+
+var assert = require('assert');
+var Todo = require('./todo');
+
+var todo = new Todo();
+var testsCompleted = 0;
+
+
+function deleteTest() {
+ todo.add('Delete Me');
+ assert.equal(todo.getCount(), 1, '1 item should exist');
+ todo.deleteAll();
+ assert.equal(todo.getCount(), 0, 'No items should exist');
+ testsCompleted++;
+}
+
+
+function addTest() {
+ todo.deleteAll();
+ todo.add('Added');
+ assert.notEqual(todo.getCount(), 0, '1 item should exist');
+ testsCompleted++;
+}
+
+deleteTest();
+addTest();
diff --git a/pool/shard004/JavaScript/0027336_app.js b/pool/shard004/JavaScript/0027336_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..f89edbc3a2771f66b55e6845db8b70bb72e574f3
--- /dev/null
+++ b/pool/shard004/JavaScript/0027336_app.js
@@ -0,0 +1,98 @@
+var express = require('express');
+var path = require('path');
+var favicon = require('static-favicon');
+var logger = require('morgan');
+var cookieParser = require('cookie-parser');
+var bodyParser = require('body-parser');
+var session = require('express-session');
+
+var routes = require('./routes/index');
+var users = require('./routes/users');
+
+var passport = require('passport');
+var CasStrategy = require('passport-cas-strategy').Strategy;
+
+passport.use(new CasStrategy({
+ postRedirect : true,
+ casServiceUrl : 'https://172.17.1.36:18443/cas', // "https://10.49.128.21:8443/cas/login"
+ serviceBaseUrl: 'http://localhost:3000',
+ validateMethod: 'serviceValidate', // ['validate', 'proxyValidate', 'serviceValidate']
+ passReqToCallback: true,
+ pgtUrl: 'https://172.17.1.36:18443/yukon-security-cas-pgt-web/proxyGrantingTicketCallback'
+ }, function(req, data, done) {
+ var user = {'email': data.user};
+ console.log(user);
+ return done(null, user, data);
+ }
+));
+
+var app = express();
+
+// view engine setup
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'jade');
+
+app.use(favicon());
+app.use(logger('dev'));
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded());
+app.use(cookieParser());
+app.use(express.static(path.join(__dirname, 'public')));
+app.use(session({secret: '1234567890QWERTY'}));
+
+var users = {};
+passport.serializeUser(function(user, done) {
+ users[user.id] = user;
+ done(null, user);
+});
+
+passport.deserializeUser(function(user, done) {
+ done(null, users[user.id]);
+});
+
+app.use(passport.initialize());
+app.use(passport.session());
+
+app.get('/login', passport.authenticate('cas', { successRedirect: '/',
+ failureRedirect: '/login' }));
+
+app.post('/login', passport.authenticate('cas', { successRedirect: '/',
+ failureRedirect: '/login' }));
+
+
+app.get('/', function(req, res) {
+ res.send('HOME PAGE:' + req.user.email);
+});
+
+/// catch 404 and forward to error handler
+app.use(function(req, res, next) {
+ var err = new Error('Not Found');
+ err.status = 404;
+ next(err);
+});
+
+// error handlers
+
+// development error handler
+// will print stacktrace
+if (app.get('env') === 'development') {
+ app.use(function(err, req, res, next) {
+ res.status(err.status || 500);
+ res.render('error', {
+ message: err.message,
+ error: err
+ });
+ });
+}
+
+// production error handler
+// no stacktraces leaked to user
+app.use(function(err, req, res, next) {
+ res.status(err.status || 500);
+ res.render('error', {
+ message: err.message,
+ error: {}
+ });
+});
+
+module.exports = app;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027338_index-test.js b/pool/shard004/JavaScript/0027338_index-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..2524e3c59a258b2509f9a9e955ef447b99ad7604
--- /dev/null
+++ b/pool/shard004/JavaScript/0027338_index-test.js
@@ -0,0 +1,40 @@
+var vows = require('vows');
+var assert = require('assert');
+var util = require('util');
+var oauthorize = require('index');
+var Server = require('server');
+
+
+vows.describe('oauthorize').addBatch({
+
+ 'should export functions': function () {
+ assert.isFunction(oauthorize.createServer);
+ assert.isFunction(oauthorize.createServiceProvider);
+ assert.strictEqual(oauthorize.createServer, oauthorize.createServiceProvider);
+ },
+
+ 'should export module function': function () {
+ assert.strictEqual(oauthorize, oauthorize.createServer);
+ },
+
+ 'should export middleware': function () {
+ assert.isFunction(oauthorize.requestToken);
+ assert.isFunction(oauthorize.accessToken);
+ },
+
+ 'should export errors': function () {
+ assert.isFunction(oauthorize.AuthorizationError);
+ assert.isFunction(oauthorize.BadRequestError);
+ },
+
+ 'createServer': {
+ topic: function() {
+ return oauthorize.createServer();
+ },
+
+ 'should return a Server' : function(s) {
+ assert.instanceOf(s, Server);
+ },
+ },
+
+}).export(module);
diff --git a/pool/shard004/JavaScript/0027339_label-common.js b/pool/shard004/JavaScript/0027339_label-common.js
new file mode 100644
index 0000000000000000000000000000000000000000..aa3c87b03cc001338b7bb86e73423aec36c3f547
--- /dev/null
+++ b/pool/shard004/JavaScript/0027339_label-common.js
@@ -0,0 +1,28 @@
+var __extends = this.__extends || function (d, b) {
+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+ function __() { this.constructor = d; }
+ __.prototype = b.prototype;
+ d.prototype = new __();
+};
+var dependencyObservable = require("ui/core/dependency-observable");
+var proxy = require("ui/core/proxy");
+var textBase = require("ui/text-base");
+var Label = (function (_super) {
+ __extends(Label, _super);
+ function Label(options) {
+ _super.call(this, options);
+ }
+ Object.defineProperty(Label.prototype, "textWrap", {
+ get: function () {
+ return this._getValue(Label.textWrapProperty);
+ },
+ set: function (value) {
+ this._setValue(Label.textWrapProperty, value);
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Label.textWrapProperty = new dependencyObservable.Property("textWrap", "Label", new proxy.PropertyMetadata(false, dependencyObservable.PropertyMetadataSettings.AffectsLayout));
+ return Label;
+})(textBase.TextBase);
+exports.Label = Label;
diff --git a/pool/shard004/JavaScript/0027340_usersRoute.js b/pool/shard004/JavaScript/0027340_usersRoute.js
new file mode 100644
index 0000000000000000000000000000000000000000..4194f647c5022b59233e596e80352f94a5a08830
--- /dev/null
+++ b/pool/shard004/JavaScript/0027340_usersRoute.js
@@ -0,0 +1,66 @@
+import express from 'express'
+import userController from '../controllers/userController'
+import {postArticle} from '../controllers/blogController'
+import {postSubscription} from '../controllers/subscriptionController'
+import {
+ addTags,
+ makePrivate,
+ getStream,
+ postContent,
+ getContent,
+ postFlag,
+ editContent,
+ deleteContent,
+ deleteTag,
+ shareByEmail
+} from '../controllers/contentController'
+import {getEvents} from '../controllers/eventController'
+
+// const {SECRET_TOKEN} = process.env
+
+const router = new express.Router()
+
+/* User */
+router.route('/session')
+ .post( userController.login )
+router.route('/user')
+ .post( userController.signUp )
+ .delete( userController.checkAuthorization, userController.deleteUser )
+router.route('/user/me')
+ .get( userController.checkAuthorization, userController.getUser )
+router.route( '/password/reset' )
+ .get( userController.sendPasswordReset )
+router.route( '/password/change' )
+ .post( userController.checkAuthorization, userController.changePassword )
+router.route('/stream/:stream/content')
+ .post( userController.checkAuthorization, ( req, res ) => (
+ req.body.format === "read" ? postArticle( req, res ) : postContent( req, res )
+ ))
+
+/* Content */
+router.route('/content/:content/tag')
+ .post( userController.checkAuthorization, addTags )
+ .delete( userController.checkAuthorization, deleteTag )
+router.route( '/content/private' )
+ .post( userController.checkAuthorization, makePrivate )
+router.route( '/content/share' )
+ .post( userController.checkAuthorization, shareByEmail )
+router.route( '/content/:content' )
+ .post( userController.checkAuthorization, editContent )
+router.route( '/content/flag' )
+ .post( userController.checkAuthorization, postFlag )
+router.route('/stream/:stream/content')
+ .get(getStream)
+
+/* Events */
+router.route('/event')
+ .get(getEvents)
+
+router.route( '/content/:slug')
+ .get( getContent )
+ .delete( userController.checkAuthorization, deleteContent)
+
+router.route('/subscription')
+ .post(postSubscription)
+
+module.exports = router
diff --git a/pool/shard004/JavaScript/0027342_throttle.js b/pool/shard004/JavaScript/0027342_throttle.js
new file mode 100644
index 0000000000000000000000000000000000000000..cc3ef160030115fb0dc4adf546d9f758b2b93d05
--- /dev/null
+++ b/pool/shard004/JavaScript/0027342_throttle.js
@@ -0,0 +1,177 @@
+
+/**
+ * Module dependencies.
+ */
+
+var fs = require('fs');
+var assert = require('assert');
+var Throttle = require('../');
+var inherits = require('util').inherits;
+var Readable = require('stream').Readable;
+
+// node v0.8.x compat
+if (!Readable) Readable = require('readable-stream');
+
+// Readable stream impl that outputs random data very quickly
+function Random (n) {
+ Readable.call(this);
+ this.remaining = +n;
+}
+inherits(Random, Readable);
+Random.prototype._read = function (n, cb) {
+ if ('function' != typeof cb) cb = function (e, b) { this.push(b); }.bind(this);
+ n = Math.min(this.remaining, n);
+ this.remaining -= n;
+ var chunk = null;
+ if (n > 0) {
+ chunk = new Buffer(n);
+ }
+ cb(null, chunk);
+};
+
+// Readable stream impl that outputs random data with a 100 ms delay per byte
+function Slow (n) {
+ Readable.call(this);
+ this.remaining = +n;
+}
+inherits(Slow, Readable);
+Slow.prototype._read = function (n, cb) {
+ if ('function' != typeof cb) cb = function (e, b) { this.push(b); }.bind(this);
+ n = 1;
+ this.remaining -= n;
+ if (this.remaining >= 0) {
+ setTimeout(cb.bind(null, null, new Buffer(n)), 100);
+ } else {
+ cb(null, null); // emit "end"
+ }
+};
+
+
+
+describe('Throttle', function () {
+
+ this.slow(8000);
+ this.timeout(10000);
+
+ it('should take ~1 second to read 10,000 bytes at 10000bps', function (done) {
+ var r = new Random(10000);
+ var t = new Throttle(10000);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 1000);
+ assert.equal(10000, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should take ~1 second to read 1,024 bytes at 1024bps', function (done) {
+ var r = new Random(1024);
+ var t = new Throttle(1024);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 1000);
+ assert.equal(1024, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should take ~2 seconds to read 2 megabytes at 1mb/s', function (done) {
+ var mb = 1048576;
+ var r = new Random(2 * mb);
+ var t = new Throttle(1 * mb);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 2000);
+ assert.equal(2 * mb, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should take ~3 seconds to read 15 megabytes at 5mb/s', function (done) {
+ var mb = 1048576;
+ var r = new Random(15 * mb);
+ var t = new Throttle(5 * mb);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 3000);
+ assert.equal(15 * mb, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should take ~500ms to read 100 bytes at 200 bps', function (done) {
+ var r = new Random(100);
+ var t = new Throttle(200);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 500);
+ assert.equal(100, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should take ~3 seconds to read 3 bytes at 1 bps', function (done) {
+ var r = new Random(3);
+ var t = new Throttle(1);
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 3000);
+ assert.equal(3, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+ it('should work as expected with a slow readable', function (done) {
+ var r = new Slow(10); // should take ~1 second
+ var t = new Throttle(100); // ~10x faster than the slow stream
+ var start = Date.now();
+ var bytes = 0;
+ t.on('data', function (data) {
+ bytes += data.length;
+ });
+ t.on('end', function () {
+ assertTimespan(start, new Date(), 1000);
+ assert.equal(10, bytes);
+ done();
+ });
+ r.pipe(t);
+ });
+
+});
+
+function assertTimespan (start, end, expected, tolerance) {
+ if (null == tolerance) tolerance = 90;
+ var diff = end - start;
+ var delta = expected - diff;
+ assert(Math.abs(delta) < tolerance, 'tolerance of ' + tolerance + ', got ' + delta);
+}
diff --git a/pool/shard004/JavaScript/0027343_cache-json.js b/pool/shard004/JavaScript/0027343_cache-json.js
new file mode 100644
index 0000000000000000000000000000000000000000..7395c24b412a88e235a932bcc57160374084a1c1
--- /dev/null
+++ b/pool/shard004/JavaScript/0027343_cache-json.js
@@ -0,0 +1,41 @@
+var fs = require('fs'),
+ path = require('path'),
+ util = require('util'),
+
+ _ = require('lodash');
+
+/**
+ * @class JSONCache
+ * @constructor
+ */
+function JSONCache() {
+
+ /**
+ *
+ * @param {*} data
+ * @param [options]
+ * @param [options.dir] absolute path directory to save JSON file
+ * @param [options.name] the name of the JSON file
+ */
+ this.save = function (data, options) {
+ var _options = _.defaults(options, {
+ dir: path.resolve(process.cwd(), '/data'),
+ name: 'cache'
+ });
+ var filename = util.format('%s.json', _options.name);
+ var content = JSON.stringify(data);
+
+ return new Promise(function (resolve, reject) {
+ fs.writeFile(path.join(_options.dir, filename), content, function (err) {
+ if (err) {
+ reject(err);
+ return;
+ }
+
+ resolve();
+ });
+ })
+ }
+}
+
+module.exports = JSONCache;
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027345_xdm.js b/pool/shard004/JavaScript/0027345_xdm.js
new file mode 100644
index 0000000000000000000000000000000000000000..970b55ad85b94355c627e1fb3ea1441e7ea34657
--- /dev/null
+++ b/pool/shard004/JavaScript/0027345_xdm.js
@@ -0,0 +1,24 @@
+
+ Q.Ready(function() {
+ var a = new easyXDM.Rpc(
+ {
+ local: "/qlib/thirdparty/easyXDM-2-4-17-1/name.html",
+ swf: "/qlib/thirdparty/easyXDM-2-4-17-1/easyxdm.swf"
+ },
+ {
+ local: {
+ request: function(a, b, c) {
+ //var d = a.method || "get";
+ //d.toLowerCase(),
+ a.oncomplete = b,
+ a.onerror = c;
+ Q.Ajax(a);
+ }
+ },
+
+ serializer: {
+ parse: Q.json_decode,
+ stringify: Q.json_encode
+ }
+ });
+});
diff --git a/pool/shard004/JavaScript/0027347_webpack.base.conf.js b/pool/shard004/JavaScript/0027347_webpack.base.conf.js
new file mode 100644
index 0000000000000000000000000000000000000000..fa88b79b4215ae0aa7fe0de28cff66327a21479f
--- /dev/null
+++ b/pool/shard004/JavaScript/0027347_webpack.base.conf.js
@@ -0,0 +1,70 @@
+var path = require('path')
+var utils = require('./utils')
+var config = require('../config')
+var vueLoaderConfig = require('./vue-loader.conf')
+
+function resolve (dir) {
+ return path.join(__dirname, '..', dir)
+}
+
+module.exports = {
+ entry: {
+ app: './src/main.js'
+ },
+ output: {
+ path: config.build.assetsRoot,
+ filename: '[name].js',
+ publicPath: process.env.NODE_ENV === 'production'
+ ? config.build.assetsPublicPath
+ : config.dev.assetsPublicPath
+ },
+ resolve: {
+ extensions: ['.js', '.vue', '.json'],
+ alias: {
+ '@': resolve('src'),
+ 'common': resolve('src/common'),
+ 'components': resolve('src/components'),
+ 'api': resolve('src/api'),
+ 'base': resolve('src/base')
+ }
+ },
+ module: {
+ rules: [
+ {
+ test: /\.(js|vue)$/,
+ loader: 'eslint-loader',
+ enforce: 'pre',
+ include: [resolve('src'), resolve('test')],
+ options: {
+ formatter: require('eslint-friendly-formatter')
+ }
+ },
+ {
+ test: /\.vue$/,
+ loader: 'vue-loader',
+ options: vueLoaderConfig
+ },
+ {
+ test: /\.js$/,
+ loader: 'babel-loader',
+ include: [resolve('src'), resolve('test')]
+ },
+ {
+ test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
+ loader: 'url-loader',
+ options: {
+ limit: 10000,
+ name: utils.assetsPath('img/[name].[hash:7].[ext]')
+ }
+ },
+ {
+ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
+ loader: 'url-loader',
+ options: {
+ limit: 10000,
+ name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
+ }
+ }
+ ]
+ }
+}
diff --git a/pool/shard004/JavaScript/0027348_implementation.js b/pool/shard004/JavaScript/0027348_implementation.js
new file mode 100644
index 0000000000000000000000000000000000000000..04149012bf742c6c4bd69a4971c40ca346c3eedf
--- /dev/null
+++ b/pool/shard004/JavaScript/0027348_implementation.js
@@ -0,0 +1,249 @@
+/* eslint-disable object-shorthand */
+
+// Get various parts of the WebExtension framework that we need.
+var { ExtensionCommon } = ChromeUtils.import("resource://gre/modules/ExtensionCommon.jsm");
+
+// You probably already know what this does.
+var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+// Compare semver versions 'x.y.z' (only numbers)
+function compareVersion(v1, v2) {
+ if (typeof v1 !== 'string') return false;
+ if (typeof v2 !== 'string') return false;
+ v1 = v1.split('.');
+ v2 = v2.split('.');
+ const commonPartsLength = Math.min(v1.length, v2.length);
+ for (let i = 0; i < commonPartsLength; ++ i) {
+ v1[i] = parseInt(v1[i], 10) || 0;
+ v2[i] = parseInt(v2[i], 10) || 0;
+ if (v1[i] > v2[i]) return 1;
+ if (v1[i] < v2[i]) return -1;
+ }
+ return v1.length == v2.length ? 0 : (v1.length < v2.length ? -1 : 1);
+}
+
+// This is the important part. It implements the functions and events defined in schema.json.
+// The variable must have the same name you've been using so far, "myapi" in this case.
+var compose_ext = class extends ExtensionCommon.ExtensionAPI {
+ getAPI(context) {
+ let { extension } = context;
+ let { tabManager, windowManager } = extension;
+ async function getTabWindow(tabId){
+ return (await tabManager.get(tabId)).nativeTab;
+ }
+
+ function ThunderbirdVersionGreaterOrEqual(otherVersion){
+ return compareVersion(Services.appinfo.version, otherVersion) >= 0;
+ }
+
+ return {
+ // Again, this key must have the same name.
+ compose_ext: {
+
+ getCurrentLanguage: async function(tabId) {
+ return (await getTabWindow(tabId)).document.documentElement.getAttribute("lang");
+ },
+
+ canSpellCheck: async function(tabId) {
+ var window = await getTabWindow(tabId);
+ if(ThunderbirdVersionGreaterOrEqual('89')) return true;
+ return window.gSpellChecker && window.gSpellChecker.canSpellCheck && window.gSpellChecker.enabled;
+ },
+
+ setSpellCheckerLanguage: async function(tabId, lang) {
+ var window = await getTabWindow(tabId);
+ var fake_event = {
+ target: {
+ value: lang
+ },
+ stopPropagation: function(){}
+ };
+ return window.ChangeLanguage(fake_event);
+ },
+
+ showNotification: async function(tabId, string, options){
+ options = options || {};
+ var window = await getTabWindow(tabId);
+ var notification_value = "show-message";
+ let nb = (window.gNotification && window.gNotification.notificationbox) || window.gComposeNotification;
+ var n = nb.getNotificationWithValue(notification_value);
+ if(n) {
+ n.label = string;
+ } else {
+ var buttons = options.buttons || [];
+ var priority = nb.PRIORITY_INFO_HIGH;
+ if(ThunderbirdVersionGreaterOrEqual('94')){
+ n = nb.appendNotification(
+ notification_value,
+ {
+ image: options.logo_url,
+ priority: priority,
+ label: string
+ },
+ buttons);
+ }else
+ n = nb.appendNotification(string, notification_value, options.logo_url, priority, buttons);
+ }
+ // setup timeout
+ if (options.notification_time) {
+ if(this.label_timeout){
+ window.clearTimeout(this.label_timeout);
+ }
+ this.label_timeout = window.setTimeout( function(){
+ nb.removeNotification( n );
+ }, options.notification_time);
+ }
+ },
+
+ // An event. Most of this is boilerplate you don't need to worry about, just copy it.
+ onLanguageChange: new ExtensionCommon.EventManager({
+ context,
+ name: "compose_ext.onLanguageChange",
+ // In this function we add listeners for any events we want to listen to, and return a
+ // function that removes those listeners. To have the event fire in your extension,
+ // call fire.async.
+ register(fire) {
+ function callback(event_name, event, language) {
+ let win = windowManager.wrapWindow(event.target.ownerGlobal);
+ var tab = tabManager.convert(win.activeTab.nativeTab);
+ return fire.async(tab.id, language);
+ }
+
+ windowListener.add(callback);
+ return function() {
+ windowListener.remove(callback);
+ };
+ },
+ }).api(),
+
+ onRecipientsChange: new ExtensionCommon.EventManager({
+ context,
+ name: "compose_ext.onRecipientsChange",
+ // In this function we add listeners for any events we want to listen to, and return a
+ // function that removes those listeners. To have the event fire in your extension,
+ // call fire.async.
+ register(fire) {
+ function callback(event_name, event) {
+ let win = windowManager.wrapWindow(event.target.ownerGlobal);
+ var tab = tabManager.convert(win.activeTab.nativeTab);
+ return fire.async(tab.id);
+ }
+
+ recipientsChangeWindowListener.add(callback);
+ return function() {
+ recipientsChangeWindowListener.remove(callback);
+ };
+ },
+ }).api(),
+
+ },
+ };
+ }
+};
+
+// A helpful class for listening to windows opening and closing.
+// (This file had a lowercase E in Thunderbird 65 and earlier.)
+var { ExtensionSupport } = ChromeUtils.import("resource:///modules/ExtensionSupport.jsm");
+
+// This object is just what we're using to listen for toolbar clicks. The implementation isn't
+// what this example is about, but you might be interested as it's a common pattern. We count the
+// number of callbacks waiting for events so that we're only listening if we need to be.
+var windowListener = new class extends ExtensionCommon.EventEmitter {
+ constructor() {
+ super();
+ this.callbackCount = 0;
+ }
+
+ handleEvent(event) {
+ var lang = event.target.getAttribute('lang');
+ windowListener.emit("language-changed", event, lang);
+ }
+
+ add(callback) {
+ this.on("language-changed", callback);
+ this.callbackCount++;
+
+ if (this.callbackCount == 1) {
+ ExtensionSupport.registerWindowListener("compose_ext-windowListener", {
+ chromeURLs: ["chrome://messenger/content/messengercompose/messengercompose.xhtml"],
+ onLoadWindow: function(window) {
+ windowListener.subscribeLanguageChangeEvents(window);
+ },
+ });
+ }
+ }
+
+ remove(callback) {
+ this.off("language-changed", callback);
+ this.callbackCount--;
+
+ if (this.callbackCount == 0) {
+ ExtensionSupport.unregisterWindowListener("compose_ext-windowListener");
+ }
+ }
+
+ subscribeLanguageChangeEvents(window) {
+ //We don't capture "spellcheck-changed" event because it's only fired
+ //when language is changed in the context menu (rigt click menu). Not when changed
+ //from any other source.
+
+ // The document lang attribute is updated always so its the best way.
+ var langObserver = new window.MutationObserver(function(mutations) {
+ mutations.forEach(function(mutation) {
+ if (mutation.type == "attributes" && mutation.attributeName == "lang") {
+ windowListener.handleEvent(mutation);
+ }
+ });
+ });
+ langObserver.observe(window.document.documentElement, { attributes: true });
+ }
+};
+
+
+var recipientsChangeWindowListener = new class extends ExtensionCommon.EventEmitter {
+ constructor() {
+ super();
+ this.callbackCount = 0;
+ }
+
+ handleEvent(event) {
+ recipientsChangeWindowListener.emit("recipients-changed", event);
+ }
+
+ add(callback) {
+ this.on("recipients-changed", callback);
+ this.callbackCount++;
+
+ if (this.callbackCount == 1) {
+ ExtensionSupport.registerWindowListener("recipientsChangeWindowListener", {
+ chromeURLs: ["chrome://messenger/content/messengercompose/messengercompose.xhtml"],
+ onLoadWindow: function(window) {
+ recipientsChangeWindowListener.detectRecipientsChange(window);
+ },
+ });
+ }
+ }
+
+ remove(callback) {
+ this.off("recipients-changed", callback);
+ this.callbackCount--;
+
+ if (this.callbackCount == 0) {
+ ExtensionSupport.unregisterWindowListener("recipientsChangeWindowListener");
+ }
+ }
+
+ detectRecipientsChange(window) {
+ window.document.getElementById('recipientsContainer').addEventListener('change', function(event) {
+ recipientsChangeWindowListener.handleEvent(event);
+ });
+
+ window.document.getElementById('msgSubject').addEventListener('focus', function(event) {
+ recipientsChangeWindowListener.handleEvent(event);
+ });
+
+ window.document.getElementById('content-frame').addEventListener('focus', function(event){
+ recipientsChangeWindowListener.handleEvent(event);
+ });
+ }
+};
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027354_environmentCheck.js b/pool/shard004/JavaScript/0027354_environmentCheck.js
new file mode 100644
index 0000000000000000000000000000000000000000..d753ac827e102b70579be2821905db223b629266
--- /dev/null
+++ b/pool/shard004/JavaScript/0027354_environmentCheck.js
@@ -0,0 +1,17 @@
+const fs = require('fs');
+
+const check = function check(variable) {
+ if (typeof process.env[variable] === 'undefined' || process.env[variable] === null) {
+ throw new Error('Path to config file is not specified.');
+ }
+
+ fs.accessSync(process.env[variable], fs.constants.R_OK, (err) => {
+ if (err) {
+ throw new Error('Config file does not have read permissions.');
+ }
+ });
+};
+
+module.exports = {
+ check,
+};
diff --git a/pool/shard004/JavaScript/0027360_1-route_for_name.js b/pool/shard004/JavaScript/0027360_1-route_for_name.js
new file mode 100644
index 0000000000000000000000000000000000000000..a55603028465d97ef58dd995e518afd1e7be40dd
--- /dev/null
+++ b/pool/shard004/JavaScript/0027360_1-route_for_name.js
@@ -0,0 +1,25 @@
+/**
+ * Created by intelligrape on 16/1/15.
+ */
+var http = require('http');
+var fs = require('fs');
+var port = 8080;
+var server = http.createServer(function (req, res) {
+ var pathname = req.url;
+ //serve plain text
+ if (pathname == '/name') {
+ res.writeHead(200, {"Content-Type": "text/plain"});
+ res.write("Hi!! i am tom..");
+ res.end();
+ }
+ else {
+ res.write("Aww!! you missed it baby...");
+ res.end();
+ }
+
+});
+server.listen(port, function () {
+ console.log('Server listening at port http://localhost:%d/', port);
+});
+
+console.log('something going to happen...');
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027367_facebook.js b/pool/shard004/JavaScript/0027367_facebook.js
new file mode 100644
index 0000000000000000000000000000000000000000..9857cfee55308a8cd9627508fee3f46e9b9165ee
--- /dev/null
+++ b/pool/shard004/JavaScript/0027367_facebook.js
@@ -0,0 +1,86 @@
+var oauthModule = require('./oauth2')
+ , url = require('url');
+
+var fb = module.exports =
+oauthModule.submodule('facebook')
+ .configurable({
+ scope: 'specify types of access: See http://developers.facebook.com/docs/authentication/permissions/',
+ fields: 'specify returned fields: See http:/developers.facebook.com/docs/reference/api/user/'
+ })
+
+ .apiHost('https://graph.facebook.com/v2.0')
+ .oauthHost('https://graph.facebook.com/v2.0')
+
+ .authPath('https://www.facebook.com/v2.0/dialog/oauth')
+
+ .entryPath('/auth/facebook')
+ .callbackPath('/auth/facebook/callback')
+
+ .authQueryParam('scope', function () {
+ return this._scope && this.scope();
+ })
+
+ .authCallbackDidErr( function (req) {
+ var parsedUrl = url.parse(req.url, true);
+ return parsedUrl.query && !!parsedUrl.query.error;
+ })
+ .handleAuthCallbackError( function (req, res) {
+ var parsedUrl = url.parse(req.url, true)
+ , errorDesc = parsedUrl.query.error_description;
+ if (res.render) {
+ res.render(__dirname + '/../views/auth-fail.jade', {
+ errorDescription: errorDesc
+ });
+ } else {
+ // TODO Replace this with a nice fallback
+ throw new Error("You must configure handleAuthCallbackError if you are not using express");
+ }
+ })
+
+ .fetchOAuthUser( function (accessToken) {
+ var p = this.Promise();
+ var fieldsQuery = "";
+ if (this._fields && this._fields.length > 0){
+ fieldsQuery = "?fields=" + this.fields();
+ }
+ this.oauth.get(this.apiHost() + '/me' + fieldsQuery, accessToken, function (err, data) {
+ if (err) return p.fail(err);
+ var oauthUser = JSON.parse(data);
+ p.fulfill(oauthUser);
+ })
+ return p;
+ })
+ .moduleErrback( function (err, seqValues) {
+ if (err instanceof Error) {
+ var next = seqValues.next;
+ return next(err);
+ } else if (err.extra) {
+ var facebookResponse = err.extra.res
+ , serverResponse = seqValues.res;
+ serverResponse.writeHead(
+ facebookResponse.statusCode
+ , facebookResponse.headers);
+ serverResponse.end(err.extra.data);
+ } else if (err.statusCode) {
+ var serverResponse = seqValues.res;
+ serverResponse.writeHead(err.statusCode);
+ serverResponse.end(err.data);
+ } else {
+ console.error(err);
+ throw new Error('Unsupported error type');
+ }
+ });
+
+fb.mobile = function (isMobile) {
+ if (isMobile) {
+ this.authPath('https://m.facebook.com/v2.0/dialog/oauth');
+ }
+ return this;
+};
+
+fb.popup = function (isPopup) {
+ if (isPopup) {
+ this.authQueryParam('display', 'popup');
+ }
+ return this;
+};
diff --git a/pool/shard004/JavaScript/0027368_aresHeader.js b/pool/shard004/JavaScript/0027368_aresHeader.js
new file mode 100644
index 0000000000000000000000000000000000000000..68da9ac0b248934cb2035cde0abf5560d695223b
--- /dev/null
+++ b/pool/shard004/JavaScript/0027368_aresHeader.js
@@ -0,0 +1,103 @@
+/**
+ * Created by kwhatcher on 4/15/2016.
+ */
+
+(function() {
+
+ 'use strict';
+
+ angular
+ .module('aresApp')
+ .directive('toolbar', toolbar);
+
+ function toolbar() {
+ return {
+ templateUrl: 'files/partials/header.html',
+ controller: toolbarController,
+ controllerAs: 'toolbar',
+ bindToController: true
+ }
+ }
+
+ function toolbarController(auth, store, $location, $http) {
+
+ function getOptionsForRole(isAdmin, token) {
+ if(isAdmin) {
+ // TODO: update roles and principals based upon your account settings.
+ return {
+ "id_token": token,
+ "role": window.config.role,
+ "principal": window.config.principal
+
+ };
+ }
+ else {
+ return {
+ "id_token": token,
+ "role": window.config.role,
+ "principal": window.config.principal
+ };
+ }
+ }
+
+ var vm = this;
+ vm.login = login;
+ vm.logout = logout;
+ vm.auth = auth;
+
+ function getStatusJsonCallBack(data){
+ console.log(data.data.options[data.data.eocstatus]);
+ vm.eocstatus = data.data.options[data.data.eocstatus];
+ }
+
+ $http.get('files/json/status.json').then(getStatusJsonCallBack);
+
+ function login() {
+ // The auth service has a signin method that
+ // makes use of Auth0Lock. If authentication
+ // is successful, the user's profile and token
+ // are saved in local storage with the store service
+ auth.signin({}, function(profile, token) {
+
+ store.set('profile', profile);
+ store.set('token', token);
+ // set admin and get delegation token from identity token.
+ profile.isAdmin = !profile.identities[0].isSocial;
+ var options = getOptionsForRole(profile.isAdmin, token);
+ console.log("here test1");
+
+ // TODO: Step 3: Enable this section once you setup AWS delegation.
+
+ auth.getToken(options)
+ .then(
+ function(delegation) {
+
+ store.set('awstoken', delegation.Credentials);
+ $location.path("/");
+ },
+ function(err) {
+ console.log('failed to acquire delegation token', err);
+ });
+
+ // TODO: Step 3: Remove this redirect after you add the get token API.
+
+ $location.path('/');
+
+ }, function(error) {
+ console.log(error);
+ })
+ }
+
+ function logout() {
+ // The signout method on the auth service
+ // sets isAuthenticated to false but we
+ // also need to remove the profile and
+ // token from local storage
+ auth.signout();
+ store.remove('profile');
+ store.remove('token');
+ $location.path('/');
+ }
+ }
+
+})();
diff --git a/pool/shard004/JavaScript/0027369_bottomSheet.js b/pool/shard004/JavaScript/0027369_bottomSheet.js
new file mode 100644
index 0000000000000000000000000000000000000000..ef1b48f97d529ab772eb501b760814ac568e10be
--- /dev/null
+++ b/pool/shard004/JavaScript/0027369_bottomSheet.js
@@ -0,0 +1,277 @@
+/*!
+ * Angular Material Design
+ * https://github.com/angular/material
+ * @license MIT
+ * v0.11.4-master-f966d0f
+ */
+(function( window, angular, undefined ){
+"use strict";
+
+/**
+ * @ngdoc module
+ * @name material.components.bottomSheet
+ * @description
+ * BottomSheet
+ */
+angular
+ .module('material.components.bottomSheet', [
+ 'material.core',
+ 'material.components.backdrop'
+ ])
+ .directive('mdBottomSheet', MdBottomSheetDirective)
+ .provider('$mdBottomSheet', MdBottomSheetProvider);
+
+/* ngInject */
+function MdBottomSheetDirective($mdBottomSheet) {
+ return {
+ restrict: 'E',
+ link : function postLink(scope, element, attr) {
+ // When navigation force destroys an interimElement, then
+ // listen and $destroy() that interim instance...
+ scope.$on('$destroy', function() {
+ $mdBottomSheet.destroy();
+ });
+ }
+ };
+}
+MdBottomSheetDirective.$inject = ["$mdBottomSheet"];
+
+
+/**
+ * @ngdoc service
+ * @name $mdBottomSheet
+ * @module material.components.bottomSheet
+ *
+ * @description
+ * `$mdBottomSheet` opens a bottom sheet over the app and provides a simple promise API.
+ *
+ * ## Restrictions
+ *
+ * - The bottom sheet's template must have an outer `` element.
+ * - Add the `md-grid` class to the bottom sheet for a grid layout.
+ * - Add the `md-list` class to the bottom sheet for a list layout.
+ *
+ * @usage
+ *
+ *
+ *
+ * Open a Bottom Sheet!
+ *
+ *
+ *
+ *
+ * var app = angular.module('app', ['ngMaterial']);
+ * app.controller('MyController', function($scope, $mdBottomSheet) {
+ * $scope.openBottomSheet = function() {
+ * $mdBottomSheet.show({
+ * template: 'Hello! '
+ * });
+ * };
+ * });
+ *
+ */
+
+ /**
+ * @ngdoc method
+ * @name $mdBottomSheet#show
+ *
+ * @description
+ * Show a bottom sheet with the specified options.
+ *
+ * @param {object} options An options object, with the following properties:
+ *
+ * - `templateUrl` - `{string=}`: The url of an html template file that will
+ * be used as the content of the bottom sheet. Restrictions: the template must
+ * have an outer `md-bottom-sheet` element.
+ * - `template` - `{string=}`: Same as templateUrl, except this is an actual
+ * template string.
+ * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope.
+ * This scope will be destroyed when the bottom sheet is removed unless `preserveScope` is set to true.
+ * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false
+ * - `controller` - `{string=}`: The controller to associate with this bottom sheet.
+ * - `locals` - `{string=}`: An object containing key/value pairs. The keys will
+ * be used as names of values to inject into the controller. For example,
+ * `locals: {three: 3}` would inject `three` into the controller with the value
+ * of 3.
+ * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the bottom sheet to
+ * close it. Default true.
+ * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the bottom sheet.
+ * Default true.
+ * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values
+ * and the bottom sheet will not open until the promises resolve.
+ * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope.
+ * - `parent` - `{element=}`: The element to append the bottom sheet to. The `parent` may be a `function`, `string`,
+ * `object`, or null. Defaults to appending to the body of the root element (or the root element) of the application.
+ * e.g. angular.element(document.getElementById('content')) or "#content"
+ * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the bottom sheet is open.
+ * Default true.
+ *
+ * @returns {promise} A promise that can be resolved with `$mdBottomSheet.hide()` or
+ * rejected with `$mdBottomSheet.cancel()`.
+ */
+
+/**
+ * @ngdoc method
+ * @name $mdBottomSheet#hide
+ *
+ * @description
+ * Hide the existing bottom sheet and resolve the promise returned from
+ * `$mdBottomSheet.show()`. This call will close the most recently opened/current bottomsheet (if any).
+ *
+ * @param {*=} response An argument for the resolved promise.
+ *
+ */
+
+/**
+ * @ngdoc method
+ * @name $mdBottomSheet#cancel
+ *
+ * @description
+ * Hide the existing bottom sheet and reject the promise returned from
+ * `$mdBottomSheet.show()`.
+ *
+ * @param {*=} response An argument for the rejected promise.
+ *
+ */
+
+function MdBottomSheetProvider($$interimElementProvider) {
+ // how fast we need to flick down to close the sheet, pixels/ms
+ var CLOSING_VELOCITY = 0.5;
+ var PADDING = 80; // same as css
+
+ bottomSheetDefaults.$inject = ["$animate", "$mdConstant", "$mdUtil", "$mdTheming", "$mdBottomSheet", "$rootElement", "$mdGesture"];
+ return $$interimElementProvider('$mdBottomSheet')
+ .setDefaults({
+ methods: ['disableParentScroll', 'escapeToClose', 'clickOutsideToClose'],
+ options: bottomSheetDefaults
+ });
+
+ /* ngInject */
+ function bottomSheetDefaults($animate, $mdConstant, $mdUtil, $mdTheming, $mdBottomSheet, $rootElement, $mdGesture) {
+ var backdrop;
+
+ return {
+ themable: true,
+ onShow: onShow,
+ onRemove: onRemove,
+ escapeToClose: true,
+ clickOutsideToClose: true,
+ disableParentScroll: true
+ };
+
+
+ function onShow(scope, element, options, controller) {
+
+ element = $mdUtil.extractElementByName(element, 'md-bottom-sheet');
+
+ // Add a backdrop that will close on click
+ backdrop = $mdUtil.createBackdrop(scope, "md-bottom-sheet-backdrop md-opaque");
+
+ if (options.clickOutsideToClose) {
+ backdrop.on('click', function() {
+ $mdUtil.nextTick($mdBottomSheet.cancel,true);
+ });
+ }
+
+ $mdTheming.inherit(backdrop, options.parent);
+
+ $animate.enter(backdrop, options.parent, null);
+
+ var bottomSheet = new BottomSheet(element, options.parent);
+ options.bottomSheet = bottomSheet;
+
+ $mdTheming.inherit(bottomSheet.element, options.parent);
+
+ if (options.disableParentScroll) {
+ options.restoreScroll = $mdUtil.disableScrollAround(bottomSheet.element, options.parent);
+ }
+
+ return $animate.enter(bottomSheet.element, options.parent)
+ .then(function() {
+ var focusable = $mdUtil.findFocusTarget(element) || angular.element(
+ element[0].querySelector('button') ||
+ element[0].querySelector('a') ||
+ element[0].querySelector('[ng-click]')
+ );
+ focusable.focus();
+
+ if (options.escapeToClose) {
+ options.rootElementKeyupCallback = function(e) {
+ if (e.keyCode === $mdConstant.KEY_CODE.ESCAPE) {
+ $mdUtil.nextTick($mdBottomSheet.cancel,true);
+ }
+ };
+ $rootElement.on('keyup', options.rootElementKeyupCallback);
+ }
+ });
+
+ }
+
+ function onRemove(scope, element, options) {
+
+ var bottomSheet = options.bottomSheet;
+
+ $animate.leave(backdrop);
+ return $animate.leave(bottomSheet.element).then(function() {
+ if (options.disableParentScroll) {
+ options.restoreScroll();
+ delete options.restoreScroll;
+ }
+
+ bottomSheet.cleanup();
+ });
+ }
+
+ /**
+ * BottomSheet class to apply bottom-sheet behavior to an element
+ */
+ function BottomSheet(element, parent) {
+ var deregister = $mdGesture.register(parent, 'drag', { horizontal: false });
+ parent.on('$md.dragstart', onDragStart)
+ .on('$md.drag', onDrag)
+ .on('$md.dragend', onDragEnd);
+
+ return {
+ element: element,
+ cleanup: function cleanup() {
+ deregister();
+ parent.off('$md.dragstart', onDragStart);
+ parent.off('$md.drag', onDrag);
+ parent.off('$md.dragend', onDragEnd);
+ }
+ };
+
+ function onDragStart(ev) {
+ // Disable transitions on transform so that it feels fast
+ element.css($mdConstant.CSS.TRANSITION_DURATION, '0ms');
+ }
+
+ function onDrag(ev) {
+ var transform = ev.pointer.distanceY;
+ if (transform < 5) {
+ // Slow down drag when trying to drag up, and stop after PADDING
+ transform = Math.max(-PADDING, transform / 2);
+ }
+ element.css($mdConstant.CSS.TRANSFORM, 'translate3d(0,' + (PADDING + transform) + 'px,0)');
+ }
+
+ function onDragEnd(ev) {
+ if (ev.pointer.distanceY > 0 &&
+ (ev.pointer.distanceY > 20 || Math.abs(ev.pointer.velocityY) > CLOSING_VELOCITY)) {
+ var distanceRemaining = element.prop('offsetHeight') - ev.pointer.distanceY;
+ var transitionDuration = Math.min(distanceRemaining / ev.pointer.velocityY * 0.75, 500);
+ element.css($mdConstant.CSS.TRANSITION_DURATION, transitionDuration + 'ms');
+ $mdUtil.nextTick($mdBottomSheet.cancel,true);
+ } else {
+ element.css($mdConstant.CSS.TRANSITION_DURATION, '');
+ element.css($mdConstant.CSS.TRANSFORM, '');
+ }
+ }
+ }
+
+ }
+
+}
+MdBottomSheetProvider.$inject = ["$$interimElementProvider"];
+
+})(window, window.angular);
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027370_15.2.3.3-4-243.js b/pool/shard004/JavaScript/0027370_15.2.3.3-4-243.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b8e07d63474e80ca541187d1d198d632b516f6e
--- /dev/null
+++ b/pool/shard004/JavaScript/0027370_15.2.3.3-4-243.js
@@ -0,0 +1,26 @@
+/// Copyright (c) 2012 Ecma International. All rights reserved.
+/// Ecma International makes this code available under the terms and conditions set
+/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
+/// "Use Terms"). Any redistribution of this code must retain the above
+/// copyright and this notice and otherwise comply with the Use Terms.
+/**
+ * @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-243.js
+ * @description Object.getOwnPropertyDescriptor - ensure that 'set' property of returned object is data property with correct 'value' attribute
+ */
+
+
+function testcase() {
+ var obj = {};
+ var fun = function () {
+ return "ownSetProperty";
+ };
+ Object.defineProperty(obj, "property", {
+ set: fun,
+ configurable: true
+ });
+
+ var desc = Object.getOwnPropertyDescriptor(obj, "property");
+
+ return desc.set === fun;
+ }
+runTestCase(testcase);
diff --git a/pool/shard004/JavaScript/0027372_WebAudioSoundManager.js b/pool/shard004/JavaScript/0027372_WebAudioSoundManager.js
new file mode 100644
index 0000000000000000000000000000000000000000..d36a31747306d85e099195f877b244fb9c7216a0
--- /dev/null
+++ b/pool/shard004/JavaScript/0027372_WebAudioSoundManager.js
@@ -0,0 +1,321 @@
+/**
+ * @author Richard Davey
+ * @author Pavle Goloskokovic (http://prunegames.com)
+ * @copyright 2018 Photon Storm Ltd.
+ * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
+ */
+
+var BaseSoundManager = require('../BaseSoundManager');
+var Class = require('../../utils/Class');
+var WebAudioSound = require('./WebAudioSound');
+
+/**
+ * @classdesc
+ * Web Audio API implementation of the sound manager.
+ *
+ * @class WebAudioSoundManager
+ * @extends Phaser.Sound.BaseSoundManager
+ * @memberOf Phaser.Sound
+ * @constructor
+ * @since 3.0.0
+ *
+ * @param {Phaser.Game} game - Reference to the current game instance.
+ */
+var WebAudioSoundManager = new Class({
+
+ Extends: BaseSoundManager,
+
+ initialize:
+
+ function WebAudioSoundManager (game)
+ {
+ /**
+ * The AudioContext being used for playback.
+ *
+ * @name Phaser.Sound.WebAudioSoundManager#context
+ * @type {AudioContext}
+ * @private
+ * @since 3.0.0
+ */
+ this.context = this.createAudioContext(game);
+
+ /**
+ * Gain node responsible for controlling global muting.
+ *
+ * @name Phaser.Sound.WebAudioSoundManager#masterMuteNode
+ * @type {GainNode}
+ * @private
+ * @since 3.0.0
+ */
+ this.masterMuteNode = this.context.createGain();
+
+ /**
+ * Gain node responsible for controlling global volume.
+ *
+ * @name Phaser.Sound.WebAudioSoundManager#masterVolumeNode
+ * @type {GainNode}
+ * @private
+ * @since 3.0.0
+ */
+ this.masterVolumeNode = this.context.createGain();
+
+ this.masterMuteNode.connect(this.masterVolumeNode);
+
+ this.masterVolumeNode.connect(this.context.destination);
+
+ /**
+ * Destination node for connecting individual sounds to.
+ *
+ * @name Phaser.Sound.WebAudioSoundManager#destination
+ * @type {AudioNode}
+ * @private
+ * @since 3.0.0
+ */
+ this.destination = this.masterMuteNode;
+
+ this.locked = this.context.state === 'suspended' && ('ontouchstart' in window || 'onclick' in window);
+
+ BaseSoundManager.call(this, game);
+
+ if (this.locked)
+ {
+ this.unlock();
+ }
+ },
+
+ /**
+ * Method responsible for instantiating and returning AudioContext instance.
+ * If an instance of an AudioContext class was provided through the game config,
+ * that instance will be returned instead. This can come in handy if you are reloading
+ * a Phaser game on a page that never properly refreshes (such as in an SPA project)
+ * and you want to reuse already instantiated AudioContext.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#createAudioContext
+ * @private
+ * @since 3.0.0
+ *
+ * @param {Phaser.Game} game - Reference to the current game instance.
+ *
+ * @return {AudioContext} The AudioContext instance to be used for playback.
+ */
+ createAudioContext: function (game)
+ {
+ var audioConfig = game.config.audio;
+
+ if (audioConfig && audioConfig.context)
+ {
+ audioConfig.context.resume();
+
+ return audioConfig.context;
+ }
+
+ return new AudioContext();
+ },
+
+ /**
+ * Adds a new sound into the sound manager.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#add
+ * @since 3.0.0
+ *
+ * @param {string} key - Asset key for the sound.
+ * @param {SoundConfig} [config] - An optional config object containing default sound settings.
+ *
+ * @return {Phaser.Sound.WebAudioSound} The new sound instance.
+ */
+ add: function (key, config)
+ {
+ var sound = new WebAudioSound(this, key, config);
+
+ this.sounds.push(sound);
+
+ return sound;
+ },
+
+ /**
+ * Unlocks Web Audio API on the initial input event.
+ *
+ * Read more about how this issue is handled here in [this article](https://medium.com/@pgoloskokovic/unlocking-web-audio-the-smarter-way-8858218c0e09).
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#unlock
+ * @since 3.0.0
+ */
+ unlock: function ()
+ {
+ var _this = this;
+
+ var unlock = function ()
+ {
+ _this.context.resume().then(function ()
+ {
+ document.body.removeEventListener('touchstart', unlock);
+ document.body.removeEventListener('touchend', unlock);
+ document.body.removeEventListener('click', unlock);
+
+ _this.unlocked = true;
+ });
+ };
+
+ if (document.body)
+ {
+ document.body.addEventListener('touchstart', unlock, false);
+ document.body.addEventListener('touchend', unlock, false);
+ document.body.addEventListener('click', unlock, false);
+ }
+ },
+
+ /**
+ * Method used internally for pausing sound manager if
+ * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#onBlur
+ * @protected
+ * @since 3.0.0
+ */
+ onBlur: function ()
+ {
+ this.context.suspend();
+ },
+
+ /**
+ * Method used internally for resuming sound manager if
+ * Phaser.Sound.WebAudioSoundManager#pauseOnBlur is set to true.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#onFocus
+ * @protected
+ * @since 3.0.0
+ */
+ onFocus: function ()
+ {
+ this.context.resume();
+ },
+
+ /**
+ * Calls Phaser.Sound.BaseSoundManager#destroy method
+ * and cleans up all Web Audio API related stuff.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#destroy
+ * @since 3.0.0
+ */
+ destroy: function ()
+ {
+ this.destination = null;
+ this.masterVolumeNode.disconnect();
+ this.masterVolumeNode = null;
+ this.masterMuteNode.disconnect();
+ this.masterMuteNode = null;
+
+ if (this.game.config.audio && this.game.config.audio.context)
+ {
+ this.context.suspend();
+ }
+ else
+ {
+ var _this = this;
+
+ this.context.close().then(function ()
+ {
+
+ _this.context = null;
+
+ });
+ }
+
+ BaseSoundManager.prototype.destroy.call(this);
+ },
+
+ /**
+ * @event Phaser.Sound.WebAudioSoundManager#muteEvent
+ * @param {Phaser.Sound.WebAudioSoundManager} soundManager - Reference to the sound manager that emitted event.
+ * @param {boolean} value - An updated value of Phaser.Sound.WebAudioSoundManager#mute property.
+ */
+
+ /**
+ * Sets the muted state of all this Sound Manager.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#setMute
+ * @fires Phaser.Sound.WebAudioSoundManager#muteEvent
+ * @since 3.3.0
+ *
+ * @param {boolean} value - `true` to mute all sounds, `false` to unmute them.
+ *
+ * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager.
+ */
+ setMute: function (value)
+ {
+ this.mute = value;
+
+ return this;
+ },
+
+ /**
+ * @name Phaser.Sound.WebAudioSoundManager#mute
+ * @type {boolean}
+ * @fires Phaser.Sound.WebAudioSoundManager#MuteEvent
+ * @since 3.0.0
+ */
+ mute: {
+
+ get: function ()
+ {
+ return (this.masterMuteNode.gain.value === 0);
+ },
+
+ set: function (value)
+ {
+ this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0);
+
+ this.emit('mute', this, value);
+ }
+
+ },
+
+ /**
+ * @event Phaser.Sound.WebAudioSoundManager#VolumeEvent
+ * @param {Phaser.Sound.WebAudioSoundManager} soundManager - Reference to the sound manager that emitted event.
+ * @param {number} value - An updated value of Phaser.Sound.WebAudioSoundManager#volume property.
+ */
+
+ /**
+ * Sets the volume of this Sound Manager.
+ *
+ * @method Phaser.Sound.WebAudioSoundManager#setVolume
+ * @fires Phaser.Sound.WebAudioSoundManager#VolumeEvent
+ * @since 3.3.0
+ *
+ * @param {number} value - The global volume of this Sound Manager.
+ *
+ * @return {Phaser.Sound.WebAudioSoundManager} This Sound Manager.
+ */
+ setVolume: function (value)
+ {
+ this.volume = value;
+
+ return this;
+ },
+
+ /**
+ * @name Phaser.Sound.WebAudioSoundManager#volume
+ * @type {number}
+ * @fires Phaser.Sound.WebAudioSoundManager#VolumeEvent
+ * @since 3.0.0
+ */
+ volume: {
+
+ get: function ()
+ {
+ return this.masterVolumeNode.gain.value;
+ },
+
+ set: function (value)
+ {
+ this.masterVolumeNode.gain.setValueAtTime(value, 0);
+
+ this.emit('volume', this, value);
+ }
+
+ }
+
+});
+
+module.exports = WebAudioSoundManager;
diff --git a/pool/shard004/JavaScript/0027373_dictionary-viewer-service.js b/pool/shard004/JavaScript/0027373_dictionary-viewer-service.js
new file mode 100644
index 0000000000000000000000000000000000000000..229ee1a8450083b92341b3149bbb1703f48c40fe
--- /dev/null
+++ b/pool/shard004/JavaScript/0027373_dictionary-viewer-service.js
@@ -0,0 +1,174 @@
+/* globals dictionaryApp */
+'use strict';
+
+angular.module('DictionaryViewerApp')
+ .service('DictionaryService', function($location, $http, $q, DictionaryAppConstants) {
+
+ var _service = this,
+ _dictionaryList = null,
+ _codeList = null,
+ _dictionaryUtils = null,
+ _versionRange = {from: null, to: null},
+ _latestDictionaryVersion = '',
+ _DEFAULT_FROM_VERSION_INDEX = 0,
+ _DEFAULT_TO_VERSION_INDEX = 0;
+
+ _service.init = _init;
+ _service.getCachedDictionaryList = _getCachedDictionaryList;
+ _service.getCachedCodeList = _getCachedCodeList;
+ _service.getViewTypes = _getViewTypes;
+ _service.setDictionaryFilterRange = _setDictionaryFilterRange;
+ _service.setView = _setView;
+ _service.getDictionaryUtils = _getDictionaryUtils;
+ _service.getDictionaryVersionList = _getDictionaryVersionList;
+ _service.getCurrentViewType = _getCurrentViewType;
+ _service.dictionaryVersionRange = _dictionaryVersionRange;
+ _service.generateChangeList = _generateChangeList;
+ _service.getLatestDictionaryVersion = _getLatestDictionaryVersion;
+
+ function _init(baseURL) {
+ return _getDictionaries(baseURL);
+ }
+
+
+ function _getDictionaries(baseURL) {
+ var deferred = $q.defer(),
+ webserviceURL = (baseURL || '') + '/ws';
+
+ $http.get(webserviceURL + '/dictionaries/versions')
+ .then(function (dictionaryList) {
+
+ // Grab the code list
+ $http.get(webserviceURL + '/codeLists')
+ .then(function (codeList) {
+ _dictionaryList = dictionaryList.data;
+ _codeList = codeList.data;
+
+ _dictionaryUtils = new dictionaryApp.DictionaryUtil(_dictionaryList, webserviceURL);
+
+ // The version list is sorted in descending order (latest version first)
+ // use the latest current version as the default.
+ _dictionaryVersionRange(
+ _dictionaryUtils.versionList[_DEFAULT_FROM_VERSION_INDEX],
+ _dictionaryUtils.versionList[_DEFAULT_TO_VERSION_INDEX]
+ );
+
+ _latestDictionaryVersion = _dictionaryUtils.versionList[0];
+
+ deferred.resolve({dictionaryList: _dictionaryList, codeList: _codeList});
+ },
+ function(reason) {
+ deferred.reject(reason);
+ }
+ );
+
+ },
+ function(reason) {
+ deferred.reject(reason);
+ });
+
+ return deferred.promise;
+ }
+
+ function _getLatestDictionaryVersion() {
+ return _latestDictionaryVersion;
+ }
+
+ function _getCachedDictionaryList() {
+ return _dictionaryList;
+ }
+
+ function _getCachedCodeList() {
+ return _codeList;
+ }
+
+ function _getViewTypes() {
+ return DictionaryAppConstants.VIEWS;
+ }
+
+ function _setDictionaryFilterRange(fromVersion, toVersion) {
+ var search = $location.search();
+ search.vFrom = encodeURIComponent(fromVersion);
+ search.vTo = encodeURIComponent(toVersion);
+
+ _dictionaryVersionRange(fromVersion, toVersion);
+ $location.search(search);
+ }
+
+ function _setView(view) {
+ console.log('change view');
+ var search = $location.search();
+
+ search.viewMode = view;
+
+ // Nullify any hash that may interfere from a pure view change
+ $location.search(search).hash(null);
+ }
+
+ function _getDictionaryUtils() {
+ return _dictionaryUtils;
+ }
+
+ function _getDictionaryVersionList() {
+ var versionList = [];
+
+ if (_dictionaryUtils) {
+ versionList = _dictionaryUtils.versionList;
+ }
+
+ return versionList;
+ }
+
+ function _getCurrentViewType() {
+ var search = $location.search();
+
+ return angular.isString(search.viewMode) ? search.viewMode : 'graph';
+ }
+
+ function _dictionaryVersionRange(from, to) {
+
+ if (arguments.length === 2) {
+ _versionRange.from = from;
+ _versionRange.to = to;
+ }
+
+ return _versionRange;
+ }
+
+ function _generateChangeList() {
+ var changeReport = null;
+
+ if (! _dictionaryUtils) {
+ return changeReport;
+ }
+
+ return _dictionaryUtils.createDiffListing(_versionRange.from, _versionRange.to).then(function (report) {
+ changeReport = report;
+
+ return changeReport;
+ });
+
+ }
+
+ })
+ .service('JSONDiffService', function($window){
+ var _service = this,
+ _formatService = $window.jsondiffpatch,
+ _diffService = _formatService.create({ textDiff: { minLength: 10 }});
+
+
+ _service.getDifferences = function(from, to){
+ var differences = _diffService.diff(from, to);
+
+ if(_.has(differences, 'expanded')){
+ differences = _.omit(differences, 'expanded');
+ }
+
+ return differences;
+ };
+
+ _service.formatDifferences = function(from, to){
+ return _formatService.formatters.html.format(_service.getDifferences(from, to));
+ };
+
+ });
\ No newline at end of file
diff --git a/pool/shard004/JavaScript/0027375_press-test.js b/pool/shard004/JavaScript/0027375_press-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..6fb9cedd049aeb022b147337dc9ab4e3744aa16c
--- /dev/null
+++ b/pool/shard004/JavaScript/0027375_press-test.js
@@ -0,0 +1,249 @@
+var testCafeCore = window.getTestCafeModule('testCafeCore');
+var preventRealEvents = testCafeCore.get('./prevent-real-events');
+var parseKeySequence = testCafeCore.get('./utils/parse-key-sequence');
+var domUtils = testCafeCore.get('./utils/dom');
+var textSelection = testCafeCore.get('./utils/text-selection');
+
+var testCafeAutomation = window.getTestCafeModule('testCafeAutomation');
+var PressAutomation = testCafeAutomation.Press;
+
+preventRealEvents();
+
+var hammerhead = window.getTestCafeModule('hammerhead');
+var iframeSandbox = hammerhead.sandbox.iframe;
+var browserUtils = hammerhead.utils.browser;
+
+
+$(document).ready(function () {
+ var $input = null;
+
+ //constants
+ var TEST_ELEMENT_CLASS = 'testElement';
+
+
+ //tests
+ QUnit.testStart(function () {
+ $input = $('').addClass(TEST_ELEMENT_CLASS).appendTo($('body'));
+ $input[0].value = 'test';
+ $input[0].focus();
+
+ textSelection.select($input[0], 4, 4);
+
+ iframeSandbox.on(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
+ iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, iframeSandbox.iframeReadyToInitHandler);
+ });
+
+ QUnit.testDone(function () {
+ $('.' + TEST_ELEMENT_CLASS).remove();
+ iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
+ });
+
+ module('different scenarios');
+
+ asyncTest('press a', function () {
+ var press = new PressAutomation(parseKeySequence('left a').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal($input[0].value, 'tesat');
+ start();
+ });
+ });
+
+ asyncTest('press +', function () {
+ var press = new PressAutomation(parseKeySequence('+ shift++').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal($input[0].value, 'test++');
+ start();
+ });
+ });
+
+ asyncTest('press space', function () {
+ var press = new PressAutomation(parseKeySequence('left space').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal($input[0].value, 'tes t');
+ start();
+ });
+ });
+
+ asyncTest('press shift+a', function () {
+ var press = new PressAutomation(parseKeySequence('shift+a').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal($input[0].value, 'testA');
+ start();
+ });
+ });
+
+ asyncTest('press shift+1', function () {
+ var press = new PressAutomation(parseKeySequence('shift+1').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal($input[0].value, 'test!');
+ start();
+ });
+ });
+
+ asyncTest('press tab', function () {
+ domUtils.getActiveElement().blur();
+ $('body').focus();
+ $input.attr('tabIndex', 1);
+
+ var press = new PressAutomation(parseKeySequence('tab').combinations);
+
+ press
+ .run()
+ .then(function () {
+ deepEqual(domUtils.getActiveElement(), $input[0]);
+ equal($input[0].selectionStart, 0);
+ equal($input[0].selectionEnd, $input[0].value.length);
+ start();
+ });
+ });
+
+ asyncTest('press tab with tabIndexes', function () {
+ var $input2 = $('')
+ .addClass(TEST_ELEMENT_CLASS)
+ .appendTo($('body'))
+ .attr('tabIndex', 1);
+
+ $input.attr('tabIndex', 2);
+ domUtils.getActiveElement().blur();
+ $('body').focus();
+
+ var press = new PressAutomation(parseKeySequence('tab').combinations);
+
+ press
+ .run()
+ .then(function () {
+ deepEqual(domUtils.getActiveElement(), $input2[0]);
+ start();
+ });
+ });
+
+ asyncTest('press tab with iframe', function () {
+ var $iframe = $('')
+ .addClass(TEST_ELEMENT_CLASS)
+ .appendTo($('body'));
+
+ var $iframeInput = $('')
+ .addClass(TEST_ELEMENT_CLASS);
+
+ window.QUnitGlobals.waitForIframe($iframe[0])
+ .then(function () {
+ $($iframe.contents()[0]).find('body').append($iframeInput);
+
+ domUtils.getActiveElement().blur();
+ $input.focus();
+
+ var press = new PressAutomation(parseKeySequence('tab').combinations);
+
+ press
+ .run()
+ .then(function () {
+ ok(domUtils.getActiveElement() !== $input[0]);
+ start();
+ });
+ });
+ });
+
+ if (!browserUtils.isSafari && (!browserUtils.isChrome || browserUtils.version > 53)) {
+ asyncTest('T334620 - Wrong "key" property in keyEvent objects (press)', function () {
+ var textarea = document.createElement('textarea');
+
+ textarea.className = TEST_ELEMENT_CLASS;
+
+ document.body.appendChild(textarea);
+
+ var keydownKeyProperty = '';
+ var keypressKeyProperty = '';
+ var keyupKeyProperty = '';
+
+ textarea.focus();
+
+ textarea.addEventListener('keydown', function (e) {
+ keydownKeyProperty += e.key;
+ });
+
+ textarea.addEventListener('keypress', function (e) {
+ keypressKeyProperty += e.key;
+ });
+
+ textarea.addEventListener('keyup', function (e) {
+ keyupKeyProperty += e.key;
+ });
+
+ var press = new PressAutomation(parseKeySequence('a A shift+a ! enter shift+1 shift+!').combinations);
+
+ press
+ .run()
+ .then(function () {
+ equal(keydownKeyProperty, 'aAShiftAShift!EnterShift!Shift!');
+ equal(keypressKeyProperty, 'aAA!Enter!!');
+ equal(keyupKeyProperty, 'aAAShift!ShiftEnter!Shift!Shift');
+ equal(textarea.value, 'aAA!\n!!');
+ start();
+ });
+ });
+ }
+ else {
+ asyncTest('T334620 - Wrong "keyIdentifier" property in keyEvent objects (press)', function () {
+ var textarea = document.createElement('textarea');
+
+ textarea.className = TEST_ELEMENT_CLASS;
+
+ document.body.appendChild(textarea);
+
+ var keydownKeyIdentifierProperty = '';
+ var keypressKeyIdentifierProperty = '';
+ var keyupKeyIdentifierProperty = '';
+
+ textarea.focus();
+
+ textarea.addEventListener('keydown', function (e) {
+ keydownKeyIdentifierProperty += e.keyIdentifier;
+ });
+
+ textarea.addEventListener('keypress', function (e) {
+ keypressKeyIdentifierProperty += e.keyIdentifier;
+ });
+
+ textarea.addEventListener('keyup', function (e) {
+ keyupKeyIdentifierProperty += e.keyIdentifier;
+ });
+
+ var press = new PressAutomation(parseKeySequence('a A shift+a ! enter shift+1 shift+!').combinations);
+
+ var s = {
+ '!': 'U+0021',
+ 'a': 'U+0041'
+ };
+
+ var expectedKeydownSequence = s['a'] + s['a'] + 'Shift' + s['a'] + 'Shift' + s['!'] + 'Enter' + 'Shift' +
+ s['!'] + 'Shift' + s['!'];
+ var expectedKeyupSequence = s['a'] + s['a'] + s['a'] + 'Shift' + s['!'] + 'Shift' + 'Enter' + s['!'] +
+ 'Shift' + s['!'] + 'Shift';
+
+ press
+ .run()
+ .then(function () {
+ equal(keydownKeyIdentifierProperty, expectedKeydownSequence);
+ equal(keypressKeyIdentifierProperty, '');
+ equal(keyupKeyIdentifierProperty, expectedKeyupSequence);
+ equal(textarea.value, 'aAA!\n!!');
+ start();
+ });
+ });
+ }
+});
diff --git a/pool/shard004/JavaScript/0027377_script.js b/pool/shard004/JavaScript/0027377_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..5d15ac974e73f6214be8d8a68ba455f29d036dfb
--- /dev/null
+++ b/pool/shard004/JavaScript/0027377_script.js
@@ -0,0 +1,42 @@
+'use strict';
+
+var JSZip = require('jszip');
+var kml = require('gtran-kml');
+var promiseLib = require('./promise.js');
+
+var Promise, writeFile;
+
+exports.setPromiseLib = setPromiseLib;
+
+exports.fromGeoJson = function(geojson, fileName, options) {
+ if (!Promise) { setPromiseLib(); }
+
+ return kml.fromGeoJson(geojson, undefined, options).then(function(file) {
+ var zip = new JSZip();
+ zip.file('doc.kml', file.data);
+
+ var buffer = zip.generate({type:"nodebuffer"});
+ if(fileName) {
+ var fileNameWithExt = fileName;
+ if(fileNameWithExt.indexOf('.kmz') === -1) {
+ fileNameWithExt += '.kmz';
+ }
+
+ writeFile(fileNameWithExt, buffer);
+
+ return Promise.resolve(fileNameWithExt);
+ } else {
+ return Promise.resolve({
+ data: buffer,
+ format: 'kmz'
+ });
+ }
+ })
+};
+
+function setPromiseLib(lib) {
+ Promise = promiseLib.set(lib);
+ writeFile = promiseLib.promisify(require('fs').writeFile);
+
+ kml.setPromiseLib(lib);
+}
diff --git a/pool/shard004/JavaScript/0027378_key.js b/pool/shard004/JavaScript/0027378_key.js
new file mode 100644
index 0000000000000000000000000000000000000000..5ad737d50ee5526d8833efd5840eb341a806f2fa
--- /dev/null
+++ b/pool/shard004/JavaScript/0027378_key.js
@@ -0,0 +1,77 @@
+var EMPTY_ARRAY = [];
+
+function Key(type, fullPath, path, stat, children, debug) {
+ this.type = type;
+ this.fullPath = fullPath;
+ this.path = path;
+ this.stat = stat;
+ this.children = children || EMPTY_ARRAY;
+ this.debug = debug;
+}
+
+Key.prototype.toString = function() {
+ return ' type: ' + this.type +
+ ' fullPath: ' + this.fullPath +
+ ' path: ' + this.path +
+ ' stat.mode: ' + this.stat.mode +
+ ' stat.size: ' + this.stat.size +
+ ' stat.mtime: ' + this.stat.mtime.getTime();
+};
+
+function logNotEqual(current, next) {
+ if (next) {
+ current.debug(" cache eviction due to: \n - {%o} \n - {%o}", current, next);
+ } else {
+ current.debug(" cache empty, priming with: - {%o} ", next);
+ }
+}
+
+Key.prototype.inspect = function() {
+ return [
+ this.type,
+ this.fullPath,
+ this.path,
+ this.stat.mode,
+ this.stat.size,
+ this.stat.size,
+ this.stat.mtime.getTime()
+ ].join(', ');
+};
+
+Key.prototype.equal = function(otherKey) {
+ if (otherKey === undefined) {
+ logNotEqual(this, otherKey);
+ return false;
+ }
+
+ if (this.type === otherKey.type && this.type === 'directory') {
+ var children = this.children;
+ var otherChildren = otherKey.children;
+
+ if (children.length === otherChildren.length) {
+ for (var i = 0; i < children.length; i++) {
+ if (children[i].equal(otherChildren[i])) {
+ // they are the same
+ } else {
+ return false;
+ }
+ }
+ } else {
+ return false;
+ }
+ }
+
+ // key represents a file, diff the file
+ if (this.type === otherKey.type &&
+ this.path === otherKey.path &&
+ this.stat.mode === otherKey.stat.mode &&
+ (this.type === 'directory' ? true : (this.stat.size === otherKey.stat.size &&
+ this.stat.mtime.getTime() === otherKey.stat.mtime.getTime()))) {
+
+ return true;
+ } else {
+ logNotEqual(this, otherKey);
+ }
+};
+
+module.exports = Key;
diff --git a/pool/shard004/JavaScript/0027381_getlocalip.js b/pool/shard004/JavaScript/0027381_getlocalip.js
new file mode 100644
index 0000000000000000000000000000000000000000..e6b5ec4f696cd8d05ac168c501baebde19242a14
--- /dev/null
+++ b/pool/shard004/JavaScript/0027381_getlocalip.js
@@ -0,0 +1,96 @@
+/*
+* getLocalIP 1.0.0 - Get IP in network
+* https://github.com/cornips/getLocalIP
+* Copyright (c) 2017 Martijn Cornips
+* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
+
+* Based on Daniel Roesler's WebRTC-IPs
+* https://github.com/diafygi/webrtc-ips
+* Copyright (c) 2015 Daniel Roesler
+* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
+*
+* THIS 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.
+*/
+
+//get the IP addresses associated with an account
+function getLocalIP(callback){
+ var ip_dups = {};
+
+ //compatibility for firefox and chrome
+ var RTCPeerConnection = window.RTCPeerConnection
+ || window.mozRTCPeerConnection
+ || window.webkitRTCPeerConnection;
+ var useWebKit = !!window.webkitRTCPeerConnection;
+
+ //bypass naive webrtc blocking using an iframe
+ if(!RTCPeerConnection){
+ //NOTE: you need to have an iframe in the page right above the script tag
+ //
+ //
+ //