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 ( +
+
+ + +
+
+ ) + } +} +export default DesignerNav diff --git a/pool/shard004/JavaScript/0026569_list_pool.js b/pool/shard004/JavaScript/0026569_list_pool.js new file mode 100644 index 0000000000000000000000000000000000000000..94bf3c637b0a4e6417b778d6f17bda8f7ff20728 --- /dev/null +++ b/pool/shard004/JavaScript/0026569_list_pool.js @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2012. The Genome Analysis Centre, Norwich, UK + * MISO project contacts: Robert Davey @ TGAC + * ********************************************************************* + * + * This file is part of MISO. + * + * MISO 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. + * + * MISO 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 MISO. If not, see . + * + * ********************************************************************* + */ + +ListTarget.pool = { + name: "Pools", + getUserManualUrl: function() { + return Urls.external.userManual('pools'); + }, + createUrl: function(config, projectId) { + if (projectId) { + return Urls.rest.pools.projectDatatable(projectId); + } else { + return Urls.rest.pools.platformDatatable(config.platformType); + } + }, + getQueryUrl: function() { + return Urls.rest.pools.query; + }, + createBulkActions: function(config, projectId) { + var actions = HotTarget.pool.getBulkActions(config); + actions.push({ + name: "Delete", + action: function(items) { + var lines = ['Are you sure you wish to delete the following pools? This cannot be undone.', + 'Any associated orders will also be deleted.', 'Note: a pool may only be deleted by its creator or an admin.']; + var ids = []; + jQuery.each(items, function(index, pool) { + lines.push('* ' + pool.name + ' (' + pool.alias + ')'); + ids.push(pool.id); + }); + Utils.showConfirmDialog('Delete Pools', 'Delete', lines, function() { + Utils.ajaxWithDialog('Deleting Pools', 'POST', Urls.rest.pools.bulkDelete, ids, function() { + Utils.page.pageReload(); + }); + }); + } + }); + actions.push({ + name: "Merge", + action: function(pools) { + var fields = pools.map(function(pool) { + return { + type: 'int', + label: pool.alias + " (" + pool.name + ")", + value: 1, + property: 'pool' + pool.id, + required: true + }; + }); + + HotUtils.showDialogForBoxCreation("Merge Proportions", "Merge", fields, Urls.ui.pools.bulkMerge, function(output) { + var ids = pools.map(Utils.array.getId); + var proportions = ids.map(function(id) { + return output['pool' + id]; + }); + return { + ids: ids.join(','), + proportions: proportions.join(',') + }; + }, function(result) { + return 1; + }); + } + }); + return actions; + }, + createStaticActions: function(config, prodjectId) { + return [{ + name: "Add", + handler: function() { + window.location = Urls.ui.pools.create; + } + }]; + }, + createColumns: function(config, projectId) { + return [{ + "sTitle": "ID", + "mData": "id", + "bVisible": false + }, { + "sTitle": "Name", + "mData": "name", + "include": true, + "iSortPriority": 1, + "iDataSort": 0, // Use ID for sorting + "mRender": Warning.tableWarningRenderer(WarningTarget.pool, function(pool) { + return Urls.ui.pools.edit(pool.id); + }), + "sClass": "nowrap" + }, ListUtils.labelHyperlinkColumn("Alias", Urls.ui.pools.edit, Utils.array.getId, "alias", 0, true), { + "sTitle": "Description", + "mData": "description", + "include": true, + "iSortPriority": 0, + "bSortable": false + }, { + "sTitle": "Date Created", + "mData": "creationDate", + "include": true, + "iSortPriority": 0 + }, { + "sTitle": "Library Aliquots", + "mData": "libraryAliquotCount", + "include": true, + "iSortPriority": 0, + "bSortable": false, + }, { + "sTitle": "Concentration", + "mData": "concentration", + "include": true, + "iSortPriority": 0, + "mRender": function(data, type, full) { + if (type === 'display' && !!data) { + var units = Constants.concentrationUnits.find(function(unit) { + return unit.name == full.concentrationUnits; + }); + if (!!units) { + return data + ' ' + units.units; + } + } + return data; + } + }, { + "sTitle": "Location", + "mData": "locationLabel", + "bSortable": false, + "mRender": function(data, type, full) { + return full.box ? "" + data + "" : data; + }, + "include": true, + "iSortPriority": 0 + }, { + "sTitle": "Average Insert Size", + "mData": "insertSize", + "bSortable": false, + "mRender": function(data, type, full) { + return data ? Math.round(data) : "N/A"; + }, + "include": true, + "iSortPriority": 0 + }, { + "sTitle": "Last Modified", + "mData": "lastModified", + "include": Constants.isDetailedSample, + "iSortPriority": 2 + }]; + }, + searchTermSelector: function(searchTerms) { + return [searchTerms['id'], searchTerms['created'], searchTerms['entered'], searchTerms['changed'], searchTerms['creator'], + searchTerms['changedby'], searchTerms['platform'], searchTerms['index_name'], searchTerms['index_seq'], searchTerms['box'], + searchTerms['freezer'], searchTerms['distributed'], searchTerms['distributedto']]; + } +}; diff --git a/pool/shard004/JavaScript/0026572_datatables-init.js b/pool/shard004/JavaScript/0026572_datatables-init.js new file mode 100644 index 0000000000000000000000000000000000000000..916b7248cd2efa7625eeab3acbff0545887b6c9f --- /dev/null +++ b/pool/shard004/JavaScript/0026572_datatables-init.js @@ -0,0 +1,53 @@ +(function ($) { + // "use strict"; + + + /* Data Table + -------------*/ + + + + + $('#bootstrap-data-table').DataTable({ + lengthMenu: [[10, 20, 50, -1], [10, 20, 50, "All"]], + }); + + + + $('#bootstrap-data-table-export').DataTable({ + dom: 'lBfrtip', + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + buttons: [ + 'copy', 'csv', 'excel', 'pdf', 'print' + ] + }); + + $('#row-select').DataTable( { + initComplete: function () { + this.api().columns().every( function () { + var column = this; + var select = $('') + .appendTo( $(column.footer()).empty() ) + .on( 'change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + + column + .search( val ? '^'+val+'$' : '', true, false ) + .draw(); + } ); + + column.data().unique().sort().each( function ( d, j ) { + select.append( '' ) + } ); + } ); + } + } ); + + + + + + +})(jQuery); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026573_assessment-test.js b/pool/shard004/JavaScript/0026573_assessment-test.js new file mode 100644 index 0000000000000000000000000000000000000000..5f29bce78276e5730d5fea192feb50e3966d4516 --- /dev/null +++ b/pool/shard004/JavaScript/0026573_assessment-test.js @@ -0,0 +1,100 @@ +import { run } from '@ember/runloop'; +import { set, get } from '@ember/object'; +import { module, test } from 'qunit'; +import { setupTest } from 'ember-qunit'; + +module('Unit | Model | assessment', function(hooks) { + setupTest(hooks); + + test('it exists', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment')); + + run(function() { + let startDate = new Date(new Date().getFullYear() - 1, 1, 1); + let endDate = new Date(new Date().getFullYear() - 1, 12, 31); + + set(model, 'startDate', startDate); + set(model, 'endDate', endDate); + + assert.equal(get(model, 'startDate'), startDate, 'start date set correctly'); + assert.equal(get(model, 'endDate'), endDate, 'end date set correctly'); + }); + }); + + test('requires supporting documents', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment')); + run(() => { + // not locked, has responses require proof + set(model, 'locked', false); + set(model, 'requiresProofCount', 12); + assert.ok(get(model, 'requiresSupportingDocumentation'), 'requires docs when unlocked'); + + // not locked, no responses that require proof + set(model, 'locked', false); + set(model, 'requiresProofCount', 0); + assert.notOk(get(model, 'requiresSupportingDocumentation'), 'does not require docs'); + + // not locked, responses require proof + set(model, 'locked', true); + set(model, 'requiresProofCount', 12); + assert.ok(get(model, 'requiresSupportingDocumentation'), 'requires docs when locked'); + }); + }); + + test('is correct document upload progress', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment')); + + run(function() { + let requiresProofCount = 20; + let requiresProofProgressCount = 10; + + set(model, 'requiresProofCount', requiresProofCount); + set(model, 'requiresProofProgressCount', requiresProofProgressCount); + + assert.equal(get(model, 'documentUploadProgress'), 50, 'document upload progress set correctly'); + }); + }); + + test('previous year', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment', { year: 2016 })); + assert.equal(get(model, 'previousYear'), 2015, 'year decremented'); + }); + + test('next year', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment', { year: 2016 })); + assert.equal(get(model, 'nextYear'), 2017, 'year incremented'); + }); + + test('is rated', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment')); + run(() => { + assert.notOk(get(model, 'isRated'), 'no status is not rated'); + + set(model, 'status', 'In Progress'); + assert.notOk(get(model, 'isRated'), 'in progress not rated'); + + set(model, 'status', 'Rated'); + assert.ok(get(model, 'isRated'), 'Rated is rated'); + + set(model, 'status', 'RaTeD'); + assert.ok(get(model, 'isRated'), 'case insensitive rated is rated'); + }); + }); + + test('hasQuestionsForDiscussion', function(assert) { + let model = run(() => this.owner.lookup('service:store').createRecord('assessment')); + run(() => { + set(model, 'requiresDiscussionCount', 0); + assert.notOk(get(model, 'hasQuestionsForDiscussion'), 'no questions marked for discussion'); + + set(model, 'requiresDiscussionCount', 1); + assert.ok(get(model, 'hasQuestionsForDiscussion'), 'has questions marked for discussion'); + + set(model, 'requiresDiscussionCount', 2); + assert.ok(get(model, 'hasQuestionsForDiscussion'), 'has questions marked for discussion'); + + set(model, 'requiresDiscussionCount', -1); + assert.notOk(get(model, 'hasQuestionsForDiscussion'), 'no questions marked for discussion'); + }); + }); +}); diff --git a/pool/shard004/JavaScript/0026577_sigint.js b/pool/shard004/JavaScript/0026577_sigint.js new file mode 100644 index 0000000000000000000000000000000000000000..58f464cdc0f7cdd14aa784b80b5da48950040df5 --- /dev/null +++ b/pool/shard004/JavaScript/0026577_sigint.js @@ -0,0 +1,16 @@ +var win32 = process.platform === 'win32'; +if (win32){ + var readline = require ('readline'), + rl = readline.createInterface ({ + input: process.stdin, + output: process.stdout + }); + + rl.on ('SIGINT', function (){ + process.emit ('SIGINT'); + }); +} + +module.exports = { + enabled: win32 +}; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026582_Permissions.js b/pool/shard004/JavaScript/0026582_Permissions.js new file mode 100644 index 0000000000000000000000000000000000000000..fe9b66514fbec2a0c0559d0f67ea2c4278eb4113 --- /dev/null +++ b/pool/shard004/JavaScript/0026582_Permissions.js @@ -0,0 +1,39 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { CAN_VOTE, getPermissionDisplay } from 'common/auth/permissions'; +import Card from '../Card'; +import IconText from '../IconText'; +import css from './Permissions.css'; + + +function Permissions({ canVote, permissions }) { + const shouldBeAbleToVote = permissions >= CAN_VOTE; + return ( + } + > +
Rettighetsnivå: {getPermissionDisplay(permissions)}
+ {shouldBeAbleToVote && +
Stemmeberettiget: {canVote ? + 'Ja' : + Nei + } +
+ } +
+ ); +} + +Permissions.defaultProps = { + canVote: false, + permissions: 0, +}; + +Permissions.propTypes = { + canVote: PropTypes.bool, + permissions: PropTypes.number, +}; + +export default Permissions; diff --git a/pool/shard004/JavaScript/0026583_token.js b/pool/shard004/JavaScript/0026583_token.js new file mode 100644 index 0000000000000000000000000000000000000000..90d1b683e8db4582f7b290cda18a66b54b360364 --- /dev/null +++ b/pool/shard004/JavaScript/0026583_token.js @@ -0,0 +1,108 @@ +var express = require('express'); +var request = require('request'); +var sign=require('../libs/sign');//微信提供的签名方法 +var config=require('../libs/config.json');//配置文件 +var router = express.Router(); + +/* 最简单的获取签名信息 */ +router.get('/', function(req, res) { + request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) { + console.log('根据appId和appSecret获取accessToken ..'); + if(error || response.statusCode != 200){ + res.send(error); + return; + } + var access_token=JSON.parse(body).access_token; + console.log('access_token: '+access_token); + + request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) { + console.log('根据accessToken获取..'); + if (error || response.statusCode != 200) { + res.send(error); + return; + } + + var ticket=JSON.parse(body).ticket; + console.log('ticket: '+ticket); + + var port = req.app.settings.port; + var url=req.protocol + '://' + req.host + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path; + var result=sign(ticket,url); + + res.send(result); + }); + }); +}); + +var globalToken={}; +var max_live=7200-1000; + +router.get('/sign',function(req,res){ + var now=new Date().getTime()/1000; + var callback=function(){ + var url= req.param('url'); + var result=sign(globalToken.ticket,url); + res.send(result); + } + + if (!globalToken.time || now-globalToken.time>max_live){ + refreshGlobalToken(req,res,function(){ + console.log('获取新的token'); + callback(); + }) + }else{ + console.log('重复使用token'); + callback(); + } +}); + +/* 正式的演示代码,包括服务器端生成签名,客户端通过签名使用微信API方法 */ +router.get('/client', function(req, res) { + var now=new Date().getTime()/1000; + + if (!globalToken.time || now-globalToken.time>max_live){ + refreshGlobalToken(req,res,function(){ + console.log('获取新的token'); + renderClient(req,res); + }) + }else{ + console.log('重复使用token'); + renderClient(req,res); + } +}); + +function refreshGlobalToken(req,res,callback){ + request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) { + console.log('根据appId和appSecret获取accessToken ..'); + if(error || response.statusCode != 200){ + res.send(error); + return; + } + var access_token=JSON.parse(body).access_token; + console.log('access_token: '+access_token); + + request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) { + console.log('根据accessToken获取..'); + if (error || response.statusCode != 200) { + res.send(error); + return; + } + + var ticket=JSON.parse(body).ticket; + console.log('ticket: '+ticket); + + globalToken.time=new Date().getTime()/1000; + globalToken.ticket=ticket; + callback(); + }); + }); +} + +function renderClient(req,res){ + var port = req.app.settings.port; + var url=req.protocol + '://' + req.host + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path; + var result=sign(globalToken.ticket,url); + res.render('client',{config:config,result:result}); +} + +module.exports = router; diff --git a/pool/shard004/JavaScript/0026584_HaProxyHelper.js b/pool/shard004/JavaScript/0026584_HaProxyHelper.js new file mode 100644 index 0000000000000000000000000000000000000000..3eae3ea816d3dba8779ffe6edbfff0296f5cdc3e --- /dev/null +++ b/pool/shard004/JavaScript/0026584_HaProxyHelper.js @@ -0,0 +1,37 @@ +// ==UserScript== +// @name Haproxy Helper +// @namespace http://www.omnimed.com/ +// @version 0.3 +// @description Adds some cool functionality to Haproxy Web Management Interface +// @author Omnimed +// @match http://*/stats* +// @grant none +// @require https://code.jquery.com/jquery-2.1.4.min.js +// @require http://nylen.github.io/shiftcheckbox/jquery.shiftcheckbox.js +// ==/UserScript== + +var DISABLE_REFRESH = true; + +var $ = jQuery; + +$(function() { + if (DISABLE_REFRESH && window.location.href.indexOf('norefresh') == -1) { + window.location.href = window.location.href + ';norefresh'; + } + + $(':checkbox').shiftcheckbox(); + + $('th.pxname').each(function() { + $(this).prepend('').attr('width', '15%'); + }); +}); + +window.toggleSection = function(thead) { + jQuery(thead).parents('table').next().toggle(); + + return false; + +}; + +/* Display Host in DRAIN mode in yellow */ +$("td.ac:contains(DRAIN)").parent().css( "background-color", "#FAED6C" ); diff --git a/pool/shard004/JavaScript/0026589_config.js b/pool/shard004/JavaScript/0026589_config.js new file mode 100644 index 0000000000000000000000000000000000000000..08cd7d276c0c52e8326ae68cb204fe17eb021612 --- /dev/null +++ b/pool/shard004/JavaScript/0026589_config.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Blog configuration. + * @author Jak Wings + * @license The MIT License (MIT) + * @preserve Copyright (c) 2013 Jak Wings + */ +'use strict'; + + +define('blog.config', function () { + /** + * Configurations. + * 让普通用户自行修改的博客配置。 + * @constant {Object.} + */ + return { + /** + * Author name or your nick name. + * 博主名称。 + * @type {string} + */ + author: 'Cyan', + /** + * Main title of your blog. + * 博客主标题。 + * @type {string} + */ + title: 'Absolute Zero', + /** + * Subtitle of your blog. + * 博客副标题。 + * @type {string} + */ + subtitle: 'Let life be beautiful like summer flowers and death like autumn leaves.', + /** + * Current timezone. Format (ABNF): + * ("+" / "-") 1*2DIGIT [":" 1*2DIGIT [":" 1*2DIGIT [":" 1*2DIGIT]]] + * 当前时区。格式可以为形如 +08 或 +08:00 或 +08:00:00 , + * 分别代表相对于格林尼治标准时区的时分秒偏移量。 + * @type {string} + */ + timezone: '+08:00', + /** + * License information. + * 博客文章的版权信息。 + * @type {{text: string, url: string}} + */ + license: { + text: 'Creative Commons BY', + url: 'http://creativecommons.org/licenses/by/3.0/deed' + }, + /** + * Bulletin on sidebar. + * 博客公告栏信息。 + * @type {string} + */ + bulletin: 'Welcome!', + /** + * Links on side bar. + * 博客相关链接。 + * @type {Array.<{{text: string, url: string}}>} + */ + links: [ + {text: 'Cyanidea', url: 'http://cyanidea.com'}, + ], + /** + * Menu on sidebar. + * 博客菜单栏链接。 + * @type {Array.<{{title: string, url: string, file: string=}}>} + */ + menu: [ + {text: '首页', url: ''}, + {text: 'Wiedersehen Wiki', url: 'wiki', file: 'archives/wiki'}, + ], + /** + * Article links + * 博客文章链接,由旧到新排序。为了 SEO ,改由 HTML 源代码指定。 + * @type {Array.<{{title: string, url: string, file: string=}}>} + */ + articles: [], + /** + * Comment system Loader + * 评论框载入函数。 + * @param {Object} window global object + * @param {Element} container container of comments + * @param {string} id indentifier + * @param {string} url full url + */ + loadComment: function (window, container, id, url) { + // duoshuo.com + var duoshuo_shortname = 'duoshuo_shortname'; //修改此处 + // DON'T EDIT BELOW THIS LINE + if (!duoshuo_shortname) { return; } + var document = window.document; + if (!window.DUOSHUO) { + window.duoshuoQuery = {short_name: duoshuo_shortname}; + container.className += ' ds-thread'; + container.setAttribute('data-thread-key', id); + container.setAttribute('data-url', url); + container.setAttribute('data-title', document.title); + var ds = document.createElement('script'); + ds.type = 'text/javascript';ds.async = true; + ds.src = 'http://static.duoshuo.com/embed.js'; + ds.charset = 'UTF-8'; + (document.getElementsByTagName('head')[0] + || document.getElementsByTagName('body')[0]).appendChild(ds); + } else { + container.innerHTML = ''; + var clone = document.createElement('div'); + clone.id = 'ds-thread'; + clone.className = 'comments hide'; + clone.setAttribute('data-thread-key', id); + clone.setAttribute('data-url', url); + clone.setAttribute('data-title', document.title); + container.parentNode.replaceChild(clone, container); + window.DUOSHUO.EmbedThread(clone); + } + + //// disqus.com + //window.disqus_shortname = ''; + //// DON'T EDIT BELOW THIS LINE + //if (!window.disqus_shortname) { return; } + //var document = window.document; + //if (!window.DISQUS) { + // window.disqus_disable_mobile = false; + // window.disqus_identifier = id; + // window.disqus_url = url; + // window.disqus_title = document.title; + // container.id = 'disqus_thread'; + // var dsq = document.createElement('script'); + // dsq.type = 'text/javascript'; + // dsq.async = true; + // dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; + // (document.getElementsByTagName('head')[0] || + // document.getElementsByTagName('body')[0]).appendChild(dsq); + //} else { + // window.DISQUS.reset({ + // reload: true, + // config: function () { + // this.page.identifier = id; + // this.page.url = url; + // this.page.title = document.title; + // } + // }); + //} + }, + }; +}); diff --git a/pool/shard004/JavaScript/0026593_styleswitch.js b/pool/shard004/JavaScript/0026593_styleswitch.js new file mode 100644 index 0000000000000000000000000000000000000000..cdfbdb0745b56c1cb9d5fac26ee95476ba5010cc --- /dev/null +++ b/pool/shard004/JavaScript/0026593_styleswitch.js @@ -0,0 +1,69 @@ +"use strict"; + +class StyleSwitcher { + constructor () { + this.currentStylesheet = this.STYLE_DAY; + this.loadStyleFromCookie(); +} + + setActiveStyleSheet (style) { + const htmlClasses = document.documentElement.classList; + const setMethod = style === StyleSwitcher.STYLE_DAY ? htmlClasses.remove : htmlClasses.add; + setMethod.call(htmlClasses, StyleSwitcher.NIGHT_CLASS); + + StyleSwitcher.setButtonText(style); + + this.currentStylesheet = style; + StyleSwitcher.createCookie(this.currentStylesheet); + } + + static setButtonText (style) { + const $button = StyleSwitcher.getButton(); + if (!$button || !$button.length) { + return; +} + $button.html(`${style === StyleSwitcher.STYLE_DAY ? "Night" : "Day"} Mode`); +} + + getActiveStyleSheet () { + return this.currentStylesheet; +} + + loadStyleFromCookie () { + this.cookie = StyleSwitcher.readCookie(); + this.cookie = this.cookie ? this.cookie : StyleSwitcher.STYLE_DAY; + this.setActiveStyleSheet(this.cookie); + } + + static getButton () { + if (!window.$) { + return; + } + return $(".nightModeToggle"); +} + + static createCookie (value) { + Cookies.set("style", value, {expires: 365}); + } + + static readCookie () { + return Cookies.get("style"); + } + + toggleActiveStyleSheet () { + const newStyle = this.currentStylesheet === StyleSwitcher.STYLE_DAY ? StyleSwitcher.STYLE_NIGHT : StyleSwitcher.STYLE_DAY; + this.setActiveStyleSheet(newStyle); + } +} + +StyleSwitcher.STYLE_DAY = "day"; +StyleSwitcher.STYLE_NIGHT = "night"; +StyleSwitcher.NIGHT_CLASS = "night-mode"; + +// NIGHT MODE ========================================================================================================== +const styleSwitcher = new StyleSwitcher(); + +window.addEventListener("unload", function () { + const title = styleSwitcher.getActiveStyleSheet(); + StyleSwitcher.createCookie(title); +}); diff --git a/pool/shard004/JavaScript/0026595_mongo_translator.js b/pool/shard004/JavaScript/0026595_mongo_translator.js new file mode 100644 index 0000000000000000000000000000000000000000..db7e752a1ac173cc2fe6199bfbdbb95b988c4cce --- /dev/null +++ b/pool/shard004/JavaScript/0026595_mongo_translator.js @@ -0,0 +1,123 @@ +'use strict'; + +/** + * Module Dependencies + */ +var QueryTranslator = require('../query_translator'); +var Junction = require('../expressions/junction'); +var LikeExpression = require('../expressions/').LikeExpression; +var _ = require('lodash'); + +/** + * Extends the Session. + */ +QueryTranslator.extend(MongoTranslator); + +/** + * Static Local Variables + */ +var OP = { + eq : '$eq', + ge : '$gte', + gt : '$gt', + le : '$lte', + lt : '$lt', + ne : '$ne', + LIKE : '$eq', + AND : '$and', + OR : '$or' +}; + +/** + * Translate the criterion query to mongodb criteria query. + * + * @returns {MongoTranslator} + */ +function MongoTranslator() { +} + +/** + * Return the specified op equivalent. + * + * @param {String} op + * @returns {Object} + */ +MongoTranslator.prototype.parseOp = function(op) { + return OP[op]; +}; + +/** + * Returns the query of the criterion. + * + * @param {CriteriaImpl} criteria + * @param {Criterion} criterion + * @returns {Scalar} + */ +MongoTranslator.prototype.getQuery = function(criteria, criterion) { + var propertyName = criterion.propertyName; + var value = criterion.value; + var op = criterion.op; + var mongoOp = this.parseOp(op); + + var query = { }; + query[propertyName] = { }; + query[propertyName][mongoOp] = value; + + if (criterion instanceof LikeExpression) { + value = value.replace(/\%/g, '.*'). + replace(/\_/g, '.'); + value = new RegExp(value, 'i'); + + query[propertyName] = value; + } + + return query; +}; + +/** + * Returns the order query. + * + * @param {CriteriaImpl} criteria + * @param {Order} order + * @returns {Scalar} + */ +MongoTranslator.prototype.getOrderQuery = function(criteria, order) { + var query = { }; + query[order.propertyName] = order.ascending ? 1 : -1; + + return query; +}; + +/** + * Returns the junction query. + * + * @param {CriteriaImpl} criteria + * @param {Junction} junction + * @returns {Scalar} + */ +MongoTranslator.prototype.getJunctionQuery = function(criteria, junction) { + var nature = junction.nature; + var conditions = junction.conditions; + + if (conditions.length === 0) { + return { }; + } + + var mongoOp = this.parseOp(nature); + + var expressions = []; + conditions.forEach(function(criterion) { + var criterionQuery = criterion.getQuery(criteria, this); + expressions.push(criterionQuery); + }.bind(this)); + + var query = { }; + query[mongoOp] = expressions; + + return query; +}; + +/** + * Module Exports + */ +module.exports = MongoTranslator; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026597_DDPConnection.js b/pool/shard004/JavaScript/0026597_DDPConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..21a367e99d3b9cbd66cc92b70d34293489c0f138 --- /dev/null +++ b/pool/shard004/JavaScript/0026597_DDPConnection.js @@ -0,0 +1,269 @@ +import _try from 'fast.js/function/try'; +import _bind from 'fast.js/function/bind'; +import HeartbeatManager from './HeartbeatManager'; +const EventEmitter = typeof window !== 'undefined' && window.Mars + ? window.Mars.EventEmitter : require('marsdb').EventEmitter; +const PromiseQueue = typeof window !== 'undefined' && window.Mars + ? window.Mars.PromiseQueue : require('marsdb').PromiseQueue; +const EJSON = typeof window !== 'undefined' && window.Mars + ? window.Mars.EJSON : require('marsdb').EJSON; +const Random = typeof window !== 'undefined' && window.Mars + ? window.Mars.Random : require('marsdb').Random; + + +// Status of a DDP connection +const DDP_VERSION = '1'; +const HEARTBEAT_INTERVAL = 17500; +const HEARTBEAT_TIMEOUT = 15000; +const RECONNECT_INTERVAL = 5000; +export const CONN_STATUS = { + CONNECTING: 'CONNECTING', + CONNECTED: 'CONNECTED', + DISCONNECTED: 'DISCONNECTED', +}; + + +export default class DDPConnection extends EventEmitter { + constructor({ url, socket, autoReconnect = true }) { + super(); + this.url = url; + this._processQueue = new PromiseQueue(1); + this._sessionId = null; + this._autoReconnect = autoReconnect; + this._socket = socket; + this._status = CONN_STATUS.DISCONNECTED; + this._fullConnectedOnce = false; + + this._heartbeat = new HeartbeatManager( + HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT + ); + this._heartbeat.on('timeout', _bind(this._handleHearbeatTimeout, this)); + this._heartbeat.on('sendPing', _bind(this.sendPing, this)); + this._heartbeat.on('sendPong', _bind(this.sendPong, this)); + } + + /** + * Returns true if client is fully connected to a server + * @return {Boolean} + */ + get isConnected() { + return this._status === CONN_STATUS.CONNECTED; + } + + /** + * Returns true if client disconnected + * @return {Boolean} + */ + get isDisconnected() { + return this._status === CONN_STATUS.DISCONNECTED; + } + + /** + * Sends a "method" message to the server with given + * parameters + * @param {String} name + * @param {String} params + * @param {String} id + * @param {String} randomSeed + */ + sendMethod(name, params = [], id, randomSeed) { + const msg = { + msg: 'method', + id: id, + method: name, + params: params, + }; + if (randomSeed) { + msg.randomSeed = randomSeed; + } + this._sendMessage(msg); + } + + /** + * Send "sub" message to the server with given + * publusher name and parameters + * @param {String} name + * @param {Array} params + * @param {String} id + */ + sendSub(name, params = [], id) { + this._sendMessage({ + msg: 'sub', + id: id, + name: name, + params: params, + }); + } + + /** + * Send "unsub" message to the server for given + * subscription id + * @param {String} id + */ + sendUnsub(id) { + this._sendMessage({ + msg: 'unsub', + id: id, + }); + } + + /** + * Send a "ping" message with randomly generated ping id + */ + sendPing() { + this._sendMessage({ + msg: 'ping', + id: Random.default().id(20), + }); + } + + /** + * Sends a "pong" message for given id of ping message + * @param {String} id + */ + sendPong(id) { + this._sendMessage({ + msg: 'pong', + id: id, + }); + } + + /** + * Make a new WebSocket connection to the server + * if we are not connected yet (isDicsonnected). + * Returns true if connecting, false if already connectiong + * @returns {Boolean} + */ + connect() { + if (this.isDisconnected) { + this._rawConn = new (this._socket)(this.url); + this._rawConn.onopen = _bind(this._handleOpen, this); + this._rawConn.onerror = _bind(this._handleError, this); + this._rawConn.onclose = _bind(this._handleClose, this); + this._rawConn.onmessage = _bind(this._handleRawMessage, this); + this._setStatus(CONN_STATUS.CONNECTING); + return true; + } + return false; + } + + /** + * Reconnect to the server with unlimited tries. A period + * of tries is 5 seconds. It reconnects only if not + * connected. It cancels previously scheduled `connect` by `reconnect`. + * Returns a function for canceling reconnection process or undefined + * if connection is not disconnected. + * @return {Function} + */ + reconnect() { + if (this.isDisconnected) { + clearTimeout(this._reconnTimer); + this._reconnecting = true; + this._reconnTimer = setTimeout( + _bind(this.connect, this), + RECONNECT_INTERVAL + ); + + return () => { + clearTimeout(this._reconnTimer); + this._reconnecting = false; + this.disconnect(); + }; + } + } + + /** + * Close WebSocket connection. If autoReconnect is enabled + * (enabled by default), then after 5 sec reconnection will + * be initiated. + */ + disconnect() { + _try(() => this._rawConn && this._rawConn.close()); + } + + _handleOpen() { + this._heartbeat.waitPing(); + + const connMsg = { + msg: 'connect', + version: DDP_VERSION, + support: [DDP_VERSION], + }; + + if (this._sessionId) { + connMsg.session = this._sessionId; + } + + this._sendMessage(connMsg); + } + + _handleConnectedMessage(msg) { + if (!this.isConnected) { + const isTrulyReconnected = this._fullConnectedOnce && this._reconnecting; + this._setStatus(CONN_STATUS.CONNECTED, isTrulyReconnected); + this._sessionId = msg.session; + this._reconnecting = false; + this._fullConnectedOnce = true; + } + } + + _handleClose() { + this._heartbeat._clearTimers(); + this._setStatus(CONN_STATUS.DISCONNECTED, this._fullConnectedOnce); + + if (this._autoReconnect) { + this._reconnecting = false; + this.reconnect(); + } + } + + _handleHearbeatTimeout() { + this.disconnect(); + } + + _handleError(error) { + this.emit('error', error); + } + + _handleRawMessage(rawMsg) { + return this._processQueue.add(() => { + const msgObj = EJSON.parse(rawMsg.data); + return this._processMessage(msgObj); + }).then(null, err => { + this._handleError(err); + }); + } + + _processMessage(msg) { + switch (msg.msg) { + case 'connected': return this._handleConnectedMessage(msg); + case 'ping': return this._heartbeat.handlePing(msg); + case 'pong': return this._heartbeat.handlePong(msg); + case 'removed': + case 'changed': + case 'added': + case 'updated': + case 'result': + case 'nosub': + case 'ready': + case 'error': + return this.emitAsync(`message:${msg.msg}`, msg); + default: + // just ignore unknown message + } + } + + _sendMessage(msgObj) { + const result = _try(() => + this._rawConn.send(EJSON.stringify(msgObj)) + ); + if (result instanceof Error) { + this._handleError(result); + } + } + + _setStatus(status, a) { + this._status = status; + this.emit(`status:${status}`.toLowerCase(), a); + } +} diff --git a/pool/shard004/JavaScript/0026598_index.js b/pool/shard004/JavaScript/0026598_index.js new file mode 100644 index 0000000000000000000000000000000000000000..78464dbea9b31dba6c579a658c8f1daf7724cc2d --- /dev/null +++ b/pool/shard004/JavaScript/0026598_index.js @@ -0,0 +1,40 @@ +"use strict"; + +var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + avatarClasses: true +}; +Object.defineProperty(exports, "default", { + enumerable: true, + get: function () { + return _Avatar.default; + } +}); +Object.defineProperty(exports, "avatarClasses", { + enumerable: true, + get: function () { + return _avatarClasses.default; + } +}); + +var _Avatar = _interopRequireDefault(require("./Avatar")); + +var _avatarClasses = _interopRequireWildcard(require("./avatarClasses")); + +Object.keys(_avatarClasses).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _avatarClasses[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _avatarClasses[key]; + } + }); +}); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026602_update.js b/pool/shard004/JavaScript/0026602_update.js new file mode 100644 index 0000000000000000000000000000000000000000..3e055b1e7dddd1cd97e47f48d703a3a3524753e3 --- /dev/null +++ b/pool/shard004/JavaScript/0026602_update.js @@ -0,0 +1,32 @@ +/** + * Created by Administrator on 2015/10/14. + */ +'use strict'; +var EditPager = require('../views/EditPager'); +var database = require('../database'); +var query = require('./query'); +var post = require('./post'); +var IndexAction = require('./index'); +var LoginAction = require('./login'); +module.exports = function(req,res){ + + if(!req.session.isLogined){ + LoginAction(req,res); + return; + } + + if(req.method == 'GET'){ + var id = query(req).id; + var article = database.list[id]; + var errors = {}; + res.end(new EditPager(id,article,errors,req.session.isLogined).render()); + }else{ + post(req).then(data =>{ +// let {id,title,body} = data; + let id = data.id; + delete data.id; + database.update(data.id,data); + IndexAction(req,res); + }) + } +}; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026605_GraphEdge.js b/pool/shard004/JavaScript/0026605_GraphEdge.js new file mode 100644 index 0000000000000000000000000000000000000000..5b1c2fc896f2d8f48fe966594cc3f768d4411cac --- /dev/null +++ b/pool/shard004/JavaScript/0026605_GraphEdge.js @@ -0,0 +1,69 @@ +var GraphEdge = cc.DrawNode.extend({ + + // + // Members + // + + m_ObjectA : null, // GraphNode + m_ObjectB : null, // GraphNode + m_NameLabel : null, // cc.Label + + // + // Construction + // + + ctor : function( + objectA, // GraphNode + objectB, // GraphNode + name // String + ) + { + this._super(); + + this.m_ObjectA = objectA; + this.m_ObjectB = objectB; + + this.m_NameLabel = cc.LabelTTF.create(name, "Arial", 20); + this.m_NameLabel.setColor(cc.color(204, 204, 0)); + this.addChild(this.m_NameLabel); + + objectA.addEdge(this); + objectB.addEdge(this); + + this.graphNodeUpdated(); + }, + + // + // Interface + // + + graphNodeUpdated : function() + { + var pos1 = this.m_ObjectA.getPosition(); + var pos2 = this.m_ObjectB.getPosition(); + + this.setPosition(pos1); + + var vector = cc.pSub(pos2, pos1); + var vectorLength = cc.pLength(vector); + + var angle = Math.acos(vector.x / vectorLength) * 57.295; + + this.setRotation(pos1.y < pos2.y ? -angle : angle); + + var size = cc.size(vectorLength, 18); + + this.clear(); + this.drawRect(cc.p(0, 0), cc.p(size.width, 3), cc.color(51, 102, 255, 255)); + + var vtx = [ + cc.p(size.width, -6), + cc.p(size.width, 6), + cc.p(size.width + 12, 1.5) + ]; + + this.drawPoly(vtx, cc.color(51, 102, 255, 255), 1, cc.color(255, 255, 255, 255)); + + this.m_NameLabel.setPosition(size.width * 0.5, size.height); + } +}); diff --git a/pool/shard004/JavaScript/0026607_addCommand.js b/pool/shard004/JavaScript/0026607_addCommand.js new file mode 100644 index 0000000000000000000000000000000000000000..74e809277d21c51f64240e78867f4cf0389a20d6 --- /dev/null +++ b/pool/shard004/JavaScript/0026607_addCommand.js @@ -0,0 +1,63 @@ +describe('addCommand', function() { + + before(h.setup()); + + describe('add regular command', function() { + + before(function() { + this.client.addCommand('getUrlAndTitle', function() { + + var result = {}; + + return this.url().then(function(url) { + result.url = url.value; + }).getTitle().then(function(title) { + result.title = title; + }).then(function() { + return result; + }); + + }); + }); + + it('added a `getUrlAndTitle` command', function() { + return this.client.getUrlAndTitle().then(function(result) { + assert.strictEqual(result.url, conf.testPage.start); + assert.strictEqual(result.title, conf.testPage.title); + }); + }); + + it('should promisify added command', function() { + return this.client.getUrlAndTitle().then(function(result) { + assert.strictEqual(result.url, conf.testPage.start); + assert.strictEqual(result.title, conf.testPage.title); + }); + }); + + }); + + describe('try to add an existing command', function() { + + it('should throw an error', function() { + var self = this; + + (function(){ + self.client.addCommand('shake', function() { + return 'should fail'; + }); + }).should.throw(); + }); + + it('should overwrite existing method if overwrite flag is given', function() { + this.client.addCommand('shake', function() { + return 'should not fail'; + }, true); + + return this.client.shake().then(function(res) { + expect(res).to.be.equal('should not fail'); + }); + }); + + }); + +}); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026612_mousepress.js b/pool/shard004/JavaScript/0026612_mousepress.js new file mode 100644 index 0000000000000000000000000000000000000000..3ce1929ab4ee4364c3fe0d6b7ce6e43f1d52db09 --- /dev/null +++ b/pool/shard004/JavaScript/0026612_mousepress.js @@ -0,0 +1,60 @@ +/* + * simple helper for a mousepress event + * used by webshims improving spinbutton controls for input[type=time], input[type=number]... + * + * $(element).bind('mousepress', function(){ + * //repeatedly called after mousedown, till mouseleave/mouseup + * }); + */ +(function($){ + var removeTimer = function(elem, full){ + var timer = elem.data('mousepresstimer'); + if(timer){ + clearTimeout(timer); + } + if(full){ + elem.unbind('mouseup.mousepressext mouseleave.mousepressext'); + } + elem = null; + }; + $.event.special.mousepress = { + setup: function(){ + var timer; + $(this).bind('mousedown.mousepressext', function(e){ + var elem = $(this); + + var startIntervall = function(delay){ + var steps = 0; + removeTimer(elem); + elem.data('mousepresstimer', setInterval(function(){ + $.event.special.mousepress.handler(elem[0], e); + steps++; + if(steps > 3 && delay > 45){ + startIntervall(delay - 40); + } + }, delay)); + }; + var target = $(e.target).trigger('mousepressstart', [e]); + + removeTimer(elem); + elem.data('mousepresstimer', setTimeout(function(){ + startIntervall(180); + }, 200)); + + elem.bind('mouseup.mousepressext mouseleave.mousepressext', function(e){ + removeTimer(elem, true); + target.trigger('mousepressend', [e]); + elem = null; + target = null; + }); + }); + }, + teardown: function(){ + removeTimer($(this).unbind('.mousepressext'), true); + }, + handler: function(elem, e){ + return ($.event.dispatch || $.event.handle).call(elem, {type: 'mousepress', target: e.target, pageX: e.pageX, pageY: e.pageY}); + } + }; + +})(jQuery); diff --git a/pool/shard004/JavaScript/0026613_input-list.js b/pool/shard004/JavaScript/0026613_input-list.js new file mode 100644 index 0000000000000000000000000000000000000000..a15e68d8969bcca0d0777a8c504cfbfdc440d035 --- /dev/null +++ b/pool/shard004/JavaScript/0026613_input-list.js @@ -0,0 +1,29 @@ +jQuery( function ( $ ) { + function update() { + var $this = $( this ), + $children = $this.closest( 'li' ).children( 'ul' ); + + if ( $this.is( ':checked' ) ) { + $children.removeClass( 'hidden' ); + } else { + $children + .addClass( 'hidden' ) + .find( 'input' ) + .removeAttr( 'checked' ); + } + } + + $( '.rwmb-input' ) + .on( 'change', '.rwmb-input-list.collapse :checkbox', update ) + .on( 'clone', '.rwmb-input-list.collapse :checkbox', update ); + $( '.rwmb-input-list.collapse :checkbox' ).each( update ); + + $( '.rwmb-input-list-select-all-none' ).toggle( + function () { + $('input.rwmb-checkbox_list[name="' + $(this).data('name') + '[]"]').prop('checked', true); + }, + function () { + $('input.rwmb-checkbox_list[name="' + $(this).data('name') + '[]"]').prop('checked', false); + } + ); +} ); diff --git a/pool/shard004/JavaScript/0026615_columnAnimationService.js b/pool/shard004/JavaScript/0026615_columnAnimationService.js new file mode 100644 index 0000000000000000000000000000000000000000..3e972d3b5b25bf8068b0dc7bfa8a8f4ffaea0248 --- /dev/null +++ b/pool/shard004/JavaScript/0026615_columnAnimationService.js @@ -0,0 +1,106 @@ +/** + * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components + * @version v18.0.0 + * @link http://www.ag-grid.com/ + * @license MIT + */ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var context_1 = require("../context/context"); +var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); +var ColumnAnimationService = (function () { + function ColumnAnimationService() { + this.executeNextFuncs = []; + this.executeLaterFuncs = []; + this.active = false; + this.animationThreadCount = 0; + } + ColumnAnimationService.prototype.registerGridComp = function (gridPanel) { + this.gridPanel = gridPanel; + }; + ColumnAnimationService.prototype.isActive = function () { + return this.active; + }; + ColumnAnimationService.prototype.start = function () { + if (this.active) { + return; + } + if (this.gridOptionsWrapper.isSuppressColumnMoveAnimation()) { + return; + } + // if doing RTL, we don't animate open / close as due to how the pixels are inverted, + // the animation moves all the row the the right rather than to the left (ie it's the static + // columns that actually get their coordinates updated) + if (this.gridOptionsWrapper.isEnableRtl()) { + return; + } + this.ensureAnimationCssClassPresent(); + this.active = true; + }; + ColumnAnimationService.prototype.finish = function () { + if (!this.active) { + return; + } + this.flush(); + this.active = false; + }; + ColumnAnimationService.prototype.executeNextVMTurn = function (func) { + if (this.active) { + this.executeNextFuncs.push(func); + } + else { + func(); + } + }; + ColumnAnimationService.prototype.executeLaterVMTurn = function (func) { + if (this.active) { + this.executeLaterFuncs.push(func); + } + else { + func(); + } + }; + ColumnAnimationService.prototype.ensureAnimationCssClassPresent = function () { + var _this = this; + // up the count, so we can tell if someone else has updated the count + // by the time the 'wait' func executes + this.animationThreadCount++; + var animationThreadCountCopy = this.animationThreadCount; + this.gridPanel.setColumnMovingCss(true); + this.executeLaterFuncs.push(function () { + // only remove the class if this thread was the last one to update it + if (_this.animationThreadCount === animationThreadCountCopy) { + _this.gridPanel.setColumnMovingCss(false); + } + }); + }; + ColumnAnimationService.prototype.flush = function () { + var nowFuncs = this.executeNextFuncs; + this.executeNextFuncs = []; + var waitFuncs = this.executeLaterFuncs; + this.executeLaterFuncs = []; + if (nowFuncs.length === 0 && waitFuncs.length === 0) { + return; + } + setTimeout(function () { return nowFuncs.forEach(function (func) { return func(); }); }, 0); + setTimeout(function () { return waitFuncs.forEach(function (func) { return func(); }); }, 300); + }; + __decorate([ + context_1.Autowired('gridOptionsWrapper'), + __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) + ], ColumnAnimationService.prototype, "gridOptionsWrapper", void 0); + ColumnAnimationService = __decorate([ + context_1.Bean('columnAnimationService') + ], ColumnAnimationService); + return ColumnAnimationService; +}()); +exports.ColumnAnimationService = ColumnAnimationService; diff --git a/pool/shard004/JavaScript/0026618_stateGetter.test.js b/pool/shard004/JavaScript/0026618_stateGetter.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bf796d156b252a4278af08c2b9cb5f03d4336c75 --- /dev/null +++ b/pool/shard004/JavaScript/0026618_stateGetter.test.js @@ -0,0 +1,160 @@ +import expect from 'expect'; +import { fromJS, Map, List } from 'immutable'; +import { stateGetter } from './../../src/util/stateGetter'; + +describe('State Getter Function', () => { + + // sample redux wrapper for state.get + function getState() { + return true; + } + + function getStateWithImmutable() { + return Map({ + x: 1 + }); + } + + it('Should return state if its registered', () => { + const state = { filterState: { get: getState } }; + const props = {}; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toBeTruthy(); + }); + + it('Should return an immutable object if state is immutable', () => { + const state = { filterState: { get: getStateWithImmutable } }; + const props = {}; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(Map({ + x: 1 + })); + }); + + it('Should return null if it\'s not registered', () => { + const state = { filterState: { get: getState } }; + const props = {}; + expect( + stateGetter(state, props, 'unknownState', 'someProp') + ).toEqual(null); + }); + + it('Should return state when a dynamic key is used if registerd', () => { + const state = { someFilterState: { get: getState } }; + const props = { + reducerKeys: { + filterState: 'someFilterState' + } + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toBeTruthy(); + }); + + it(['Should return state when a dynamic key ', + 'is used, and has immutable state'].join(''), () => { + const state = { someFilterState: { get: getStateWithImmutable } }; + const props = { + reducerKeys: { + filterState: 'someFilterState' + } + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(Map({ + x: 1 + })); + }); + + it('Should return null if a dynamic key is used if not registered', () => { + const state = {}; + const props = { + reducerKeys: { + filterState: 'someFilterState' + } + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(null); + }); + + it('Should return state when it is nested and registered', () => { + const state = { nested: {filterState: { get: getState } } }; + const props = { + reducerKeys: 'nested' + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toBeTruthy(); + }); + + it(['Should return state when it is nested ', + 'and has immutable state'].join(''), () => { + const state = { + nested: { filterState: { get: getStateWithImmutable } } + }; + + const props = { + reducerKeys: 'nested' + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(Map({ + x: 1 + })); + }); + + it(['Should return state when it is nested in an immutable object ', + 'and has immutable state'].join(''), () => { + const state = Map({ + nested: { filterState: { get: getStateWithImmutable } } + }); + + const props = { + reducerKeys: 'nested' + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(Map({ + x: 1 + })); + }); + + it('Should return null if state is nested and not registered', () => { + const state = { nested: {} }; + const props = { + reducerKeys: 'nested' + }; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(null); + }); + + it('Should return null when no keys and no state are provided', () => { + const state = {}; + const props = {}; + expect( + stateGetter(state, props, 'filterState', 'someProp') + ).toEqual(null); + }); + + it('Should return state when its stored using immutable', () => { + const state = fromJS({ data: { thing: [1] } }); + const props = {}; + + expect( + stateGetter(state, props, 'data', 'thing') + ).toEqual(List([1])); + }); + + it('Should return state when its not stored using immutable', () => { + const state = { data: { thing: [1] } }; + const props = {}; + + expect( + stateGetter(state, props, 'data', 'thing') + ).toEqual([1]); + }); +}); diff --git a/pool/shard004/JavaScript/0026621_selenium.js b/pool/shard004/JavaScript/0026621_selenium.js new file mode 100644 index 0000000000000000000000000000000000000000..dc656d49b56331c293986d45fa7b790ca4059492 --- /dev/null +++ b/pool/shard004/JavaScript/0026621_selenium.js @@ -0,0 +1,222 @@ +steal('steal/browser', function(){ + steal.browser.selenium = function(options){ + // kill the server in case it was running from before + this.killServer(); + steal.browser.call(this, options, 'selenium') + this._startServer(); + this.clientPath = "funcunit/selenium"; + } + steal.extend(steal.browser.selenium, { + defaults: { + serverPort: 4444, + serverHost: "localhost" + }, + trigger: function(){ + browser.trigger.apply(self, arguments); + } + }); + steal.browser.selenium.prototype = new steal.browser(); + steal.extend(steal.browser.selenium.prototype, { + /** + * Opens the browser, at each of the specified browsers, one by one + * @param {Object} page + * @param {Object} browsers + */ + open: function(page, browsers){ + this._currentBrowserIndex = 0; + this.page = this._getPageUrl(page); + this.browsers = browsers || ["*firefox"]; + this._browserStart(0); + this._poll(); + // block until we're done + this.browserOpen = true; + while(this.browserOpen) { + java.lang.Thread.currentThread().sleep(1000); + } + return this; + }, + _loadDriverClass: function() { + var URLClassLoader = Packages.java.net.URLClassLoader, + URL = java.net.URL, + File = java.io.File, + ss = new File("funcunit/selenium/selenium-java-client-driver.jar"), + ssurl = ss.toURL(), + urls = java.lang.reflect.Array.newInstance(URL, 1); + urls[0] = new URL(ssurl); + + var clazzLoader = new URLClassLoader(urls), + mthds = clazzLoader.loadClass("com.thoughtworks.selenium.DefaultSelenium").getDeclaredConstructors(), + rawMeth = null; + //iterate through methods to find the one we are looking for + for ( var i = 0; i < mthds.length; i++ ) { + var meth = mthds[i]; + if ( meth.toString().match(/DefaultSelenium\(java.lang.String,int,java.lang.String,java.lang.String\)/) ) { + constructor = meth; + } + } + return function( serverHost, serverPort, browserStartCommand, browserURL ) { + var host = new java.lang.String(serverHost), + port = new java.lang.Integer(serverPort), + cmd = new java.lang.String(browserStartCommand), + url = new java.lang.String(browserURL); + return constructor.newInstance(host, port, cmd, url); + }; + }, + _startServer: function(){ + //first lets ping and make sure the server is up + var port = this.options.serverPort, + addr = java.net.InetAddress.getByName(this.options.serverHost) + try { + var s = new java.net.Socket(addr, port) + } + catch (ex) { + spawn(function(){ + var jarCommand = 'java -jar '+ + 'funcunit/selenium/selenium-server-standalone-2.12.0.jar'+ + ' -userExtensions funcunit/selenium/user-extensions.js'; + if (java.lang.System.getProperty("os.name").indexOf("Windows") != -1) { + var command = 'start "selenium" ' + jarCommand; + runCommand("cmd", "/C", command.replace(/\//g, "\\")) + } + else { + var command = jarCommand + " > selenium.log 2> selenium.log &"; + runCommand("sh", "-c", command); + } + }) + var timeouts = 0, + started = false; + var pollSeleniumServer = function(){ + try { + var s = new java.net.Socket(addr, port) + started = true; + } + catch (ex) { + if (timeouts > 20) { + print("Selenium is not running. Please use js -selenium to start it.") + quit(); + } else { + timeouts++; + } + } + } + while(!started){ + java.lang.Thread.currentThread().sleep(1000); + pollSeleniumServer(); + } + } + this.DefaultSelenium = this._loadDriverClass(); + }, + killServer: function(){ + if (java.lang.System.getProperty("os.name").indexOf("Windows") != -1) { + runCommand("cmd", "/C", 'taskkill /fi "Windowtitle eq selenium" > NUL') + } else { // mac + runCommand("sh", "-c", "ps aux | awk '/selenium\\// {print$2}' | xargs kill -9") + } + }, + // create new selenium instance, start it, open page, set FuncUnit.mode = "Selenium", start polling for data + _browserStart: function(index){ + var browser = this.browsers[this._currentBrowserIndex]; + this.trigger("browserStart", { + browser: browser + }) + this.selenium = this.DefaultSelenium(this.options.serverHost, + this.options.serverPort, + browser, + this.page); + this.selenium.start(); + this.selenium.open(this.page); + selThreads.resumePolling(); + }, + close: function(data){ + //print(">>>>>>>>>> CLOSING") + //this.keepPolling = false; + var browser = this.browsers[this._currentBrowserIndex]; + this.trigger("browserDone", { + browser: browser + }); + selThreads.pausePolling(); + this.selenium.close(); + this.selenium.stop(); + //print(">>>>>>>>>> STOPPED") + this._currentBrowserIndex++; + if (this._currentBrowserIndex < this.browsers.length) { + this._browserStart(this._currentBrowserIndex) + } + else { + selThreads.stopPolling(); + //print(">>>>>>>>>> ALL DONE") + this.trigger("allDone"); + this.killServer(); + this.browserOpen = false; + } + }, + evaluate: function(fn){ + var txt = fn.toString().replace(/\n|\r\n/g,""), + evalText = "Selenium.evaluate('"+txt+"')"; + var res = this.selenium.getEval(evalText); + res = ""+res; + return res; + }, + injectJS: function(file){ + var scriptText = readFile(file).replace(/\n|\r\n/g,""), + evalText = "Selenium.injectJS('"+escape(scriptText)+"')"; + this.selenium.getEval(evalText); + return true; + }, + _poll: function(){ + selThreads.poll(this); + + } + }); + + var keepPolling = false, + stopPolling = false; + + + var selThreads = { + poll : function(self){ + this.resumePolling(); + + spawn(function(){ + + var stop = selThreads.getResult(self); + if(!stop){ + java.lang.Thread.currentThread().sleep(350); + arguments.callee(); + } + }) + + }, + pausePolling : sync(function(){ + keepPolling = false; + }), + resumePolling : sync(function(){ + keepPolling = true; + }), + stopPolling : sync(function(){ + stopPolling = true; + keepPolling = false; + }), + getResult : sync(function(self){ + if(!keepPolling){ + return stopPolling; + } + var resultJSON, + res, + evt; + //self.keepPolling = true; + //print(">>>>>>>>>> POLLING") + resultJSON = self.selenium.getEval("Selenium.getResult()"); + eval("res = "+resultJSON); + if(res && res.length){ + for (var i = 0; i < res.length; i++) { + evt = res[i]; + self.trigger(evt.type, evt.data); + } + } + return stopPolling; + }), + keepPolling : false + } + +}) \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026623_tooltip.js b/pool/shard004/JavaScript/0026623_tooltip.js new file mode 100644 index 0000000000000000000000000000000000000000..cf38c6542db9e01835381acbe6586f00ff91fd51 --- /dev/null +++ b/pool/shard004/JavaScript/0026623_tooltip.js @@ -0,0 +1,127 @@ +'use strict'; + +/* Services */ + + +angular.module('tooltip', []). + factory('tooltip', ['$rootScope', '$compile', function($rootScope, $compile) { + // init tooltip + var scope = $rootScope.$new(true); + var isMouseInTooltip = false; + scope.onmouseenter = function() { + // mouse enters tooltip + isMouseInTooltip = true; + }; + scope.onmouseleave = function() { + // mouse leaves tooltip + isMouseInTooltip = false; + hide(); + }; + var _left = 0; + var _top = 0; + + var tooltip = $compile('
')(scope); + tooltip.css('max-width', viewWidth() + 'px'); + + // append tooltip to the end of body element + angular.element(document.getElementsByTagName('body')[0]).append(tooltip); + + + function viewWidth() { + // FIXME: why -32 here? + return (window.innerWidth || document.documentElement.clientWidth) - 32; + } + + function setContent(content) { + tooltip.children().remove(); + if (angular.isUndefined(content)) { + throw 'In tooltip: content undefined!'; + } else if (angular.isString(content)) { + tooltip.html(content); + } else { + tooltip.append(content); + } + } + + function setPosition(position) { + _left = parseInt(position.left.replace('px', '')); + _top = parseInt(position.top.replace('px', '')); + } + + function show() { + // move tooltip to the right + // (don't cross the right side of browser inner window) + var _right = _left + tooltip.prop('offsetWidth'); + if ( _right > viewWidth() ) + _left -= (_right - viewWidth()); + + tooltip.css('left', _left + 'px'); + tooltip.css('top', _top + 'px'); + } + + function hide() { + if (!isMouseInTooltip) + tooltip.css('left', '-9999px'); + } + + var serviceInstance = { + viewWidth: viewWidth, + isHidden: function() {return (tooltip.css('left') === '-9999px');}, + getLeftSpace: function() {return _left;}, + getRightSpace: function() {return viewWidth() - _left - tooltip.prop('offsetWidth');}, + setContent: setContent, + setPosition: setPosition, + show: show, + hide: hide + }; + return serviceInstance; + }]). + + factory('AddTooltipToElement', ['tooltip', function(tooltip) { + // when user's mouse hovers over words, + // delay a period of time before look up. + var DELAY_INTERVAL = 1000; // ms + + var isMouseInWord = false; + + function onWordMouseOver(e) { + isMouseInWord = true; + this.style.color = 'red'; + + setTimeout(angular.bind(this, function() { + // 'this' keyword here refers to raw dom element + if (this.style.color === 'red') { + // mouse is still on word + var word = this.innerHTML.toLowerCase(); + tooltip.setContent( + word + ' ' + word + '
' + + '' + word + '' + ' ' + word + ); + tooltip.setPosition({ + 'left': (this.getBoundingClientRect().left + 'px'), + 'top': (this.getBoundingClientRect().top + this.offsetHeight + 'px'), + }); + tooltip.show(); + } + }), DELAY_INTERVAL); + } + + function onWordMouseOut(e) { + isMouseInWord = false; + this.style.color = ''; + + setTimeout(angular.bind(this, function() { + if (!isMouseInWord) { + tooltip.hide(); + } + }), DELAY_INTERVAL); + } + + function add(elm) { + elm.onmouseover = onWordMouseOver; + elm.onmouseout = onWordMouseOut; + } + + var serviceInstance = { add: add }; + return serviceInstance; + }]); diff --git a/pool/shard004/JavaScript/0026626_cookies.js b/pool/shard004/JavaScript/0026626_cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..1915a48f6b38b572e571d0b2ec3f63aa6ce6a3ce --- /dev/null +++ b/pool/shard004/JavaScript/0026626_cookies.js @@ -0,0 +1,147 @@ +/* + * Cookies.js - 1.0.1 + * https://github.com/ScottHamper/Cookies + * + * This is free and unencumbered software released into the public domain. + */ +(function (undefined) { + 'use strict'; + + var Cookies = function (key, value, options) { + return arguments.length === 1 ? + Cookies.get(key) : Cookies.set(key, value, options); + }; + + // Allows for setter injection in unit tests + Cookies._document = document; + Cookies._navigator = navigator; + + // Used to ensure cookie keys do not collide with + // built-in `Object` properties + Cookies._cacheKeyPrefix = 'cookey.'; // Hurr hurr, :) + + Cookies.defaults = { + path: '/', + secure: false + }; + + Cookies.get = function (key) { + if (Cookies._cachedDocumentCookie !== Cookies._document.cookie) { + Cookies._renewCache(); + } + + return Cookies._cache[Cookies._cacheKeyPrefix + key]; + }; + + Cookies.set = function (key, value, options) { + options = Cookies._getExtendedOptions(options); + options.expires = Cookies._getExpiresDate(value === undefined ? -1 : options.expires); + + Cookies._document.cookie = Cookies._generateCookieString(key, value, options); + + return Cookies; + }; + + Cookies.expire = function (key, options) { + return Cookies.set(key, undefined, options); + }; + + Cookies._getExtendedOptions = function (options) { + return { + path: options && options.path || Cookies.defaults.path, + domain: options && options.domain || Cookies.defaults.domain, + expires: options && options.expires || Cookies.defaults.expires, + secure: options && options.secure !== undefined ? options.secure : Cookies.defaults.secure + }; + }; + + Cookies._isValidDate = function (date) { + return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime()); + }; + + Cookies._getExpiresDate = function (expires, now) { + now = now || new Date(); + switch (typeof expires) { + case 'number': expires = new Date(now.getTime() + expires * 1000); break; + case 'string': expires = new Date(expires); break; + } + + if (expires && !Cookies._isValidDate(expires)) { + throw new Error('`expires` parameter cannot be converted to a valid Date instance'); + } + + return expires; + }; + + Cookies._generateCookieString = function (key, value, options) { + key = key.replace(/[^#$&+\^`|]/g, encodeURIComponent); + key = key.replace(/\(/g, '%28').replace(/\)/g, '%29'); + value = (value + '').replace(/[^!#$&-+\--:<-\[\]-~]/g, encodeURIComponent); + options = options || {}; + + var cookieString = key + '=' + value; + cookieString += options.path ? ';path=' + options.path : ''; + cookieString += options.domain ? ';domain=' + options.domain : ''; + cookieString += options.expires ? ';expires=' + options.expires.toUTCString() : ''; + cookieString += options.secure ? ';secure' : ''; + + return cookieString; + }; + + Cookies._getCacheFromString = function (documentCookie) { + var cookieCache = {}; + var cookiesArray = documentCookie ? documentCookie.split('; ') : []; + + for (var i = 0; i < cookiesArray.length; i++) { + var cookieKvp = Cookies._getKeyValuePairFromCookieString(cookiesArray[i]); + + if (cookieCache[Cookies._cacheKeyPrefix + cookieKvp.key] === undefined) { + cookieCache[Cookies._cacheKeyPrefix + cookieKvp.key] = cookieKvp.value; + } + } + + return cookieCache; + }; + + Cookies._getKeyValuePairFromCookieString = function (cookieString) { + // "=" is a valid character in a cookie value according to RFC6265, so cannot `split('=')` + var separatorIndex = cookieString.indexOf('='); + + // IE omits the "=" when the cookie value is an empty string + separatorIndex = separatorIndex < 0 ? cookieString.length : separatorIndex; + + return { + key: decodeURIComponent(cookieString.substr(0, separatorIndex)), + value: decodeURIComponent(cookieString.substr(separatorIndex + 1)) + }; + }; + + Cookies._renewCache = function () { + Cookies._cache = Cookies._getCacheFromString(Cookies._document.cookie); + Cookies._cachedDocumentCookie = Cookies._document.cookie; + }; + + Cookies._areEnabled = function () { + var testKey = 'cookies.js'; + var areEnabled = Cookies.set(testKey, 1).get(testKey) === '1'; + Cookies.expire(testKey); + return areEnabled; + }; + + Cookies.enabled = Cookies._areEnabled(); + + // AMD support + if (typeof define === 'function' && define.amd) { + define(function () { return Cookies; }); + // CommonJS and Node.js module support. + } else if (typeof exports !== 'undefined') { + // Support Node.js specific `module.exports` (which can be a function) + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Cookies; + } + // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function) + exports.Cookies = Cookies; + } else { + window.Cookies = Cookies; + } +})(); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026631_jobStatistic.js b/pool/shard004/JavaScript/0026631_jobStatistic.js new file mode 100644 index 0000000000000000000000000000000000000000..98bd9d096fbce6692c9abc0e92f12f9d4cd50bb6 --- /dev/null +++ b/pool/shard004/JavaScript/0026631_jobStatistic.js @@ -0,0 +1,108 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +(function () { + /** + * `register` without params will load the module which using require + */ + register(function (jpmApp) { + jpmApp.directive("jpmWidget", function () { + return { + restrict: 'AE', + controller: function($scope, $interval, Application, JPM, Time) { + var site = $scope.site; + var refreshInterval; + + if(!site) { + $scope.list = $.map(Application.find("JPM_WEB_APP"), function (app) { + return { + siteId: app.site.siteId, + siteName: app.site.siteName || app.site.siteId, + count: -1 + }; + }); + } else { + $scope.list = [{ + siteId: site.siteId, + siteName: site.siteName || site.siteId, + count: -1 + }]; + } + + function refresh() { + $.each($scope.list, function (i, site) { + var query = JPM.getQuery("GROUPS", site.siteId); + var url = common.template(query, { + query: "RunningJobExecutionService", + condition: '@site="' + site.siteId + '" AND @internalState="RUNNING"', + groups: "@site", + field: "count", + order: "", + top: "", + limit: 100000, + startTime: Time.format(Time().subtract(3, "d")), + endTime: Time.format(Time().add(1, "d")) + }); + JPM.get(url).then(function (res) { + site.count = common.getValueByPath(res, ["data", "obj", 0, "value", 0]); + }); + }); + } + + refresh(); + refreshInterval = $interval(refresh, 30 * 1000); + + $scope.$on('$destroy', function() { + $interval.cancel(refreshInterval); + }); + }, + template: + '
' + + '' + + '
' + + '' + + '
' + + '
', + replace: true + }; + }); + + /** + * Customize the widget content. Return false will prevent auto compile. + * @param {{}} $element + * @param {function} $element.append + */ + function registerWidget($element) { + $element.append( + $("
") + ); + } + + jpmApp.widget("jobStatistic", registerWidget); + jpmApp.widget("jobStatistic", registerWidget, true); + }); +})(); diff --git a/pool/shard004/JavaScript/0026635_editor_plugin.js b/pool/shard004/JavaScript/0026635_editor_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f2c8273867b3583614f37a77b8a9fd5c39de83b7 --- /dev/null +++ b/pool/shard004/JavaScript/0026635_editor_plugin.js @@ -0,0 +1,80 @@ +/** + * editor_plugin_src.js + * + * Copyright 2009, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://tinymce.moxiecode.com/license + * Contributing: http://tinymce.moxiecode.com/contributing + */ + +(function() { + tinymce.create('tinymce.plugins.StylePlugin', { + init : function(ed, url) { + // Register commands + ed.addCommand('mceStyleProps', function() { + + var applyStyleToBlocks = false; + var blocks = ed.selection.getSelectedBlocks(); + var styles = []; + + if (blocks.length === 1) { + styles.push(ed.selection.getNode().style.cssText); + } + else { + tinymce.each(blocks, function(block) { + styles.push(ed.dom.getAttrib(block, 'style')); + }); + applyStyleToBlocks = true; + } + + ed.windowManager.open({ + file : url + '/props.htm', + width : 480 + parseInt(ed.getLang('style.delta_width', 0)), + height : 380 + parseInt(ed.getLang('style.delta_height', 0)), + inline : 1 + }, { + applyStyleToBlocks : applyStyleToBlocks, + plugin_url : url, + styles : styles + }); + }); + + ed.addCommand('mceSetElementStyle', function(ui, v) { + if (e = ed.selection.getNode()) { + ed.dom.setAttrib(e, 'style', v); + ed.execCommand('mceRepaint'); + } + }); + + /* + ed.on("NodeChange", function(ed, cm, n) { + cm.setDisabled('styleprops', n.nodeName === 'BODY'); + }); + */ + + // Register buttons + ed.addButton( + 'styleprops', + { + title : 'style.desc', + cmd : 'mceStyleProps', + disabledStateSelector: "body" + } + ); + }, + + getInfo : function() { + return { + longname : 'Style', + author : 'Moxiecode Systems AB', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/style', + version : tinymce.majorVersion + "." + tinymce.minorVersion + }; + } + }); + + // Register plugin + tinymce.PluginManager.add('style', tinymce.plugins.StylePlugin); +})(); diff --git a/pool/shard004/JavaScript/0026636_date-format.filter.js b/pool/shard004/JavaScript/0026636_date-format.filter.js new file mode 100644 index 0000000000000000000000000000000000000000..dce773f35da8c226464eda5e8bf4f2d88e1cef8f --- /dev/null +++ b/pool/shard004/JavaScript/0026636_date-format.filter.js @@ -0,0 +1,19 @@ +function dateFormatFilter() { + return function dateFormat(oldValue) { + var newValue; + + if (oldValue) { + var year = oldValue.substr(0, 4); + var month = oldValue.substr(5, 2); + var day = oldValue.substr(8, 2); + + newValue = day + '/' + month + '/' + year; + } else { + newValue = '-'; + } + + return newValue; + }; +} + +export default dateFormatFilter; diff --git a/pool/shard004/JavaScript/0026638_compareTest.js b/pool/shard004/JavaScript/0026638_compareTest.js new file mode 100644 index 0000000000000000000000000000000000000000..e8b6cbc4d41c3845d8cea2157b791e27a1b13768 --- /dev/null +++ b/pool/shard004/JavaScript/0026638_compareTest.js @@ -0,0 +1,67 @@ +describe('compare', function() { + + var stringA1 = 'hello'; + var stringA2 = 'hello'; + var stringB1 = 'goodbye'; + var arrayA1 = ['a', 'b', 'c']; + var arrayA2 = ['a', 'b', 'c']; + var arrayB1 = ['c', 'b', 'a']; + var objectA1 = {greeting: 'hello', colour: 'red'}; + var objectA2 = {greeting: 'hello', colour: 'red'}; + var objectB1 = {greeting: 'goodbye', colour: 'blue'}; + var objectC1 = {favouriteobject: stringA1, otherobjects: [arrayA1, objectA1]}; + var objectC2 = {favouriteobject: stringA2, otherobjects: [arrayA2, objectA2]}; + var objectD1 = {favouriteobject: stringB1, otherobjects: [arrayB1, objectB1]}; + + runtests = function(object_type, objA1, objA2, objB1) { + describe(object_type, function() { + it('should be true for matching ' + object_type, function() { + expect(Object.objects_equal(objA1, objA1)).toBe(true); + expect(Object.objects_equal(objA1, objA2)).toBe(true); + expect(Object.objects_equal(objA2, objA1)).toBe(true); + }); + it('should be false for ' + object_type + ' that don\'t match', function() { + expect(Object.objects_equal(objA1, objB1)).toBe(false); + expect(Object.objects_equal(objA2, objB1)).toBe(false); + }); + it('should be false for comparison with a null object', function() { + expect(Object.objects_equal(objA1, null)).toBe(false); + }); + }); + }; + + runtests('strings', stringA1, stringA2, stringB1); + runtests('arrays', arrayA1, arrayA2, arrayB1); + runtests('objects', objectA1, objectA2, objectB1); + runtests('complex objects', objectA1, objectA2, objectB1); + + describe('string comparison', function() { + it('should sort strings alphanumerically', function() { + expect('a'<'b').toBe(true); + expect('b'>'a').toBe(true); + expect('a'>'0').toBe(true); + expect('a'<'aa').toBe(true); + expect('b'>'ab').toBe(true); + expect('a'>'b').toBe(false); + expect('b'<'a').toBe(false); + expect('a'<'0').toBe(false); + expect('a'>'aa').toBe(false); + expect('b'<'ab').toBe(false); + }) + }) + describe('array comparison', function() { + describe('when given two arrays of the same length', function() { + it('should sort them by sorting each element', function() { + expect(['a']<['b']).toBe(true); + expect(['a','c']<['a','d']).toBe(true); + expect(['b','c']>['a','d']).toBe(true); + expect([2,'c']>[1,'c']).toBe(true); + expect(['a']>['b']).toBe(false); + expect(['a','c']>['a','d']).toBe(false); + expect(['b','c']<['a','d']).toBe(false); + expect([2,'c']<[1,'c']).toBe(false); + }) + }) + }) + +}); \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026641_stockData.js b/pool/shard004/JavaScript/0026641_stockData.js new file mode 100644 index 0000000000000000000000000000000000000000..eb6282f17beda6188d985adf36f2b3dbe53f0858 --- /dev/null +++ b/pool/shard004/JavaScript/0026641_stockData.js @@ -0,0 +1,167 @@ +isc.defineClass("FinanceDataSource", "DataSource").addProperties({ + canMultiSort: false, + allowAdvancedCriteria: false, + + fields: [ + { name: "symbol", title: "Symbol" }, + { name: "date", title: "Date", type: "date" }, + { name: "open", title: "Open", type: "float" }, + { name: "high", title: "High", type: "float" }, + { name: "low", title: "Low", type: "float" }, + { name: "close", title: "Close", type: "float" }, + { name: "volume", title: "Volume", type: "float" }, + { name: "adjClose", title: "Adj Close", type: "float" } + ], + + handleError : function (response, request) { + // Suppress RPCManager.handleError() from being called. In the sample, + // an error label is drawn rather than showing the default warning dialog. + return false; + }, + + // Parses the CSV formatted data returned from the server into a list of records. + _parseData : function (data, symbol) { + var records = [], + fields = [], + len = data.length, + i = -1, j; + + // The line separator is "\n" and the value separator is ",". + while (true) { + j = data.indexOf("\n", i + 1); + if (j == -1) j = len; + + if (j > i + 1) { // Skip consecutive newlines. + + var record = {}, k = i, l, index = 0; + while (true) { + l = Math.min(data.indexOf(",", k + 1), j); + if (l == -1) l = j; + + if (i == -1) { + // The first line is a header: + // e.g. "Date,Open,High,Low,Close,Volume,Adj Close" + fields[index] = this.getFieldByTitle(data.substring(k + 1, l)); + + } else { + var field = fields[index]; + if (field != null) { + var fieldName = field.name, + fieldType = field.type, + value = data.substring(k + 1, l); + + if (fieldType === "float") { + record[fieldName] = parseFloat(value); + } else if (fieldType === "date") { + // e.g. "2012-07-19" is July 19, 2012 + var year = parseInt(value.substring(0, 4)); + var month = 10 * parseInt(value.charAt(5)) + parseInt(value.charAt(6)); + var day = 10 * parseInt(value.charAt(8)) + parseInt(value.charAt(9)); + record[fieldName] = isc.DateUtil.createLogicalDate(year, month - 1, day); + } else { + record[fieldName] = value; + } + } + } + + if (!(l != -1 && l < j)) break; + k = l; + ++index; + } + + if (i != -1) { + record.symbol = symbol; + records.push(record); + } + } + + if (!(j != -1 && j < len)) break; + i = j; + } + + return records; + } +}); + +var stockData = isc.FinanceDataSource.create({ + ID: "stockData", + dataURL: "http://ichart.finance.yahoo.com/table.csv", + dataProtocol: "getParams", + dataFormat: "custom", + + _months: ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11"], + + // Options for the query parameter "g": + _daily: "d", + _weekly: "w", + _month: "m", + _dividendsOnly: "v", + transformRequest : function (dsRequest) { + if (dsRequest.operationType === "fetch") { + var criteria = dsRequest.data, + symbol = criteria && criteria.symbol; + + if (symbol == null) return; + + var to = new Date(), + from = new Date(to.getFullYear() - 10, to.getMonth(), to.getDate()), + startMonth = this._months[from.getMonth()], + startDay = from.getDate(), + startYear = from.getFullYear(), + endMonth = this._months[to.getMonth()], + endDay = to.getDate(), + endYear = to.getFullYear(); + + dsRequest.clientContext = isc.addProperties({ symbol: symbol }, dsRequest.clientContext); + + return { + s: symbol, + a: startMonth, + b: startDay, + c: startYear, + d: endMonth, + e: endDay, + f: endYear, + g: this._daily, + ignore: ".csv" + }; + } + }, + + transformResponse : function (dsResponse, dsRequest, data) { + var status = dsResponse.status, + success = !(dsResponse.status < 0), + symbol = dsRequest.clientContext.symbol; + + dsResponse.data = success ? this._parseData(data, symbol) : null; + dsResponse.status = status; + delete dsResponse.startRow; + delete dsResponse.endRow; + delete dsResponse.totalRows; + return dsResponse; + } +}); + +var staticStockData = isc.FinanceDataSource.create({ + ID: "staticStockData", + dataProtocol: "clientCustom", + + transformRequest : function (dsRequest) { + if (dsRequest.operationType === "fetch") { + var symbol = dsRequest.data.symbol; + isc.RPCManager.sendRequest({ + actionURL: isc.Page.getURL("[ISOMORPHIC]/system/reference/inlineExamples/charts/" + symbol + ".txt"), + willHandleError: true, + callback : function (rpcResponse, rawData, rpcRequest) { + var dsResponse = { + status: rpcResponse.status + }; + if (!(rpcResponse.status < 0)) { + data = dsResponse.data = staticStockData._parseData(rawData, symbol); + } + staticStockData.processResponse(dsRequest.requestId, dsResponse); + } + }); + } + } +}); diff --git a/pool/shard004/JavaScript/0026642_adaptation.list_custom_classes.js b/pool/shard004/JavaScript/0026642_adaptation.list_custom_classes.js new file mode 100644 index 0000000000000000000000000000000000000000..2a908a619b0f894dd88c51d9dbf6ee56f3fed9d8 --- /dev/null +++ b/pool/shard004/JavaScript/0026642_adaptation.list_custom_classes.js @@ -0,0 +1,75 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +'use strict'; + +function main(parent) { + // [START speech_v1p1beta1_generated_Adaptation_ListCustomClasses_async] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The parent, which owns this collection of custom classes. Format: + * `projects/{project}/locations/{location}/customClasses` + * Speech-to-Text supports three locations: `global`, `us` (US North America), + * and `eu` (Europe). If you are calling the `speech.googleapis.com` + * endpoint, use the `global` location. To specify a region, use a + * regional endpoint (/speech-to-text/docs/endpoints) with matching `us` or + * `eu` location value. + */ + // const parent = 'abc123' + /** + * The maximum number of custom classes to return. The service may return + * fewer than this value. If unspecified, at most 50 custom classes will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + */ + // const pageSize = 1234 + /** + * A page token, received from a previous `ListCustomClass` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListCustomClass` must + * match the call that provided the page token. + */ + // const pageToken = 'abc123' + + // Imports the Speech library + const {AdaptationClient} = require('@google-cloud/speech').v1p1beta1; + + // Instantiates a client + const speechClient = new AdaptationClient(); + + async function callListCustomClasses() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = await speechClient.listCustomClassesAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListCustomClasses(); + // [END speech_v1p1beta1_generated_Adaptation_ListCustomClasses_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/pool/shard004/JavaScript/0026644_collision.js b/pool/shard004/JavaScript/0026644_collision.js new file mode 100644 index 0000000000000000000000000000000000000000..00a52bc6350930d4900fe9324c08634b534098ba --- /dev/null +++ b/pool/shard004/JavaScript/0026644_collision.js @@ -0,0 +1,86 @@ +var moment = require('moment-timezone'), + Promise = require('bluebird'), + _ = require('lodash'), + errors = require('../../errors'); + +module.exports = function (Bookshelf) { + var ParentModel = Bookshelf.Model, + Model; + + Model = Bookshelf.Model.extend({ + /** + * Update collision protection. + * + * IMPORTANT NOTES: + * The `sync` method is called for any query e.g. update, add, delete, fetch + * + * We had the option to override Bookshelf's `save` method, but hooking into the `sync` method gives us + * the ability to access the `changed` object. Bookshelf already knows which attributes has changed. + * + * Bookshelf's timestamp function can't be overridden, as it's synchronous, there is no way to return an Error. + * + * If we want to enable the collision plugin for other tables, the queries might need to run in a transaction. + * This depends on if we fetch the model before editing. Imagine two concurrent requests come in, both would fetch + * the same current database values and both would succeed to update and override each other. + */ + sync: function timestamp(options) { + var parentSync = ParentModel.prototype.sync.apply(this, arguments), + originalUpdateSync = parentSync.update, + self = this; + + // CASE: only enabled for posts table + if (this.tableName !== 'posts' || + !self.serverData || + ((options.method !== 'update' && options.method !== 'patch') || !options.method) + ) { + return parentSync; + } + + /** + * Only hook into the update sync + * + * IMPORTANT NOTES: + * Even if the client sends a different `id` property, it get's ignored by bookshelf. + * Because you can't change the `id` of an existing post. + * + * HTML is always auto generated, ignore. + */ + parentSync.update = function update() { + var changed = _.omit(self.changed, [ + 'created_at', 'updated_at', 'author_id', 'id', + 'published_by', 'updated_by', 'html', 'plaintext' + ]), + clientUpdatedAt = moment(self.clientData.updated_at || self.serverData.updated_at || new Date()), + serverUpdatedAt = moment(self.serverData.updated_at || clientUpdatedAt); + + if (Object.keys(changed).length) { + if (clientUpdatedAt.diff(serverUpdatedAt) !== 0) { + return Promise.reject(new errors.InternalServerError({ + message: 'Saving failed! Someone else is editing this post.', + code: 'UPDATE_COLLISION' + })); + } + } + + return originalUpdateSync.apply(this, arguments); + }; + + return parentSync; + }, + + /** + * We have to remember current server data and client data. + * The `sync` method has no access to it. + * `updated_at` is already set to "Date.now" when the overridden `sync.update` is called. + * See https://github.com/tgriesser/bookshelf/blob/79c526870e618748caf94e7476a0bc796ee090a6/src/model.js#L955 + */ + save: function save(data) { + this.clientData = _.cloneDeep(data) || {}; + this.serverData = _.cloneDeep(this.attributes); + + return ParentModel.prototype.save.apply(this, arguments); + } + }); + + Bookshelf.Model = Model; +}; diff --git a/pool/shard004/JavaScript/0026645_card-poster.js b/pool/shard004/JavaScript/0026645_card-poster.js new file mode 100644 index 0000000000000000000000000000000000000000..f6aa7b98cded3dfd1a871a3d768733133e1d70d0 --- /dev/null +++ b/pool/shard004/JavaScript/0026645_card-poster.js @@ -0,0 +1,86 @@ +var load = require('../../js/lib/load'); +var notice = require('../component/notice'); +var crop= require('./card-poster-crop'); +var uploader; + +function PageView() { + this.init(); +}; + +PageView.prototype.init = function() { + load('//cdn.bootcss.com/plupload/2.1.7/plupload.full.min.js', function() { + fileupload(); + }); +}; + +PageView.prototype.close = function() { + uploader.destroy(); + crop.destroy(); +}; + +function fileupload() { + var domain = $('#domain').val(); + + uploader = new plupload.Uploader({ + runtimes : 'html5,flash,html4', + browse_button : 'pickfile', + max_file_size : '4mb', + + // Fake server response here + url: "http://upload.qiniu.com/", + + flash_swf_url : '/js/plupload/Moxie.swf', + filters : [ + {title : "Image files", extensions : "jpg,gif,png"}, + ], + multipart_params: { + token: $('#uptoken').val() + }, + + init: { + PostInit: function() { + $('filelist').innerHTML = ''; + + $('uploadfiles').onclick = function() { + uploader.start(); + return false; + }; + }, + + FilesAdded: function(up, files) { + uploader.start(); + $('.upload-progress').show(); + $('.image-preview').removeClass('image-bg'); + }, + + UploadProgress: function(up, file) { + $('.upload-progress .bar').css('width', file.percent + '%'); + }, + + FileUploaded: function(up, file, info) { + var res = $.parseJSON(info.response); + var img = new Image(); + img.onload = function() { + $('.image-preview').addClass('image-bg'); + $('#poster-preview').attr('src', this.src); + $('#imagePreview').attr('src', this.src); + $('#saveCrop').removeClass('disabled'); + crop.reload(this.src); + } + img.src = domain + res.key; + + setTimeout(function() { + $('.upload-progress').find('.bar').css('width', '1%').end().hide(); + }, 500); + }, + + Error: function(up, err) { + notice.alert(err.message); + } + } + }); + + uploader.init(); +} + +module.exports = PageView; \ No newline at end of file diff --git a/pool/shard004/JavaScript/0026649_markdownFilter.js b/pool/shard004/JavaScript/0026649_markdownFilter.js new file mode 100644 index 0000000000000000000000000000000000000000..b567f2190992b42a42ba8472a7bad8af200a7002 --- /dev/null +++ b/pool/shard004/JavaScript/0026649_markdownFilter.js @@ -0,0 +1,23 @@ +(function (angular) { + + 'use strict'; + + angular.module('birdyard.utilities') + + .directive('markdownFilter', ['$timeout', 'markdownFilterService', function($timeout, markdownFilterService) { + + return { + restrict: 'A', + replace: false, + link: function (scope, element, attrs) { + $timeout(function () { + var limit = parseInt(attrs['markdownFilter'], 10) || 0; + var text = element.text(); + var filtered = markdownFilterService.filter(text); + var limited = (limit) ? filtered.slice(0, limit) : filtered; + element.text(limited); + }); + } + } + }]); +})(angular); diff --git a/pool/shard004/JavaScript/0026651_1012101.js b/pool/shard004/JavaScript/0026651_1012101.js new file mode 100644 index 0000000000000000000000000000000000000000..3f36b7f372a1186b8b2373c468a1b3dc25a03ebd --- /dev/null +++ b/pool/shard004/JavaScript/0026651_1012101.js @@ -0,0 +1,48 @@ +/* + This file is part of the OdinMS Maple Story Server + Copyright (C) 2008 Patrick Huy + Matthias Butz + Jan Christian Meyer + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License version 3 + as published by the Free Software Foundation. You may not use, modify + or distribute this program under any other version of the + GNU Affero General Public License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +/* + 玛亚 +*/ + +var status = 0; + +function start() { + status = -1; + action(1, 0, 0); +} + +function action(mode, type, selection) { + if (mode == -1) { + cm.dispose(); + } else { + if (mode == 1) + status++; + else + status--; + if (status == 0) { + cm.sendNext("你找我有事么?如果你足够强大的话,可以看看任务面板!"); + } else if (status == 1) { + cm.sendOk("任务面板没有任务的话,那赶紧去升级吧!"); + cm.dispose(); + } + } +} diff --git a/pool/shard004/JavaScript/0026653_includes.js b/pool/shard004/JavaScript/0026653_includes.js new file mode 100644 index 0000000000000000000000000000000000000000..a44b33d92f980035b8cd359cbc757f404bb22879 --- /dev/null +++ b/pool/shard004/JavaScript/0026653_includes.js @@ -0,0 +1,146 @@ +var assert = require("chai").assert; +var crossbow = require("../../index"); + +describe("Doing includes", function() { + + it("Add 1 page & compile with includes", function(done) { + + var site = crossbow.builder({ + config: { + base: "test/fixtures" + }, + errorHandler: function (err) { + console.log(err); + } + }); + + var item = site.add({key: "src/docs/index.html", content: "{{inc src='button.html' name='kittie'}}"}); + + site.freeze(); + + site.compile({ + item: item, + cb: function (err, out) { + assert.include(out.get("compiled"), ""); + done(); + } + }); + }); + + it("Add 1 page & compile with includes in simple mode", function(done) { + + crossbow.compile({ + config: { + base: "test/fixtures" + }, + key: "src/docs/index.html", + content: "{{inc src='button.html' name='kittie'}}", + cb: function (err, out) { + assert.include(out.get("compiled"), ""); + done(); + } + }); + }); + + it("Add 1 page & compile without markdown", function(done) { + + var site = crossbow.builder({ + config: { + base: "test/fixtures" + }, + errorHandler: function (err) { + console.log(err); + } + }); + + var item = site.add({key: "src/docs/index.html", content: "This is not a P"}); + + site.freeze(); + + site.compile({ + item: item, + cb: function (err, out) { + assert.notInclude(out.get("compiled"), "

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