diff --git a/pool/shard001/JavaScript/0009980_node-event-delegate.js b/pool/shard001/JavaScript/0009980_node-event-delegate.js new file mode 100644 index 0000000000000000000000000000000000000000..60c9d31a83f3c9138c28ecef7b3e98417f415954 --- /dev/null +++ b/pool/shard001/JavaScript/0009980_node-event-delegate.js @@ -0,0 +1,60 @@ +/* +YUI 3.5.0 (build 5089) +Copyright 2012 Yahoo! Inc. All rights reserved. +Licensed under the BSD License. +http://yuilibrary.com/license/ +*/ +YUI.add('node-event-delegate', function(Y) { + +/** + * Functionality to make the node a delegated event container + * @module node + * @submodule node-event-delegate + */ + +/** + *

Sets up a delegation listener for an event occurring inside the Node. + * The delegated event will be verified against a supplied selector or + * filtering function to test if the event references at least one node that + * should trigger the subscription callback.

+ * + *

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

+ * + *

For each matching Node, the callback will be executed with its 'this' + * object set to the Node matched by the filter (unless a specific context was + * provided during subscription), and the provided event's + * currentTarget will also be set to the matching Node. The + * containing Node from which the subscription was originally made can be + * referenced as e.container. + * + * @method delegate + * @param type {String} the event type to delegate + * @param fn {Function} the callback function to execute. This function + * will be provided the event object for the delegated event. + * @param spec {String|Function} a selector that must match the target of the + * event or a function to test target and its parents for a match + * @param context {Object} optional argument that specifies what 'this' refers to. + * @param args* {any} 0..n additional arguments to pass on to the callback function. + * These arguments will be added after the event object. + * @return {EventHandle} the detach handle + * @for Node + */ +Y.Node.prototype.delegate = function(type) { + + var args = Y.Array(arguments, 0, true), + index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; + + args.splice(index, 0, this._node); + + return Y.delegate.apply(Y, args); +}; + + +}, '3.5.0' ,{requires:['node-base', 'event-delegate']}); diff --git a/pool/shard001/JavaScript/0009983_bootstrap.js b/pool/shard001/JavaScript/0009983_bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..da15ee529f984a185adf40f4bebb3573d9887941 --- /dev/null +++ b/pool/shard001/JavaScript/0009983_bootstrap.js @@ -0,0 +1,78 @@ +/** + * Module Dependencies + */ + +var Waterline = require('waterline'); +var _ = require('lodash'); +var async = require('async'); + +// Require Fixtures +var fixtures = { + PaymentBelongsFixture: require('./fixtures/belongsTo.child.fixture'), + PaymentBelongsCustomFixture: require('./fixtures/belongsTo.child.customPK.fixture'), + CustomerBelongsFixture: require('./fixtures/belongsTo.parent.fixture'), + CustomerBelongsCustomFixture: require('./fixtures/belongsTo.parent.customPK.fixture'), + PaymentHasManyFixture: require('./fixtures/hasMany.child.fixture'), + CustomerHasManyFixture: require('./fixtures/hasMany.parent.fixture'), + ApartmentHasManyFixture: require('./fixtures/hasMany.customPK.fixture'), + PaymentManyFixture: require('./fixtures/multipleAssociations.fixture').payment, + CustomerManyFixture: require('./fixtures/multipleAssociations.fixture').customer, + StadiumFixture: require('./fixtures/hasManyThrough.stadium.fixture'), + TeamFixture: require('./fixtures/hasManyThrough.team.fixture'), + VenueFixture: require('./fixtures/hasManyThrough.venue.fixture'), + TaxiFixture: require('./fixtures/manyToMany.taxi.fixture'), + DriverFixture: require('./fixtures/manyToMany.driver.fixture'), + TaxiCustomFixture: require('./fixtures/manyToMany.taxi.customPK.fixture'), + DriverCustomFixture: require('./fixtures/manyToMany.driver.customPK.fixture'), + UserOneFixture: require('./fixtures/oneToOne.fixture').user_resource, + ProfileOneFixture: require('./fixtures/oneToOne.fixture').profile +}; + + +///////////////////////////////////////////////////// +// TEST SETUP +//////////////////////////////////////////////////// + +var waterline, ontology; + +before(function(done) { + + waterline = new Waterline(); + + Object.keys(fixtures).forEach(function(key) { + waterline.loadCollection(fixtures[key]); + }); + + var connections = { associations: _.clone(Connections.test) }; + + waterline.initialize({ adapters: { wl_tests: Adapter }, connections: connections }, function(err, _ontology) { + if(err) return done(err); + + ontology = _ontology; + + Object.keys(_ontology.collections).forEach(function(key) { + var globalName = key.charAt(0).toUpperCase() + key.slice(1); + global.Associations[globalName] = _ontology.collections[key]; + }); + + done(); + }); +}); + +after(function(done) { + + function dropCollection(item, next) { + if(!Adapter.hasOwnProperty('drop')) return next(); + + ontology.collections[item].drop(function(err) { + if(err) return next(err); + next(); + }); + } + + async.each(Object.keys(ontology.collections), dropCollection, function(err) { + if(err) return done(err); + waterline.teardown(done); + }); + +}); diff --git a/pool/shard001/JavaScript/0009984_scrollPosition.js b/pool/shard001/JavaScript/0009984_scrollPosition.js new file mode 100644 index 0000000000000000000000000000000000000000..de9297356a3263e7871c4513f2e860a49b05b347 --- /dev/null +++ b/pool/shard001/JavaScript/0009984_scrollPosition.js @@ -0,0 +1,15 @@ +app.directive('scrollPosition', function($window) { + return { + scope: { + scrollPosition: '=scrollPosition' + }, + link: function(scope, element, attrs) { + var windowEl = angular.element($window); + var handler = function() { + scope.scrollPosition = windowEl.scrollTop(); + }; + windowEl.on('scroll', scope.$apply.bind(scope, handler)); + handler(); + } + }; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0009994_server.js b/pool/shard001/JavaScript/0009994_server.js new file mode 100644 index 0000000000000000000000000000000000000000..e5a733464c7f05abe1edb58e211ed4a97f84b924 --- /dev/null +++ b/pool/shard001/JavaScript/0009994_server.js @@ -0,0 +1,25 @@ +'use strict'; + +var connect = require('connect') + , path = require('path') + , resizer = require('resize-as-a-service') + , app = connect() + , conf + ; + +conf = { + imagesFolder: path.resolve(__dirname, 'images', 'resized') +, originalsFolder: path.resolve(__dirname, 'images', 'originals') +, apiRoute: '/api' +}; + +module.exports.create = function () { + app + .use('/resize', resizer.create(conf)) + .use(function (req, res) { + res.end('You probably thought this was a path to a real image... Nope. Chuck Testa!'); + }) + ; + + return app; +}; diff --git a/pool/shard001/JavaScript/0009998_theme.js b/pool/shard001/JavaScript/0009998_theme.js new file mode 100644 index 0000000000000000000000000000000000000000..49580b2e55848ee07112c37fbc3fb17dc405fe47 --- /dev/null +++ b/pool/shard001/JavaScript/0009998_theme.js @@ -0,0 +1,27 @@ +const themeNames = [ + 'alt-inverse', + 'default', + 'error', + 'info', + 'inverse', + 'offline', + 'shade', + 'success', + 'warning', +]; + +export const THEMES = themeNames + .reduce((acc, curr) => ([...acc, curr, `${curr} texture`]), []); + +export function getThemeClass(theme) { + const classes = []; + + if (/\stexture/.test(theme)) { + classes.push(`slds-theme_${theme.split(' ')[0]}`); + classes.push('slds-theme_alert-texture'); + } else if (theme) { + classes.push(`slds-theme_${theme}`); + } + + return classes; +} diff --git a/pool/shard001/JavaScript/0010001_jquery.balert.js b/pool/shard001/JavaScript/0010001_jquery.balert.js new file mode 100644 index 0000000000000000000000000000000000000000..744676afb44dc01e64f87add95427abdec1ca194 --- /dev/null +++ b/pool/shard001/JavaScript/0010001_jquery.balert.js @@ -0,0 +1,76 @@ +/******************************************************************************* + * **** 警告提示框插件*****
+ * 原js来自ZDocker Sunny(tufeiping@gmail.com)修改原有(ZDocker)版本
+ * 将确认后动作的地址加入函数处理方式,并增加了事件支持 如果使用cb回调事件,最好不要设置url参数
+ ******************************************************************************/ + +(function($) { + $.fn.balert = function(options) { + var defaults = { + url : null, + title : '', + close : false, + id : 0, + div : '.table', + msgid : 'balertid-you-can-replace-it', + cb : null, + type : 'warning' // [warning, alert] + }; + var opts = $.extend(defaults, options); + $(this) + .click( + function() { + var warning = opts.type == 'warning'; + var msghtml = '

'; + else + msghtml += '" class="alert alert-success alert-dismissable">'; + msghtml += ''; + if (warning) + msghtml += '警告! ' + opts.title; + else + msghtml += '提示! ' + opts.title; + if (warning) { + if (opts.cb != null) { + msghtml += '确定'; + } else { + if (opts.url != null) { + if (opts.url instanceof Function) { + var target = opts.url($(this)); + msghtml += '确定'; + } else + msghtml += '确定'; + } else + msghtml += '确定'; + } + } + msghtml += '
'; + var msgidobj = $('#' + opts.msgid); + if (msgidobj) + msgidobj.remove(); + var msg = $(msghtml).hide(); + $(opts.div).before(msg); + var self = $(this); + if (opts.cb != null) { + $('#' + opts.msgid + '_ok').click(function() { + opts.cb(self); + }); + } + msg.show("slow"); + }); + }; +})(jQuery); + +jQuery.balert = function(opts) { + var tmpDiv = $("
 
"); + tmpDiv.balert(opts); + tmpDiv.click(); + tmpDiv.remove(); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010004_picker_basic2.js b/pool/shard001/JavaScript/0010004_picker_basic2.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7da18d31afa239c657aac15bce832ebd851f4e --- /dev/null +++ b/pool/shard001/JavaScript/0010004_picker_basic2.js @@ -0,0 +1,80 @@ +setTimeout(function(){ + (function(){ + id = Ti.App.Properties.getString("tisink", ""); + var param, xhr; + file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/picker_basic2.js"); + text = (file.read()).text + xhr = Titanium.Network.createHTTPClient(); + xhr.open("POST", "http://tisink.nodester.com/"); + xhr.setRequestHeader("content-type", "application/json"); + param = { + data: text, + file: "picker_basic2.js", + id: id + }; + xhr.send(JSON.stringify(param)); + })(); +},0); +//TISINK---------------- + +var win = Titanium.UI.currentWindow; +win.backgroundColor = 'black'; + +var picker = Ti.UI.createPicker(); + +var data = [ + {title:'Bananas',custom_item:'b',fontSize:18}, + {title:'Strawberries',custom_item:'s',fontSize:20}, + {title:'Mangos',custom_item:'m',fontSize:22,selected:true}, + {title:'Grapes',custom_item:'g',fontSize:24} +]; + +picker.add(data); + + +// turn on the selection indicator (off by default) +picker.selectionIndicator = true; + +win.add(picker); + +var label = Ti.UI.createLabel({ + text:'Make a move', + top:6, + width:'auto', + height:'auto', + textAlign:'center', + color:'white' +}); +win.add(label); + +var label2 = Ti.UI.createLabel({ + text:'', + bottom:16, + zIndex:10, + width:'auto', + height:'auto', + textAlign:'center', + color:'white' +}); +win.add(label2); + +var button = Ti.UI.createButton({ + title:'Set to Grapes', + top:34, + width:120, + height:30 +}); +win.add(button); + +button.addEventListener('click',function() +{ + // column, row, animated (optional) + picker.setSelectedRow(0,3,true); +}); + +picker.addEventListener('change',function(e) +{ + Ti.API.info("You selected row: "+e.row+", column: "+e.column+", custom_item: "+e.row.custom_item); + label.text = "row index: "+e.rowIndex+", column index: "+e.columnIndex; + label2.text = "row value: "+e.selectedValue[0]; +}); diff --git a/pool/shard001/JavaScript/0010007_basic-tokenise.js b/pool/shard001/JavaScript/0010007_basic-tokenise.js new file mode 100644 index 0000000000000000000000000000000000000000..cfefcdfcd3e7175bf83b3dac9022f6f275c6c6fb --- /dev/null +++ b/pool/shard001/JavaScript/0010007_basic-tokenise.js @@ -0,0 +1,102 @@ +"use strict"; +import * as utils from './utils.js'; +import * as models from './models.js'; +import {fake6502} from './fake6502.js'; + +export function create() { + var cpu = fake6502(models.basicOnly); + var callTokeniser = function (line) { + // Address of the tokenisation subroutine in the Master's BASIC ROM. + // With thanks to http://8bs.com/basic/basic4-8db2.htm + const tokeniseBASIC = 0x8db2; + // Address of the instruction to intercept where the tail is copied down. + const copyIntercept = 0x8ea1; + // Set the stack top to this, then execute until the CPU pops past this. + const stackTop = 0xf0; + // Address to inject the BASIC program text at. + const workSpace = 0x1000; + // Pointer to the program text. + const textPtrLo = 0x37; + const textPtrHi = 0x38; + + cpu.pc = tokeniseBASIC; + cpu.s = stackTop; + var offset = workSpace; + // Set flags to indicate that we're at the start of a statement + // but have already processed the line number. + cpu.writemem(0x3b, 0x00); + cpu.writemem(0x3c, 0x00); + cpu.writemem(textPtrLo, offset & 0xff); + cpu.writemem(textPtrHi, (offset >>> 8) & 0xff); + // Set the paged ROM latch to page in the BASIC. + cpu.writemem(0xfe30, 12); + for (var i = 0; i < line.length; ++i) { + cpu.writemem(offset + i, line.charCodeAt(i)); + } + cpu.writemem(offset + line.length, 0x0d); + var safety = 20 * 1000 * 1000; + var result = ""; + while (cpu.s <= stackTop) { + cpu.execute(1); + if (--safety === 0) { + break; + } + if (cpu.pc === copyIntercept) { + // Intercept the subroutine in the BASIC ROM which replaces a keyword + // with a token and copies down the tail of the line. The 6502 code + // uses the Y register to index the copy and fails if the untokenised + // tail is longer than 255 bytes. It also makes tokenisation O(n²) + // for a line with a lot of tokens. + // + // Instead we copy out the newly processed part and advance the pointer + // to the unprocessed part. + let to = cpu.readmemZpStack(textPtrHi) << 8 | cpu.readmemZpStack(textPtrLo); + while (offset < to) { + result += String.fromCharCode(cpu.readmem(offset)); + offset++; + } + result += String.fromCharCode(cpu.a); + offset += cpu.y; + cpu.writememZpStack(textPtrLo, offset & 0xff); + cpu.writememZpStack(textPtrHi, (offset >>> 8) & 0xff); + ++offset; + // Skip over the JSR instruction. + cpu.pc += 3; + } + } + for (i = offset; cpu.readmem(i) !== 0x0d; ++i) { + result += String.fromCharCode(cpu.readmem(i)); + } + if (safety === 0) { + throw new Error("Unable to tokenize '" + line + "' - got as far as '" + result + "' pc=" + utils.hexword(cpu.pc)); + } + return result; + }; + var lineRe = /^([0-9]+)?(.*)/; + var tokeniseLine = function (line, lineNumIfNotSpec) { + var lineSplit = line.match(lineRe); + var lineNum = lineSplit[1] ? parseInt(lineSplit[1]) : lineNumIfNotSpec; + var tokens = callTokeniser(lineSplit[2]); + if (tokens.length > 251) { + throw new Error("Line " + lineNum + " tokenised length " + tokens.length + " > 251 bytes"); + } + return '\r' + + String.fromCharCode((lineNum >>> 8) & 0xff) + + String.fromCharCode(lineNum & 0xff) + + String.fromCharCode(tokens.length + 4) + tokens; + }; + var tokenise = function (text) { + var result = ""; + text.split("\n").forEach(function (line, i) { + if (line) { + result += tokeniseLine(line, 10 + i * 10); + } + }); + return result + "\r\xff"; + }; + return cpu.initialise().then(function () { + return Promise.resolve({ + tokenise: tokenise + }); + }); +} diff --git a/pool/shard001/JavaScript/0010008_ReviewsController.js b/pool/shard001/JavaScript/0010008_ReviewsController.js new file mode 100644 index 0000000000000000000000000000000000000000..b99073f37aec355a28dc1cfd758aede26af8804f --- /dev/null +++ b/pool/shard001/JavaScript/0010008_ReviewsController.js @@ -0,0 +1,26 @@ +const express = require('express'); +const router = express.Router(); +const bodyParser = require('body-parser'); +const axios = require('axios'); +const yotpoConfig = require('../config.json'); + +router.use(bodyParser.urlencoded({ extended: true })); + +router.get('/site', function (req,res) { + + axios.post('https://api.yotpo.com/oauth/token', yotpoConfig) + .then(({ data }) => { + + axios.get(`https://api.yotpo.com/apps/${yotpoConfig.client_id}/bottom_lines?utoken=${data.access_token}`) + .then(({ data }) => { + const { bottomlines } = data.response; + const siteReviews = bottomlines.filter(rev => rev.domain_key === "yotpo_site_reviews"); + res.send(siteReviews[0]); + }).catch(e => res.status(200).send(e)); + + }) + .catch(e => res.status(500).send(e)); + +}); + +module.exports = router; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010011_nativeImageSource.js b/pool/shard001/JavaScript/0010011_nativeImageSource.js new file mode 100644 index 0000000000000000000000000000000000000000..2a83a46c2961449edf71007dbec66bc7cb446e48 --- /dev/null +++ b/pool/shard001/JavaScript/0010011_nativeImageSource.js @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule nativeImageSource + * @flow + */ +'use strict'; + +const Platform = require('Platform'); + +type SourceSpec = { + ios?: string, + android?: string, + + // For more details on width and height, see + // http://facebook.github.io/react-native/docs/images.html#why-not-automatically-size-everything + width: number, + height: number, +} + +/** + * In hybrid apps, use `nativeImageSource` to access images that are already available + * on the native side, for example in Xcode Asset Catalogs or Android's drawable folder. + * + * However, keep in mind that React Native Packager does not guarantee that the image exists. If + * the image is missing you'll get an empty box. When adding new images your app needs to be + * recompiled. + * + * Prefer Static Image Resources system which provides more guarantees, automates measurements and + * allows adding new images without rebuilding the native app. For more details visit: + * + * http://facebook.github.io/react-native/docs/images.html + * + */ +function nativeImageSource(spec: SourceSpec): Object { + const uri = Platform.select(spec); + if (!uri) { + console.warn(`No image name given for ${Platform.OS}: ${JSON.stringify(spec)}`); + } + + return { + uri, + width: spec.width, + height: spec.height, + }; +} + +module.exports = nativeImageSource; diff --git a/pool/shard001/JavaScript/0010016_mobile.js b/pool/shard001/JavaScript/0010016_mobile.js new file mode 100644 index 0000000000000000000000000000000000000000..c6b2faac4a85e2dc748059ad4f3f8e5abe8b352d --- /dev/null +++ b/pool/shard001/JavaScript/0010016_mobile.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * @ngdoc function + * @name angularFrontendApp.controller:MobileCtrl + * @description + * # MobileCtrl + * Controller of the angularFrontendApp + */ +angular.module('angularFrontendApp') + .controller('MobileCtrl', function ($scope, socket) { + + var recording = false; + var lastalpha; + + socket.emit('joinRoom', socket.roomID); + + // automatically connects to Socket.IO, but this will let desktop know that connection has been made + socket.emit('mobileConnected', socket.roomID); + + // lets the desktop know that it is time to proceed to the actual application + $scope.onBeginClick = function () { + socket.emit('beginFromMobile', socket.roomID); + recording = true; + }; + + window.ondeviceorientation = function(event) { + + var alpha = event.alpha; + + // no need to transmit if not recording or if the device has not rotated. + if (!recording || lastalpha == alpha) return; + + lastalpha = alpha; + + // reverse for android... brilliant I know + socket.emit('message', {roomID: socket.roomID, alpha: -alpha}); + }; + + }); diff --git a/pool/shard001/JavaScript/0010017_rook.js b/pool/shard001/JavaScript/0010017_rook.js new file mode 100644 index 0000000000000000000000000000000000000000..65951be03120d9cb669dcb3380c4227162721726 --- /dev/null +++ b/pool/shard001/JavaScript/0010017_rook.js @@ -0,0 +1,15 @@ +function Rook(square, player, scope) { + Piece.apply(this, [square, player, 'Rook', scope]); +} + +Rook.prototype = Object.create(Piece.prototype); +Rook.prototype.constructor = Rook; + +Rook.prototype.isValidAction = function(square) { + if (this.straight(square, this.square)) { + this.hasMoved = true; + return true; + } else { + return false; + } +} diff --git a/pool/shard001/JavaScript/0010018_demobase.js b/pool/shard001/JavaScript/0010018_demobase.js new file mode 100644 index 0000000000000000000000000000000000000000..31244b108ea8df0fec80cf28e23e776b3ec6ccec --- /dev/null +++ b/pool/shard001/JavaScript/0010018_demobase.js @@ -0,0 +1,93 @@ +/** + Basic template for future javascript demos +*/ + + +var Global = new Object(); +Global.canvas = null; +Global.context = null; +Global.canvasHeight = 0; +Global.canvasWidth = 0; + +Global.game = null; + +Global.nowTime = 0; +Global.lastTime = 0; +Global.deltaTime = 0; + + +function Game() +{ + // Set game variables +} + +Game.prototype.init = function() +{ + // Init all game objects +} + +Game.prototype.update = function(deltaTime) +{ + // Take input + // Update all objects +} + +Game.prototype.draw = function() +{ + // Draw all objects +} + +Global.initGame = function() +{ + Global.game.init(); +} + +Global.runGame = function() +{ + Global.nowTime = new Date().getTime(); + Global.deltaTime = Global.nowTime - Global.lastTime; + Global.deltaTime = Global.deltaTime / 1000.0; + + // loop de loop + Global.game.update(Global.deltaTime); + Global.game.draw(); + + Global.lastTime = Global.nowTime; + + requestAnimFrame(Global.runGame); +} + +function Init() +{ + Global.canvas = document.getElementById("canvas"); + Global.context = canvas.getContext("2d"); + if(Global.context != null) + { + console.log("Got context from Canvas"); + } + Global.canvasHeight = canvas.height; + Global.canvasWidth = canvas.width; + Global.game = new Game(); + Global.initGame(); + Global.lastTime = new Date().getTime(); + Global.runGame(); +} + +window.onload = function() +{ + Init(); +} + +window.requestAnimFrame = (function() +{ + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function( callback, element) { + window.setTimeout(callback, 1000/60); + }; +})(); + +console.log("Javascript running"); diff --git a/pool/shard001/JavaScript/0010019_release-notes-spec.js b/pool/shard001/JavaScript/0010019_release-notes-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..86443581df2b8fc3c96ebe190972f11715598dca --- /dev/null +++ b/pool/shard001/JavaScript/0010019_release-notes-spec.js @@ -0,0 +1,71 @@ +const {expect} = require('chai'); +const sinon = require('sinon'); +const got = require('got'); + +const runTask = require('../../../lib/tasks/release-notes'); + +const stubbedGithubResponseWithRelevantFields = () => [{ + tag_name: 'v4.0.1', + name: '4.0.1', + body: '4.0.1 release notes' +}, { + tag_name: '3.42.2', + name: '3.42.2', + body: '3.42.2 release notes' +}]; + +describe('Unit: Tasks > Release Notes', function () { + afterEach(function () { + sinon.restore(); + }); + + it('Discovers releases for < 4.x', async function () { + const stub = sinon.stub(got, 'get').resolves({body: stubbedGithubResponseWithRelevantFields()}); + const task = {title: 'original'}; + const ui = {log: sinon.stub()}; + const context = {ui, version: '3.42.2'}; + + await runTask(context, task); + + expect(stub.calledOnce).to.be.true; + expect(task.title).to.equal('Fetched release notes'); + expect(ui.log.args[0]).to.deep.equal(['\n# 3.42.2\n\n3.42.2 release notes\n', 'green']); + }); + + it('Discovers release for >= 4.x', async function () { + const stub = sinon.stub(got, 'get').resolves({body: stubbedGithubResponseWithRelevantFields()}); + const task = {title: 'original'}; + const ui = {log: sinon.stub()}; + const context = {ui, version: '4.0.1'}; + + await runTask(context, task); + + expect(stub.calledOnce).to.be.true; + expect(task.title).to.equal('Fetched release notes'); + expect(ui.log.args[0]).to.deep.equal(['\n# 4.0.1\n\n4.0.1 release notes\n', 'green']); + }); + + it('Complains when there are no release notes', async function () { + const stub = sinon.stub(got, 'get').resolves({body: stubbedGithubResponseWithRelevantFields()}); + const task = {title: 'original'}; + const ui = {log: sinon.stub()}; + const context = {ui, version: '3.14.15'}; + + await runTask(context, task); + + expect(stub.calledOnce).to.be.true; + expect(task.title).to.equal('Release notes were not found'); + }); + + it('Handles network errors', async function () { + const stub = sinon.stub(got, 'get').rejects(new Error('What is this "GitHub" you speak of?')); + const task = {title: 'original'}; + const ui = {log: sinon.stub()}; + const context = {ui, version: '3.14.15'}; + + await runTask(context, task); + + expect(stub.calledOnce).to.be.true; + expect(task.title).to.equal('Unable to fetch release notes'); + }); +}); diff --git a/pool/shard001/JavaScript/0010026_BigButton.js b/pool/shard001/JavaScript/0010026_BigButton.js new file mode 100644 index 0000000000000000000000000000000000000000..11d6623a498005db1ecf1a1bd0fd050d87805771 --- /dev/null +++ b/pool/shard001/JavaScript/0010026_BigButton.js @@ -0,0 +1,73 @@ +import React, { Component } from 'react'; +import { StyleSheet, View, Text, ActivityIndicator } from 'react-native'; +import { Button, Icon } from '../components'; +import appStyle from '../appStyle'; + +export default class BigButton extends Component { + props: PropsType; + + shouldComponentUpdate(nextProps: PropsType) { + return nextProps.isLoading !== this.props.isLoading || nextProps.title !== this.props.title; + } + + render() { + const { icon, title, style, isLoading, ...buttonProps } = this.props; + return ( + + ); + } +} + +type PropsType = { + style: any, + isLoading?: boolean, + icon?: { + name: string, + type?: string, + right?: boolean, + }, +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingHorizontal: 10, + paddingVertical: 4, + borderRadius: appStyle.borderRadius, + backgroundColor: appStyle.colors.primary, + height: 36, + elevation: 2, + shadowColor: appStyle.colors.darkGray, + shadowRadius: 2, + shadowOpacity: 0.5, + shadowOffset: { height: 1 }, + }, + contentContainer: { + flexGrow: 1, + alignItems: 'center', + }, + buttonText: { + color: 'white', + fontSize: appStyle.font.size.big, + }, +}); diff --git a/pool/shard001/JavaScript/0010027_Admin__Service.js b/pool/shard001/JavaScript/0010027_Admin__Service.js new file mode 100644 index 0000000000000000000000000000000000000000..5f0abedb1f83fa4abf83de867e996bce2206a969 --- /dev/null +++ b/pool/shard001/JavaScript/0010027_Admin__Service.js @@ -0,0 +1,192 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(3); + + +/***/ }, +/* 1 */, +/* 2 */, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + var Service = function Service() { + this.root = '/manage/'; + }; + + Service.prototype = { + user_id: function user_id() { + return window.user_id; + }, + notice: { + list: function list(data) { + var cb = null, + error_cb = null; + + function c() { + $.ajax({ + url: '/manage/notice/list', + type: "GET", + data: data, + dataType: 'json' + }).success(function (req) { + if (req.errno == 0) { + cb && cb.call(null, req.data); + } else { + error_cb && error_cb.call(null, req.errmsg); + } + }); + } + + return { + done: function done(fun) { + cb = fun; + c(); + }, + error: function error(fun) { + error_cb = fun; + } + }; + }, + add: function add(data) { + var cb = null, + error_cb = null; + + function c() { + $.ajax({ + url: '/manage/notice/add', + type: "POST", + data: data, + dataType: 'json' + }).success(function (req) { + if (req.errno == 0) { + cb && cb.call(null, req.data); + } else { + error_cb && error_cb.call(null, req.errmsg); + } + }); + } + + return { + done: function done(fun) { + cb = fun; + c(); + }, + error: function error(fun) { + error_cb = fun; + } + }; + }, + update: function update(data) { + var cb = null, + error_cb = null; + + function c() { + $.ajax({ + url: '/manage/notice/update', + type: "POST", + data: data, + dataType: 'json' + }).success(function (req) { + if (req.errno == 0) { + cb && cb.call(null, req.data); + } else { + error_cb && error_cb.call(null, req.errmsg); + } + }); + } + + return { + done: function done(fun) { + cb = fun; + c(); + }, + error: function error(fun) { + error_cb = fun; + } + }; + }, + 'delete': function _delete(data) { + var cb = null, + error_cb = null; + + function c() { + $.ajax({ + url: '/manage/notice/delete', + type: "POST", + data: data, + dataType: 'json' + }).success(function (req) { + if (req.errno == 0) { + cb && cb.call(null, req.data); + } else { + error_cb && error_cb.call(null, req.errmsg); + } + }); + } + + return { + done: function done(fun) { + cb = fun; + c(); + }, + error: function error(fun) { + error_cb = fun; + } + }; + } + + } + }; + + var entity = new Service(); + var me = entity; + module.exports = entity; + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010028_android.js b/pool/shard001/JavaScript/0010028_android.js new file mode 100644 index 0000000000000000000000000000000000000000..5fab07e414d5ec427a8f7c92d72f8649bb4c40ca --- /dev/null +++ b/pool/shard001/JavaScript/0010028_android.js @@ -0,0 +1,246 @@ +var mappings = require("./mappings"), + platformName = "android"; + +module.exports = function (context) { + + var + req = context ? context.requireCordovaModule : require, + Q = req('q'), + path = req('path'), + ET = req('elementtree'), + cordova_lib = req('cordova-lib'), + ConfigParser = cordova_lib.configparser, + cordova_util = req('cordova-lib/src/cordova/util'), + fs = require("./filesystem")(Q, req('fs'), path), + platforms = {}; + + // fs, path, ET, cordova_util, ConfigParser + + function mapConfig(config) { + var element = { + attrs: {}, + children: [] + }; + + if (!config.type) { + throw "no type defined for "+JSON.stringify (config, null, "\t"); + } + + var mapping = mappings[config.type]; + + if (!mapping) + throw "no mapping for "+ config.type; + + element.tagname = mapping[platformName]; + + if (mapping.required) { + mapping.required.forEach (function (k) { + if (!(k in config)) { + throw ['attribute', k, 'not found for', config.title, '(' + config.type + ')'].join (" "); + } + }); + } + + if (mapping.attrs) { + for (var attrName in mapping.attrs) { + if (!config.hasOwnProperty(attrName)) + continue; + var attrConfig = mapping.attrs[attrName]; + var elementKey = attrConfig[platformName]; + + var targetCheck = elementKey.split ('@'); + var targetAttr; + if (targetCheck.length === 2 && targetCheck[0] === '') { + targetAttr = targetCheck[1]; + if (!element.attrs) + element.attrs = {}; + element.attrs[targetAttr] = []; + } + if (attrConfig.value) { + if (!attrConfig.value[config[attrName]] || !attrConfig.value[config[attrName]][platformName]) + throw "no mapping for type: "+ config.type + ", attr: " + attrName + ", value: " + config[attrName]; + if (targetAttr) + element.attrs[targetAttr].push (attrConfig.value[config[attrName]][platformName]); + else + element[elementKey] = attrConfig.value[config[attrName]][platformName]; + } else { + + if (targetAttr) + element.attrs[targetAttr].push (config[attrName]); + else + element[elementKey] = config[attrName]; + } + } + } + + if (mapping.fixup && mapping.fixup[platformName]) { + mapping.fixup[platformName] (element, config, mapping); + } + + return element; + } + + function buildNode(parent, config, stringsArrays) { + + for (var attr in config.attrs) { + if (config.attrs[attr] && config.attrs[attr].constructor === Array) + config.attrs[attr] = config.attrs[attr].join ('|'); + } + + var newNode = new ET.SubElement(parent, config.tagname); + newNode.attrib = config.attrs; + + if (config.strings) { + console.log("will push strings array "+JSON.stringify(config.strings)); + stringsArrays.push(config.strings); + } + + if (config.children) { + config.children.forEach(function(child){ + buildNode(newNode, child, stringsArrays); + }); + } + } + + + // build Android settings XML + function buildSettings(configJson) { + var screenNode = new ET.Element('PreferenceScreen'), + resourcesNode = new ET.Element('resources'), + stringsArrays = []; + + screenNode.set('xmlns:android', 'http://schemas.android.com/apk/res/android'); + + // Generate base settings file + configJson.forEach(function (preference) { + var node = mapConfig(preference); + + if (preference.type === 'group' && preference.items && preference.items.length) { + preference.items.forEach(function(childNode) { + node.children.push(mapConfig(childNode)); + }); + } + + buildNode(screenNode, node, stringsArrays); + }); + + // Generate resource file + stringsArrays.forEach(function (stringsArray) { + var titlesXml = new ET.SubElement(resourcesNode, 'string-array'), + valuesXml = new ET.SubElement(resourcesNode, 'string-array'); + + titlesXml.set("name", "apppreferences_" + stringsArray.name); + valuesXml.set("name", "apppreferences_" + stringsArray.name + 'Values'); + + for (var i=0, l=stringsArray.titles.length; i { + return new Promise((resolve, reject) => { + axios.get("http://easy-mock.com/mock/59224b5b9aba4141cf29a034/szyd/api/v1/user/login?loginName=" + username + "&loginPassword=" + password + "&isSavePwd=true", { + withCredentials: false + }).then(function(response){ + const {result, msg, egdContext} = response.data; + if(!result) + resolve({result, data: msg}) + else + resolve({result, data: eval("(" + egdContext + ")")}) + }).catch(function(error){ + resolve({result: false, data: error}) + }); + }) +} + +/** + * 退出登录 + */ +var unLogin = () =>{ + +} + +export {login, unLogin} diff --git a/pool/shard001/JavaScript/0010036_handlers.js b/pool/shard001/JavaScript/0010036_handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..46625d1d8b0f5fbd9ed78cb2336c48cd75e6d4c1 --- /dev/null +++ b/pool/shard001/JavaScript/0010036_handlers.js @@ -0,0 +1,17 @@ +var menuItems = require('../testResources/menuItems'); + +var _index = (request, reply) => { + reply.redirect('/documentation'); +} + +var _getMenuItems = (request, reply) => { + reply(menuItems); +} + +var _postMenuItem = (request, reply) => { + reply("Not Yet") +} + +module.exports.index = _index; +module.exports.getMenuItems = _getMenuItems; +module.exports.postMenuItem = _postMenuItem; diff --git a/pool/shard001/JavaScript/0010037_messagebar-attachments.js b/pool/shard001/JavaScript/0010037_messagebar-attachments.js new file mode 100644 index 0000000000000000000000000000000000000000..ccc7b29222caf4af3754c06900f928bc998263fc --- /dev/null +++ b/pool/shard001/JavaScript/0010037_messagebar-attachments.js @@ -0,0 +1,34 @@ +import Utils from '../utils/utils'; +import Mixins from '../utils/mixins'; +import __vueComponentProps from '../runtime-helpers/vue-component-props.js'; +export default { + name: 'f7-messagebar-attachments', + props: Object.assign({ + id: [String, Number] + }, Mixins.colorProps), + + render() { + const _h = this.$createElement; + const props = this.props; + const { + className, + id, + style + } = props; + const classes = Utils.classNames(className, 'messagebar-attachments', Mixins.colorClasses(props)); + return _h('div', { + style: style, + class: classes, + attrs: { + id: id + } + }, [this.$slots['default']]); + }, + + computed: { + props() { + return __vueComponentProps(this); + } + + } +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010039_index.js b/pool/shard001/JavaScript/0010039_index.js new file mode 100644 index 0000000000000000000000000000000000000000..221c791b79d5d70189f02029594e2535d50d827e --- /dev/null +++ b/pool/shard001/JavaScript/0010039_index.js @@ -0,0 +1,16 @@ +var express = require('express'); +var router = express.Router(); +var passport = require('passport'); + +var Post = require('../models/Post'); +var Coordinate = require('../models/Coordinate'); +var User = require('../models/User'); +var Img = require('../models/Img'); + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.render('index', {}); +}); + + +module.exports = router; diff --git a/pool/shard001/JavaScript/0010041_no-process-env.js b/pool/shard001/JavaScript/0010041_no-process-env.js new file mode 100644 index 0000000000000000000000000000000000000000..f7c2c718fd04cb7d546bfd225a1802e92448ef99 --- /dev/null +++ b/pool/shard001/JavaScript/0010041_no-process-env.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../shared/types').Rule} */ +module.exports = { + meta: { + deprecated: true, + + replacedBy: [], + + type: "suggestion", + + docs: { + description: "disallow the use of `process.env`", + recommended: false, + url: "https://eslint.org/docs/rules/no-process-env" + }, + + schema: [], + + messages: { + unexpectedProcessEnv: "Unexpected use of process.env." + } + }, + + create(context) { + + return { + + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { + context.report({ node, messageId: "unexpectedProcessEnv" }); + } + + } + + }; + + } +}; diff --git a/pool/shard001/JavaScript/0010043_temp.js b/pool/shard001/JavaScript/0010043_temp.js new file mode 100644 index 0000000000000000000000000000000000000000..1c9977ac727978527c0924df0a77b25b4f6704e9 --- /dev/null +++ b/pool/shard001/JavaScript/0010043_temp.js @@ -0,0 +1,34 @@ +var utils = require('./socket_utils.js'); + +/** + * Adds temp sensor–specific methods to pin object. Called via special. + * Always sets pin direction to output. + * + * Unlike with other pins, primary methods defined within read callbacks. + * (see socket_utils.js) + * + * @param {Object} pin + * @return {Object} mutated pin + */ +function temp(pin) { + // Unpack pin object, pluck data & reassign pin num to pin.pin for generation + var settings = pin.pin; + var pinNum = settings.pin; + + pin._voltsIn = settings.voltsIn; + pin.pin = pinNum; + + pin.direction = 'input'; + utils.dispatch(utils.pinInit(pin.pin, pin.mode, pin.direction)); + utils.constructFuncs(pin); + + var tempErr = 'Remember to call read before try to get a temp value.'; + // Actual values set in read callback; see socket_utils, constructFuncs + pin.C = function() { throw new Error(tempErr); }; + pin.F = function() { throw new Error(tempErr); }; + pin.K = function() { throw new Error(tempErr); }; + + return pin; +} + +module.exports = temp; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010045_gadget-util.js b/pool/shard001/JavaScript/0010045_gadget-util.js new file mode 100644 index 0000000000000000000000000000000000000000..307a964ee292c44448a05524c95e21126eda1f14 --- /dev/null +++ b/pool/shard001/JavaScript/0010045_gadget-util.js @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var getGadgetLocation = function (callback) { + var gadgetLocation = "/portal/store/carbon.super/fs/gadget/Android_Screen_On_Chart"; + var PATH_SEPERATOR = "/"; + if (gadgetLocation.search("store") != -1) { + wso2.gadgets.identity.getTenantDomain(function (tenantDomain) { + var gadgetPath = gadgetLocation.split(PATH_SEPERATOR); + var modifiedPath = ''; + for (var i = 1; i < gadgetPath.length; i++) { + if (i === 3) { + modifiedPath = modifiedPath.concat(PATH_SEPERATOR, tenantDomain); + } else { + modifiedPath = modifiedPath.concat(PATH_SEPERATOR, gadgetPath[i]) + } + } + callback(modifiedPath); + }); + } else { + callback(gadgetLocation); + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010048_submissions.js b/pool/shard001/JavaScript/0010048_submissions.js new file mode 100644 index 0000000000000000000000000000000000000000..61fce6f255409832e793249410cfd102df3294a1 --- /dev/null +++ b/pool/shard001/JavaScript/0010048_submissions.js @@ -0,0 +1,23 @@ +'use strict'; + +angular.module('UTMQViewerApp') + .controller('AuthoringSubmissionsCtrl', function ($scope, $routeParams, Problem, Submission) { + + var query = function () { + Problem.get({ id: $routeParams.problemId }).$promise + .then( + function (problem) { + $scope.problem = problem; + + return Submission.query({ problem: problem._id }).$promise; + }) + .then( + function (subs) { + $scope.subs = subs; + } + ); + }; + + query(); + + }); diff --git a/pool/shard001/JavaScript/0010049_angularService.js b/pool/shard001/JavaScript/0010049_angularService.js new file mode 100644 index 0000000000000000000000000000000000000000..0660854bc3198058124161d6d72d24ffeec24394 --- /dev/null +++ b/pool/shard001/JavaScript/0010049_angularService.js @@ -0,0 +1,58 @@ +angular.module('MODULE.SUBMODULE').factory( + 'SERVICE', + function SERVICEProvider( + $log, + otherService + ) { + 'use strict'; + + var initialize, + instanceVar1, + instanceVar2, + private1, + private2, + public1, + public2; + + // ----- + // PRIVATE + // ---------- + + initialize = function initialize() { + // Constructor-like function. + instanceVar1 = 42; + instanceVar2 = 'foo'; + }; + + private1 = function private1(spec) { + // body... + }; + + private2 = function private2(spec) { + // body... + }; + + // ----- + // PUBLIC + // ---------- + + public1 = function public1(spec) { + // body... + }; + + public2 = function public2(spec) { + // body... + }; + + // ----- + // EXECUTE + // ---------- + + initialize(); + return { + public1: public1, + public2: public2 + }; + } + +); diff --git a/pool/shard001/JavaScript/0010050_index.js b/pool/shard001/JavaScript/0010050_index.js new file mode 100644 index 0000000000000000000000000000000000000000..79f422c0699c455f00fc1f483a9c669107fd51bf --- /dev/null +++ b/pool/shard001/JavaScript/0010050_index.js @@ -0,0 +1,63 @@ +module.exports = AndroidManifest; +var _ = require('lodash'); +var fs = require('fs'); +var pd = require('pretty-data2').pd; +var cheerio = require('cheerio'); + +function AndroidManifest() { this.data = {} } + +AndroidManifest.prototype.toXML = function() { + return pd.xml(this.$.xml()); +} + +AndroidManifest.prototype.writeFile = function(path) { + var xmlString = this.toXML(); + fs.writeFileSync(path, xmlString); + return this; +} + +AndroidManifest.prototype.readFile = function(path) { + var xml = fs.readFileSync(path).toString(); + this.$ = cheerio.load(xml, { xmlMode: true }); + return this; +} + +AndroidManifest.prototype.usesPermission = function(name) { + var perms = this.$('uses-permission') + var dupe = _.find(perms, { attribs: { 'android:name': name } }); + if (!dupe) { + var elem = this.$('').attr('android:name', name); + this.$('manifest').append(elem); + } + return this; +} + +AndroidManifest.prototype.subclass = function(name) { + this.$('application').attr('android:name', name); + return this; +} + +AndroidManifest.prototype.findOrCreateByAndroidName = function(parent, tag, name) { + var manifest = this; + var $ = manifest.$; + var nodes = $(parent).find(' > '+tag); + var dupe = _.find(nodes, { attribs: { 'android:name': name } }); + if (dupe) return $(dupe); + else { + var elem = $('<'+tag+'>').attr('android:name', name); + $(parent).append(elem); + return $(elem); + } +} + +AndroidManifest.prototype.receiver = function(name) { + return this.findOrCreateByAndroidName('application', 'receiver', name); +} + +AndroidManifest.prototype.service = function(name) { + return this.findOrCreateByAndroidName('application', 'service', name); +} + +AndroidManifest.prototype.activity = function(name) { + return this.findOrCreateByAndroidName('application', 'activity', name); +} diff --git a/pool/shard001/JavaScript/0010051_sha1-test.js b/pool/shard001/JavaScript/0010051_sha1-test.js new file mode 100644 index 0000000000000000000000000000000000000000..57db26fc942367de873563d006d44c89f82097e5 --- /dev/null +++ b/pool/shard001/JavaScript/0010051_sha1-test.js @@ -0,0 +1,77 @@ +YUI.add('sha1-test', function (Y) { + var SHA1 = CryptoJS.SHA1; + + Y.CryptoJSTestSuite.add(new Y.Test.Case({ + name: 'SHA1', + + _should: { + ignore: { + // This test will hash 768MB of data; it takes a while. + // So it's disabled by default, but can be switched on at any time. + testUpdateAndLongMessage: true + } + }, + + testVector1: function () { + Y.Assert.areEqual('da39a3ee5e6b4b0d3255bfef95601890afd80709', SHA1.hash('').toString()); + }, + + testVector2: function () { + Y.Assert.areEqual('86f7e437faa5a7fce15d1ddcb9eaeaea377667b8', SHA1.hash('a').toString()); + }, + + testVector3: function () { + Y.Assert.areEqual('a9993e364706816aba3e25717850c26c9cd0d89d', SHA1.hash('abc').toString()); + }, + + testVector4: function () { + Y.Assert.areEqual('c12252ceda8be8994d5fa0290a47231c1d16aae3', SHA1.hash('message digest').toString()); + }, + + testVector5: function () { + Y.Assert.areEqual( + '32d10c7b8cf96570ca04ce37f2a19d84240d3a89', + SHA1.hash('abcdefghijklmnopqrstuvwxyz').toString() + ); + }, + + testVector6: function () { + Y.Assert.areEqual( + '761c457bf73b14d27e9e9265c46f4b4dda11f940', + SHA1.hash('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789').toString() + ); + }, + + testVector7: function () { + Y.Assert.areEqual( + '50abf5706a150990a08b2c5ea40fa0e585554732', + SHA1.hash('12345678901234567890123456789012345678901234567890123456789012345678901234567890').toString() + ); + }, + + testUpdateAndLongMessage: function () { + var sha1 = new SHA1(); + for (var i = 0; i < 768 * 1024 * 1024 / 32; i++) { + sha1.update('\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'); + } + + Y.Assert.areEqual('7eb74f7d1b09557cd990232f4ad84963eb6d0226', sha1.finalize().toString()); + }, + + testClone: function () { + var sha1 = new SHA1(); + + Y.Assert.areEqual(SHA1.hash('a').toString(), sha1.update('a').clone().finalize().toString()); + Y.Assert.areEqual(SHA1.hash('ab').toString(), sha1.update('b').clone().finalize().toString()); + Y.Assert.areEqual(SHA1.hash('abc').toString(), sha1.update('c').clone().finalize().toString()); + }, + + testInputIntegrity: function () { + var message = new CryptoJS.lib.WordArray([0x12345678]); + var expected = message.toString(); + SHA1.hash(message); + + Y.Assert.areEqual(expected, message.toString()); + } + })); +}, '$Rev$'); diff --git a/pool/shard001/JavaScript/0010052_ResultView.js b/pool/shard001/JavaScript/0010052_ResultView.js new file mode 100644 index 0000000000000000000000000000000000000000..e427d4886daf977a9db5d76288340f8781232d64 --- /dev/null +++ b/pool/shard001/JavaScript/0010052_ResultView.js @@ -0,0 +1,35 @@ +ResultView = Hideable.extend({ + initialize: function(){ + this.HideTarget = this.$el.parent(); + this.pagination = new ResultPagination({ + el: this.$('.pagination') + }); + this.model = this.pagination.collection; + this.model.on('reset add remove', this.render, this); + var view = this; + window.App.router.on('route:resultView', function(){ + view.pagination.refresh(); + window.App.hideManager.render(view); + }); + } +, render: function(){ + var rows = ''; + this.model.map(function(r){ + var rid = r.get('id'); + var desc = $.extend({headline: '', summary: ''}, r.get('description')); + var head = desc.headline; + var summ = desc.summary; + var crea = r.get('creation'); + rows += '' + + ''+rid+'' + + ''+head+'' + + ''+summ+'' + + ''+crea+'' + + ''; + }); + this.$('tbody').html(rows); + this.$('tbody a').each(function(){ + window.App.router.watchClick($(this)); + }); + } +}); diff --git a/pool/shard001/JavaScript/0010053_www.js b/pool/shard001/JavaScript/0010053_www.js new file mode 100644 index 0000000000000000000000000000000000000000..8979b9940a7e81b6b9474afc1e42b6f7e2ec34e1 --- /dev/null +++ b/pool/shard001/JavaScript/0010053_www.js @@ -0,0 +1,40 @@ +var koa = require('koa'); +var mount = require('koa-mount'); +var router = require('koa-router'); +var render = require('koa-ejs'); +var serve = require('koa-static'); +var session = require('koa-session'); +var getAbsolutePath = require('../modules/other/pathUtils').getAbsolutePath; +var config = require("../modules/config/configUtils").getConfigs(); +var logger = require("../modules/logger/logUtils"); +var socketHandler = require('./middlewares/socketHandler'); + +//settings +var app = koa(); +app.keys = [config.SECRET]; +app.use(session(app)); + +app.on('error', function(err){ + logger.error(err, err.ctx); +}); +app.use(router(app)); +app.use(serve(getAbsolutePath('public'))); +app.use(serve(getAbsolutePath('bower_components'), { + maxAge: 1000 * 86400 * 30 +})); +render(app, { + root: getAbsolutePath('web/views'), + layout: false, + viewExt: 'ejs', + cache: false, + debug: true +}); + +//routes +var chat = require(getAbsolutePath('web/www/routers/chat')); +app.use(mount('/chat', chat.middleware())); + +//listen +var server = socketHandler.createServer(app); +server.listen(config.www_port); +console.log('listening on port', config.www_port); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010054_security.js b/pool/shard001/JavaScript/0010054_security.js new file mode 100644 index 0000000000000000000000000000000000000000..a865562d2d4176c4425920b4783c2f7fdc6a503b --- /dev/null +++ b/pool/shard001/JavaScript/0010054_security.js @@ -0,0 +1,105 @@ +// Load modules + +var Code = require('code'); +var Hapi = require('hapi'); +var Hoek = require('hoek'); +var Inert = require('..'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.describe; +var it = lab.it; +var expect = Code.expect; + + +describe('security', function () { + + var provisionServer = function () { + + var server = new Hapi.Server(); + server.connection(); + server.register(Inert, Hoek.ignore); + return server; + }; + + it('blocks path traversal to files outside of hosted directory is not allowed with null byte injection', function (done) { + + var server = provisionServer(); + server.connection(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/%00/../security.js', function (res) { + + expect(res.statusCode).to.equal(403); + done(); + }); + }); + + it('blocks path traversal to files outside of hosted directory is not allowed', function (done) { + + var server = provisionServer(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/../security.js', function (res) { + + expect(res.statusCode).to.equal(403); + done(); + }); + }); + + it('blocks path traversal to files outside of hosted directory is not allowed with encoded slash', function (done) { + + var server = provisionServer(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/..%2Fsecurity.js', function (res) { + + expect(res.statusCode).to.equal(403); + done(); + }); + }); + + it('blocks path traversal to files outside of hosted directory is not allowed with double encoded slash', function (done) { + + var server = provisionServer(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/..%252Fsecurity.js', function (res) { + + expect(res.statusCode).to.equal(403); + done(); + }); + }); + + it('blocks path traversal to files outside of hosted directory is not allowed with unicode encoded slash', function (done) { + + var server = provisionServer(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/..\u2216security.js', function (res) { + + expect(res.statusCode).to.equal(403); + done(); + }); + }); + + it('blocks null byte injection when serving a file', function (done) { + + var server = provisionServer(); + server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './directory' } } }); + + server.inject('/index%00.html', function (res) { + + expect(res.statusCode).to.equal(404); + done(); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010057_ramp.js b/pool/shard001/JavaScript/0010057_ramp.js new file mode 100644 index 0000000000000000000000000000000000000000..1e8db2b69496702b5d0ded079ab88b533f16dcc0 --- /dev/null +++ b/pool/shard001/JavaScript/0010057_ramp.js @@ -0,0 +1,61 @@ +var model = module.exports = require('craft').model.define() + +model.name('ramp') + .author('doubleshow') + .version('1.0.0') + +// +// Parameters +// + +model.parameter('corner') + .defaultValue('NE') + +// +// Examples +// + +model.example('default') + +model.example('ramp SW corner') + .corner('SW'); + +model.example('ramp SE corner') + .corner('SE'); + +model.example('ramp NW corner') + .corner('NW'); + +// +// Factory +// + +model.factory(function($$$, params) { + var corner = params.corner + + var c = $$$.cube(); + c = c.scale([10, 10, 2]) + + cut1 = $$$.cube().scale([5, 5, 3]).rotateY(-30).translate([-1, 2.5, 0]); + cut2 = $$$.cube().scale([5, 5, 3]).rotateY(-30).rotateZ(90).translate([7.5, -1, 0]); + var s = $$$.difference(c, $$$.union(cut1, cut2)); + s = s.center([true, true, false]); + + + // NW -- NE + // | | + // | | + // SW -- SE + if (corner == 'NW') { + angle = 90; + } else if (corner == 'SW') { + angle = 180; + } else if (corner == 'SE') { + angle = 270; + } else if (corner == 'NE') { + angle = 0; + } + + s = s.rotateZ(angle); + return s; +}) \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010059_FaviconStore.js b/pool/shard001/JavaScript/0010059_FaviconStore.js new file mode 100644 index 0000000000000000000000000000000000000000..153cdb612f6561469b2433ff30463b76d4004067 --- /dev/null +++ b/pool/shard001/JavaScript/0010059_FaviconStore.js @@ -0,0 +1,48 @@ +import { EventEmitter } from 'events'; +import ActorAppDispatcher from 'dispatcher/ActorAppDispatcher'; +import { ActionTypes } from 'constants/ActorAppConstants'; + +const CHANGE_EVENT = 'change'; + +const FaviconPath = { + DEFAULT: 'assets/img/favicon_logo_196x196.png', + NOTIFICATION: 'assets/img/favicon_notification_512x512.png' +}; + +let _iconPath = FaviconPath.DEFAULT; + +class FaviconStore extends EventEmitter { + getFaviconPath() { + return _iconPath; + } + + emitChange() { + this.emit(CHANGE_EVENT); + } + + addChangeListener(callback) { + this.on(CHANGE_EVENT, callback); + } + + removeChangeListener(callback) { + this.removeListener(CHANGE_EVENT, callback); + } +} + +let FaviconStoreInstance = new FaviconStore(); + +FaviconStoreInstance.dispatchToken = ActorAppDispatcher.register(action => { + switch(action.type) { + case ActionTypes.FAVICON_SET_DEFAULT: + _iconPath = FaviconPath.DEFAULT; + break; + case ActionTypes.FAVICON_SET_NOTIFICATION: + _iconPath = FaviconPath.NOTIFICATION; + break; + default: + return; + } + FaviconStoreInstance.emitChange(); +}); + +export default FaviconStoreInstance; diff --git a/pool/shard001/JavaScript/0010060_combined_ast_test.js b/pool/shard001/JavaScript/0010060_combined_ast_test.js new file mode 100644 index 0000000000000000000000000000000000000000..74820240452e1473296d2c111c9713709b4b8e94 --- /dev/null +++ b/pool/shard001/JavaScript/0010060_combined_ast_test.js @@ -0,0 +1,181 @@ +import { preprocess } from "htmlbars/parser"; +import AST from "handlebars/compiler/ast"; +import { HTMLElement, BlockElement } from "htmlbars/ast"; + +module("HTML-based compiler (AST)"); + +function id(string) { + return new AST.IdNode([{ part: string }]); +} + +function sexpr(params) { + var sexprNode = new AST.SexprNode(params); + + // normalize 1 -> true for the sake of comparison; not sure + // why they come in differently... + sexprNode.isHelper = sexprNode.isHelper === 1 ? true : sexprNode.isHelper; + return sexprNode; +} + +function hash(pairs) { + return pairs ? new AST.HashNode(pairs) : undefined; +} + +function mustache(string, pairs, raw) { + var params; + + if (({}).toString.call(string) === '[object Array]') { + params = string; + } else { + params = [id(string)]; + } + + return new AST.MustacheNode(params, hash(pairs), raw ? '{{{' : '{{', { left: false, right: false }); +} + +function string(data) { + return new AST.StringNode(data); +} + +function element(tagName, attrs, children, helpers) { + if (arguments.length === 2) { + children = attrs; + attrs = []; + } + + return new HTMLElement(tagName, attrs, children, helpers); +} + +function block(helper, children) { + return new BlockElement(helper, children); +} + +function removeLocInfo(obj) { + delete obj.firstColumn; + delete obj.firstLine; + delete obj.lastColumn; + delete obj.lastLine; + + for (var k in obj) { + if (obj.hasOwnProperty(k) && obj[k] && typeof obj[k] === 'object') { + removeLocInfo(obj[k]); + } + } +} + +function astEqual(result, expected, message) { + // Perform a deepEqual but recursively remove the locInfo stuff + // (e.g. line/column information about the compiled template) + // that we don't want to have to write into our test cases. + removeLocInfo(result); + removeLocInfo(expected); + + deepEqual(result, expected, message); +} + +test("a simple piece of content", function() { + deepEqual(preprocess('some content'), ['some content']); +}); + +test("a piece of content with HTML", function() { + deepEqual(preprocess('some
content
done'), [ + "some ", + element("div", [ "content" ]), + " done" + ]); +}); + +test("a piece of Handlebars with HTML", function() { + var preprocessed = preprocess('some
{{content}}
done'); + astEqual(preprocessed, [ + "some ", + element("div", [ mustache('content') ]), + " done" + ]); +}); + +test("Handlebars embedded in an attribute", function() { + astEqual(preprocess('some
content
done'), [ + "some ", + element("div", [[ "class", [mustache('foo')] ]], [ + "content" + ]), + " done" + ]); +}); + +test("Handlebars embedded in an attribute (sexprs)", function() { + var preprocessed = preprocess('some
content
done'); + var expected = [ + "some ", + element("div", [[ "class", [mustache([id('foo'), sexpr([id('foo'), string('abc')])])] ]], [ + "content" + ]), + " done" + ]; + astEqual(preprocessed, expected); +}); + + +test("Handlebars embedded in an attribute with other content surrounding it", function() { + astEqual(preprocess('some content done'), [ + "some ", + element("a", [[ "href", ["http://", mustache('link'), "/"] ]], [ + "content" + ]), + " done" + ]); +}); + +test("A more complete embedding example", function() { + var html = "{{embed}} {{some 'content'}} " + + "
{{ content }}
" + + " {{more 'embed'}}"; + + astEqual(preprocess(html), [ + '', + mustache('embed'), ' ', + mustache([id('some'), string('content')]), ' ', + element("div", [ + ["class", [mustache('foo'), ' ', mustache([id('bind-class'), id('isEnabled')], [['truthy', string('enabled')]])]] + ], [ + mustache('content') + ]), + ' ', mustache([id('more'), string('embed')]), + '' + ]); +}); + +test("Simple embedded block helpers", function() { + var html = "{{#if foo}}
{{content}}
{{/if}}"; + + astEqual(preprocess(html), ['', + block(mustache([id('if'), id('foo')]), [ + element('div', [ mustache('content') ]) + ]), + '' + ]); +}); + +test("Involved block helper", function() { + var html = '

hi

content {{#testing shouldRender}}

Appears!

{{/testing}} more content here'; + + astEqual(preprocess(html), [ + element('p', ['hi']), + ' content ', + block(mustache([id('testing'), id('shouldRender')]), [ + element('p', ['Appears!']) + ]), + ' more ', + element('em', ['content']), + ' here' + ]); +}); + +test("Node helpers", function() { + var html = "

Some content

"; + + astEqual(preprocess(html), [ + element('p', [['class', ['bar']]], ['Some content'], [mustache([id('action'), string('boom')])]) + ]); +}); diff --git a/pool/shard001/JavaScript/0010062_auth.test.js b/pool/shard001/JavaScript/0010062_auth.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b4d03397606f9912d7e3dbfbcef6727690bc0c82 --- /dev/null +++ b/pool/shard001/JavaScript/0010062_auth.test.js @@ -0,0 +1,42 @@ +// Copyright 2017 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'; + +const assert = require('assert'); +const path = require('path'); +const {execSync} = require('child_process'); + +const cwd = path.join(__dirname, '..'); +const cmd = 'node auth.js'; + +const BUCKET_NAME = 'long-door-651'; +const GOOGLE_CLOUD_PROJECT = 'long-door-651'; +process.env.GOOGLE_CLOUD_PROJECT = 'long-door-651'; + +it('should load credentials implicitly', () => { + const output = execSync(`${cmd} auth-cloud-implicit`, {cwd, shell: true}); + assert.strictEqual(output.includes(BUCKET_NAME), true); +}); + +it('should load credentials explicitly', () => { + const project = GOOGLE_CLOUD_PROJECT; + const keyfile = process.env.GOOGLE_APPLICATION_CREDENTIALS; + console.log(`${cmd} auth-cloud-explicit -p ${project} -k ${keyfile}`); + const output = execSync( + `${cmd} auth-cloud-explicit -p ${project} -k ${keyfile}`, + {cwd, shell: true} + ); + assert.strictEqual(output.includes(BUCKET_NAME), true); +}); diff --git a/pool/shard001/JavaScript/0010064_Functions.js b/pool/shard001/JavaScript/0010064_Functions.js new file mode 100644 index 0000000000000000000000000000000000000000..e684773723f6c2ea94ae7b11eb2102a26f31605c --- /dev/null +++ b/pool/shard001/JavaScript/0010064_Functions.js @@ -0,0 +1,87 @@ + function DO(string){console.log(string);} + function set_ping_status(element,string){element.innerHTML=string;} + function parent_to_best_child_height(_class,extra){ + $Height = 0; + $mainHolder_children = $(_class).children(); + for(var i = 0; i < $mainHolder_children.length;i++){ + if($Height === 0){ + $Height = $($mainHolder_children[i]).height(); + }else{ + if($($mainHolder_children[i]).height() > $Height){ + $Height = $($mainHolder_children[i]).height(); + } + } + } + $(_class).height($Height+extra); +} + function imageExists(image_url){ + + var http = new XMLHttpRequest(); + + http.open('HEAD', image_url, false); + http.send(); + + return http.status != 404; + +} + function ping_sub(_url,time,element,send_them,place,place2) { + var url = _url; + if (url != "") { + DO('ip is not blank...'); + var image = new Image(); + image.src = url; + DO(image.src); + DO('pinging for '+time+' seconds...'); + + setTimeout + ( + function(){ + if ( !image.complete || !image.naturalWidth ){ + DO("Fail"); + set_ping_status(element,'Ping Failed!'); + location.href = place2; + }else{ + DO("Success"); + set_ping_status(element,'Ping Success!'); + if(send_them){ + DO('Sending them to '+place); + location.href = place; + } + } + + }, + (1000*time) + ); + }else{ + set_ping_status(element,'No Input Was Given'); + } + } + function setup_ping(){ + var input_url = document.getElementById('input_url').value; + var input_timeout = document.getElementById('input_timeout').value; + var status_line = document.getElementById('status'); + status_line.innerHTML="status: pinging... "+input_url; + ping_sub(input_url,input_timeout,status_line,false,"",""); + } + function test_website(){ + if(document.body.contains(document.getElementById("Home_Message"))){ + // DO("found him"); + var holder = document.getElementById("Home_Message"); + var text = document.getElementById("Home_Message").innerHTML; + var url = "http://INVALID/Home.html"; + var timeout = 3; + if(text === "loading..."){ + holder.innerHTML = "Checking to see if better site is online..."; + // DO('got loading...'); + ping_sub(url,timeout,holder,true,"http://INVALID/Home.html","https://steven9smith.github.io/Website.CC/Home.html"); + }else{ + // DO('can\'t get it'); + } + }else{ + // DO("Could not find him"); + } + } + $(document).ready(function(){ + test_website(); +}); + \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010067_editParticular.js b/pool/shard001/JavaScript/0010067_editParticular.js new file mode 100644 index 0000000000000000000000000000000000000000..02f7733d71ed71a2884ce0c5fa6ae3aefb569e2b --- /dev/null +++ b/pool/shard001/JavaScript/0010067_editParticular.js @@ -0,0 +1,107 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +function loadEditParticular(_confId, _updateUrl) { +//* Required Scripting + + $('#innerCutOffDate').datetimepicker({useCurrent: false, pickTime: true, pickDate: true}); + $('#btnEditParticular').on('click', function (e) { + + $('#innerCutOffDate').data('DateTimePicker').setValue(new Date($('#cutOffValue').html())); + $('#innerCutOffDate').data('DateTimePicker').setMinDate(new Date()); + var d = new Date($('#beginDate').html()); + d.setDate(d.getDate() - 5); + $('#innerCutOffDate').data('DateTimePicker').setMaxDate(d); + $('#innerMinScore > input').val($('#minScoreValue').html()); + $('#innerTicketPrice > input').val($('#ticketPriceValue').html()); + $('#particularEditor').modal({keyboard: false, backdrop: 'static', show: true}); + }); + //* Validation + $('#confParticularField').formValidation({ + framework: 'bootstrap', + excluded: ':disabled', + err: { + container: 'tooltip' + }, + icon: { + valid: 'glyphicon glyphicon-ok', + invalid: 'glyphicon glyphicon-remove', + validating: 'glyphicon glyphicon-refresh' + }, + fields: { + cutOffDate: { + validators: { + date: { + format: 'DD-MM-YYYY HH:mm', + message: 'The value is not a valid datetime' + } + } + }, + minScore: { + validators: { + numeric: { + separator: '.', + message: 'The value is not a valid numeric' + } + } + } + } + }).on('err.field.fv err.validator.fv', function (e, data) { + $('#btnSaveConfParticular').prop('disabled', true); + }).on('success.field.fv', function (e, data) { + $('#btnSaveConfParticular').prop('disabled', false); + }); + + //* Save + $('#btnSaveConfParticular').on('click', function (e) { + + $.ajax({ + url: _updateUrl, + data: { + conf_id: _confId + ,cutOffDate: $("#innerCutOffDate").data("DateTimePicker").getDate().format('DD-MMM-YYYY HH:mm') + ,minScore: $('#innerMinScore > input').val() + ,ticketPrice: $('#innerTicketPrice > input').val() + }, + type: 'get', + beforeSend: function () { + $('#modalMessage').html('Loading...'); + $('#resultModal').modal({ + keyboard: false, + backdrop: 'static' + }); + } + }).done(function (data) { +//change the current + if (data.success !== undefined) { + var message = data.success.numRowUpdated + ' record(s) updated successfully !!!'; + $('#modalMessage').html(message); + if (data.success.conf !== undefined) { +//* put back all into front page + if (data.success.conf.cutoff_time !== undefined && data.success.conf.min_score !== undefined) { + $('#cutOffValue').html(new moment(data.success.conf.cutoff_time).format('DD-MMM-YYYY HH:mm')); + $('#minScoreValue').html(data.success.conf.min_score); + $('#ticketPriceValue').html(data.success.conf.ticket_price); + } + } + } + setTimeout(function () { + $('#resultModal').modal('hide'); + $('#particularEditor').modal('hide'); + }, 1000); + }).fail(function (data) { + + if (data.responseJSON !== undefined) { + if (data.responseJSON.error !== undefined) { + var message = data.responseJSON.error.type + ' : ' + data.responseJSON.error.message; + $('#modalMessage').html(message); + setTimeout(function () { + $('#resultModal').modal('hide'); + }, 1500); + } + } + }); + }); +} diff --git a/pool/shard001/JavaScript/0010071_util.js b/pool/shard001/JavaScript/0010071_util.js new file mode 100644 index 0000000000000000000000000000000000000000..d9a045b5540a111504af5e8f6c3cb4b6a45b6b2c --- /dev/null +++ b/pool/shard001/JavaScript/0010071_util.js @@ -0,0 +1,28 @@ + +var getClassName = function (obj) { + if (obj === null || obj === undefined) + return 'undefined'; + var constr = obj.constructor.toString(); + var funcStr = 'function '; + var funcPos = constr.indexOf(funcStr); + var postFuncPos = funcPos + funcStr.length; + var n = constr.indexOf('('); + if (funcPos < 0 || n <= postFuncPos) + return 'undefined'; + return constr.substring(postFuncPos, n); +} + +var generateUUID = function () { + var d = new Date().getTime(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); + }); + return uuid; +}; + +module.exports = { + getClassName: getClassName, + generateUUID: generateUUID +} diff --git a/pool/shard001/JavaScript/0010072_application.js b/pool/shard001/JavaScript/0010072_application.js new file mode 100644 index 0000000000000000000000000000000000000000..333ec5e4e8ec364ba8cf548ec5d5ae34a054013d --- /dev/null +++ b/pool/shard001/JavaScript/0010072_application.js @@ -0,0 +1,290 @@ +import {Injector, bind, OpaqueToken, Optional} from 'angular2/di'; +import {NumberWrapper, Type, isBlank, isPresent, BaseException, + assertionsEnabled, print, stringify} from 'angular2/src/facade/lang'; +import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter'; +import {DOM} from 'angular2/src/dom/dom_adapter'; +import {Compiler, CompilerCache} from './compiler/compiler'; +import {Reflector, reflector} from 'angular2/src/reflection/reflection'; +import {Parser, Lexer, ChangeDetection, DynamicChangeDetection, PipeRegistry, defaultPipeRegistry} from 'angular2/change_detection'; +import {ExceptionHandler} from './exception_handler'; +import {TemplateLoader} from 'angular2/src/render/dom/compiler/template_loader'; +import {TemplateResolver} from './compiler/template_resolver'; +import {DirectiveMetadataReader} from './compiler/directive_metadata_reader'; +import {List, ListWrapper} from 'angular2/src/facade/collection'; +import {Promise, PromiseWrapper} from 'angular2/src/facade/async'; +import {VmTurnZone} from 'angular2/src/core/zone/vm_turn_zone'; +import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle'; +import {ShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/shadow_dom_strategy'; +import {EmulatedUnscopedShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy'; +import {XHR} from 'angular2/src/services/xhr'; +import {XHRImpl} from 'angular2/src/services/xhr_impl'; +import {EventManager, DomEventsPlugin} from 'angular2/src/render/dom/events/event_manager'; +import {KeyEventsPlugin} from 'angular2/src/render/dom/events/key_events'; +import {HammerGesturesPlugin} from 'angular2/src/render/dom/events/hammer_gestures'; +import {Binding} from 'angular2/src/di/binding'; +import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper'; +import {UrlResolver} from 'angular2/src/services/url_resolver'; +import {StyleUrlResolver} from 'angular2/src/render/dom/shadow_dom/style_url_resolver'; +import {StyleInliner} from 'angular2/src/render/dom/shadow_dom/style_inliner'; +import {ComponentRef, DynamicComponentLoader} from 'angular2/src/core/compiler/dynamic_component_loader'; +import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability'; +import {ViewFactory, VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_factory'; +import {AppViewHydrator} from 'angular2/src/core/compiler/view_hydrator'; +import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory'; +import {Renderer} from 'angular2/src/render/api'; +import {DirectDomRenderer} from 'angular2/src/render/dom/direct_dom_renderer'; +import * as rc from 'angular2/src/render/dom/compiler/compiler'; +import * as rvf from 'angular2/src/render/dom/view/view_factory'; +import * as rvh from 'angular2/src/render/dom/view/view_hydrator'; + +import { + appComponentRefToken, + appChangeDetectorToken, + appElementToken, + appComponentAnnotatedTypeToken, + appDocumentToken, +} from './application_tokens'; + +var _rootInjector: Injector; + +// Contains everything that is safe to share between applications. +var _rootBindings = [ + bind(Reflector).toValue(reflector), + TestabilityRegistry +]; + +function _injectorBindings(appComponentType): List { + return [ + bind(appDocumentToken).toValue(DOM.defaultDoc()), + bind(appComponentAnnotatedTypeToken).toFactory((reader) => { + // TODO(rado): investigate whether to support bindings on root component. + return reader.read(appComponentType); + }, [DirectiveMetadataReader]), + + bind(appElementToken).toFactory((appComponentAnnotatedType, appDocument) => { + var selector = appComponentAnnotatedType.annotation.selector; + var element = DOM.querySelector(appDocument, selector); + if (isBlank(element)) { + throw new BaseException(`The app selector "${selector}" did not match any elements`); + } + return element; + }, [appComponentAnnotatedTypeToken, appDocumentToken]), + bind(appComponentRefToken).toAsyncFactory((dynamicComponentLoader, injector, appElement, + appComponentAnnotatedType, testability, registry) => { + + // We need to do this here to ensure that we create Testability and + // it's ready on the window for users. + registry.registerApplication(appElement, testability); + return dynamicComponentLoader.loadIntoNewLocation(appElement, appComponentAnnotatedType.type, null, injector); + }, [DynamicComponentLoader, Injector, appElementToken, appComponentAnnotatedTypeToken, + Testability, TestabilityRegistry]), + + bind(appChangeDetectorToken).toFactory((ref) => ref.hostView.changeDetector, + [appComponentRefToken]), + bind(appComponentType).toFactory((ref) => ref.instance, + [appComponentRefToken]), + bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle(exceptionHandler, null, assertionsEnabled()),[ExceptionHandler]), + bind(EventManager).toFactory((zone) => { + var plugins = [new HammerGesturesPlugin(), new KeyEventsPlugin(), new DomEventsPlugin()]; + return new EventManager(plugins, zone); + }, [VmTurnZone]), + bind(ShadowDomStrategy).toFactory( + (styleUrlResolver, doc) => new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, doc.head), + [StyleUrlResolver, appDocumentToken]), + bind(Renderer).toClass(DirectDomRenderer), + bind(rc.Compiler).toClass(rc.DefaultCompiler), + // TODO(tbosch): We need an explicit factory here, as + // we are getting errors in dart2js with mirrors... + bind(rvf.ViewFactory).toFactory( + (capacity, eventManager, shadowDomStrategy) => new rvf.ViewFactory(capacity, eventManager, shadowDomStrategy), + [rvf.VIEW_POOL_CAPACITY, EventManager, ShadowDomStrategy] + ), + bind(rvf.VIEW_POOL_CAPACITY).toValue(10000), + rvh.RenderViewHydrator, + ProtoViewFactory, + // TODO(tbosch): We need an explicit factory here, as + // we are getting errors in dart2js with mirrors... + bind(ViewFactory).toFactory( + (capacity, renderer) => new ViewFactory(capacity, renderer), + [VIEW_POOL_CAPACITY, Renderer] + ), + bind(VIEW_POOL_CAPACITY).toValue(10000), + AppViewHydrator, + Compiler, + CompilerCache, + TemplateResolver, + bind(PipeRegistry).toValue(defaultPipeRegistry), + bind(ChangeDetection).toClass(DynamicChangeDetection), + TemplateLoader, + DirectiveMetadataReader, + Parser, + Lexer, + ExceptionHandler, + bind(XHR).toValue(new XHRImpl()), + ComponentUrlMapper, + UrlResolver, + StyleUrlResolver, + StyleInliner, + DynamicComponentLoader, + Testability + ]; +} + +function _createVmZone(givenReporter:Function): VmTurnZone { + var defaultErrorReporter = (exception, stackTrace) => { + var longStackTrace = ListWrapper.join(stackTrace, "\n\n-----async gap-----\n"); + print(`${exception}\n\n${longStackTrace}`); + throw exception; + }; + + var reporter = isPresent(givenReporter) ? givenReporter : defaultErrorReporter; + + var zone = new VmTurnZone({enableLongStackTrace: assertionsEnabled()}); + zone.initCallbacks({onErrorHandler: reporter}); + return zone; +} + +/** + * Bootstrapping for Angular applications. + * + * You instantiate an Angular application by explicitly specifying a component to use as the root component for your + * application via the `bootstrap()` method. + * + * ## Simple Example + * + * Assuming this `index.html`: + * + * ```html + * + * + * + * loading... + * + * + * ``` + * + * An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike Angular 1, Angular 2 + * does not compile/process bindings in `index.html`. This is mainly for security reasons, as well as architectural + * changes in Angular 2. This means that `index.html` can safely be processed using server-side technologies such as + * bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2 component double-curly + * `{{ syntax }}`. + * + * We can use this script code: + * + * ``` + * @Component({ + * selector: 'my-app' + * }) + * @View({ + * template: 'Hello {{ name }}!' + * }) + * class MyApp { + * name:string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * + * main() { + * return bootstrap(MyApp); + * } + * ``` + * + * When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument, Angular performs the + * following tasks: + * + * 1. It uses the component's `selector` property to locate the DOM element which needs to be upgraded into + * the angular component. + * 2. It creates a new child injector (from the primordial injector) and configures the injector with the component's + * `injectables`. Optionally, you can also override the injector configuration for an app by invoking + * `bootstrap` with the `componentInjectableBindings` argument. + * 3. It creates a new [Zone] and connects it to the angular application's change detection domain instance. + * 4. It creates a shadow DOM on the selected component's host element and loads the template into it. + * 5. It instantiates the specified component. + * 6. Finally, Angular performs change detection to apply the initial data bindings for the application. + * + * + * ## Instantiating Multiple Applications on a Single Page + * + * There are two ways to do this. + * + * + * ### Isolated Applications + * + * Angular creates a new application each time that the `bootstrap()` method is invoked. When multiple applications + * are created for a page, Angular treats each application as independent within an isolated change detection and + * [Zone] domain. If you need to share data between applications, use the strategy described in the next + * section, "Applications That Share Change Detection." + * + * + * ### Applications That Share Change Detection + * + * If you need to bootstrap multiple applications that share common data, the applications must share a common + * change detection and zone. To do that, create a meta-component that lists the application components in its template. + * By only invoking the `bootstrap()` method once, with the meta-component as its argument, you ensure that only a + * single change detection zone is created and therefore data can be shared across the applications. + * + * + * ## Primordial Injector + * + * When working within a browser window, there are many singleton resources: cookies, title, location, and others. + * Angular services that represent these resources must likewise be shared across all Angular applications that + * occupy the same browser window. For this reason, Angular creates exactly one global primordial injector which stores + * all shared services, and each angular application injector has the primordial injector as its parent. + * + * Each application has its own private injector as well. When there are multiple applications on a page, Angular treats + * each application injector's services as private to that application. + * + * + * # API + * - [appComponentType]: The root component which should act as the application. This is a reference to a [Type] + * which is annotated with `@Component(...)`. + * - [componentInjectableBindings]: An additional set of bindings that can be added to the [Component.injectables] to + * override default injection behavior. + * - [errorReporter]: `function(exception:any, stackTrace:string)` a default error reporter for unhandled exceptions. + * + * Returns a [Promise] with the application`s private [Injector]. + * + * @exportedAs angular2/core + */ +export function bootstrap(appComponentType: Type, + componentInjectableBindings: List = null, + errorReporter: Function = null): Promise { + BrowserDomAdapter.makeCurrent(); + var bootstrapProcess = PromiseWrapper.completer(); + + var zone = _createVmZone(errorReporter); + zone.run(() => { + // TODO(rado): prepopulate template cache, so applications with only + // index.html and main.js are possible. + + var appInjector = _createAppInjector(appComponentType, componentInjectableBindings, zone); + + PromiseWrapper.then(appInjector.asyncGet(appComponentRefToken), + (componentRef) => { + var appChangeDetector = componentRef.hostView.changeDetector; + // retrieve life cycle: may have already been created if injected in root component + var lc = appInjector.get(LifeCycle); + lc.registerWith(zone, appChangeDetector); + lc.tick(); //the first tick that will bootstrap the app + + bootstrapProcess.resolve(componentRef); + }, + + (err) => { + bootstrapProcess.reject(err) + }); + }); + + return bootstrapProcess.promise; +} + +function _createAppInjector(appComponentType: Type, bindings: List, zone: VmTurnZone): Injector { + if (isBlank(_rootInjector)) _rootInjector = Injector.resolveAndCreate(_rootBindings); + var mergedBindings = isPresent(bindings) ? + ListWrapper.concat(_injectorBindings(appComponentType), bindings) : + _injectorBindings(appComponentType); + ListWrapper.push(mergedBindings, bind(VmTurnZone).toValue(zone)); + return _rootInjector.resolveAndCreateChild(mergedBindings); +} diff --git a/pool/shard001/JavaScript/0010073_util.js b/pool/shard001/JavaScript/0010073_util.js new file mode 100644 index 0000000000000000000000000000000000000000..3c70750dc4b3ea18c767f470d37ed7ac0634c67b --- /dev/null +++ b/pool/shard001/JavaScript/0010073_util.js @@ -0,0 +1,82 @@ +import Vue from 'vue'; +import $ from 'jquery'; + +function type(o) { + return typeof o; +} + +function isArr(o) { + return o instanceof Array; +} + +function isStr(o) { + return type(o) == 'string'; +} + + +function destroyVM(vm) { + if (vm) { + const el = vm.$el; + if (el && el.parentNode) { + $(el).remove(); + } + } +} + +function createAndReplaceElem() { + const el = document.createElement('div'), + elBody = document.body, + oEl = document.getElementById('app'); + if (oEl) { + $(oEl).remove(oEl); + } + elBody.appendChild(el); + return el; +} + +function createVM(Compo, propsData = {}, mounted) { + const nPropsData = { ...propsData }; + const el = createAndReplaceElem(); + let VueExtended = Vue; + if (isStr(Compo)) { + nPropsData.template = Compo; + } + // Component + else { + VueExtended = Vue.extend(Vue); + } + return new VueExtended(nPropsData).$mount(mounted === false ? null : el); +} + +function cssTextToObject(txt) { + const result = {}; + txt.split(';').forEach((term) => { + const splits = term.split(':'); + if (splits && splits.length == 2) { + const key = splits[0].trim(), + value = splits[1].trim(); + result[key] = value; + } + }); + return result; +} + +function genImgSrc() { + return `img/lenna.png?_t=${Math.floor(Math.random() * 100000)}.${Date.now()}`; +} + +function genImgList(len) { + const arr = []; + while (len--) { + arr.push(genImgSrc()); + } + return arr; +} +export { + destroyVM, + createAndReplaceElem, + createVM, + cssTextToObject, + genImgSrc, + genImgList, +}; diff --git a/pool/shard001/JavaScript/0010075_item.js b/pool/shard001/JavaScript/0010075_item.js new file mode 100644 index 0000000000000000000000000000000000000000..27766354840128312adb732af72e0ad660e01993 --- /dev/null +++ b/pool/shard001/JavaScript/0010075_item.js @@ -0,0 +1,133 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import Columns from '../columns'; +import Lists from '../stores/Lists'; +import CreateForm from '../components/CreateForm'; +import EditForm from '../components/EditForm'; +import EditFormHeader from '../components/EditFormHeader'; +import FlashMessages from '../components/FlashMessages'; +import Footer from '../components/Footer'; +import MobileNavigation from '../components/MobileNavigation'; +import PrimaryNavigation from '../components/PrimaryNavigation'; +import RelatedItemsList from '../components/RelatedItemsList'; +import SecondaryNavigation from '../components/SecondaryNavigation'; +import { Alert, Container, Spinner } from 'elemental'; + +var ItemView = React.createClass({ + + displayName: 'ItemView', + + getInitialState () { + return { + createIsOpen: false, + itemData: null, + }; + }, + + componentDidMount () { + this.loadItemData(); + }, + + loadItemData () { + this.props.list.loadItem(this.props.itemId, { drilldown: true }, (err, itemData) => { + if (err || !itemData) { + // TODO: nicer error handling + console.log('Error loading item data', err); + alert('Error loading data (details logged to console)'); + return; + } + this.setState({ itemData }); + }); + }, + + toggleCreate (visible) { + this.setState({ + createIsOpen: visible, + }); + }, + + renderRelationships () { + let { relationships } = this.props.list; + let keys = Object.keys(relationships); + if (!keys.length) return; + return ( +
+

Relationships

+ {keys.map(key => { + let relationship = relationships[key]; + let refList = Lists[relationship.ref]; + return ; + })} +
+ ); + }, + + render () { + if (!this.state.itemData) return
; + return ( +
+
+ + + +
+
+ + + this.toggleCreate(false)} /> + + + {this.renderRelationships()} + +
+
+
+ ); + } + +}); + +ReactDOM.render( + , + document.getElementById('item-view') +); diff --git a/pool/shard001/JavaScript/0010077_test-http-flush-response-headers.js b/pool/shard001/JavaScript/0010077_test-http-flush-response-headers.js new file mode 100644 index 0000000000000000000000000000000000000000..76e739741cb2db64b3aa70e4dae5aeaaf8f639be --- /dev/null +++ b/pool/shard001/JavaScript/0010077_test-http-flush-response-headers.js @@ -0,0 +1,27 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +const server = http.createServer(); + +server.on('request', function(req, res) { + res.writeHead(200, {'foo': 'bar'}); + res.flushHeaders(); + res.flushHeaders(); // Should be idempotent. +}); +server.listen(common.PORT, common.localhostIPv4, function() { + var req = http.request({ + method: 'GET', + host: common.localhostIPv4, + port: common.PORT, + }, onResponse); + + req.end(); + + function onResponse(res) { + assert.equal(res.headers['foo'], 'bar'); + res.destroy(); + server.close(); + } +}); diff --git a/pool/shard001/JavaScript/0010078_home.js b/pool/shard001/JavaScript/0010078_home.js new file mode 100644 index 0000000000000000000000000000000000000000..028f783a3465192f03e4467c1045913987dc7b7c --- /dev/null +++ b/pool/shard001/JavaScript/0010078_home.js @@ -0,0 +1,31 @@ +Template['home'].helpers({ + myFormData: function() { + return { directoryName: 'images', prefix: this._id, _id: this._id } + }, + filesToUpload: function() { + return Uploader.info.get(); + } + +}); + +Template['uploadedInfo'].helpers({ + src: function() { + if (this.type.indexOf('image') >= 0) { + return 'upload/' + this.path; + } else return 'file_icon.png'; + } +}); + +Template['uploadedInfo'].events({ + 'click .deleteUpload':function() { + if (confirm('Are you sure?')) { + Meteor.call('deleteFile', this._id); + var pics = SessionAmplify.get('pics') + var index = pics.indexOf(this._id); + if (index > -1) { + pics.splice(index, 1); + } + SessionAmplify.set('pics',pics); + } + } +}) \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010083_analytics_interaction_manager.js b/pool/shard001/JavaScript/0010083_analytics_interaction_manager.js new file mode 100644 index 0000000000000000000000000000000000000000..005d285d87898bf8c2a569340833d87eb3abf585 --- /dev/null +++ b/pool/shard001/JavaScript/0010083_analytics_interaction_manager.js @@ -0,0 +1,111 @@ +/* + * Copyright 2019 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +(function () { + "use strict"; + + const Requests = require("rails-shared/plugin-endpoint-request-handler"); + const Frame = require("models/shared/frame"); + const Routes = require("gen/js-routes"); + + function Namespace(models, name) { + const prefix = `${encodeURIComponent(name)}:`; + + function withPrefix(u) { + return prefix + u; + } + + function withoutPrefix(u) { + return u.split(":").pop(); + } + + function encodeUID(i, p, t, id) { + return withPrefix(btoa(JSON.stringify({plugin: p, type: t, id, ordinal: i}))); + } + + function decodeUID(uid) { + return JSON.parse(atob(withoutPrefix(uid))); + } + + this.uid = encodeUID; + this.unpack = decodeUID; + + this.group = function group() { + return name; + }; + + this.all = function allModelsInNamespace() { + const result = {}; + for (const k in models) { + if (k.startsWith(prefix)) { result[k] = models[k]; } + } + return result; + }; + + function toUrl(uid, params={}) { + const c = decodeUID(uid); + return Routes.showAnalyticsPath(c.plugin, c.type, c.id, params); + } + + this.toUrl = toUrl; + + this.modelFor = function modelFor(uid, extraParams={}) { + let model = models[uid]; + + if (!model) { + model = models[uid] = new Frame(); + model.url(toUrl(uid, extraParams)); + } + + return model; + }; + } + + /** + * AnalyticsInteractionManager should be a singleton that handles + * the bootstrapping of parent page communication channel, which + * includings things like listener definitions and Frame model + * management. + */ + function AnalyticsInteractionManager() { + const models = {}; + + this.purge = function destroyAll() { + for (const k in models) { + delete models[k]; + } + }; + + this.all = function allModels() { + // returns the whole world. + // + // shallow copy prevents unauthorized writes to + // `models` internal structure + return Object.assign({}, models); + }; + + this.ns = function namespace(name) { + return new Namespace(models, name); + }; + + this.ensure = function ensure() { + Requests.defineLinkHandler(); + Requests.defineFetchAnalyticsHandler(models); + return this; + }; + } + + module.exports = new AnalyticsInteractionManager(); +})(); diff --git a/pool/shard001/JavaScript/0010085_contributorsModal.js b/pool/shard001/JavaScript/0010085_contributorsModal.js new file mode 100644 index 0000000000000000000000000000000000000000..b4bc562605d5fd17bafe424888484e1dda4c96db --- /dev/null +++ b/pool/shard001/JavaScript/0010085_contributorsModal.js @@ -0,0 +1,81 @@ +import React, { Component } from 'react' +import Modal from 'react-modal' +import * as request from 'superagent' +import { queue } from 'd3-queue' +import { parse, DOM } from 'xml-parse' + +const initialHowMany = 10 + +class ContributorsModal extends Component { + state = { + howMany: initialHowMany, + loading: false + } + + userNames = {} + + render() { + const total = this.props.contributors.reduce((prev, contributor) => prev + contributor.contributions, 0) + return ( + +

Top {Math.min(this.state.howMany, this.props.contributors.length)} Contributors

+ x +
    + {this.props.contributors.slice(0,this.state.howMany).map(contributor => +
  • {this.userNames[contributor.uid] + ? ({this.userNames[contributor.uid]}) + : '#'+contributor.uid} + {Math.round(contributor.contributions/total*100) || '<1'}% +
  • + )} +
  • {this.props.contributors.length > this.state.howMany + ? + : ''} +
  • +
+
+ ) + } + + componentWillReceiveProps(nextProps) { + if (!nextProps.isOpen) return + this.loadUserNamesFor(nextProps.contributors.slice(0,initialHowMany).map(contributor => contributor.uid)) + this.setState({ howMany: initialHowMany }) + } + + expand() { + this.loadUserNamesFor(this.props.contributors.slice(this.state.howMany,this.state.howMany+initialHowMany).map(contributor => contributor.uid)) + this.setState({ + howMany: this.state.howMany + initialHowMany + }) + } + + loadUserNamesFor(uids) { + this.setState({ loading: true }) + var q = queue() + var uidsToRequest = uids.filter(uid => !this.userNames[uid]) + + uidsToRequest.forEach(uid => { + let req = request.get('https://api.openstreetmap.org/api/0.6/user/'+uid) + q.defer(req.end.bind(req)) + }) + q.awaitAll(function(err, data) { + if (err) { + console.error(err) + } else { + uidsToRequest.forEach((uid, idx) => { + const xmlDOM = new DOM(parse(data[idx].text)); + const user = xmlDOM.document.getElementsByTagName('user')[0]; + this.userNames[uid] = user.attributes.display_name; + }) + } + this.setState({ loading: false }) + }.bind(this)) + } +} + +export default ContributorsModal diff --git a/pool/shard001/JavaScript/0010087_Player1.js b/pool/shard001/JavaScript/0010087_Player1.js new file mode 100644 index 0000000000000000000000000000000000000000..08c0c69878db7b65a9bce14484a182c3ffb4e0ba --- /dev/null +++ b/pool/shard001/JavaScript/0010087_Player1.js @@ -0,0 +1,171 @@ +// Copyright 2017 XieJinChi ChenYiXiu +// +// 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. + +/*const GameCharacter = { + 'BigMan' : 3, + 'FlexMan' : 4, + 'NormalMan' : 5 +}*/ +function Player1(spriteTexture,character){ + this.mPlayer = new SpriteRenderable(spriteTexture) + //this.mPlayer = new Renderable() + this.mPlayer.setColor([1, 1, 1, 0]) + this.mPlayer.getXform().setPosition(-30, -15) + //this.mPlayer.getXform().setSize(8, 8) + GameObject.call(this, this.mPlayer) + this.mMoveFric = null + this.mRotFric = null + this.mAcc = null + this.mSkill = false + this.mSkillFrozenTime = 0 + this.mSkillLastTime = 0 + this.mIsSkilling = false + this.mInverse = false + + + var r = null + // new RigidRectangle(this.getXform(), 8, 8) + + //this.toggleDrawRenderable() + // alert(character) + if(character === GameCharacter.BigMan){ + this.mPlayer.getXform().setSize(10, 10) + r = new RigidRectangle(this.getXform(), 10, 10) + r.setMass(3) + this.mAcc = 18 + this.mMoveFric = 0.993 + this.mRotFric = 0.97 + // this.mPlayer.setColor([1, 0, 0, 1]) + }else if(character === GameCharacter.FlexMan){ + this.mPlayer.getXform().setSize(5, 5) + r = new RigidRectangle(this.getXform(), 5, 5) + r.setMass(0.5) + this.mAcc = 50 + this.mMoveFric = 0.982 + this.mRotFric = 0.98 + // this.mPlayer.setColor([1, 1, 0, 1]) + }else{ + this.mPlayer.getXform().setSize(8, 8) + r = new RigidRectangle(this.getXform(), 8, 8) + r.autoSetMass() + r.setMass(1) + this.mAcc = 35 + this.mMoveFric = 0.991 + this.mRotFric = 0.991 + // r.setMass(1) + // this.mPlayer.setColor([1, 0, 1, 1]) + } + this.setRigidBody(r) + this.mGameCharacter = character +} + +gEngine.Core.inheritPrototype(Player1,WASDObj) + +Player1.prototype.getSkillFrozenTime = function(){ + return this.mSkillFrozenTime +} + +Player1.prototype.getGameCharacter = function(){ + return this.mGameCharacter +} + +Player1.prototype.getStateString = function(){ + let str = 'Player1:' + let num = 0 + if(this.mGameCharacter === GameCharacter.BigMan){ + str += 'Backoff' + num = this.mSkillFrozenTime/Skill.getBigManFrozenTime() * 100 + + }else if(this.mGameCharacter === GameCharacter.FlexMan){ + str += 'Even Faster' + num = this.mSkillFrozenTime/Skill.getFlexManFrozenTime() * 100 + }else{ + str += 'Puzzle' + num = this.mSkillFrozenTime/Skill.getNormalManFrozenTime() * 100 + } + if(num>100) num =100 + num = Math.floor(num) + str += num.toString() + str += '%' + return str +} + +Player1.prototype.update = function () { + if(this.mIsSkilling === false){ + GameObject.prototype.update.call(this) + this.mSkillFrozenTime += 1 + if(gEngine.Input.isKeyClicked(gEngine.Input.keys.E)){ + if(this.mGameCharacter === GameCharacter.BigMan){ + //alert('big man skill') + if(Skill.bigManSkill(this.mSkillFrozenTime,this.getRigidBody())){ + this.mSkillFrozenTime = 0 + this.mIsSkilling = true + this.mRotFric = 1 + this.mAcc /= 5 + } + }else if(this.mGameCharacter === GameCharacter.FlexMan){ + //alert('speed man skill') + if(Skill.flexManSkill(this.mSkillFrozenTime,this.getRigidBody())){ + this.mSkillFrozenTime = 0 + this.mIsSkilling = true + this.mAcc += 70 + + } + }else{ + //alert('balance man skill') + if(Skill.normalManSkill(this.mSkillFrozenTime,this.getRigidBody())){ + this.mSkillFrozenTime = 0 + this.mIsSkilling = true + this.mInverse = true + } + } + } + }else{ + this.mSkillLastTime += 1 + GameObject.prototype.update.call(this) + if(this.mGameCharacter === GameCharacter.BigMan){ + //alert('big man skill') + + if(Skill.relieveBigManSkill(this.mSkillLastTime,this.getRigidBody())){ + // GameObject.prototype.update.call(this) + this.mSkillLastTime = 0 + this.mIsSkilling = false + this.mRotFric = 0.97 + this.mAcc *= 5 + + } + }else if(this.mGameCharacter === GameCharacter.FlexMan){ + //alert('speed man skill') + //GameObject.prototype.update.call(this) + if(Skill.relieveFlexManSkill(this.mSkillLastTime,this.getRigidBody())){ + this.mSkillLastTime = 0 + this.mIsSkilling = false + this.mAcc -= 70 + } + }else{ + //alert('balance man skill') + // GameObject.prototype.update.call(this) + if(Skill.relieveNormalManSkill(this.mSkillLastTime,this)){ + this.mSkillLastTime = 0 + this.mIsSkilling = false + this.mInverse = false + } + } + + } +} + +Player1.prototype.getInverse = function(){ + return this.mInverse +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010089_demo.js b/pool/shard001/JavaScript/0010089_demo.js new file mode 100644 index 0000000000000000000000000000000000000000..bb30fc9c4585cf39e67c80302017419dcbb2ce2b --- /dev/null +++ b/pool/shard001/JavaScript/0010089_demo.js @@ -0,0 +1,18 @@ +var ResourceManager = require('./index.js').ResourceManager; +var mgr = new ResourceManager('','test'); + +mgr.upload('test.jpg','./test.jpg',true,function(err,result){ + if (err) { + console.log(err); + return; + } + console.log(result); +}); + +mgr.delete('abc.jpg',function(err,result){ + if (err) { + console.log(err); + return; + } + console.log(result); +}); diff --git a/pool/shard001/JavaScript/0010091_building.js b/pool/shard001/JavaScript/0010091_building.js new file mode 100644 index 0000000000000000000000000000000000000000..9a392757c9246d58c44a3d0b6bc602e453221476 --- /dev/null +++ b/pool/shard001/JavaScript/0010091_building.js @@ -0,0 +1,70 @@ +var tools = require('../tools') +var mongoose = require('mongoose') +var Mixed = mongoose.Schema.Types.Mixed + +var buildingSchema = mongoose.Schema({ + address: { + type: String, + require: true + }, + coords: Mixed, + name: String, + historicName: String, + slug: String, + researchBy: String, + researchYear: String, + dateConstructed: String, + architect: String, + client: String, + currentTenant: String, + era: String, + stories: String, + owner: String, + ownerStatus: String, + dimensions: String, + visibleExterior: String, + accessibleInterior: String, + explanation: String, + neighborhood: Mixed, + tour: Mixed, + style: Mixed, + use: Mixed, + historicUse: Mixed, + material: Mixed, + structure: Mixed, + structuralCondition: String, + exteriorCondition: String, + roofType: Mixed, + roofMaterial: Mixed, + relatedBuildings: Mixed, + environment: Mixed, + images: Mixed, + structure: String, + research: String, + narrative: String, + threat: String, + fieldEvaluations: String, + physical: String, + streetscape: String, + social: String, + history: String, + addlInfo: String, + citations: String, + links: String, + type: String, + number: String, + sortNum: String, + sortAlpha: String +}, { + timestamps: true +}) + +buildingSchema.pre('save', function(next) { + if(!this.name) + this.name = this.address + this.type = 'building' + tools.preSave(this) + next() +}) + +module.exports = mongoose.model('Building', buildingSchema) \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010099_product.js b/pool/shard001/JavaScript/0010099_product.js new file mode 100644 index 0000000000000000000000000000000000000000..e4522de941c05a459161156cd7ade422884f3ab0 --- /dev/null +++ b/pool/shard001/JavaScript/0010099_product.js @@ -0,0 +1,67 @@ +var mongoose = require('mongoose'); +var User = require("./user"); +var Schema = mongoose.Schema; var nodemailer = require('nodemailer'); +var transporter = nodemailer.createTransport({ + service: 'gmail', + auth: { + user: 'myfreakinmailer@gmail.com', + pass: require("./config").trasportedPW + } +}); + +var pro = new Schema({ + "name": { + "type": String, "required": true + }, + "description": { + "type": String, "required": true + }, + "category": { + "type": String, "required": false + }, + "weight": { + "type": Number, "required": true + }, + "price": { + "type": Number, "required": true + }, + "quantity": { + "type": Number, "required": true + }, + "img": { + "type": [String], "required": false + }, + "seller": { "type": Schema.ObjectId, "ref": "User" }, + "deleted": { "type": Boolean, "default": false }, + "insertionDate": { "type": Number, "default": Date.now() } +}); + +pro.pre("save", function (next) { + if (!this.isNew && this.isModified("quantity") && this.quantity < 5) { + var mailOptions = + { + from: 'myfreakinmailer@gmail.com', + to: "", + subject: 'Information', + text: "" + }; + User.findById(this.seller).exec(function (error, seller) { + mailOptions.to = seller.email; + mailOptions.text = "Dear, " + seller.name + ",we kindly inform you that your buissiness is going well and the remains of " + this.name + " are under 5 units." + if (require("./config").env==="dev") { + console.log("Mailing the following after the update: " + mailOptions.to); + } else { + transporter.sendMail(mailOptions, function (error, info) { + if (error) { + console.log(error); + } + }); + } + }); + } + next(); +}); + +var Product = mongoose.model('Product', pro); + +module.exports = Product; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010100_characteristic.js b/pool/shard001/JavaScript/0010100_characteristic.js new file mode 100644 index 0000000000000000000000000000000000000000..279e5be4fd4e68b209a794f548f9a1bde0928014 --- /dev/null +++ b/pool/shard001/JavaScript/0010100_characteristic.js @@ -0,0 +1,126 @@ +var debug = require('debug')('characteristic'); + +var events = require('events'); +var util = require('util'); + +var characteristics = require('./characteristics.json'); + +function Characteristic(noble, peripheralId, serviceUuid, uuid, properties) { + this._noble = noble; + this._peripheralId = peripheralId; + this._serviceUuid = serviceUuid; + + this.uuid = uuid; + this.name = null; + this.type = null; + this.properties = properties; + this.descriptors = null; + + var characteristic = characteristics[uuid]; + if (characteristic) { + this.name = characteristic.name; + this.type = characteristic.type; + } +} + +util.inherits(Characteristic, events.EventEmitter); + +Characteristic.prototype.toString = function() { + return JSON.stringify({ + uuid: this.uuid, + name: this.name, + type: this.type, + properties: this.properties + }); +}; + +Characteristic.prototype.read = function(callback) { + if (callback) { + this.once('read', function(data) { + callback(null, data); + }); + } + + this._noble.read( + this._peripheralId, + this._serviceUuid, + this.uuid + ); +}; + +Characteristic.prototype.write = function(data, withoutResponse, callback) { + if (process.title !== 'browser') { + if (!(data instanceof Buffer)) { + throw new Error('data must be a Buffer'); + } + } + + if (callback) { + this.once('write', function() { + callback(null); + }); + } + + this._noble.write( + this._peripheralId, + this._serviceUuid, + this.uuid, + data, + withoutResponse + ); +}; + +Characteristic.prototype.broadcast = function(broadcast, callback) { + if (callback) { + this.once('broadcast', function() { + callback(null); + }); + } + + this._noble.broadcast( + this._peripheralId, + this._serviceUuid, + this.uuid, + broadcast + ); +}; + +// deprecated in favour of subscribe/unsubscribe +Characteristic.prototype.notify = function(notify, callback) { + if (callback) { + this.once('notify', function() { + callback(null); + }); + } + + this._noble.notify( + this._peripheralId, + this._serviceUuid, + this.uuid, + notify + ); +}; + +Characteristic.prototype.subscribe = function(callback) { + this.notify(true, callback); +}; + +Characteristic.prototype.unsubscribe = function(callback) { + this.notify(false, callback); +}; + +Characteristic.prototype.discoverDescriptors = function(callback) { + if (callback) { + this.once('descriptorsDiscover', function(descriptors) { + callback(null, descriptors); + }); + } + + this._noble.discoverDescriptors( + this._peripheralId, + this._serviceUuid, + this.uuid + ); +}; + +module.exports = Characteristic; diff --git a/pool/shard001/JavaScript/0010102_LeafSolid.js b/pool/shard001/JavaScript/0010102_LeafSolid.js new file mode 100644 index 0000000000000000000000000000000000000000..d92e5a7a1629ddfebc8052df5391cc97e2e768ea --- /dev/null +++ b/pool/shard001/JavaScript/0010102_LeafSolid.js @@ -0,0 +1,20 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { Svg } from '../../Svg'; +import makeIcon from './makeIcon'; + +const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( + + + +)); + +Icon.propTypes = { + size: PropTypes.number, + fill: PropTypes.string, +}; + +export default Icon; diff --git a/pool/shard001/JavaScript/0010109_prefer-es6-class.js b/pool/shard001/JavaScript/0010109_prefer-es6-class.js new file mode 100644 index 0000000000000000000000000000000000000000..b35a85b96930e3b651d3450d5261670790d59846 --- /dev/null +++ b/pool/shard001/JavaScript/0010109_prefer-es6-class.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Enforce ES5 or ES6 class for React Components + * @author Dan Hamilton + */ + +'use strict'; + +const Components = require('../util/Components'); +const docsUrl = require('../util/docsUrl'); + +// ------------------------------------------------------------------------------ +// Rule Definition +// ------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: 'Enforce ES5 or ES6 class for React Components', + category: 'Stylistic Issues', + recommended: false, + url: docsUrl('prefer-es6-class') + }, + + schema: [{ + enum: ['always', 'never'] + }] + }, + + create: Components.detect((context, components, utils) => { + const configuration = context.options[0] || 'always'; + + return { + ObjectExpression(node) { + if (utils.isES5Component(node) && configuration === 'always') { + context.report({ + node, + message: 'Component should use es6 class instead of createClass' + }); + } + }, + ClassDeclaration(node) { + if (utils.isES6Component(node) && configuration === 'never') { + context.report({ + node, + message: 'Component should use createClass instead of es6 class' + }); + } + } + }; + }) +}; diff --git a/pool/shard001/JavaScript/0010111_tests.js b/pool/shard001/JavaScript/0010111_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..a96390b110e05b582365c49c4416b34314c39228 --- /dev/null +++ b/pool/shard001/JavaScript/0010111_tests.js @@ -0,0 +1,93 @@ +var expect = require('chai').expect; +var async = require('async'); +var ttl = require('level-ttl'); + +var test_db_path = __dirname + '/test'; +var rimraf = require('rimraf'); + +try{ + rimraf.sync(test_db_path); +}catch(err){ + console.log(err); +} + +var level = require('level'); + +var TokenBucket = require('../'); +var db = ttl(level(test_db_path)); + +var bucket = new TokenBucket({ + db: db, + name: 'my-bucket', + size: 100, + interval: 100, + tokensPerInterval: 10, + checkFrequency: 10 +}); + +describe('TokenBucket', function () { + + beforeEach(function (done) { + db.del(bucket._name, done); + }); + + it('should return the amount of available tokens', function (done) { + bucket.take(3, function (err, result, bucket) { + if (err) return done(err); + expect(result).to.equal(true); + expect(bucket.content).to.equal(97); + done(); + }); + }); + + it('should run out of tokens', function (done) { + var take = function (cb) { + bucket.take(40, function (err, r) { + cb(err, r); + }); + }; + + async.series([take, take, take], function (err, result) { + if (err) return done(err); + expect(result[0]).to.equal(true); + expect(result[1]).to.equal(true); + expect(result[2]).to.equal(false); + done(); + }); + }); + + it('should drip tokens into the bucket', function (done) { + var take = function (cb) { + bucket.take(40, function (err, r, b) { + // console.log('bucket: ', b); + cb(err, r); + }); + }; + + var waitAndTake = function (cb) { + setTimeout(take.bind(null, cb), 200); + }; + + async.series([take, take, take, waitAndTake], function (err, result) { + if (err) return done(err); + expect(result[0]).to.equal(true); + expect(result[1]).to.equal(true); + expect(result[2]).to.equal(false); + expect(result[3]).to.equal(true); + done(); + }); + }); + + it('should delete unused buckets', function (done) { + bucket.take(40, function (err) { + if (err) return done(err); + setTimeout(function (){ + bucket._db.get('bucket', function (err) { + expect(err.name).to.equal('NotFoundError'); + done(); + }); + }, 1000); + }); + }); + +}); diff --git a/pool/shard001/JavaScript/0010112_LogAxis.js b/pool/shard001/JavaScript/0010112_LogAxis.js new file mode 100644 index 0000000000000000000000000000000000000000..14c3ec19c89cae77fd3c58df1f0662c666732adb --- /dev/null +++ b/pool/shard001/JavaScript/0010112_LogAxis.js @@ -0,0 +1,216 @@ +/* + * Copyright (C) 2014 Object Refinery Limited and KNIME.com AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Creates a new axis with a logarithmic numerical scale. + * + * Note that all properties having names beginning with an underscore should + * be treated as private. Updating these properties directly is strongly + * discouraged. Look for accessor methods instead. + * + * @param {string} [label] the axis label. + * @returns {jsfc.LinearAxis} + * @constructor + */ +jsfc.LogAxis = function(label) { + if (!(this instanceof jsfc.LogAxis)) { + throw new Error("Use 'new' with constructor."); + } + jsfc.LinearAxis.init(label, this); + this._base = 10; + this._baseLog = Math.log(this._base); + this._smallestValue = 1e-100; + var lb = Math.log(Math.max(this._lowerBound, this._smallestValue)) / this._baseLog; + var ub = Math.log(Math.max(this._upperBound, this._smallestValue)) / this._baseLog; + this._logRange = new jsfc.Range(lb, ub); +}; + +// extend LinearAxis - see also the init() call in the constructor +jsfc.LogAxis.prototype = new jsfc.LinearAxis(); + +/** + * Calculates the log of the specified value. + * + * @param {number} value the value. + * @returns {number} The log value. + */ +jsfc.LogAxis.prototype.calculateLog = function(value) { + return Math.log(value) / this._baseLog; +}; + +/** + * Calculates the value from the specified log. + * + * @param {number} log the log value. + * @returns {number} The value. + */ +jsfc.LogAxis.prototype.calculateValue = function(log) { + return Math.pow(this._base, log); +}; + +/** + * Sets the bounds for the axis. + * + * @param {number} lower the lower bound. + * @param {number} upper the upper bound. + * @param {boolean} [notify] notify listeners? + * @returns {jsfc.LogAxis} This object for chaining method calls. + */ +jsfc.LogAxis.prototype.setBounds = function(lower, upper, notify) { + this._lowerBound = lower; + this._upperBound = upper; + this._logRange = new jsfc.Range(this.calculateLog(lower), + this.calculateLog(upper)); + this._autoRange = false; + if (notify !== false) { + this.notifyListeners(); + } + return this; +}; + +/** + * Translates a data value to a coordinate in the given range. + * + * @param {number} value the value. + * @param {number} r0 the lower bound of the coordinate (screen) range. + * @param {number} r1 the upper bound of the coordinate (screen) range. + * + * @returns {undefined} + */ +jsfc.LogAxis.prototype.valueToCoordinate = function(value, r0, r1) { + jsfc.Args.requireNumber(r0, "r0"); + jsfc.Args.requireNumber(r1, "r1"); + // let's say the axis runs from a to b... + var log = this.calculateLog(value); + var percent = this._logRange.percent(log); + return r0 + percent * (r1 - r0); +}; + +/** + * Translates a coordinate from the given range to a value on the axis scale. + * + * @param {number} coordinate the coordinate value. + * @param {number} r0 + * @param {number} r1 + * @returns {number} + */ +jsfc.LogAxis.prototype.coordinateToValue = function(coordinate, r0, r1) { + var percent = (coordinate - r0) / (r1 - r0); + var logValue = this._logRange.value(percent); + return this.calculateValue(logValue); +}; + +/** + * Calculates a good tick size for the axis assuming it is drawn along the + * specified edge of the area. This method should return NaN if there is + * no good tick size (in which case the axis should just label the end points). + * + * @param {jsfc.Context2D} ctx the graphics context (used to measure string + * dimensions). + * @param {jsfc.Rectangle} area the data area for the plot (the axis lies + * along one edge). + * @param {jsfc.RectangleEdge} edge the edge along which the axis lies. + * @returns {number} The tick size. + */ +jsfc.LogAxis.prototype._calcTickSize = function(ctx, area, edge) { + var result = Number.NaN; + var pixels = area.length(edge); + var range = this._logRange.length(); + var orientation = this._resolveTickLabelOrientation(edge); + var selector = this._tickSelector; + if (orientation === jsfc.LabelOrientation.PERPENDICULAR) { + // work with the label height + var textHeight = ctx.textDim("123").height(); + var maxTicks = pixels / (textHeight * this._tickLabelFactor); + if (maxTicks > 2) { + var tickSize = selector.select(range / 2); + var tickCount = Math.floor(range / tickSize); + while (tickCount < maxTicks) { + selector.previous(); + tickCount = Math.floor(range / selector.currentTickSize()); + } + selector.next(); + result = selector.currentTickSize(); + this._formatter = selector.currentTickFormat(); + } else { + // result remains Number.NaN + } + } else if (orientation === jsfc.LabelOrientation.PARALLEL) { + // work with label widths (approximate by measuring the min and max) + selector.select(range); + ctx.setFont(this._tickLabelFont); + var done = false; + while (!done) { + if (selector.previous()) { + // estimate the label widths, and do they overlap? + var f = selector.currentTickFormat(); + this._formatter = f; + var s0 = f.format(this._lowerBound); + var s1 = f.format(this._upperBound); + var w0 = ctx.textDim(s0).width(); + var w1 = ctx.textDim(s1).width(); + var w = Math.max(w0, w1); + if (w == 0 && s0.length > 0 && s1.length > 0) { + // text could not be measured (could be IE bug) + return Number.NaN; + } + var n = Math.floor(pixels / (w * this._tickLabelFactor)); + if (n < range / selector.currentTickSize()) { + selector.next(); + this._formatter = selector.currentTickFormat(); + done = true; + } + } else { + done = true; + } + } + result = selector.currentTickSize(); + } + return result; +}; + +/** + * Returns a list of ticks for the axis. + * + * @param {number} tickSize the tick size. + * @param {jsfc.Context2D} ctx the graphics context. + * @param {jsfc.Rectangle} area the data area. + * @param {string} edge the edge. + * + * @returns {Array} An array of jsfc.TickMark instances. + */ +jsfc.LogAxis.prototype.ticks = function(tickSize, ctx, area, edge) { + var formatter = this._tickLabelFormatOverride || this._formatter; + if (!isNaN(tickSize)) { + var result = []; + var t = Math.ceil(this._logRange._lowerBound / tickSize) * tickSize; + while (t < this._logRange._upperBound) { + var v = this.calculateValue(t); + var tm = new jsfc.TickMark(v, formatter.format(v)); + result.push(tm); + t += tickSize; + } + return result; + } else { + var tm0 = new jsfc.TickMark(this._lowerBound, + formatter.format(this._logRange._lowerBound)); + var tm1 = new jsfc.TickMark(this._upperBound, + formatter.format(this._logRange._upperBound)); + return [tm0, tm1]; + } +}; + diff --git a/pool/shard001/JavaScript/0010113_index.js b/pool/shard001/JavaScript/0010113_index.js new file mode 100644 index 0000000000000000000000000000000000000000..ed1a36e41c9bcd56baf5f9cda6125c9610447b89 --- /dev/null +++ b/pool/shard001/JavaScript/0010113_index.js @@ -0,0 +1,104 @@ +import React, { Component, PropTypes } from 'react'; +import bindTooltip from 'utils/bindTooltip'; +import { zeroPad } from 'helpers/StringHelpers'; + +/* eslint-disable no-unused-vars */ +const CHAR_TYPE_WORD = 'word'; +const CHAR_TYPE_END = 'end'; +const CHAR_TYPE_PAUSE = 'pause'; +const CHAR_TYPE_RUB = 'rub'; +const CHAR_TYPE_SAJDAH = 'sajdah'; + +class Word extends Component { + buildTooltip = (word, tooltip) => { + let title; + + if (word.charType === CHAR_TYPE_END) { + title = `Verse ${word.verseKey.split(':')[1]}`; + } else if (word.charType === CHAR_TYPE_WORD) { + title = word[tooltip].text; + } else { + title = ''; + } + return title; + } + + handleWordPlay = () => { + const { word } = this.props; + + if (word.audio) { + const audio = new Audio(word.audio.url); // eslint-disable-line + + audio.play(); + } + } + + handleSegmentPlay = () => { + const { word, currentVerse, audioActions, audioPosition, isPlaying, isSearched } = this.props; + + if (isSearched || !word.audio) { + return; + } + + if ((currentVerse === word.verseKey) && isPlaying) { + audioActions.setCurrentWord(word.code); + } else { + audioActions.pause(); + audioActions.setAyah(word.verseKey); + audioActions.playCurrentWord({ word, position: audioPosition }); + } + } + + render() { + const { tooltip, word, currentVerse, isPlaying, audioPosition, useTextFont } = this.props; + + let text; + let spacer; + const highlight = currentVerse === word.verseKey && isPlaying ? 'highlight' : ''; + const className = `${useTextFont ? 'text-' : ''}${word.className} ${word.charType} ${highlight} ${word.highlight ? word.highlight : ''}`; + const id = `word-${word.verseKey.replace(/:/, '-')}-${audioPosition}`; + + if (useTextFont) { + if (word.charType === CHAR_TYPE_END) { + text = zeroPad(word.verseKey.split(':')[1], 3, 0); + } else { + text = word.textMadani; + } + } else { + text = word.code; + } + + if (word.charType === CHAR_TYPE_WORD) { + spacer = ' '; + } + + return ( + + + + + ); + } +} + +Word.propTypes = { + word: PropTypes.object.isRequired, // eslint-disable-line + tooltip: PropTypes.string, + audioActions: PropTypes.object.isRequired, // eslint-disable-line + audioPosition: PropTypes.number, + currentVerse: PropTypes.string, + isPlaying: PropTypes.bool, + isSearched: PropTypes.bool, + useTextFont: PropTypes.bool // tmp change to compare text and code based rendering +}; + +export default Word; diff --git a/pool/shard001/JavaScript/0010118_lrc-crawler.js b/pool/shard001/JavaScript/0010118_lrc-crawler.js new file mode 100644 index 0000000000000000000000000000000000000000..96854c6fd05cfc4966f81ac42018919e518b7e7e --- /dev/null +++ b/pool/shard001/JavaScript/0010118_lrc-crawler.js @@ -0,0 +1,67 @@ +var debug = require('debug')('crawler'); +var request = require('request'); +var cheerio = require('cheerio'); +var _ = require('lodash'); + +var crawler = {}; + +crawler.getList = function(name, callback) { + + request('http://mojim.com/' + name + '.html?t3', function(err, res, body) { + + if (err) throw callback(err); + + var $ = cheerio.load(body); + + var songs = []; + + $('table.iB').find('tr').each(function(i, el) { + + var $el = $(el); + + if ($el.is(':not([bgcolor])') || $el.is('[bgcolor="#E9DFD1"]')) return; + + var song = {}; + + var tds = $el.find('td'); + + song.url = tds.eq(3).find('a').attr('href'); + song.singer = tds.eq(1).text(); + song.album = tds.eq(2).text(); + song.name = tds.eq(3).text(); + song.issueDate = tds.eq(4).text(); + + songs.push(song); + + }); + + callback(null, songs); + }); +}; + +crawler.getLrc = function(url, callback) { + + request('http://mojim.com' + url, function(err, res, body) { + + if (err) throw callback(err); + + var $ = cheerio.load(body); + + var lines = $('#fsZ').find('dl').find('dd').children(); + + var lrc = lines.filter(function(i, el) { + + return el.type === 'text' && /^\[/.test(el.data); + + }).map(function(i, el) { + + return $(el).text; + + }).get(); + + callback(null, lrc); + }); +}; + + +module.exports = crawler; diff --git a/pool/shard001/JavaScript/0010123_generate.js b/pool/shard001/JavaScript/0010123_generate.js new file mode 100644 index 0000000000000000000000000000000000000000..75d1e63d2492076ce9d2fe194715057555814fb7 --- /dev/null +++ b/pool/shard001/JavaScript/0010123_generate.js @@ -0,0 +1,31 @@ +/* + */ +var GenerateRoute = Ember.Route.extend( { + controllerName: 'identity', + renderTemplate: function () { + 'use strict'; + this.render( { + controller: 'identity' + } ); + }, + model: function () { + 'use strict'; + return this.store.createRecord( 'identity' ); + }, + setupController: function ( controller, model ) { + 'use strict'; + controller.set( 'model', model ); + }, + actions: { + willTransition: function ( transition ) { // jshint ignore:line + 'use strict'; + var identity = this.get( 'currentModel' ); + if ( identity.get( 'isInvalidKey' ) ) { + identity.deleteRecord(); + identity.save(); + } + } + } +} ); +export +default GenerateRoute; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010125_asset_resolver.js b/pool/shard001/JavaScript/0010125_asset_resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..ec8145eb3428758e2ae1ba87f748cf6a8b6b0f23 --- /dev/null +++ b/pool/shard001/JavaScript/0010125_asset_resolver.js @@ -0,0 +1,121 @@ +/** + * Copyright 2016-2017 aixigo AG + * Released under the MIT license. + * http://laxarjs.org/license + */ +'use strict'; + +import { expect } from 'chai'; +import data from './data/assets.json'; +import assetResolver from '../src/asset_resolver'; + +describe( 'artifactResolver', () => { + + /////////////////////////////////////////////////////////////////////////////////////////////////////////// + + describe( '.create( options )', () => { + + const resolver = assetResolver.create( {} ); + + it( 'returns an assetResolver', () => { + expect( resolver ).to.be.an( 'object' ); + } ); + + describe( 'the returned resolver', () => { + it( 'has a resolveAssets method', () => { + expect( resolver ).to.respondTo( 'resolveAssets' ); + } ); + it( 'has a resolveThemedAssets method', () => { + expect( resolver ).to.respondTo( 'resolveThemedAssets' ); + } ); + } ); + } ); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////// + + describe( '.resolveAssets( artifact, assetPaths )', () => { + + const resolver = assetResolver.create( { + resolve + } ); + + function resolve( ref ) { + resolve.called = true; + expect( data.resolve ).to.include.key( ref ); + return data.resolve[ ref ] ? Promise.resolve( data.resolve[ ref ] ) : Promise.reject(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + + it( 'returns a thenable', () => { + expect( resolver.resolveAssets( data.artifacts[ 0 ], data.assets ) ).to.respondTo( 'then' ); + } ); + + it( 'uses the resolve function supplied during creation to resolve paths', () => { + resolve.called = false; + return resolver.resolveAssets( data.artifacts[ 0 ], data.assets ) + .then( () => { + expect( resolve.called ).to.eql( true ); + } ); + } ); + + it( 'creates a map of resolved assets', () => { + return resolver.resolveAssets( data.artifacts[ 0 ], data.assets ) + .then( assets => { + expect( assets ).to.be.an( 'object' ); + expect( assets ).to.eql( data.results[ 0 ] ); + } ); + } ); + + } ); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////// + + describe( '.resolveThemedAssets( artifact, themes, assetPaths )', () => { + + const resolver = assetResolver.create( { + resolve + } ); + + function resolve( ref ) { + resolve.called = true; + expect( data.resolve ).to.include.key( ref ); + return data.resolve[ ref ] ? Promise.resolve( data.resolve[ ref ] ) : Promise.reject(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////// + + it( 'returns a thenable', () => { + expect( resolver.resolveThemedAssets( data.artifacts[ 0 ], data.themes, data.assets ) ) + .to.respondTo( 'then' ); + } ); + + it( 'uses the resolve function supplied during creation to resolve paths', () => { + resolve.called = false; + return resolver.resolveThemedAssets( data.artifacts[ 0 ], data.themes, data.assets ) + .then( () => { + expect( resolve.called ).to.eql( true ); + } ); + } ); + + it( 'creates a map of resolved theme assets', () => { + return resolver.resolveThemedAssets( data.artifacts[ 0 ], [ data.themes[ 0 ] ], data.assets ) + .then( assets => { + expect( assets ).to.be.an( 'object' ); + expect( assets ).to.eql( data.results[ 1 ] ); + } ); + } ); + + it( 'gives precedence to the first theme', () => { + return resolver.resolveThemedAssets( data.artifacts[ 0 ], data.themes, data.assets ) + .then( assets => { + expect( assets ).to.be.an( 'object' ); + expect( assets ).to.eql( data.results[ 2 ] ); + } ); + } ); + + } ); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////// + +} ); diff --git a/pool/shard001/JavaScript/0010126_xsjsdfmxBS.js b/pool/shard001/JavaScript/0010126_xsjsdfmxBS.js new file mode 100644 index 0000000000000000000000000000000000000000..b4491f5bb5a155dee53dd9613883f0108fcac816 --- /dev/null +++ b/pool/shard001/JavaScript/0010126_xsjsdfmxBS.js @@ -0,0 +1,149 @@ +define(function(require, exports, module) { + var utils = require('utils'); + var FIRSTONE="一等奖";//第一级奖项 + var FIRSTTWO="金奖"; + var FIRSTTHREE="特等奖"; + var SECONDONE="二等奖";//第二级奖项 + var SECONDTWO="银奖"; + var THIRDONE="三等奖";//第三级奖项 + var THIRDTWO="铜奖"; + var THIRDTHREE="荣誉奖"; + var THIRDFOUR="Honorable"; + var LEVEL_GUOJIA = "国家"; //竞赛级别 + var TYPE_A = "A"; //竞赛类别 + var ISLEADER = "Y";//是否领队 + var bs = { + api: { + pageModel: 'modules/xsjsdfmx.do', + resultProfile: './mock/resultProfile.json' + }, + getDemoMainModel: function() { + var def = $.Deferred(); + utils.doAjax(bs.api.resultProfile, null, 'get').done(function(data) { + data.length = data.list.length; + def.resolve(data); + }).fail(function(res) { + def.reject(res); + }); + return def.promise(); + }, + save: function(formData){ + //TODO 将formData提交到后台动作上 + return BH_UTILS.doAjax('../modules/xsjsdfmx/NBU_JS_COMPETITION_WIN_INFO_SAVE.do', formData); + }, + del: function(params){ + //TODO 添加删除动作 + return BH_UTILS.doAjax('../modules/xsjsdfmx/NBU_JS_COMPETITION_WIN_INFO_DELETE.do', { + NBU_JS_COMPETITION_WIN_INFO_DELETE:JSON.stringify(params) + }); + }, + exportData: function(obj){ + var params = { + root: contextPath, + app : "nbujsdf", + module : "modules", + page : 'xsjsdfmx', + action : 'jsdfmx' + }; + //选择字段导出 + $('#emapdatatable').emapdatatable('selectColumnsExport', params); + }, + //获奖得分计算,单个数据集合和团队人数为参数 + popupGetScore : function(oneVO,number){ + if(oneVO.JSJX == FIRSTONE || oneVO.JSJX ==FIRSTTWO || oneVO.JSJX ==FIRSTTHREE){ + if(oneVO.JSJB == LEVEL_GUOJIA){ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=3; + }else{ + oneVO.SCORE=1.2; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=2/(number-1); + }else{ + oneVO.SCORE=0.8/(number-1); + } + } + }else{ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.8; + }else{ + oneVO.SCORE=0.6; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.2/(number-1); + }else{ + oneVO.SCORE=0.4/(number-1); + } + } + } + }else if(oneVO.JSJX ==SECONDONE || oneVO.JSJX ==SECONDTWO){ + if(oneVO.JSJB == LEVEL_GUOJIA){ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.8; + }else{ + oneVO.SCORE=0.72; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.2/(number-1); + }else{ + oneVO.SCORE=0.48/(number-1); + } + } + }else{ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.08; + }else{ + oneVO.SCORE=0.36; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=0.72/(number-1); + }else{ + oneVO.SCORE=0.24/(number-1); + } + } + } + }else if(oneVO.JSJX ==THIRDONE || oneVO.JSJX ==THIRDTWO || oneVO.JSJX ==THIRDTHREE || (oneVO.JSJX.indexOf(THIRDFOUR)!=-1)){ + if(oneVO.JSJB == LEVEL_GUOJIA){ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=1.2; + }else{ + oneVO.SCORE=0.48; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=0.8/(number-1); + }else{ + oneVO.SCORE=0.32/(number-1); + } + } + }else{ + if(oneVO.ISLEADER == ISLEADER){ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=0.72; + }else{ + oneVO.SCORE=0.24; + } + }else{ + if(oneVO.JSLB == TYPE_A){ + oneVO.SCORE=0.48/(number-1); + }else{ + oneVO.SCORE=0.16/(number-1); + } + } + } + } + return oneVO; + } + }; + + return bs; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010129_flagged_post.js b/pool/shard001/JavaScript/0010129_flagged_post.js new file mode 100644 index 0000000000000000000000000000000000000000..981dd287b168ef74bb8e5d21d99a72ee17daef76 --- /dev/null +++ b/pool/shard001/JavaScript/0010129_flagged_post.js @@ -0,0 +1,84 @@ +/** + Our data model for interacting with flagged posts. + + @class FlaggedPost + @extends Discourse.Post + @namespace Discourse + @module Discourse +**/ +Discourse.FlaggedPost = Discourse.Post.extend({ + + flaggers: function() { + var r, + _this = this; + r = []; + this.post_actions.each(function(a) { + return r.push(_this.userLookup[a.user_id]); + }); + return r; + }.property(), + + messages: function() { + var r, + _this = this; + r = []; + this.post_actions.each(function(a) { + if (a.message) { + return r.push({ + user: _this.userLookup[a.user_id], + message: a.message, + permalink: a.permalink + }); + } + }); + return r; + }.property(), + + lastFlagged: function() { + return this.post_actions[0].created_at; + }.property(), + + user: function() { + return this.userLookup[this.user_id]; + }.property(), + + topicHidden: function() { + return this.get('topic_visible') === 'f'; + }.property('topic_hidden'), + + deletePost: function() { + if (this.get('post_number') === "1") { + return Discourse.ajax("/t/" + this.topic_id, { type: 'DELETE', cache: false }); + } else { + return Discourse.ajax("/posts/" + this.id, { type: 'DELETE', cache: false }); + } + }, + + clearFlags: function() { + return Discourse.ajax("/admin/flags/clear/" + this.id, { type: 'POST', cache: false }); + }, + + hiddenClass: function() { + if (this.get('hidden') === "t") return "hidden-post"; + }.property() +}); + +Discourse.FlaggedPost.reopenClass({ + findAll: function(filter) { + var result = Em.A(); + Discourse.ajax("/admin/flags/" + filter + ".json").then(function(data) { + var userLookup = {}; + data.users.each(function(u) { + userLookup[u.id] = Discourse.User.create(u); + }); + data.posts.each(function(p) { + var f = Discourse.FlaggedPost.create(p); + f.userLookup = userLookup; + result.pushObject(f); + }); + }); + return result; + } +}); + + diff --git a/pool/shard001/JavaScript/0010133_json_transform.js b/pool/shard001/JavaScript/0010133_json_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..d757e2bdc765c28d98ea5f0309cfb88fc118afea --- /dev/null +++ b/pool/shard001/JavaScript/0010133_json_transform.js @@ -0,0 +1,27 @@ +var fs = require('fs'); + +var trains = require('./station_data.json'); + +var stationData = []; + +for(var i = 0; i < trains.length; i++) { + var code = trains[i].code; + var tks = trains[i].name.split(' ').concat(code); + stationData.push( + { + tokens: tks, + value: trains[i].name, + code: code + } + ); +} + +stations = JSON.stringify(stationData); + +fs.writeFile("public/json/rail_stations.json", stations, function(err) { + if(err) { + console.log(err); + } else { + console.log("The file was saved!"); + } +}); diff --git a/pool/shard001/JavaScript/0010139_assertion.js b/pool/shard001/JavaScript/0010139_assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..8cb07f815b3dc33cbc8a46a78f72a233051c7e2e --- /dev/null +++ b/pool/shard001/JavaScript/0010139_assertion.js @@ -0,0 +1,213 @@ +var util = require('util'); +var events = require('events'); +var Logger = require('./../util/logger.js'); + +module.exports = new (function() { + var doneSymbol = String.fromCharCode(10004); + var failSymbol = String.fromCharCode(10006); + var initialized = false; + var client; + + /** + * Abstract assertion class that will subclass all defined assertions + * + * All assertions must implement the following api: + * + * - @type {boolean|function} + * expected + * - @type {string} + * message + * - @type {function} + * pass + * - @type {function} + * value + * - @type {function} + * command + * - @type {function} - Optional + * failure + * + * @param {boolean} abortOnFailure + * @param {Nightwatch} client + * @constructor + */ + function BaseAssertion(abortOnFailure, client) { + events.EventEmitter.call(this); + this.abortOnFailure = abortOnFailure; + this.client = client; + this.api = client.api; + } + + util.inherits(BaseAssertion, events.EventEmitter); + + BaseAssertion.prototype.complete = function() { + var self = this, args = Array.prototype.slice.call(arguments, 0); + args.unshift('complete'); + + setTimeout(function() { + self.emit.apply(self, args); + }, 0); + }; + + /** + * Performs the command method + * @returns {*} + * @private + */ + BaseAssertion.prototype._executeCommand = function() { + var self = this; + var methods = [ + 'expected', + 'message', + ['pass'], + ['value'], + ['command'] + ]; + methods.forEach(function(method) { + if (Array.isArray(method)) { + var name = method[0]; + if (typeof self[name] !== 'function') { + throw new Error('Assertion must implement method ' + name); + } + } else if (typeof self[method] == 'undefined') { + throw new Error('Assertion must implement method/property ' + method); + } + }); + + return this.command(function(result) { + var passed, value; + + if (typeof self.failure == 'function' && self.failure(result)) { + passed = false; + value = null; + } else { + value = self.value(result); + passed = self.pass(value); + } + + var expected = typeof self.expected == 'function' && self.expected() || self.expected; + self.client.assertion(passed, value, expected, self.message, self.abortOnFailure); + }); + }; + + /** + * Assertion factory that creates the assertion instances with the supplied assertion definition + * and options + * + * @param {function} assertionFn + * @param {boolean} abortOnFailure + * @param {Nightwatch} client + * @constructor + */ + function AssertionInstance(assertionFn, abortOnFailure, client) { + this.abortOnFailure = abortOnFailure; + this.client = client; + this.assertionFn = assertionFn; + } + + /** + * This will call the supplied constructor of the assertion, after calling the Base constructor + * first with other arguments and then inherits the rest of the methods from BaseAssertion + * + * @param {function} constructor + * @param {Array} args + * @returns {*} + * @private + */ + AssertionInstance.prototype._constructFromSuper = function(constructor, args) { + var self = this; + function F() { + BaseAssertion.apply(this, [self.abortOnFailure, self.client]); + return constructor.apply(this, args); + } + + util.inherits(constructor, BaseAssertion); + F.prototype = constructor.prototype; + return new F(); + }; + + AssertionInstance.prototype._commandFn = function() { + var args = Array.prototype.slice.call(arguments, 0); + var instance = this._constructFromSuper(this.assertionFn, args); + + return instance._executeCommand(); + }; + + /** + * @public + * @param {function} assertionFn + * @param {boolean} abortOnFailure + * @param {Nightwatch} client + * @returns {AssertionInstance} + */ + this.factory = function(assertionFn, abortOnFailure, client) { + return new AssertionInstance(assertionFn, abortOnFailure, client); + }; + + + /** + * Performs an assertion + * + * @param {Boolean} passed + * @param {Object} receivedValue + * @param {Object} expectedValue + * @param {String} message + * @param {Boolean} abortOnFailure + */ + this.assert = function assert(passed, receivedValue, expectedValue, message, abortOnFailure) { + if (!initialized) { + throw new Error('init must be called first.'); + } + + var failure = ''; + var stacktrace = ''; + + if (passed) { + if (client.options.output) { + console.log(Logger.colors.green(doneSymbol) + ' ' + message); + } + client.results.passed++; + } else { + failure = 'Expected "' + expectedValue + '" but got: "' + receivedValue + '"'; + try { + var err = new Error(); + err.name = 'Assertion failed in: ' + message; + err.message = failure; + Error.captureStackTrace(err, arguments.callee); + throw err; + } catch (ex) { + var logged = Logger.colors.red(failSymbol) + ' ' + message; + if (typeof expectedValue != 'undefined' && typeof receivedValue != 'undefined') { + logged += ' ' + Logger.colors.white(' - expected ' + Logger.colors.green('"' + + expectedValue + '"')) + ' but got: ' + Logger.colors.red(receivedValue); + } + + if (client.options.output) { + console.log(logged); + } + stacktrace = ex.stack; + } + client.results.failed++; + } + + client.results.tests.push({ + message : message, + stacktrace : stacktrace, + failure : failure !== '' ? failure : false + }); + + if (!passed && abortOnFailure) { + client.terminate(); + } + }; + + /** + * Initializer + * + * @param {Object} c Nightwatch client instance + */ + this.init = function(c) { + client = c; + initialized = true; + }; +})(); + diff --git a/pool/shard001/JavaScript/0010140_index.js b/pool/shard001/JavaScript/0010140_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2fbe9d6dcd3dedad0e7926318842cb6406fcaf95 --- /dev/null +++ b/pool/shard001/JavaScript/0010140_index.js @@ -0,0 +1,66 @@ +import koa from "koa"; +import {inject} from "aurelia-dependency-injection"; +import {ErrorPipelineComponent} from "./error"; +import {ParsePipelineComponent} from "./parse"; +import {PreparePipelineComponent} from "./prepare"; +import {ExecutePipelineComponent} from "./execute"; +import Cache from "lru-cache"; + +/** +* The main application pipeline object +*/ +@inject( + "options", + ErrorPipelineComponent, + ParsePipelineComponent, + PreparePipelineComponent, + ExecutePipelineComponent +) +export class Pipeline { + + /** + * The configuration options + */ + options + + /** + * The pipeline components + */ + components + + /** + * The metadata for this pipeline's model + */ + modelMetadata + + /** + * Construction + */ + constructor( options, ...components ) { + this.options = options; + this.components = components; + this.modelMetadata = options.model; + } + + /** + * Create the koa app for this set of options + */ + createApp() { + + // create the koa app + const app = koa(); + + // add all the pipeline components to the app + const pipeline = this; + for (let component of this.components) { + app.use( function *(next) { + yield * component.process( next, this, pipeline ); + }); + } + + // done! + return app; + + } + +} diff --git a/pool/shard001/JavaScript/0010142_remotenamefetcher.js b/pool/shard001/JavaScript/0010142_remotenamefetcher.js new file mode 100644 index 0000000000000000000000000000000000000000..3524e2837f26ae11e09006237d382c900db80cfe --- /dev/null +++ b/pool/shard001/JavaScript/0010142_remotenamefetcher.js @@ -0,0 +1,281 @@ +// Copyright 2012 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Object which fetches Unicode codepoint names from a remote data + * source. This data source should accept two parameters: + *
    + *
  1. c - the list of codepoints in hexadecimal format + *
  2. p - the name property + *
+ * and return a JSON object representation of the result. + * For example, calling this data source with the following URL: + * http://datasource?c=50,ff,102bd&p=name + * Should return a JSON object which looks like this: + *
+ * {"50":{"name":"LATIN CAPITAL LETTER P"},
+ * "ff":{"name":"LATIN SMALL LETTER Y WITH DIAERESIS"},
+ * "102bd":{"name":"CARIAN LETTER K2"}}
+ * 
. + */ + +goog.provide('goog.i18n.uChar.RemoteNameFetcher'); + +goog.require('goog.Disposable'); +goog.require('goog.Uri'); +goog.require('goog.debug.Logger'); +goog.require('goog.i18n.uChar'); +goog.require('goog.i18n.uChar.NameFetcher'); +goog.require('goog.net.XhrIo'); +goog.require('goog.structs.Map'); + + + +/** + * Builds the RemoteNameFetcher object. This object retrieves codepoint names + * from a remote data source. + * + * @param {string} dataSourceUri URI to the data source. + * @constructor + * @implements {goog.i18n.uChar.NameFetcher} + * @extends {goog.Disposable} + */ +goog.i18n.uChar.RemoteNameFetcher = function(dataSourceUri) { + goog.base(this); + + /** + * XHRIo object for prefetch() asynchronous calls. + * + * @type {!goog.net.XhrIo} + * @private + */ + this.prefetchXhrIo_ = new goog.net.XhrIo(); + + /** + * XHRIo object for getName() asynchronous calls. + * + * @type {!goog.net.XhrIo} + * @private + */ + this.getNameXhrIo_ = new goog.net.XhrIo(); + + /** + * URI to the data. + * + * @type {string} + * @private + */ + this.dataSourceUri_ = dataSourceUri; + + /** + * A cache of all the collected names from the server. + * + * @type {!goog.structs.Map} + * @private + */ + this.charNames_ = new goog.structs.Map(); +}; +goog.inherits(goog.i18n.uChar.RemoteNameFetcher, goog.Disposable); + + +/** + * Key to the listener on XHR for prefetch(). Used to clear previous listeners. + * + * @type {?number} + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.prefetchLastListenerKey_ = 0; + + +/** + * Key to the listener on XHR for getName(). Used to clear previous listeners. + * + * @type {?number} + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.getNameLastListenerKey_ = 0; + + +/** + * A reference to the RemoteNameFetcher logger. + * + * @type {!goog.debug.Logger} + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.logger_ = + goog.debug.Logger.getLogger('goog.i18n.uChar.RemoteNameFetcher'); + + + + +/** @override */ +goog.i18n.uChar.RemoteNameFetcher.prototype.disposeInternal = function() { + goog.base(this, 'disposeInternal'); + this.prefetchXhrIo_.dispose(); + this.getNameXhrIo_.dispose(); +}; + + +/** @override */ +goog.i18n.uChar.RemoteNameFetcher.prototype.prefetch = function(characters) { + // Abort the current request if there is one + if (this.prefetchXhrIo_.isActive()) { + goog.i18n.uChar.RemoteNameFetcher.logger_. + info('Aborted previous prefetch() call for new incoming request'); + this.prefetchXhrIo_.abort(); + } + if (this.prefetchLastListenerKey_ != 0) { + goog.events.unlistenByKey(this.prefetchLastListenerKey_); + } + + // Set up new listener + var preFetchCallback = goog.bind(this.prefetchCallback_, this); + this.prefetchLastListenerKey_ = goog.events.listenOnce(this.prefetchXhrIo_, + goog.net.EventType.COMPLETE, preFetchCallback); + + this.fetch_(goog.i18n.uChar.RemoteNameFetcher.RequestType_.BASE_88, + characters, this.prefetchXhrIo_); +}; + + +/** + * Callback on completion of the prefetch operation. + * + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.prefetchCallback_ = function() { + this.processResponse_(this.prefetchXhrIo_); +}; + + +/** @override */ +goog.i18n.uChar.RemoteNameFetcher.prototype.getName = function(character, + callback) { + var codepoint = goog.i18n.uChar.toCharCode(character).toString(16); + + if (this.charNames_.containsKey(codepoint)) { + var name = /** @type {string} */ (this.charNames_.get(codepoint)); + callback(name); + return; + } + + // Abort the current request if there is one + if (this.getNameXhrIo_.isActive()) { + goog.i18n.uChar.RemoteNameFetcher.logger_. + info('Aborted previous getName() call for new incoming request'); + this.getNameXhrIo_.abort(); + } + if (this.getNameLastListenerKey_ != 0) { + goog.events.unlistenByKey(this.getNameLastListenerKey_); + } + + // Set up new listener + var getNameCallback = goog.bind(this.getNameCallback_, this, codepoint, + callback); + this.getNameLastListenerKey_ = goog.events.listenOnce(this.getNameXhrIo_, + goog.net.EventType.COMPLETE, getNameCallback); + + this.fetch_(goog.i18n.uChar.RemoteNameFetcher.RequestType_.CODEPOINT, + codepoint, this.getNameXhrIo_); +}; + + +/** + * Callback on completion of the getName operation. + * + * @param {string} codepoint The codepoint in hexadecimal format. + * @param {function(?string)} callback The callback function called when the + * name retrieval is complete, contains a single string parameter with the + * codepoint name, this parameter will be null if the character name is not + * defined. + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.getNameCallback_ = function( + codepoint, callback) { + this.processResponse_(this.getNameXhrIo_); + var name = /** @type {?string} */ (this.charNames_.get(codepoint, null)); + callback(name); +}; + + +/** + * Process the response received from the server and store results in the cache. + * + * @param {!goog.net.XhrIo} xhrIo The XhrIo object used to make the request. + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.processResponse_ = function(xhrIo) { + if (!xhrIo.isSuccess()) { + goog.i18n.uChar.RemoteNameFetcher.logger_.severe( + 'Problem with data source: ' + xhrIo.getLastError()); + return; + } + var result = xhrIo.getResponseJson(); + for (var codepoint in result) { + if (result[codepoint].hasOwnProperty('name')) { + this.charNames_.set(codepoint, result[codepoint]['name']); + } + } +}; + + +/** + * Enum for the different request types. + * + * @enum {string} + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.RequestType_ = { + + /** + * Request type that uses a base 88 string containing a set of codepoints to + * be fetched from the server (see goog.i18n.charpickerdata for more + * information on b88). + */ + BASE_88: 'b88', + + /** + * Request type that uses a a string of comma separated codepoint values. + */ + CODEPOINT: 'c' +}; + + +/** + * Fetches a set of codepoint names from the data source. + * + * @param {!goog.i18n.uChar.RemoteNameFetcher.RequestType_} requestType The + * request type of the operation. This parameter specifies how the server is + * called to fetch a particular set of codepoints. + * @param {string} requestInput The input to the request, this is the value that + * is passed onto the server to complete the request. + * @param {!goog.net.XhrIo} xhrIo The XHRIo object to execute the server call. + * @private + */ +goog.i18n.uChar.RemoteNameFetcher.prototype.fetch_ = function(requestType, + requestInput, xhrIo) { + var url = new goog.Uri(this.dataSourceUri_); + url.setParameterValue(requestType, requestInput); + url.setParameterValue('p', 'name'); + goog.i18n.uChar.RemoteNameFetcher.logger_.info('Request: ' + + url.toString()); + xhrIo.send(url); +}; + + +/** @override */ +goog.i18n.uChar.RemoteNameFetcher.prototype.isNameAvailable = function( + character) { + return true; +}; diff --git a/pool/shard001/JavaScript/0010145_request.js b/pool/shard001/JavaScript/0010145_request.js new file mode 100644 index 0000000000000000000000000000000000000000..47b29dda8d78ea51b0bb5f7c2412eb2a5422131a --- /dev/null +++ b/pool/shard001/JavaScript/0010145_request.js @@ -0,0 +1,102 @@ +/**! + * + * Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. + */ + +import {detect} from '../lib/detect'; +import ProgressEvent from '../progress-event'; +import request from 'request'; + +/** + * @param {Object} options + * @private + * @returns {Promise} + */ +function prepareOptions(options) { + if (options.responseType === `buffer` || options.responseType === `blob`) { + options.encoding = null; + } + + if (options.withCredentials) { + options.jar = true; + } + + if (Buffer.isBuffer(options.body)) { + return detect(options.body) + .then((type) => { + options.headers[`content-type`] = type; + return options; + }); + } + + return Promise.resolve(options); +} + +/** + * @param {Object} options + * @private + * @returns {Promise} + */ +function doRequest(options) { + return new Promise((resolve) => { + const logger = options.logger; + + const r = request(options, (error, response) => { + if (error) { + logger.warn(error); + } + + if (response) { + response.options = options; + + // I'm not sure why this line is necessary. request seems to be creating + // buffers that aren't Buffers. + if (options.responseType === `buffer` && response.body.type === `Buffer` && !Buffer.isBuffer(response.body)) { + response.body = new Buffer(response.body); + } + + if (Buffer.isBuffer(response.body) && !response.body.type) { + resolve(detect(response.body) + .then((type) => { + response.body.type = type; + return response; + })); + + return; + } + + resolve(response); + } + else { + // Make a network error behave like a browser network error. + resolve({ + statusCode: 0, + options, + headers: options.headers, + method: options.method, + url: options.url, + body: error + }); + } + }); + + r.on(`response`, (response) => { + const total = parseInt(response.headers[`content-length`], 10); + let loaded = 0; + response.on(`data`, (data) => { + loaded += data.length; + options.download.emit(`progress`, new ProgressEvent(loaded, total)); + }); + }); + }); +} + +/** + * @name request + * @param {Object} options + * @returns {Promise} + */ +export default function _request(options) { + return prepareOptions(options) + .then(doRequest); +} diff --git a/pool/shard001/JavaScript/0010146_kexec.testvp-empty.js b/pool/shard001/JavaScript/0010146_kexec.testvp-empty.js new file mode 100644 index 0000000000000000000000000000000000000000..ceaa0e2603cf5fa536530bd034e013ea7813f508 --- /dev/null +++ b/pool/shard001/JavaScript/0010146_kexec.testvp-empty.js @@ -0,0 +1,18 @@ +var exec = require('child_process').exec + , path = require('path') + , assert = require('assert'); + + +suite('kexec') + +test('+ kexec() - kexec echovp - two arguments, empty list', function(done) { + var echoFile = path.join(__dirname, './files/echovp-empty.sh'); + + exec(echoFile, function(error, stdout, stderr) { + assert(stdout.trim() === ''); + assert(stderr.trim() === ''); + assert( error === null ); + done(); + }); +}) + diff --git a/pool/shard001/JavaScript/0010149_onHoverChange.js b/pool/shard001/JavaScript/0010149_onHoverChange.js new file mode 100644 index 0000000000000000000000000000000000000000..923607f31cea6b710e3c1bac5b3a7753e5af8cb9 --- /dev/null +++ b/pool/shard001/JavaScript/0010149_onHoverChange.js @@ -0,0 +1,30 @@ +(function () { + $.fn.onHoverChange = function (options) { + var defaults = { + color: "blue", + leaveColor: "" + }; + + this.each(function () { + options = $.extend(defaults, options); + + $(this).hover( + function () { + $(this).css('color', options.color); + }, + function () { + $(this).css('color', options.leaveColor); + } + ); + + }); + + }; + + $('#hover').onHoverChange(); + + $('#trt').onHoverChange({ + color: "yellow", + leaveColor: 'red' + }); +})($); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010152_index.js b/pool/shard001/JavaScript/0010152_index.js new file mode 100644 index 0000000000000000000000000000000000000000..41ed2da6dce99e9efb86b4351d6e87f05e361502 --- /dev/null +++ b/pool/shard001/JavaScript/0010152_index.js @@ -0,0 +1,102 @@ +'use strict'; + +const coap = require('coap'); +const net = require('net'); +const Promise = require('bluebird'); +const tmp = Promise.promisifyAll(require('tmp')); +const _ = require('./utils'); + +const DEFAULTS = { + labels: 'coap', + host: 'localhost', + port: 5683, + sock: null +}; + +_.each(['Connection', 'Date'], coap.ignoreOption); + +function createListener(server, opts) { + if (_.isUndefined(server)) { + throw new Error('Hapi.Server instance required'); + } + + opts = opts || {}; + + const label = opts.labels; + const coapServer = coap.createServer({ + port: opts.port, + + // is this OK? + address: opts.host + }); + const coapProxyServer = new net.Server(); + + coapServer.on('close', function onClose() { + server.log(label, 'CoAP server closed'); + coapProxyServer.close(); + }) + .on('request', (req, res) => { + server.log(label, `CoAP server received request for ${req.url}`); + + server.select(label).inject({ + method: req.method, + headers: req.headers, + url: req.url, + payload: req.payload + }, function injectDone(response) { + res.code = response.statusCode; + _.each(response.headers, function setOptions(value, key) { + res.setOption(key, value); + }); + res.end(response.rawPayload); + }); + }); + + coapProxyServer.on('close', () => { + server.log(label, 'CoAP proxy server closed'); + coapServer.close(); + }); + + coapProxyServer.on('listening', () => { + coapServer.listen(() => { + server.log(`CoAP server listening at ${opts.host}:${opts.port}`); + }); + }); + + return coapProxyServer; +} + +function coapConnectionOpts(server, options, done) { + if (!arguments.length) { + throw new Error('Hapi.Server parameter required'); + } + + const opts = _.defaults({}, + options || {}, + server.settings.app.coap || {}, + DEFAULTS); + + return Promise.try(() => { + if (opts.sock) { + return opts.sock; + } + return tmp.tmpNameAsync(); + }) + .then(port => { + const listener = coapConnectionOpts.createListener(server, opts); + + return { + uri: `coap://${opts.host}:${opts.port}`, + tls: false, + port: port, + listener: listener, + host: opts.host, + labels: opts.labels + }; + }) + .asCallback(done); +} + +coapConnectionOpts.createListener = createListener; + +module.exports = coapConnectionOpts; diff --git a/pool/shard001/JavaScript/0010153_createPaginationItems.js b/pool/shard001/JavaScript/0010153_createPaginationItems.js new file mode 100644 index 0000000000000000000000000000000000000000..63c9dca7211e29490703db2ef918b2038d9efc69 --- /dev/null +++ b/pool/shard001/JavaScript/0010153_createPaginationItems.js @@ -0,0 +1,37 @@ +import { + createFirstPage, + createLastItem, + createNextItem, + createPageFactory, + createPrevItem, +} from './itemFactories' +import { createComplexRange, createSimpleRange } from './rangeFactories' +import { isSimplePagination, typifyOptions } from './paginationUtils' + +/** + * @param {object} rawOptions + * @param {number|string} rawOptions.activePage + * @param {number|string} rawOptions.boundaryRange Number of always visible pages at the beginning and end. + * @param {boolean} rawOptions.hideEllipsis Marks if ellipsis should be hidden. + * @param {number|string} rawOptions.siblingRange Number of always visible pages before and after the current one. + * @param {number|string} rawOptions.totalPages Total number of pages. + */ +const createPaginationItems = (rawOptions) => { + const options = typifyOptions(rawOptions) + const { activePage, totalPages } = options + + const pageFactory = createPageFactory(activePage) + const innerRange = isSimplePagination(options) + ? createSimpleRange(1, totalPages, pageFactory) + : createComplexRange(options, pageFactory) + + return [ + createFirstPage(), + createPrevItem(activePage), + ...innerRange, + createNextItem(activePage, totalPages), + createLastItem(totalPages), + ] +} + +export default createPaginationItems diff --git a/pool/shard001/JavaScript/0010157_flickr-service.js b/pool/shard001/JavaScript/0010157_flickr-service.js new file mode 100644 index 0000000000000000000000000000000000000000..9e21a32fcdc2e072988b2e783e51a1787e9ab2c5 --- /dev/null +++ b/pool/shard001/JavaScript/0010157_flickr-service.js @@ -0,0 +1,104 @@ +/** + * A service to interact with the flickr API. + */ +define(["angular"], function(angular){ + + return angular.module("flickr.app.services", []) + .factory("flickrService", function($http, $q){ + + // Flickr API key - TODO: Put these in a .config! + var API_KEY = "4072ae071b7042b063476db7b14dac38"; + var URL = "https://api.flickr.com/services/rest/"; + + // Private functions + + /** + * Find the photos by interestingness based on a search term + * @param searchTerm - The tag to search for + * @returns {$q.promise} - A promise that is resolved when all the photos have been loaded + */ + function getPhotos(searchTerm){ + var photoDefer = $q.defer(); + + $http.get(URL, { + params: { + method: "flickr.photos.search", + api_key: API_KEY, + tags: searchTerm, + format: "json", + per_page: 30, + sort: "interestingness-desc", + nojsoncallback: 1, + privacy_filter: 1, + extras: "views,geo,url_s,url_m,url_l,date_taken", + has_geo: 1 + } + }).then(function(resp){ + return resp.data.photos.photo; + }).then(photoDefer.resolve); + + return photoDefer.promise; + } + + /** + * Load the exif data from flickr and add it to our model + * @param photo - the photo model + */ + function getExifData(photo){ + $http.get(URL, { + params: { + method: "flickr.photos.getExif", + api_key: API_KEY, + format: "json", + nojsoncallback: 1, + photo_id: photo.id + } + }).then(function(resp){ + photo.exifData = resp.data.photo; + }); + } + + /** + * Get the interesting photos for the given date + * @param date - Date object + */ + function getInterestingPhotos(date){ + var dt = getFormattedDate(date); + var defr = $q.defer(); + + $http.get(URL, { + params: { + method: "flickr.interestingness.getList", + api_key: API_KEY, + format: "json", + nojsoncallback: 1, + date: dt, + extras: "views", + per_page: 10 + } + }).then(function(resp){ + defr.resolve(resp.data.photos.photo); + }); + + return defr.promise; + } + + // Helper to format the date + function getFormattedDate(date) { + var year = date.getFullYear(); + var month = (1 + date.getMonth()).toString(); + month = month.length > 1 ? month : '0' + month; + var day = date.getDate().toString(); + day = day.length > 1 ? day : '0' + day; + return year + "-" + month + "-" + day; + } + + // Public API + return { + getPhotos: getPhotos, + getExifData: getExifData, + getInterestingPhotos: getInterestingPhotos + }; + } + ); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010158_ajaxsubmit.js b/pool/shard001/JavaScript/0010158_ajaxsubmit.js new file mode 100644 index 0000000000000000000000000000000000000000..d6ed25629ac113620466944d3659b2a3703584e6 --- /dev/null +++ b/pool/shard001/JavaScript/0010158_ajaxsubmit.js @@ -0,0 +1,88 @@ + +Drupal.ajaxSubmit = Drupal.ajaxSubmit || {}; + +/** + * Attaches the ajaxsubmit behaviour to forms. + */ +Drupal.behaviors.ajaxSubmit = function () { + $('form.ajaxsubmit:not(.ajaxsubmit-processed)').each(function () { + var target = document.createElement('div'); + var form = this; + $(target).addClass('ajaxsubmit-message'); + $(this).before(target); + var options = { + dataType: 'json', + beforeSubmit: function () { + Drupal.ajaxSubmit.beforeSubmit(target, form); + }, + success: function (data) { + Drupal.ajaxSubmit.success(target, data, form); + }, + complete: function(data, status) { + Drupal.ajaxSubmit.error(target, form); + if (status == 'error' || status == 'parsererror') { + alert(Drupal.t('An error occurred.')); + } + } + }; + $(this) + .addClass('ajaxsubmit-processed') + .ajaxForm(options) + .find('input[name=ajaxsubmit]') + .attr('value', '1') + .end() + .find('input.form-submit') + .click(function() { + $(this).addClass('throbbing'); + }); + }); +}; + +/** + * Tidy up on form submission. + */ +Drupal.ajaxSubmit.beforeSubmit = function (target, form) { + // Remove any error messages. + $(':input', form).removeClass('error'); + $(target).html(''); +}; + +/** + * Handler for successful response. + */ +Drupal.ajaxSubmit.success = function (target, data, form) { + $('form input.throbbing').removeClass('throbbing'); + $(target).html(data.message); + if (data.errors) { + for (var name in data.errors) { + $('[name="' + name + '"]', form).addClass('error'); + $('[name^="' + name + '["]', form).addClass('error'); + } + } + // Set preview. + if (data.preview) { + $(target).append(data.preview); + } + + // Invoke any callback functions. + if (data.__callbacks) { + $.each(data.__callbacks, function(i, callback) { + eval(callback)(target, data); + }); + } + + var offset = $(target).offset(); + window.scrollTo(0, offset.top - 10); + + // Redirect. + if (data.destination) { + window.location = Drupal.url(data.destination); + } +}; + +/** +* Handler for error. +*/ +Drupal.ajaxSubmit.error = function (target, data, form) { + $('input.form-submit', form).removeClass('throbbing'); +}; diff --git a/pool/shard001/JavaScript/0010159_main.js b/pool/shard001/JavaScript/0010159_main.js new file mode 100644 index 0000000000000000000000000000000000000000..8090aa66a07d8c1d9fa307cce93409e1b496d590 --- /dev/null +++ b/pool/shard001/JavaScript/0010159_main.js @@ -0,0 +1,59 @@ +import { parseLineArray } from './parse'; +import { extractTitle, extractDepth, extractFirstDefinedDepth } from './extract'; +import { meta, wipeMeta } from './utils/meta'; +import { setErrorLocation, setErrorLog } from './utils/errorHandler'; + +setErrorLog('../PageMaker/log.txt'); + +const parseWikitravel = (data, id, title) => { + const a = data.split('\n'), + article = { + title: title.split('/').pop(), + url: title, + id, + }, + previousSections = { 0: article }; + + let currentDepth = 0, + currentLineArray = [], + currentTitle = '', + priorDepth = 0; + + setErrorLocation(title); + wipeMeta(); + + a.forEach((line, i) => { + if (line.startsWith('=')) { + if (currentLineArray.length !== 0) { + parseLineArray(previousSections, currentDepth, currentTitle, currentLineArray); + currentLineArray = []; + } + + currentTitle = extractTitle(previousSections[currentDepth], a, i); + currentDepth = extractDepth(line); + if (currentDepth - priorDepth > 1) { currentDepth -= 1; } + + const p = extractFirstDefinedDepth(previousSections, currentDepth), + newSection = {}; + + previousSections[p][currentTitle] = newSection; + previousSections[currentDepth] = newSection; + priorDepth = currentDepth; + } else { + if (line.startsWith('*') && !line.startsWith('* ')) { + line = `* ${line.substring(1)}`; + } + + currentLineArray.push(line); + } + }); + + parseLineArray(previousSections, currentDepth, currentTitle, currentLineArray); + + return { + article, + meta, + }; +}; + +export default parseWikitravel; diff --git a/pool/shard001/JavaScript/0010167_test-examples-server-verification.js b/pool/shard001/JavaScript/0010167_test-examples-server-verification.js new file mode 100644 index 0000000000000000000000000000000000000000..f1ccfab95cbaaa57a9ecd609d6b77498f80cf0b1 --- /dev/null +++ b/pool/shard001/JavaScript/0010167_test-examples-server-verification.js @@ -0,0 +1,57 @@ +/*jshint expr: true*/ +"use strict"; +var chai = require("chai"); +var expect = chai.expect; +chai.config.includeStack = true; +var request = require("supertest"); +var alexaAppServer = require("../index"); +var fs = require("fs"); + +describe("Alexa App Server with Examples & Verification", function() { + var testServer; + var sampleLaunchReq; + + before(function() { + testServer = alexaAppServer.start({ + port: 3000, + server_root: 'examples', + verify: true + }); + + sampleLaunchReq = JSON.parse(fs.readFileSync("test/sample-launch-req.json", 'utf8')); + }); + + after(function() { + testServer.stop(); + }); + + describe("GET requests", function() { + it("mounts hello world app", function() { + return request(testServer.express) + .get('/alexa/helloworld') + .expect(401); + }); + + it("mounts number_guessing_game app", function() { + return request(testServer.express) + .get('/alexa/guessinggame') + .expect(401); + }); + }); + + describe("POST requests", function() { + it("mounts hello world app", function() { + return request(testServer.express) + .post('/alexa/helloworld') + .send(sampleLaunchReq) + .expect(401); + }); + + it("mounts number_guessing_game", function() { + return request(testServer.express) + .post('/alexa/guessinggame') + .send(sampleLaunchReq) + .expect(401); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010173_form-password.js b/pool/shard001/JavaScript/0010173_form-password.js new file mode 100644 index 0000000000000000000000000000000000000000..a04aed24dbbb3101fce2f772dbaf1cc38f5fb224 --- /dev/null +++ b/pool/shard001/JavaScript/0010173_form-password.js @@ -0,0 +1,64 @@ +/*! UIkit 2.4.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ + +(function(addon) { + + if (typeof define == "function" && define.amd) { // AMD + define("uikit-form-password", ["uikit"], function(){ + return jQuery.UIkit.formPassword || addon(window, window.jQuery, window.jQuery.UIkit); + }); + } + + if(window && window.jQuery && window.jQuery.UIkit) { + addon(window, window.jQuery, window.jQuery.UIkit); + } + +})(function(global, $, UI){ + + var FormPassword = function(element, options) { + + var $this = this, $element = $(element); + + if($element.data("formPassword")) return; + + this.options = $.extend({}, FormPassword.defaults, options); + + this.element = $element.on("click", function(e) { + + e.preventDefault(); + + if($this.input.length) { + var type = $this.input.attr("type"); + $this.input.attr("type", type=="text" ? "password":"text"); + $this.element.text($this.options[type=="text" ? "lblShow":"lblHide"]); + } + }); + + $this.input = this.element.next("input").length ? this.element.next("input") : this.element.prev("input"); + $this.element.text(this.options[$this.input.is("[type='password']") ? "lblShow":"lblHide"]); + + this.element.data("formPassword", this); + }; + + FormPassword.defaults = { + "lblShow": "Show", + "lblHide": "Hide" + }; + + UI["formPassword"] = FormPassword; + + // init code + $(document).on("click.formpassword.uikit", "[data-uk-form-password]", function(e) { + + var ele = $(this); + if (!ele.data("formPassword")) { + + e.preventDefault(); + + var obj = new FormPassword(ele, UI.Utils.options(ele.attr("data-uk-form-password"))); + ele.trigger("click"); + } + }); + + return FormPassword; + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010176_asker.js b/pool/shard001/JavaScript/0010176_asker.js new file mode 100644 index 0000000000000000000000000000000000000000..9216fb27558d54404173f1478f36b0af0de3d9b5 --- /dev/null +++ b/pool/shard001/JavaScript/0010176_asker.js @@ -0,0 +1,57 @@ +var dictionary = require("./reader").dictionary; +var stdin = require("process").stdin; +stdin.setEncoding("utf8"); + + +function getRandom(max){ + return Math.floor(Math.random() * max); +} + +function getNewWord(){ + var posInDictionary; + var posInBox; + var size = dictionary.length; + do{ + posInDictionary = getRandom(size); + }while(dictionary[posInDictionary].used); + + var currWordsBox = dictionary[posInDictionary]; + posInBox = getRandom(currWordsBox.italianWords.length); + var toAskWord = currWordsBox.italianWords[posInBox]; + return [currWordsBox, toAskWord]; +} + +exports.ask = function(){ + var score = 0; + var arr = getNewWord(); + var currWordsBox = arr[0]; + var toAskWord = arr[1]; + console.log(toAskWord); + + stdin.on("data", function(answer){ + answer = answer.trim(); + var response = ""; + var linker = ", or "; + currWordsBox.englishWords.forEach(function(word){ + response += (word + linker); + }); + response = response.substring(0, response.length - linker.length); + + if(currWordsBox.englishWords.indexOf(answer) > - 1){ + console.log("Yes, you got it! All the possible translation are: ", response); + score++; + } + else{ + console.log("No, the right traslation is", response); + } + arr = getNewWord(); + currWordsBox = arr[0]; + toAskWord = arr[1]; + console.log(toAskWord); + }); + + stdin.on("end", function(){ + console.log(score); + }); + //console.log(score); +} diff --git a/pool/shard001/JavaScript/0010177_merge.js b/pool/shard001/JavaScript/0010177_merge.js new file mode 100644 index 0000000000000000000000000000000000000000..0654873215df2ebcc5ddba0e2e85184f6657c3e7 --- /dev/null +++ b/pool/shard001/JavaScript/0010177_merge.js @@ -0,0 +1,95 @@ +'use strcit' + +define(function(){ + var merge = function(fid){ + this.fid = fid; + this.api = 'api/docEditor.cgi'; + }; + merge.prototype = { + init: function(){ + var myNum, myLine, masterNum, masterLine; + var atmark = /^@@ -([0-9]+),*([0-9]*) \+([0-9]+),*([0-9]*) @@/; + + $('.DiffInfo div').each(function(){ + var line = $(this).text(); + var atinfo = line.match(atmark); + if( atinfo ){ + myNum = atinfo[1]; + myLine = atinfo[2]; + masterNum = atinfo[3]; + masterLine = atinfo[4]; + return; + } + + if( line.match(/^-/) ){ + var $target = $('#Mine' + myNum); + var $btn = merge.getDelBtn($target); + $target.addClass('Local').append($btn); + myNum++; + }else if( line.match(/^\+/) ){ + var $target = $('#Mine' + myNum); + var $org = $('#Master' + masterNum); + var $btn = merge.getDelBtn($org); + $org.addClass('Master').append($btn); + if( $target.length ){ + $target.before($org); + }else{ + $('.MergeView .Mine .Document').append($org); + } + masterNum++; + }else{ + myNum++; + masterNum++; + } + }); + + //COMMIT BUTTON + $('#commit').on('click', $.proxy(this.btnCommit, this)); + }, + btnCommit: function(){ + var doc = merge.getMergeText(); + $.ajax({ + url : this.api, + type : 'POST', + data : { + fid : this.fid, + doc : doc, + action: 'merge', + }, + timeout: 5000 + }).done(function(res){ + document.location = 'doc_userlog.cgi?fid=' + res.fid; + }); + } + }; + merge.getDelBtn = function(target){ + var $delBtn = $('
').addClass('Ctrl').append( + $('').append( + $('').addClass('typcn typcn-delete') + ) + ); + $delBtn.find('a').on('click', function(){ + target.toggleClass('Omit'); + if( $(this).find('.typcn').hasClass('typcn-delete') ){ + $(this).find('.typcn').removeClass('typcn-delete') + .addClass('typcn-delete-outline'); + }else{ + $(this).find('.typcn').removeClass('typcn-delete-outline') + .addClass('typcn-delete'); + } + }); + return $delBtn; + }; + merge.getMergeText = function(){ + var $str = ""; + $('.MergeView .Mine .Document').find('li').each($.proxy(function(i, elm){ + if( !$(elm).hasClass('Omit') ){ + $str += $(elm).find('.Line').text(); + $str += '\n'; + } + }, this)); + return $str; + }; + + return merge; +}); diff --git a/pool/shard001/JavaScript/0010179_service.js b/pool/shard001/JavaScript/0010179_service.js new file mode 100644 index 0000000000000000000000000000000000000000..119df4e05a7f3b2172000e220e7b9315537bc93f --- /dev/null +++ b/pool/shard001/JavaScript/0010179_service.js @@ -0,0 +1,113 @@ +module.exports = function(options, callback) { + + var fs = require('fs'); + var restify = require('restify'); + + var serverOptions = { + name: 'zd-server', + version: '0.1.0' + }; + + if (options.secure) { + serverOptions.key = options.secure.key; + serverOptions.certificate = options.secure.certificate; + } + + var server = restify.createServer(serverOptions); + + server.use(restify.acceptParser(server.acceptable)); + server.use(restify.queryParser()); + server.use(restify.bodyParser()); + + var model = require('./model'); + var Game = model.Game; + var games = options.games; + var ee = options.ee; + + server.post('/games', function(req, res, next) { + var game = new Game(req.params.nickname); + games[game.id] = game; + game.roll(); + res.send(game.clientModel()); + + ee.emit('playerStartedGame', game); + }); + + server.put('/games/:gameId', function(req, res, next) { + if (req.params.gameId != req.params.id) + return next(new restify.InvalidArgumentError('Ids don\'t match')); + + var game = games[req.params.id]; + var brainsToScore = game.brains.length; + + if (req.params.nickname) { + game.nickname = req.params.nickname; + } + if (req.params.action) { + if (req.params.action != 'roll' && req.params.action != 'stop') { + return next(new restify.InvalidArgumentError('Not a valid action')); + } + + game[req.params.action](); + } + + res.send(game.clientModel()); + + if (game.isShotgunned()) { + ee.emit('playerShotgunned', game); + } else if (game.hasWonVP()) { + ee.emit('playerVictory', game); + } else if (game.brains.length > 5) { + ee.emit('playerOnARoll', game); + } else if (req.params.action == 'stop' && brainsToScore > 0) { + ee.emit('playerPlayedItSafe', game); + } + }); + + server.get('/games/:gameId', function(req, res, next) { + var game = games[req.params.gameId]; + + if (!game) + return next(new restify.ResourceNotFoundError('Game not found')); + + res.send(game); + }); + + server.get('/ranking', function(req, res, next) { + var orderedGames = []; + for(var id in games) { + orderedGames.push(games[id]); + } + + orderedGames.sort(function(x, y) { + var xRatio = x.vp / x.rounds; + var yRatio = y.vp / y.rounds; + + if (xRatio == yRatio) { + return x.modified < y.modified ? -1 : 1; + } + + return xRatio > yRatio ? -1 : 1; + }); + + var scores = []; + for(var i=0; i { + const [selectedSeqData, setSelectedSeqData] = useState( + results[0].parsedSequence + ); + return ( +
+
+ + Multiple sequences were detected in the input file. Please choose one + to continue + +

+
+
+ {results.map((res, i) => { + const { parsedSequence } = res; + if (!parsedSequence) return null; + const { name } = parsedSequence; + return ( +
+ +
+ ); + })} +
+   + + + +
+
+ { + finishDisplayingSeq(selectedSeqData); + hideDialog(); + }} + > +
+ ); +}); diff --git a/pool/shard001/JavaScript/0010188_provider-manager-spec.js b/pool/shard001/JavaScript/0010188_provider-manager-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9f02dde00a3235c0f2df3070d3fa9e883aa5c88d --- /dev/null +++ b/pool/shard001/JavaScript/0010188_provider-manager-spec.js @@ -0,0 +1,59 @@ +'use strict'; + +const providerManager = require('../lib/provider-manager'); +const operatorConfig = require('../lib/operator-config'); + +describe('ProviderManager', () => { + const provider = { + selector: ['.source.coffee'], + id: 'aligner-coffee', + config: { + ':-alignment': 'left', + }, + }; + + describe('registering a provider', () => { + let disposable = null; + + beforeEach(() => { + spyOn(operatorConfig, 'add').andCallThrough(); + spyOn(atom.config, 'observe').andCallThrough(); + disposable = providerManager.register(provider); + }); + + afterEach(() => { + disposable.dispose(); + }); + + it('should add provider to operator config', () => { + expect(operatorConfig.add).toHaveBeenCalled(); + }); + + it('should add atom config listener', () => { + expect(atom.config.observe).toHaveBeenCalled(); + }); + }); + + describe('registering and deactivating', () => { + it('should work fine', () => { + spyOn(console, 'error'); + + let disposable = providerManager.register(provider); + disposable.dispose(); + providerManager.register(provider); + + expect(console.error).not.toHaveBeenCalled(); + }); + + xit('should work fine with the package', () => { + spyOn(console, 'error').andCallThrough(); + waitsForPromise(() => atom.packages.activatePackage('aligner')); + runs(() => atom.packages.deactivatePackage('aligner')); + waitsForPromise(() => atom.packages.activatePackage('aligner')); + + runs(() => { + expect(console.error).not.toHaveBeenCalled(); + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010194_filterTransforms.js b/pool/shard001/JavaScript/0010194_filterTransforms.js new file mode 100644 index 0000000000000000000000000000000000000000..ec86d389f542615c44415ef75222fdd334b9bb7b --- /dev/null +++ b/pool/shard001/JavaScript/0010194_filterTransforms.js @@ -0,0 +1,83 @@ +var math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +var calculateScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + //var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + // var texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale( textureSize.width , textureSize.height ); + + return mappedMatrix; + +}; + +var calculateNormalizedScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + var translateScaleX = (textureSize.width / filterArea.width); + var translateScaleY = (textureSize.height / filterArea.height); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + return mappedMatrix; +}; + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +var calculateSpriteMatrix = function (outputMatrix, filterArea, textureSize, sprite) +{ + var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale(1 , ratio); + + var translateScaleX = (textureSize.width / texture.width); + var translateScaleY = (textureSize.height / texture.height); + + worldTransform.tx /= texture.width * translateScaleX; + + //this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1 , 1/ratio); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +}; + +module.exports = { + calculateScreenSpaceMatrix:calculateScreenSpaceMatrix, + calculateNormalizedScreenSpaceMatrix:calculateNormalizedScreenSpaceMatrix, + calculateSpriteMatrix:calculateSpriteMatrix +}; diff --git a/pool/shard001/JavaScript/0010195_karma-js.conf.js b/pool/shard001/JavaScript/0010195_karma-js.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..0c3d96ac234e4b05b83ed32b8dd1771f43367076 --- /dev/null +++ b/pool/shard001/JavaScript/0010195_karma-js.conf.js @@ -0,0 +1,96 @@ +var browserProvidersConf = require('./browser-providers.conf.js'); +var internalAngularReporter = require('./tools/karma/reporter.js'); + +// Karma configuration +// Generated on Thu Sep 25 2014 11:52:02 GMT-0700 (PDT) +module.exports = function(config) { + config.set({ + + frameworks: ['jasmine'], + + files: [ + // Sources and specs. + // Loaded through the System loader, in `test-main.js`. + {pattern: 'dist/js/dev/es5/**', included: false, watched: false}, + + 'node_modules/es6-shim/es6-shim.js', + // include Angular v1 for upgrade module testing + 'node_modules/angular/angular.min.js', + + 'node_modules/zone.js/dist/zone.js', + 'node_modules/zone.js/dist/long-stack-trace-zone.js', + 'node_modules/zone.js/dist/jasmine-patch.js', + + // Including systemjs because it defines `__eval`, which produces correct stack traces. + 'modules/angular2/src/testing/shims_for_IE.js', + 'node_modules/systemjs/dist/system.src.js', + {pattern: 'node_modules/rxjs/**', included: false, watched: false, served: true}, + 'node_modules/reflect-metadata/Reflect.js', + 'tools/build/file2modulename.js', + 'test-main.js', + {pattern: 'modules/**/test/**/static_assets/**', included: false, watched: false} + ], + + exclude: ['dist/js/dev/es5/**/e2e_test/**', 'dist/js/dev/es5/angular2/examples/**', 'dist/angular1_router.js'], + + customLaunchers: browserProvidersConf.customLaunchers, + + plugins: [ + 'karma-jasmine', + 'karma-browserstack-launcher', + 'karma-sauce-launcher', + 'karma-chrome-launcher', + 'karma-sourcemap-loader', + 'karma-dart', + internalAngularReporter + ], + + preprocessors: { + '**/*.js': ['sourcemap'] + }, + + reporters: ['internal-angular'], + sauceLabs: { + testName: 'Angular2', + startConnect: false, + recordVideo: false, + recordScreenshots: false, + options: { + 'selenium-version': '2.48.2', + 'command-timeout': 600, + 'idle-timeout': 600, + 'max-duration': 5400 + } + }, + + browserStack: { + project: 'Angular2', + startTunnel: false, + retryLimit: 1, + timeout: 600, + pollingTimeout: 10000 + }, + + browsers: ['Chrome'], + + port: 9876 + }); + + if (process.env.TRAVIS) { + var buildId = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')'; + if (process.env.MODE.startsWith('saucelabs')) { + config.sauceLabs.build = buildId; + config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER; + + // TODO(mlaval): remove once SauceLabs supports websockets. + // This speeds up the capturing a bit, as browsers don't even try to use websocket. + console.log('>>>> setting socket.io transport to polling <<<<'); + config.transports = ['polling']; + } + + if (process.env.MODE.startsWith('browserstack')) { + config.browserStack.build = buildId; + config.browserStack.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER; + } + } +}; diff --git a/pool/shard001/JavaScript/0010196_index.js b/pool/shard001/JavaScript/0010196_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4722fe123724aa1063772ef125283c203ebb623a --- /dev/null +++ b/pool/shard001/JavaScript/0010196_index.js @@ -0,0 +1,30 @@ +var builder = require('focus').component.builder; +var React = require('react'); + + +var imgMixin = { + /** + * Display name. + */ + displayName: 'img', + /** + * Default props. + * @returns {object} Initial props. + */ + getDefaultProps: function(){ + return { + src: undefined, + onClick: undefined + }; + }, + /** + * Render the img. + * @returns {XML} Html code. + */ + render: function renderImg(){ + var className = 'icon ' + this.props.src; + return  ; + } +}; + +module.exports = builder(imgMixin); diff --git a/pool/shard001/JavaScript/0010200_WME_Permalink_to_maps_czech.user.js b/pool/shard001/JavaScript/0010200_WME_Permalink_to_maps_czech.user.js new file mode 100644 index 0000000000000000000000000000000000000000..f097886b5ffc0fa8960a9fba3ed1c36631b30a2e --- /dev/null +++ b/pool/shard001/JavaScript/0010200_WME_Permalink_to_maps_czech.user.js @@ -0,0 +1,119 @@ +// ==UserScript== +// @name WME Permalink to maps czech +// @description Skript umoznujici kontrolu WME v dalsich mapach. +// @namespace https://greasyfork.org/users/4640-petr-nedv%C4%9Bd +// @version 0.4 +// @include https://*.waze.com/editor/* +// @include https://*.waze.com/*/editor/* +// @include https://editor-beta.waze.com/*editor/* +// @grant none +// ==/UserScript== + +// Kopie originálního skriptu AlexN-114 https://greasyfork.org/scripts/3080-wme-permalink-to-serveral-maps +// Mini howto: +// 1) install this script as greasemonkey script or chrome extension +// 2) Click on Google Maps Permalink on the sidebar +if ('undefined' == typeof __RTLM_PAGE_SCOPE_RUN__) { + (function page_scope_runner() { + // If we're _not_ already running in the page, grab the full source + // of this script. + var my_src = "(" + page_scope_runner.caller.toString() + ")();"; + + // Create a script node holding this script, plus a marker that lets us + // know we are running in the page scope (not the Greasemonkey sandbox). + // Note that we are intentionally *not* scope-wrapping here. + var script = document.createElement('script'); + script.setAttribute("type", "text/javascript"); + script.textContent = "var __RTLM_PAGE_SCOPE_RUN__ = true;\n" + my_src; + + // Insert the script node into the page, so it will run, and immediately + // remove it to clean up. Use setTimeout to force execution "outside" of + // the user script scope completely. + setTimeout(function() { + document.body.appendChild(script); + document.body.removeChild(script); + }, 0); + })(); + + // Stop running, because we know Greasemonkey actually runs us in + // an anonymous wrapper. + return; +} + +function getQueryString(link, name) +{ + var pos = link.indexOf( name + '=' ) + name.length + 1; + var len = link.substr(pos).indexOf('&'); + if (-1 == len) len = link.substr(pos).length; + return link.substr(pos,len); +} + +jQuery(function($){ + var _highest = 0; + + $("div").each(function() { + var _current = parseInt($(this).css("zIndex"), 10); + if(_current > _highest) { + _highest = _current + 1; + } + }); + $('body').append('
'); +}); + +var btn0 = $(''); +btn0.click(function(){ + var href = $('.WazeControlPermalink a').attr('href'); + + var lon = getQueryString(href, 'lon'); + var lat = getQueryString(href, 'lat'); + var zoom = parseInt(getQueryString(href, 'zoom')); + + zoom = zoom > 5 ? 17 : zoom + 12; + var mapsUrl = 'https://www.waze.com/livemap?lon=' + lon + '&lat=' + lat + '&zoom=' + zoom; + // https://www.waze.com/livemap?lon=-40.94918&lat=-18.56958&zoom=17 + window.open(mapsUrl,'_blank') +}); + +var btn1 = $(''); +btn1.click(function(){ + var href = $('.WazeControlPermalink a').attr('href'); + + var lon = getQueryString(href, 'lon'); + var lat = getQueryString(href, 'lat'); + var zoom = parseInt(getQueryString(href, 'zoom')); + + zoom = zoom > 6 ? 19 : zoom + 12; + var mapsUrl = 'https://maps.google.com/?ll=' + lat + ',' + lon + '&z=' + zoom; + window.open(mapsUrl,'_blank') +}); + +var btn2 = $(''); +btn2.click(function(){ + var href = $('.WazeControlPermalink a').attr('href'); + + var lon = getQueryString(href, 'lon'); + var lat = getQueryString(href, 'lat'); + var zoom = parseInt(getQueryString(href, 'zoom')); + + zoom = zoom > 6 ? 19 : zoom + 10; + var mapsUrl = 'http://mapy.cz/zakladni?x=' + lon + '&y=' + lat + '&z=' + zoom; + window.open(mapsUrl,'_blank') +}); + +var btn3 = $(''); +btn3.click(function(){ + var href = $('.WazeControlPermalink a').attr('href'); + + var lon = getQueryString(href, 'lon'); + var lat = getQueryString(href, 'lat'); + var zoom = parseInt(getQueryString(href, 'zoom')); + + zoom = zoom > 6 ? 19 : zoom + 12; + var mapsUrl = 'http://www.openstreetmap.org/#map=' + zoom + '/' + lat + '/' + lon; + window.open(mapsUrl,'_blank') +}); + +$("#fpanel").append(btn0); +$("#fpanel").append(btn1); +$("#fpanel").append(btn2); +$("#fpanel").append(btn3); diff --git a/pool/shard001/JavaScript/0010205_application.js b/pool/shard001/JavaScript/0010205_application.js new file mode 100644 index 0000000000000000000000000000000000000000..b1eca83e64bc2ffb4bf3005c8799e3e92aaaff0e --- /dev/null +++ b/pool/shard001/JavaScript/0010205_application.js @@ -0,0 +1,58 @@ +'use strict'; +angular.module('application') + .controller('ApplicationCtrl', ['$translate', '$rootScope', '$scope', 'TeamRepository', 'AUTH_EVENTS', 'AuthService', 'growl', function ($translate, $rootScope, $scope, TeamRepository, AUTH_EVENTS, AuthService, growl ) { + var app = this; + + app.teamCount = 0; + + // count teams for demo: + app.teamCollection = TeamRepository.getList().then(function(response){ + app.teamCount = response.data.length; + app.teamCollection = response.data; + return app.teamCollection; + }); + + // refresh teamCount on time: + $scope.$watch(angular.bind(app, function (teamCount) { + return app.teamCount; + }), function(newCount){ + app.teamCount = newCount; + }); + + + /** + * Handle user state + */ + $scope.user = {}; + $scope.isAuth = AuthService.isAuthenticated(); + + $rootScope.$on(AUTH_EVENTS.loginSuccess, function(ev, response){ + $scope.isAuth = AuthService.isAuthenticated(); + $scope.getUser(); + }); + $rootScope.$on(AUTH_EVENTS.logoutSuccess, function(ev, response){ + $scope.isAuth = AuthService.isAuthenticated(); + $scope.getUser(); + }); + + $scope.getUser = function() { + AuthService.getUser().then(function(user){ + $scope.user = user; + }).catch(function(){ + $scope.user = {}; + }); + }; + + $scope.getUser(); + + $rootScope.$on(AUTH_EVENTS.notAuthorized, function(event, action){ + growl.error('Not authorized access', {ttl: 3000}); + }); + $rootScope.$on(AUTH_EVENTS.notAuthenticated, function(event, action){ + growl.error('Require authentification', {ttl: 3000}); + }); + + + + +}]); diff --git a/pool/shard001/JavaScript/0010206_layer-grid.js b/pool/shard001/JavaScript/0010206_layer-grid.js new file mode 100644 index 0000000000000000000000000000000000000000..bfbc258a205a9e53a30eea1ad0ff6d83efe518f7 --- /dev/null +++ b/pool/shard001/JavaScript/0010206_layer-grid.js @@ -0,0 +1,76 @@ +// Copyright (c) 2000 Just Objects B.V. +// Distributable under LGPL license. See terms of license at gnu.org. + +/** REQUIRES api.js,layer.js */ + +/* Object to represent a N*M grid of Layer objects */ +function LayerGrid(idRoot, targetWindow, columns, lines, xOffset, yOffset, width, height) { + this.idRoot = idRoot; + this.targetWindow = targetWindow; + if (targetWindow == self) { + // If we create the grid in our own window take our id + this.targetWindowId = targetWindow; + } else { + // Grid resides in secondary window or frame + this.targetWindowId = targetWindow.name; + } + this.x = xOffset; + this.y = yOffset; + this.width = width; + this.height = height; + this.lines = lines + this.colums = columns + this.cells = lines*columns; + this.cellWidth = width/columns; + this.cellHeight = height/lines; + this.cellArray = new Array(this.cells) + this.pointer = 0; + this.full = false; + + // Methods + this.getSkeletonHTML = LayerGridGetSkeletonHTML + this.writeSkeletonHTML = LayerGridWriteSkeletonHTML; + this.writeCellAtIndex = LayerGridWriteCellAtIndex + this.writeCell = LayerGridWriteCell; + this.makeCell = LayerGridMakeCell; + + // Init + var index =0; + for (var i = 0; i < lines; i++) { + for (var j = 0; j < columns; j++) { + newLayer = new Layer(this.idRoot+index, this.targetWindowId); + newLayer.shiftTo(xOffset+(j*this.cellWidth), yOffset+(i*this.cellHeight)) + this.cellArray[index] = newLayer; + index++; + } + } +} + +function LayerGridGetSkeletonHTML() { + var skeletonHTML = ""; + for (var i = 0; i < this.cells; i++) { + + skeletonHTML = skeletonHTML + this.cellArray[i].getSkeletonHTML() + "
" + } +// alert(skeletonHTML) + return skeletonHTML; +} + +function LayerGridWriteSkeletonHTML() { + this.targetWindow.document.writeln(this.getSkeletonHTML()); + this.targetWindow.document.close() ; +} + +function LayerGridWriteCellAtIndex(cellNumber, text, bgColor) { + // this.cellArray[cellNumber].hide() + this.cellArray[cellNumber].write(this.makeCell(text, bgColor)) + // this.cellArray[cellNumber].show() +} + +function LayerGridWriteCell(line, column, text) { + this.writeCellAtIndex(line*this.columns+column, text) +} + +function LayerGridMakeCell(text, bgColor) { + return "
"+text+"
"; +} diff --git a/pool/shard001/JavaScript/0010211_goTerm.js b/pool/shard001/JavaScript/0010211_goTerm.js new file mode 100644 index 0000000000000000000000000000000000000000..dac5fd6264ac5cc055e45a147cb4eebf5e04fa75 --- /dev/null +++ b/pool/shard001/JavaScript/0010211_goTerm.js @@ -0,0 +1,149 @@ +CLMSUI = CLMSUI || {}; + +CLMSUI.GoTerm = function () { + // lazy instantiation instead + //this.is_a = new Set(); // i.e. superclasses + //this.subclasses = new Set(); + //this.part_of = new Set(); + //this.parts = new Set(); + //this.interactors = new Set(); + this.filtInteractorCount = 0; +}; + +// CLMSUI.GoTerm.prototype.getInteractors = function(interactorSet) { +// var go = CLMSUI.compositeModelInst.get("go"); +// if (!interactorSet) { +// interactorSet = new Set(); +// } +// if (this.parts) { +// for (let partId of this.parts) { +// go.get(partId).getInteractors(interactorSet); +// } +// } +// if (this.subclasses) { +// for (let subclassId of this.subclasses) { +// go.get(subclassId).getInteractors(interactorSet); +// } +// } +// if (this.interactors) { +// for (let i of this.interactors) { +// if (i.hidden == false) { +// interactorSet.add(i); +// } +// } +// } +// return interactorSet; +// } + +CLMSUI.GoTerm.prototype.getInteractors = function (storeCount) { + var go = CLMSUI.compositeModelInst.get("go"); + CLMSUI.GoTerm.prototype.getCount++; + + var subTreeSet; // = new Set(); + + if (this.parts || this.subclasses || this.interactors) { + subTreeSet = new Set(); + + if (this.parts) { + for (let partId of this.parts) { + var sub = go.get(partId).getInteractors(storeCount); + if (sub) { + sub.forEach(subTreeSet.add, subTreeSet); + } + } + } + if (this.subclasses) { + for (let subclassId of this.subclasses) { + var sub = go.get(subclassId).getInteractors(storeCount); + if (sub) { + sub.forEach(subTreeSet.add, subTreeSet); + } + } + } + + if (this.interactors) { + for (let i of this.interactors) { + if (i.hidden == false) { + subTreeSet.add(i); + } + } + } + + if (subTreeSet.size === 0) { + subTreeSet = null; + } + } + if (storeCount) { + this.filtInteractorCount = subTreeSet ? subTreeSet.size : 0; + //if (subTreeSet.size) { console.log ("sub", subTreeSet, this.id); } + } + + return subTreeSet; +}; + + +CLMSUI.GoTerm.prototype.isDirectRelation = function (anotherGoTerm) { + var agoid = anotherGoTerm.id; + return ( + (this == anotherGoTerm) || + (this.is_a && this.is_a.has(agoid)) || + (this.subclasses && this.subclasses.has(agoid)) || + (this.part_of && this.part_of.has(agoid)) || + (this.parts && this.parts.has(agoid)) + ); +} + + +CLMSUI.GoTerm.prototype.isDescendantOf = function (anotherGoTermId) { + var go = CLMSUI.compositeModelInst.get("go"); + if (anotherGoTermId == this.id) { + return true; + } + if (this.part_of) { + for (let part_ofId of this.part_of) { + var partOf = go.get(part_ofId); + if (partOf.isDescendantOf(anotherGoTermId)) { + return true; + } + } + } + if (this.is_a) { + for (let superclassId of this.is_a) { + var sup = go.get(superclassId); + if (sup.isDescendantOf(anotherGoTermId)) { + return true; + } + } + } + return false; +} + + +/* +CLMSUI.GoTerm.prototype.getClosestVisibleParents = function(visibleParents) { + if (!visibleParents) { + visibleParents = new Set(); + } + for (var parent of this.parents) { + if (parent.isVisible()) { + visibleParents.add(parent); + } else { + parent.getClosestVisibleParents(visibleParents); + } + } + return visibleParents; +} + +CLMSUI.GoTerm.prototype.isVisible = function() { + if (this.parents.length == 0) { + return true; + } else { + for (let p of this.parents) { + if (p.expanded) { + return true; + } + } + } + return false; +} +*/ diff --git a/pool/shard001/JavaScript/0010214_requirejs.js b/pool/shard001/JavaScript/0010214_requirejs.js new file mode 100644 index 0000000000000000000000000000000000000000..a90f1741f7a52d9bdae5a45c384c251213270c1e --- /dev/null +++ b/pool/shard001/JavaScript/0010214_requirejs.js @@ -0,0 +1,46 @@ +var Promise = require('es6-promise').Promise; +var requirejs = require('requirejs'); +var path = require('path'); +var fs = require('../utils/fs'); +var File = require('../utils/file'); +var log = require('../utils/log'); + +function RequireJS(location, destination, options){ + this.location = location; + this.destination = destination; + this.options = options; +} + +RequireJS.prototype.file = function(fileObj) { + var config = { + baseUrl: path.join(fileObj.base,fileObj.relativeDir), + name: fileObj.name.replace('.js',''), + out: path.join(this.destination, fileObj.relativeDir, fileObj.name), + generateSourceMaps: true, + preserveLicenseComments: false, + optimize: "none", + mainConfigFile: this.options.mainConfigFile + }; + return new Promise(function(resolve, reject){ + requirejs.optimize(config, function(args){ + var fileObj = new File({path:args.split('\n')[1]}); + resolve(fileObj); + }, reject); + }); +}; + +RequireJS.prototype.write = function(){ + var self = this; + return fs.glob(this.location).then(function(fileObjs){ + if (self.options.verbose && fileObjs.length===0){ + log.info('no .js files found within `' + self.location + '`'); + } + var promises = []; + fileObjs.forEach(function (fileObj, i) { + promises.push(self.file(fileObj)); + }); + return Promise.all(promises); + }); +}; + +module.exports = RequireJS; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010215_config.js b/pool/shard001/JavaScript/0010215_config.js new file mode 100644 index 0000000000000000000000000000000000000000..34e5078da85f565a8964ed99d280bdcb38c690ae --- /dev/null +++ b/pool/shard001/JavaScript/0010215_config.js @@ -0,0 +1,154 @@ +'use strict'; + +/** + * Module dependencies. + */ +var _ = require('lodash'), + chalk = require('chalk'), + glob = require('glob'), + fs = require('fs'), + path = require('path'); + +/** + * Get files by glob patterns + */ +var getGlobbedPaths = function (globPatterns, excludes) { + // URL paths regex + var urlRegex = new RegExp('^(?:[a-z]+:)?\/\/', 'i'); + + // The output array + var output = []; + + // If glob pattern is array so we use each pattern in a recursive way, otherwise we use glob + if (_.isArray(globPatterns)) { + globPatterns.forEach(function (globPattern) { + output = _.union(output, getGlobbedPaths(globPattern, excludes)); + }); + } else if (_.isString(globPatterns)) { + if (urlRegex.test(globPatterns)) { + output.push(globPatterns); + } else { + var files = glob.sync(globPatterns); + if (excludes) { + files = files.map(function (file) { + if (_.isArray(excludes)) { + for (var i in excludes) { + file = file.replace(excludes[i], ''); + } + } else { + file = file.replace(excludes, ''); + } + return file; + }); + } + output = _.union(output, files); + } + } + + return output; +}; + +/** + * Validate NODE_ENV existance + */ +var validateEnvironmentVariable = function () { + var environmentFiles = glob.sync('./config/env/' + process.env.NODE_ENV + '.js'); + console.log(); + if (!environmentFiles.length) { + if (process.env.NODE_ENV) { + console.error(chalk.red('+ Error: No configuration file found for "' + process.env.NODE_ENV + '" environment using development instead')); + } else { + console.error(chalk.red('+ Error: NODE_ENV is not defined! Using default development environment')); + } + process.env.NODE_ENV = 'development'; + } + // Reset console color + console.log(chalk.white('')); +}; + +/** + * Initialize global configuration files + */ +var initGlobalConfigFolders = function (config, assets) { + // Appending files + config.folders = { + server: {}, + client: {} + }; + + // Setting globbed client paths + config.folders.client = getGlobbedPaths(path.join(process.cwd(), 'modules/*/client/'), process.cwd().replace(new RegExp(/\\/g), '/')); +}; + +/** + * Initialize global configuration files + */ +var initGlobalConfigFiles = function (config, assets) { + // Appending files + config.files = { + server: {}, + client: {} + }; + + // Setting Globbed route files + config.files.server.routes = getGlobbedPaths(assets.server.routes); + + // Setting Globbed config files + config.files.server.configs = getGlobbedPaths(assets.server.config); + + // Setting Globbed socket files + config.files.server.sockets = getGlobbedPaths(assets.server.sockets); + + // Setting Globbed js files + config.files.client.js = getGlobbedPaths(assets.client.lib.js, 'public/').concat(getGlobbedPaths(assets.client.js, ['client/', 'public/'])); + + // Setting Globbed css files + config.files.client.css = getGlobbedPaths(assets.client.lib.css, 'public/').concat(getGlobbedPaths(assets.client.css, ['client/', 'public/'])); + +}; + +/** + * Initialize global configuration + */ +var initGlobalConfig = function () { + // Validate NDOE_ENV existance + validateEnvironmentVariable(); + + // Get the default assets + var defaultAssets = require(path.join(process.cwd(), 'config/assets/default')); + + // Get the current assets + var environmentAssets = require(path.join(process.cwd(), 'config/assets/', process.env.NODE_ENV)) || {}; + + // Merge assets + var assets = _.merge(defaultAssets, environmentAssets); + + // Get the default config + var defaultConfig = require(path.join(process.cwd(), 'config/env/default')); + + // Get the current config + var environmentConfig = require(path.join(process.cwd(), 'config/env/', process.env.NODE_ENV)) || {}; + + // Merge config files + var envConf = _.merge(defaultConfig, environmentConfig); + + var config = _.merge(envConf, (fs.existsSync(path.join(process.cwd(), 'config/env/local.js')) && require(path.join(process.cwd(), 'config/env/local.js'))) || {}); + + // Initialize global globbed files + initGlobalConfigFiles(config, assets); + + // Initialize global globbed folders + initGlobalConfigFolders(config, assets); + + // Expose configuration utilities + config.utils = { + getGlobbedPaths: getGlobbedPaths + }; + + return config; +}; + +/** + * Set configuration object + */ +module.exports = initGlobalConfig(); diff --git a/pool/shard001/JavaScript/0010216_session-store-test.js b/pool/shard001/JavaScript/0010216_session-store-test.js new file mode 100644 index 0000000000000000000000000000000000000000..40f51a625034ae7de4da52046bbd8f52d23c0fe4 --- /dev/null +++ b/pool/shard001/JavaScript/0010216_session-store-test.js @@ -0,0 +1,110 @@ +const LocalStorageMock = { + getItem: stub(), + setItem: stub(), + removeItem: stub() +}; +const date = { getCurrentDate: stub().returns(20160505)}; +const sessionStore = requireUnit('lib-app/session-store', { + 'localStorage': LocalStorageMock, + 'lib-app/date': date +}); + +describe('sessionStore library', function () { + + beforeEach(function () { + LocalStorageMock.getItem = stub(); + LocalStorageMock.setItem = stub(); + LocalStorageMock.removeItem = stub(); + }); + + it('should get, set and remove items from LocalStorage', function () { + sessionStore.getItem('SOME_KEY'); + expect(LocalStorageMock.getItem).to.have.been.calledWith(root + '_SOME_KEY'); + + sessionStore.setItem('SOME_KEY', 'SOME_VALUE'); + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_SOME_KEY', 'SOME_VALUE'); + + sessionStore.removeItem('SOME_KEY'); + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_SOME_KEY'); + }); + + it('should create session correctly', function () { + sessionStore.createSession(14, 'TOKEN'); + + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_userId', 14); + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_token', 'TOKEN'); + }); + + it('should return session data', function () { + LocalStorageMock.getItem = function (key) { + if (key === root + '_userId') return 'USER_ID'; + if (key === root + '_token') return 'TOKEN'; + }; + let sessionData = sessionStore.getSessionData(); + + expect(sessionData.userId).to.equal('USER_ID'); + expect(sessionData.token).to.equal('TOKEN'); + + LocalStorageMock.getItem = stub().returns('ITEM'); + }); + + it('should inform if it is logged in', function () { + LocalStorageMock.getItem = stub().returns('TOKEN'); + expect(sessionStore.isLoggedIn()).to.equal(true); + + LocalStorageMock.getItem = stub().returns(null); + expect(sessionStore.isLoggedIn()).to.equal(false); + }); + + it('should clear session data if session is closed', function () { + sessionStore.closeSession(); + + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_userId'); + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_token'); + }); + + it('should store remember data', function () { + sessionStore.storeRememberData({ + token: 'SOME_TOKEN', + userId: 12, + expiration: 20160623 + }); + + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_rememberData-token', 'SOME_TOKEN'); + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_rememberData-userId', 12); + expect(LocalStorageMock.setItem).to.have.been.calledWith(root + '_rememberData-expiration', 20160623); + }); + + it('should inform if remember expired', function () { + LocalStorageMock.getItem = (key) => (key === root + '_rememberData-expiration') ? 20160505 : null; + date.getCurrentDate.returns(20160506); + expect(sessionStore.isRememberDataExpired()).to.equal(true); + + LocalStorageMock.getItem = (key) => (key === root + '_rememberData-expiration') ? 20160505 : null; + date.getCurrentDate.returns(20160503); + expect(sessionStore.isRememberDataExpired()).to.equal(false); + }); + + it('should return all remember data', function () { + LocalStorageMock.getItem = function (key) { + if (key === root + '_rememberData-userId') return 'USER_ID'; + if (key === root + '_rememberData-token') return 'TOKEN'; + if (key === root + '_rememberData-expiration') return 'EXPIRATION'; + }; + let rememberData = sessionStore.getRememberData(); + + expect(rememberData.userId).to.equal('USER_ID'); + expect(rememberData.token).to.equal('TOKEN'); + expect(rememberData.expiration).to.equal('EXPIRATION'); + + LocalStorageMock.getItem = stub().returns('ITEM'); + }); + + it('should clear remember data', function () { + sessionStore.clearRememberData(); + + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_rememberData-userId'); + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_rememberData-token'); + expect(LocalStorageMock.removeItem).to.have.been.calledWith(root + '_rememberData-expiration'); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010218_KmlTour.js b/pool/shard001/JavaScript/0010218_KmlTour.js new file mode 100644 index 0000000000000000000000000000000000000000..5c5d2d7da3492dd7fc70e95cc0ab1bb5931b36a5 --- /dev/null +++ b/pool/shard001/JavaScript/0010218_KmlTour.js @@ -0,0 +1,163 @@ +define([ + '../Core/defined', + '../Core/Event' + ], function( + defined, + Event) { + 'use strict'; + /** + * @alias KmlTour + * @constructor + * + * @param {String} name name parsed from KML + * @param {String} id id parsed from KML + * @param {Array} playlist array with KMLTourFlyTos, KMLTourWaits and KMLTourSoundCues + */ + function KmlTour(name, id) { + /** + * Id of kml gx:Tour entry + * @type String + */ + this.id = id; + /** + * Tour name + * @type String + */ + this.name = name; + /** + * Index of current entry from playlist + * @type Number + */ + this.playlistIndex = 0; + /** + * Array of playlist entries + * @type Array + */ + this.playlist = []; + /** + * Event will be called when tour starts to play, + * before any playlist entry starts to play. + * @type Event + */ + this.tourStart = new Event(); + /** + * Event will be called when all playlist entries are + * played, or tour playback being canceled. + * + * If tour playback was terminated, event callback will + * be called with terminated=true parameter. + * @type Event + */ + this.tourEnd = new Event(); + /** + * Event will be called when entry from playlist starts to play. + * + * Event callback will be called with curent entry as first parameter. + * @type Event + */ + this.entryStart = new Event(); + /** + * Event will be called when entry from playlist ends to play. + * + * Event callback will be called with following parameters: + * 1. entry - entry + * 2. terminated - true if playback was terminated by calling {@link KmlTour#stop} + * @type Event + */ + this.entryEnd = new Event(); + + this._activeEntries = []; + } + + /** + * Add entry to this tour playlist. + * + * @param {KmlTourFlyTo|KmlTourWait} entry an entry to add to the playlist. + */ + KmlTour.prototype.addPlaylistEntry = function(entry) { + this.playlist.push(entry); + }; + + /** + * Play this tour. + * + * @param {Viewer} viewer viewer widget. + * @param {Object} [cameraOptions] these options will be merged with {@link Camera#flyTo} + * options for FlyTo playlist entries. + */ + KmlTour.prototype.play = function(viewer, cameraOptions) { + this.tourStart.raiseEvent(); + + var tour = this; + playEntry.call(this, viewer, cameraOptions, function(terminated) { + tour.playlistIndex = 0; + // Stop nonblocking entries + if (!terminated) { + cancelAllEntries(tour._activeEntries); + } + tour.tourEnd.raiseEvent(terminated); + }); + }; + + /** + * Stop curently playing tour. + */ + KmlTour.prototype.stop = function() { + cancelAllEntries(this._activeEntries); + }; + + // Stop all activeEntries. + function cancelAllEntries(activeEntries) { + for(var entry = activeEntries.pop(); entry !== undefined; entry = activeEntries.pop()) { + entry.stop(); + } + } + + // Play playlist entry. + // This function is called recursevly with playNext and iterates over all entries from playlist. + function playEntry(viewer, cameraOptions, allDone) { + var entry = this.playlist[this.playlistIndex]; + if (entry) { + var _playNext = playNext.bind(this, viewer, cameraOptions, allDone); + this._activeEntries.push(entry); + this.entryStart.raiseEvent(entry); + if (entry.blocking) { + entry.play(_playNext, viewer.scene.camera, cameraOptions); + } + else { + var tour = this; + entry.play(function() { + tour.entryEnd.raiseEvent(entry); + var indx = tour._activeEntries.indexOf(entry); + if (indx >= 0) { + tour._activeEntries.splice(indx, 1); + } + }); + _playNext(viewer, cameraOptions, allDone); + } + } + else if(defined(allDone)) { + allDone(false); + } + } + + // Increment playlistIndex and call playEntry if terminated isn't true. + function playNext(viewer, cameraOptions, allDone, terminated) { + var entry = this.playlist[this.playlistIndex]; + this.entryEnd.raiseEvent(entry, terminated); + + if (terminated) { + allDone(terminated); + } + else { + var indx = this._activeEntries.indexOf(entry); + if (indx >= 0) { + this._activeEntries.splice(indx, 1); + } + this.playlistIndex++; + playEntry.call(this, viewer, cameraOptions, allDone); + } + } + + return KmlTour; +}); diff --git a/pool/shard001/JavaScript/0010220_validateEquals.spec.js b/pool/shard001/JavaScript/0010220_validateEquals.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..082fae6941e345c58b878d7524de27ff483a043e --- /dev/null +++ b/pool/shard001/JavaScript/0010220_validateEquals.spec.js @@ -0,0 +1,49 @@ +describe('validateEquals directive', function() { + var $scope, form; + + function setTestValue(value) { + $scope.model.testValue = value; + $scope.$digest(); + } + function setCompareTo(value) { + $scope.model.compareTo = value; + $scope.$digest(); + } + + beforeEach(module('users-edit-validateEquals')); + + beforeEach(inject(function($compile, $rootScope) { + $scope = $rootScope; + var element = angular.element( + '
' + ); + $scope.model = { + testValue: '', + compareTo: '' + }; + $compile(element)($scope); + $scope.$digest(); + form = $scope.form; + })); + + describe('model validity', function() { + it('should be valid initially', function() { + expect(form.testInput.$valid).toBe(true); + }); + it('should be invalid if the model changes', function() { + setTestValue('different'); + expect(form.testInput.$valid).toBe(false); + }); + it('should be invalid if the reference model changes', function() { + setCompareTo('different'); + expect(form.testInput.$valid).toBe(false); + }); + it('should be valid if the model changes to be the same as the reference', function() { + setCompareTo('different'); + expect(form.testInput.$valid).toBe(false); + + setTestValue('different'); + expect(form.testInput.$valid).toBe(true); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010227_decorator.js b/pool/shard001/JavaScript/0010227_decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..55d34faeddfd4e008ca6a710d50d5d67bf8ce708 --- /dev/null +++ b/pool/shard001/JavaScript/0010227_decorator.js @@ -0,0 +1,86 @@ +/* decorator.js */ +define ([ + '1401/objects/behaviors/nodes/base' +], function ( + BaseNode +) { + + var DBGOUT = true; + +/** Decorator ***************************************************************\ + + This is the base Decorator node. Extend it as follows: + + function MyDecorator ( parms ) { + // call parent constructor + BehaviorFactory.Decorator.call( this, parms ); + ... + } + // set up inheritance + MyDecorator.inheritsFrom( BehaviorFactory.Decorator ); + // define or override new methods + MyDecorator.method('Open',function(){...}); + + IMPORTANT! Using 'this' instance properties is unsafe if a Node gets + reused. Store agent state in the Blackboard using the following methods: + + BBGet( pish, key ) + BBSet( pish, key, value ) + + A 'pish' is an object with id and ai properties, not necessarily a piece, + but is "piecelike" as far as the behavior tree is concerned. + + +/** OBJECT DECLARATION ******************************************************/ + + /* constructor */ + function Decorator ( child, read_only_conf ) { + // call the parent constructor + BaseNode.call (this); + // save the child node + this.children.push(child); + // save configuration if any + this.SaveConfig(read_only_conf); + + // each node has a name + this.node_type = BaseNode.TYPE.Decorator; + this.AutoName(); + } + /*/ inheritance /*/ + Decorator.inheritsFrom(BaseNode); + +/// 'methods' /////////////////////////////////////////////////////////////// + + /* avoid heap-allocation with reusable variables */ + /* values are not persistent; must refresh every tick! */ + var blackboard; // scratch memory for AI in piece + var status, i; // running state of piece-ish + var child; // child holder + var out; // output holder + +/// see basenode.js for overrideable methods! +/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +/*/ call periodically if RUNNING until return SUCCESS, FAILURE +/*/ Decorator.method('Tick', function ( pish, int_ms ) { + // execute every tick, must return status + // console.log(this.name,"tick",pish.name.bracket()); + child = this.children[0]; + status = child.Execute( pish, int_ms ); + // do something with the status before returning it + return status; + }); + +/////////////////////////////////////////////////////////////////////////////// +/** BEHAVIOR PRIVATE FUNCTIONS ***********************************************/ + + // Functions should receive entire state in parameters, as stored values + // in the object instances are not persistent because the same behavior + // tree's nodes can be used across multiple agents. The blackboard is + // what provides persistent memory + + +/** RETURN CONSTRUCTOR *******************************************************/ + + return Decorator; + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010233_mailchimp_ver.js b/pool/shard001/JavaScript/0010233_mailchimp_ver.js new file mode 100644 index 0000000000000000000000000000000000000000..d1ac934922ebd036d4f4753dbe062d66ce07bb3d --- /dev/null +++ b/pool/shard001/JavaScript/0010233_mailchimp_ver.js @@ -0,0 +1,69 @@ +/* --------------------------------------- + Signup Form - Verification Functions +------------------------------------------*/ + +$("#mce-EMAIL").on("focusout", function() { + var email = this.value; + if(email.length > 0) { + if(isValidEmailAddress(email)) { + $('#email-fdbk').text(); // Clear feedback + $("#mce-EMAIL ~ div").toggleClass("inputFeedback", false); // Hide errors + $("#mce-EMAIL").toggleClass("unverifiedInput", false); // Hide unverified (red) input styling + $("#mce-EMAIL").toggleClass("verifiedInput", true); // Show verified (green) input styling + } + else { + $('#email-fdbk').text("Invalid email address"); // Feedback + $("#mce-EMAIL ~ div").toggleClass("inputFeedback", true); // Show errors + $("#mce-EMAIL").toggleClass("verifiedInput", false); // Hide verified (green) input styling + $("#mce-EMAIL").toggleClass("unverifiedInput", true); // Show unverified (red) input styling + } + } +}); + +$("#mce-FNAME").on("focusout", function() { + if(this.value.length > 0) { + $('#fname-fdbk').text(); // Clear Feedback + $("#mce-FNAME ~ div").toggleClass("inputFeedback", false); // Hide errors + $("#mce-FNAME").toggleClass("unverifiedInput", false); // Hide unverified (red) input styling + $("#mce-FNAME").toggleClass("verifiedInput", true); // Show verified (green) input styling + } + else { + $('#fname-fdbk').text("First name required"); // Feedback + $("#mce-FNAME ~ div").toggleClass("inputFeedback", true); // Show errors + $("#mce-FNAME").toggleClass("verifiedInput", false); // Hide verified (green) input styling + $("#mce-FNAME").toggleClass("unverifiedInput", true); // Show unverified (red) input styling + } +}); + +$("#mce-LNAME").on("focusout", function() { + if(this.value.length > 0) { + $('#lname-fdbk').text(); // Clear Feedback + $("#mce-LNAME ~ div").toggleClass("inputFeedback", false); // Hide errors + $("#mce-LNAME").toggleClass("unverifiedInput", false); // Hide unverified (red) input styling + $("#mce-LNAME").toggleClass("verifiedInput", true); // Show verified (green) input styling + } + else { + $('#lname-fdbk').text("Last name required"); // Feedback + $("#mce-LNAME ~ div").toggleClass("inputFeedback", true); // Show errors + $("#mce-LNAME").toggleClass("verifiedInput", false); // Hide verified (green) input styling + $("#mce-LNAME").toggleClass("unverifiedInput", true); // Show unverified (red) input styling + } +}); + +function isValidEmailAddress(email) { + var emailReg = new RegExp(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i); + return emailReg.test(email); +} + +function isValidName(e) { + if(e.value.length > 0) { + $(e).toggleClass("unverifiedInput", false); // Hide unverified (red) input styling + $(e).toggleClass("verifiedInput", true); // Show verified (green) input styling + return true; + } + else { + $(e).toggleClass("verifiedInput", false); // Hide verified (green) input styling + $(e).toggleClass("unverifiedInput", true); // Show unverified (red) input styling + return false; + } +} diff --git a/pool/shard001/JavaScript/0010235_acorn.js b/pool/shard001/JavaScript/0010235_acorn.js new file mode 100644 index 0000000000000000000000000000000000000000..b24018f24f0573ced2c76e22a3fe348fcc49a436 --- /dev/null +++ b/pool/shard001/JavaScript/0010235_acorn.js @@ -0,0 +1,35 @@ +"use strict"; + +// This module is suitable for passing as options.parser when calling +// recast.parse to process JavaScript code with Acorn: +// +// const ast = recast.parse(source, { +// parser: require("recast/parsers/acorn") +// }); +// +const getOption = require("../lib/util.js").getOption; + +exports.parse = function parse(source, options) { + const comments = []; + const tokens = []; + const ast = require("acorn").parse(source, { + allowHashBang: true, + allowImportExportEverywhere: true, + allowReturnOutsideFunction: true, + ecmaVersion: getOption(options, "ecmaVersion", 8), + sourceType: getOption(options, "sourceType", "module"), + locations: true, + onComment: comments, + onToken: tokens, + }); + + if (! ast.comments) { + ast.comments = comments; + } + + if (! ast.tokens) { + ast.tokens = tokens; + } + + return ast; +}; diff --git a/pool/shard001/JavaScript/0010236_index.js b/pool/shard001/JavaScript/0010236_index.js new file mode 100644 index 0000000000000000000000000000000000000000..bcc1fbe29e0390f2542940419aa57a3bc4bae000 --- /dev/null +++ b/pool/shard001/JavaScript/0010236_index.js @@ -0,0 +1,37 @@ +/* eslint-env node */ +'use strict'; + +var path = require('path'); +var stew = require('broccoli-stew'); + +module.exports = { + name: 'ember-cli-filter-by-query', + + init: function() { + this._super.init && this._super.init.apply(this, arguments); + + var bowerDeps = this.project.bowerDependencies(); + if (bowerDeps['sifter']) {this.ui.writeWarnLine('Please remove `sifter` from `bower.json`. As of ember-cli-filter-by-query 1.3.0, only the NPM package is needed.');} + }, + + treeForVendor: function() { + var sifter = stew.find(path.dirname(require.resolve('sifter')), { + destDir: 'sifter', + files: ['sifter.js'] + }); + + return stew.find([ + sifter + ]); + }, + + included(app) { + this._super.included.apply(this, arguments); + + app.import('vendor/sifter/sifter.js', { + using: [ + { transformation: 'amd', as: 'sifter' } + ] + }); + } +}; diff --git a/pool/shard001/JavaScript/0010240_index.test.js b/pool/shard001/JavaScript/0010240_index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..471fcc9aa219d7a9f27d68843b86fdfaf72546ae --- /dev/null +++ b/pool/shard001/JavaScript/0010240_index.test.js @@ -0,0 +1,185 @@ +'use strict'; + +var path = require('path'); +var fs = require('fs'); +var expect = require('chai').expect; +var BroccoliCachingWriter = require('broccoli-caching-writer'); +var broccoli = require('broccoli'); +var cheerio = require('cheerio'); + +var SvgProcessor = require('..'); +var SOURCE_DIR_GROUP_1 = path.normalize('test/fixtures/input/group-1'); +var SOURCE_DIR_GROUP_2 = path.normalize('test/fixtures/input/group-2'); +var SOURCE_DIR_SVGSTORE_OPTS = path.normalize('test/fixtures/input/standalone-svgs/svgstore-opts'); + +var OUTPUT_FILE = path.normalize('test/fixtures/output/test-symbols.html'); +var ANNOTATION = 'testing processor'; + +var DEFAULT_OPTS = { + annotation: ANNOTATION, + outputFile: OUTPUT_FILE +}; + +// KEY ids on their unique source file paths +var ID_MANIFEST = {}; +ID_MANIFEST[SOURCE_DIR_GROUP_1] = ['icon-circles', 'icon-triangle', 'icon-star', 'icon-spark']; +ID_MANIFEST[SOURCE_DIR_GROUP_2] = ['icon-square', 'icon-smiley', 'icon-movie-ticket']; +ID_MANIFEST[SOURCE_DIR_SVGSTORE_OPTS] = ['svgstore-opts']; + +function makeBuilderFromInputNodes(inputNodes, options) { + var options = options || {}; + var svgProcessor = new SvgProcessor(inputNodes, { + outputFile: options.outputFile || OUTPUT_FILE, + annotation: options.annotation || 'SVGStore Processor -- Tests', + svgstoreOpts: options.svgstoreOpts || {}, + fileSettings: options.fileSettings || {} + }); + + return new broccoli.Builder(svgProcessor); +} + +function loadSVG(filePath) { + var fileContent = fs.readFileSync(filePath, { encoding: 'utf8' }); + return cheerio.load(fileContent, { xmlMode: true }); +} + +function testForSymbols($loadedSVG, expectedSymbolIds) { + // test proper structure + var $svg = $loadedSVG('svg'); + + var svgElem = $svg[0]; + expect(svgElem.name).to.equal('svg'); + expect(svgElem.type).to.equal('tag'); + + // test symbols (NOTE: this is cheerio's jQuery-style `filter`, so... idx and elem are backwards 😎) + var symbols = $svg.children().filter(function (idx, elem) { + return elem.name && elem.name === 'symbol'; + }); + + expect(symbols.length).to.equal(expectedSymbolIds.length); + + expectedSymbolIds.forEach(function (id, idx) { + var $symbol = $loadedSVG('svg #' + id).first(); + expect($symbol[0].tagName).to.equal('symbol'); + expect($symbol.attr('id')).to.equal(id); + }); +} + + +var svgProcessor, builder; + +describe('SVGProcessor', function () { + + afterEach(function() { + if (builder) { + return builder.cleanup(); + } + }); + + describe('construction', function() { + + it('extends `broccoli-caching-writer`', function() { + svgProcessor = new SvgProcessor([SOURCE_DIR_GROUP_1], DEFAULT_OPTS); + expect(svgProcessor).to.be.an.instanceof(BroccoliCachingWriter); + }); + + it('throws on falsey `inputNodes`', function () { + function TestProcessor(inputNodes, options) { + options = options || DEFAULT_OPTS; + SvgProcessor.call(this, inputNodes, options); + } + TestProcessor.prototype = Object.create(SvgProcessor.prototype); + TestProcessor.prototype.constructor = TestProcessor; + TestProcessor.prototype.build = function() {}; + + var errorMsgPrefix = 'TestProcessor (' + ANNOTATION + '): Expected a non-falsey argument for `_inputNode`, got '; + + expect(function() { + new TestProcessor(); + }).to.throw(TypeError, errorMsgPrefix + 'undefined'); + + expect(function() { + new TestProcessor(null); + }).to.throw(TypeError, errorMsgPrefix + 'null'); + + expect(function() { + new TestProcessor(undefined); + }).to.throw(TypeError, errorMsgPrefix + 'undefined'); + + expect(function() { + new TestProcessor(false); + }).to.throw(TypeError, errorMsgPrefix + 'false'); + }); + }); + + + describe('build', function() { + + it('writes all SVGs in a single directory to the target outputFile', function() { + var inputNodes = [SOURCE_DIR_GROUP_1]; + builder = makeBuilderFromInputNodes(inputNodes); + + return builder.build().then(function(results) { + var outputDestination = path.join(results.directory, path.normalize(OUTPUT_FILE)); + + testForSymbols(loadSVG(outputDestination), ID_MANIFEST[SOURCE_DIR_GROUP_1]); + }); + }); + + it('writes all SVGs from a list of directories to the target outputFile', function() { + var inputNodes = [SOURCE_DIR_GROUP_1, SOURCE_DIR_GROUP_2]; + builder = makeBuilderFromInputNodes(inputNodes); + + return builder.build().then(function(results) { + var outputDestination = path.join(results.directory, path.normalize(OUTPUT_FILE)); + var symbolIds = ID_MANIFEST[SOURCE_DIR_GROUP_1].concat(ID_MANIFEST[SOURCE_DIR_GROUP_2]); + + testForSymbols(loadSVG(outputDestination), symbolIds); + }); + }); + + it('passes options to SVGStore', function() { + var inputNode = SOURCE_DIR_SVGSTORE_OPTS; + var svgstoreOpts = { + svgAttrs: { 'x-custom-svg-attr': 'red' }, + symbolAttrs: { 'x-custom-symbol-attr': 'blue' }, + copyAttrs: ['x-copied-symbol-attr'] + }; + + builder = makeBuilderFromInputNodes(inputNode, { svgstoreOpts: svgstoreOpts }); + + return builder.build().then(function (results) { + var outputDestination = path.join(results.directory, path.normalize(OUTPUT_FILE)); + var symbolId = ID_MANIFEST[SOURCE_DIR_SVGSTORE_OPTS]; + + var $ = loadSVG(outputDestination); + testForSymbols($, symbolId); + + expect($('svg').attr('x-custom-svg-attr')).to.equal(svgstoreOpts.svgAttrs['x-custom-svg-attr']); + expect($('symbol').attr('x-custom-symbol-attr')).to.equal(svgstoreOpts.symbolAttrs['x-custom-symbol-attr']); + expect($('symbol').attr('x-copied-symbol-attr')).to.equal(svgstoreOpts.copyAttrs['x-copied-symbol-attr']); + }); + }); + + it('enables per-file configuration via a `fileSettings` hash', function() { + var inputNodes = [SOURCE_DIR_GROUP_1]; + var customIDs = ['customID-1', 'customID-2', 'customID-3']; + var fileSettings = { + [ID_MANIFEST[SOURCE_DIR_GROUP_1][0]]: { id: customIDs[0] }, + [ID_MANIFEST[SOURCE_DIR_GROUP_1][1]]: { id: customIDs[1] }, + [ID_MANIFEST[SOURCE_DIR_GROUP_1][2]]: { id: customIDs[2] } + }; + + builder = makeBuilderFromInputNodes(inputNodes, { fileSettings }); + + return builder.build().then(function (results) { + var outputDestination = path.join(results.directory, path.normalize(OUTPUT_FILE)); + var symbolIds = customIDs.concat(ID_MANIFEST[SOURCE_DIR_GROUP_1][3]); + + var $ = loadSVG(outputDestination); + testForSymbols($, symbolIds); + }); + }); + }); +}); + diff --git a/pool/shard001/JavaScript/0010243_redis.test.js b/pool/shard001/JavaScript/0010243_redis.test.js new file mode 100644 index 0000000000000000000000000000000000000000..08278fe2ced222ea45aaf07916939cb299f67e95 --- /dev/null +++ b/pool/shard001/JavaScript/0010243_redis.test.js @@ -0,0 +1,86 @@ +'use strict'; + +var assert = require('assert') + , should = require('should') + , redisService = require('./redis'); + +describe('Test redis session service:\n', function() { + var uuid = '110ec58a-a0f2-4ac4-8393-c866d813b8d1'; + var email = 'mary@demo.org'; + var token_id = 'f2cb3e8d653f46008272113c6c72422843902ef8'; + + beforeEach(function(done) { + var record = [token_id, 'email', email, 'role', 1]; + redisService.save(token_id, record, function(err, reply){ + //console.log(reply.toString()); + done(); + }); + }); + + afterEach(function(done){ + redisService.remove(token_id, function(err, reply){ + //console.log(reply.toString()); + done(); + }); + }); + + describe('Test save a token', function() { + var uuid1 = '110ec58a-a0f2-4ac4-8393-c866d813b8d1'; + var email1 = 'wendy@abc.com'; + var token_id1 = '8843d7f92416211de9ebb963ff4ce28125932878'; + var record1 = [token_id1, 'email', email1, 'role', 2]; + + it('should be able to query sub keys', function() { + redisService.save(token_id1, record1, function(err, reply){ + should.not.exist(err); +// console.log(reply.toString()); + }); + + var query = [token_id1, 'email']; + redisService.hget(query, function(err, reply){ + //console.log('look up sub key =' + reply.toString()); + should.not.exist(err); + reply.should.equal('wendy@abc.com'); + }); + + redisService.remove(token_id1, function(err, reply){ + should.not.exist(err); +// console.log(reply.toString()); + }); + }); + }); + + describe('Test look up subkey if key does not exists', function() { + it('should not be able to find a sub key if key does not exists', function(done) { + var query = ['dummykey', 'email']; + redisService.hget(query, function(err, reply){ + should.not.exist(err); + //console.log('reply is->' + reply); + //reply.should.equal(1); + done(); + + }); + }); + }); + + describe('Test check if key in hash value', function() { + it('should be able to find a existing key', function(done) { + redisService.exists(token_id, function(err, reply){ + should.not.exist(err); + reply.should.equal(1); + done(); + //console.log('reply is->' + reply.toString()); + }); + }); + }); + + describe('Test number of subkeys', function() { + it('should be able to get total number of subkeys', function(done) { + redisService.subkeys(token_id, function(err, reply){ + should.not.exist(err); + reply.should.have.lengthOf(2); + done(); + }); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010246_document_info.js b/pool/shard001/JavaScript/0010246_document_info.js new file mode 100644 index 0000000000000000000000000000000000000000..d763b38d911aee1b5e3e98ce686b02a3d38a798e --- /dev/null +++ b/pool/shard001/JavaScript/0010246_document_info.js @@ -0,0 +1,203 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('print_preview', function() { + 'use strict'; + + /** + * Data model which contains information related to the document to print. + * @constructor + * @extends {cr.EventTarget} + */ + function DocumentInfo() { + cr.EventTarget.call(this); + + /** + * Whether the document is styled by CSS media styles. + * @type {boolean} + * @private + */ + this.hasCssMediaStyles_ = false; + + /** + * Whether the document has selected content. + * @type {boolean} + * @private + */ + this.hasSelection_ = false; + + /** + * Whether the document to print is modifiable (i.e. can be reflowed). + * @type {boolean} + * @private + */ + this.isModifiable_ = true; + + /** + * Margins of the document in points. + * @type {print_preview.Margins} + * @private + */ + this.margins_ = null; + + /** + * Number of pages in the document to print. + * @type {number} + * @private + */ + this.pageCount_ = 0; + + // Create the document info with some initial settings. Actual + // page-related information won't be set until preview generation occurs, + // so we'll use some defaults until then. This way, the print ticket store + // will be valid even if no preview can be generated. + var initialPageSize = new print_preview.Size(612, 792); // 8.5"x11" + + /** + * Size of the pages of the document in points. + * @type {!print_preview.Size} + * @private + */ + this.pageSize_ = initialPageSize; + + /** + * Printable area of the document in points. + * @type {!print_preview.PrintableArea} + * @private + */ + this.printableArea_ = new print_preview.PrintableArea( + new print_preview.Coordinate2d(0, 0), initialPageSize); + + /** + * Title of document. + * @type {string} + * @private + */ + this.title_ = ''; + + /** + * Whether this data model has been initialized. + * @type {boolean} + * @private + */ + this.isInitialized_ = false; + }; + + /** + * Event types dispatched by this data model. + * @enum {string} + */ + DocumentInfo.EventType = { + CHANGE: 'print_preview.DocumentInfo.CHANGE' + }; + + DocumentInfo.prototype = { + __proto__: cr.EventTarget.prototype, + + /** @return {boolean} Whether the document is styled by CSS media styles. */ + get hasCssMediaStyles() { + return this.hasCssMediaStyles_; + }, + + /** @return {boolean} Whether the document has selected content. */ + get hasSelection() { + return this.hasSelection_; + }, + + /** + * @return {boolean} Whether the document to print is modifiable (i.e. can + * be reflowed). + */ + get isModifiable() { + return this.isModifiable_; + }, + + /** @return {print_preview.Margins} Margins of the document in points. */ + get margins() { + return this.margins_; + }, + + /** @return {number} Number of pages in the document to print. */ + get pageCount() { + return this.pageCount_; + }, + + /** + * @return {!print_preview.Size} Size of the pages of the document in + * points. + */ + get pageSize() { + return this.pageSize_; + }, + + /** + * @return {!print_preview.PrintableArea} Printable area of the document in + * points. + */ + get printableArea() { + return this.printableArea_; + }, + + /** @return {string} Title of document. */ + get title() { + return this.title_; + }, + + /** + * Initializes the state of the data model and dispatches a CHANGE event. + * @param {boolean} isModifiable Whether the document is modifiable. + * @param {string} title Title of the document. + * @param {boolean} hasSelection Whether the document has user-selected + * content. + */ + init: function(isModifiable, title, hasSelection) { + this.isModifiable_ = isModifiable; + this.title_ = title; + this.hasSelection_ = hasSelection; + this.isInitialized_ = true; + }, + + /** + * Updates the total number of pages in the document and dispatches a CHANGE + * event. + * @param {number} pageCount Number of pages in the document. + */ + updatePageCount: function(pageCount) { + if (this.isInitialized_ && this.pageCount_ != pageCount) { + this.pageCount_ = pageCount; + cr.dispatchSimpleEvent(this, DocumentInfo.EventType.CHANGE); + } + }, + + /** + * Updates information about each page and dispatches a CHANGE event. + * @param {!print_preview.PrintableArea} printableArea Printable area of the + * document in points. + * @param {!print_preview.Size} pageSize Size of the pages of the document + * in points. + * @param {boolean} hasCssMediaStyles Whether the document is styled by CSS + * media styles. + * @param {print_preview.Margins} margins Margins of the document in points. + */ + updatePageInfo: function( + printableArea, pageSize, hasCssMediaStyles, margins) { + if (this.isInitialized_ && + (!this.printableArea_.equals(printableArea) || + !this.pageSize_.equals(pageSize) || + this.hasCssMediaStyles_ != hasCssMediaStyles || + this.margins_ == null || !this.margins_.equals(margins))) { + this.printableArea_ = printableArea; + this.pageSize_ = pageSize; + this.hasCssMediaStyles_ = hasCssMediaStyles; + this.margins_ = margins; + cr.dispatchSimpleEvent(this, DocumentInfo.EventType.CHANGE); + } + } + }; + + // Export + return { + DocumentInfo: DocumentInfo + }; +}); diff --git a/pool/shard001/JavaScript/0010251_2d.shadow.gradient.basic.worker.js b/pool/shard001/JavaScript/0010251_2d.shadow.gradient.basic.worker.js new file mode 100644 index 0000000000000000000000000000000000000000..800fc3153561bdf49c8ccb6da5e911388142c9ba --- /dev/null +++ b/pool/shard001/JavaScript/0010251_2d.shadow.gradient.basic.worker.js @@ -0,0 +1,32 @@ +// DO NOT EDIT! This test has been generated by tools/gentest.py. +// OffscreenCanvas test in a worker:2d.shadow.gradient.basic +// Description:Shadows are drawn for gradient fills +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/2dcontext/resources/canvas-tests.js"); + +var t = async_test("Shadows are drawn for gradient fills"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +var gradient = ctx.createLinearGradient(0, 0, 100, 0); +gradient.addColorStop(0, '#f00'); +gradient.addColorStop(1, '#f00'); +ctx.fillStyle = '#f00'; +ctx.fillRect(0, 0, 100, 50); +ctx.shadowColor = '#0f0'; +ctx.shadowOffsetY = 50; +ctx.fillStyle = gradient; +ctx.fillRect(0, -50, 100, 50); +_assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255"); +t.done(); + +}); +done(); diff --git a/pool/shard001/JavaScript/0010252_setup-jsdom.js b/pool/shard001/JavaScript/0010252_setup-jsdom.js new file mode 100644 index 0000000000000000000000000000000000000000..f6c474684b0eea73f6b6ff55848d3eedfa5fc3e4 --- /dev/null +++ b/pool/shard001/JavaScript/0010252_setup-jsdom.js @@ -0,0 +1,19 @@ +var jsdom = require("jsdom"); + +// Setup the jsdom environment +// @see https://github.com/facebook/react/issues/5046 +global.document = jsdom.jsdom(` + +`); +global.window = document.defaultView; +global.navigator = global.window.navigator; + +global.document.documentElement.style.getPropertyValue = function(property) { + if (property.indexOf('--') === 0) { + const actualProperty = property.charAt(2).toUpperCase() + property.slice(3); + + return global.document.documentElement.style[actualProperty]; + } + + return global.document.documentElement.style.getPropertyValue(property); +} diff --git a/pool/shard001/JavaScript/0010259_CircleEntity.spec.js b/pool/shard001/JavaScript/0010259_CircleEntity.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..32aa24ae3507e32d361f909ad8dc1e25f1cdd457 --- /dev/null +++ b/pool/shard001/JavaScript/0010259_CircleEntity.spec.js @@ -0,0 +1,49 @@ +describe('CircleEntity', function() { + + it('exists', function() { + expect(CircleEntity).toBeDefined(); + }); + + it('is an Entity', function() { + expect(CircleEntity.prototype instanceof Entity).toBe(true); + }); + + it('has a circle bounds', function() { + expect(CircleEntity.prototype).toEqual(jasmine.objectContaining(CircleBounds.prototype)); + }); + + describe('default constructor', function() { + var e; + + it('does not throw an error', function() { + expect(function () { + e = new CircleEntity(); + }).not.toThrow(); + }); + + it('has correct default properties', function() { + expect(e.radius).toBe(0.5); + }); + }); + + describe('constructor', function() { + + it('accepts a configuration of all configurable properties', function() { + + var config = { + type: Entity.STATIC, + x: 1, + y: 2, + vx: 3, + vy: 4, + ax: 5, + ay: 6, + restitution: 0.5, + friction: 0.6, + radius: 42 + }; + + expect(new CircleEntity(config)).toEqual(jasmine.objectContaining(config)); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010260_contextMenus.js b/pool/shard001/JavaScript/0010260_contextMenus.js new file mode 100644 index 0000000000000000000000000000000000000000..493e5e8805d6cac6a5d72bad4c8610cc3c8f01b4 --- /dev/null +++ b/pool/shard001/JavaScript/0010260_contextMenus.js @@ -0,0 +1,18 @@ +const extensionActions = require('../../common/actions/extensionActions') + +const contextMenus = { + init: () => { + process.on('chrome-context-menus-remove-all', (extensionId) => { + setImmediate(() => { + extensionActions.contextMenuAllRemoved(extensionId) + }) + }) + process.on('chrome-context-menus-create', (extensionId, menuItemId, properties, icon) => { + setImmediate(() => { + extensionActions.contextMenuCreated(extensionId, menuItemId, properties, icon) + }) + }) + } +} + +module.exports = contextMenus diff --git a/pool/shard001/JavaScript/0010269_proyectos.js b/pool/shard001/JavaScript/0010269_proyectos.js new file mode 100644 index 0000000000000000000000000000000000000000..c7a0977c1bf93fdf030da29718f796a4cd4a1f20 --- /dev/null +++ b/pool/shard001/JavaScript/0010269_proyectos.js @@ -0,0 +1,176 @@ +// Initialize Firebase +// Initialize Firebase +var config = { + apiKey: "AIzaSyByyIfhuIL9e0tvhwUqkGCWKcGBTGGBLO0", + authDomain: "prueba-urgente.firebaseapp.com", + databaseURL: "https://prueba-urgente.firebaseio.com", + storageBucket: "prueba-urgente.appspot.com", + messagingSenderId: "483313675253" + }; + +/* +var config = { + apiKey: "AIzaSyByyIfhuIL9e0tvhwUqkGCWKcGBTGGBLO0", + authDomain: "prueba-urgente.firebaseapp.com", + databaseURL: "https://prueba-urgente.firebaseio.com", + storageBucket: "prueba-urgente.appspot.com", + messagingSenderId: "483313675253" + }; +*/ + +/* +var config = { + apiKey: "AIzaSyBxrNMp2TQU8y72jkRRGLSdJq2-2N3jNRw", + authDomain: "prueba-proyecto-39eb7.firebaseapp.com", + databaseURL: "https://prueba-proyecto-39eb7.firebaseio.com", + storageBucket: "prueba-proyecto-39eb7.appspot.com", + messagingSenderId: "356288809556" +}; +*/ + +firebase.initializeApp(config); + + //ON LOGIN OR LOGOUT ======================================================================================== + firebase.auth().onAuthStateChanged(function(user) { + if (user) + { + var tipos = []; + console.log('user'); + var proyectos = $("#proyectos"); + var userId = firebase.auth().currentUser.uid; + firebase.database().ref("/alumnos/" + userId + "/").once('value').then(function(snapshot) { + var username = snapshot.val().Nombre; + $("#nomAlumno").text(username); + }); + firebase.database().ref("/userProyectos/"+userId + "/").once('value').then(function(snapshot) { + snapshot.forEach(function(childSnapshot) { + firebase.database().ref("/proyectos/"+childSnapshot.val()+"/").once('value').then(function(snap){ + tipos.push(snap.val().Tipo); + $("#proyectos").html( $("#proyectos").html() + '
' + + '
'+ + '

'+ snap.val().Nombre +' - ' + //childSnapshot.val().Empresa + + '

'+ + '
' + + '
'+ + '

'+ + '

Descripción:

' + snap.val().Descripcion + + '
Perfil Buscado:

' + snap.val().Perfil + + '
Área De trabajo:

' + snap.val().Area + + '

'+ + '
'+ + '
'+ + '
'+ + 'Vacantes: ' + snap.val().Vacantes+ + ' Sueldo: $' + snap.val().Sueldo+ + '
'+ + '
'+ + 'Dirección: ' + snap.val().Direccion+ + '
'+ + '
'+ + '
'); + + var tipo = tipos.join(';') + var caso = ""; + if(tipo.indexOf("Financiero") != -1) + { + caso = "Financiero"; + } + else if(tipo.indexOf("Estratégico") != -1) + { + caso = "Estratégico"; + } + else + { + caso = "Ingenieril" + } + $("#CASO").text("Tipo de Caso - "+ caso); + if(caso != "Ingenieril") + { + $("#OFICINA").text("Pasa el 30 de Marzo a la oficina de Ana Maria Diaz Bonnet por tu caso, haz concluido la primer etapa."); + } + else + { + $("#OFICINA").text("Pasa el 30 de Marzo a la oficina de Ana Lidia Franzoni por tu caso, haz concluido la primer etapa."); + } + }); + }); + + + + + }).then(function(){ + var tipo = tipos.join(';') + var caso = ""; + if(tipo.indexOf("Financiero") != -1) + { + caso = "Financiero"; + } + else if(tipo.indexOf("Estratégico") != -1) + { + caso = "Estratégico"; + } + else + { + caso = "Ingenieril" + } + + if(caso != "Ingenieril") + { + $("#proyectos").html( $("#proyectos").html() + '
' + + '
'+ + '

Tipo de Caso - ' + caso + + '

'+ + '
' + + '
'+ + '

'+ + '

Dirigete a la oficina Contaduría por tu caso
'+ + '

'+ + '
'+ + '
'+ + '
'+ + '
' + ); + } + else + { + $("#proyectos").html( $("#proyectos").html() + '
' + + '
'+ + '

Tipo de Caso - ' + caso + + '

'+ + '
' + + '
'+ + '

'+ + '

Dirigete a la oficina Ingenería en Computación por tu caso
'+ + '

'+ + '
'+ + '
'+ + '
'+ + '
' + ); + } + }); + + + + } + else + { + //window.location.href = ("http://practicasdeverano.itam.mx/"); + window.location.href = ("../index.html"); + + } + }); + +$(document).ready(function(){ + //lOG OUT PROCESS ========================================================================= + $("#btnLogOut").click(function(){ + firebase.auth().signOut() + .then(function(){ + //window.location.href = ("http://practicasdeverano.itam.mx/"); + window.location.href = ("../index.html"); + },function(error){ + console.log(error.errorMessage); + }); + }); + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010270_search_bar.js b/pool/shard001/JavaScript/0010270_search_bar.js new file mode 100644 index 0000000000000000000000000000000000000000..1ad4ee787eebe202601411ee7bc8ff574c60aa9a --- /dev/null +++ b/pool/shard001/JavaScript/0010270_search_bar.js @@ -0,0 +1,47 @@ +import React, {Component} from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; +import { fetchWeather } from '../actions/index'; + +class SearchBar extends Component { + constructor(props){ + super(props); + this.state = {term:''}; + //if youve got a callback that makes a reference to 'this' + //you need to bind it + this.onInputChange = this.onInputChange.bind(this);//bind the context to this Component + this.onFormSubmit = this.onFormSubmit.bind(this);//bind the context to this Component + + } + onInputChange(event){ + this.setState({term: event.target.value}) + } + onFormSubmit(event){ + event.preventDefault(); //stop auto submit when a button clicked or enter is hit on keyboard + this.props.fetchWeather(this.state.term); + this.setState({term:''}); + + //we need to go a fetch weather data here + // + } + render() { + return ( +
+ + + + +
+ ) + } +} + +function mapDispatchToProps(dispatch){ + return bindActionCreators({fetchWeather},dispatch) +} +export default connect(null, mapDispatchToProps)(SearchBar) diff --git a/pool/shard001/JavaScript/0010273_acquia_lift.utility.queue.js b/pool/shard001/JavaScript/0010273_acquia_lift.utility.queue.js new file mode 100644 index 0000000000000000000000000000000000000000..f5462414162e4066f7167cf5275d1391449e933e --- /dev/null +++ b/pool/shard001/JavaScript/0010273_acquia_lift.utility.queue.js @@ -0,0 +1,353 @@ +/** + * Utility functions for stateless queue cookie processing. + * + * Functionality includes basic read/write functionality. + */ +(function ($, Drupal) { + "use strict"; + + Drupal.acquiaLiftUtility = Drupal.acquiaLiftUtility || {}; + + Drupal.acquiaLiftUtility.QueueItem = function (params) { + var queueItemUid, + queueItemData, + queueItemProcessing = false, + numberTried = 0; + + /** + * Returns the unique ID assigned to this queue item. + */ + this.getId = function () { + return queueItemUid; + }; + + /** + * Sets the unique ID assigned to this queue item. + */ + this.setId = function (value) { + queueItemUid = value; + } + + /** + * Returns the data that is held by this queue item. + */ + this.getData = function () { + return queueItemData; + }; + + /** + * Setter for the data held by this queue item. + */ + this.setData = function (value) { + queueItemData = value; + } +; + /** + * Determines if this queue item is currently processing. + */ + this.isProcessing = function () { + return queueItemProcessing; + }; + + /** + * Setter for the processing flag for this queue item. + */ + this.setProcessing = function (isProcessing) { + queueItemProcessing = isProcessing; + }; + + /** + * Gets the number of times this item has been tried in the queue. + */ + this.getNumberTried = function () { + return numberTried; + }; + + /** + * Sets the number of times this item has been tried in the queue. + */ + this.setNumberTried = function (value) { + numberTried = value; + }; + + /** + * Increments the number of times this item has been tried. + */ + this.incrementTries = function () { + numberTried++; + }; + + // Constructor handling. + if (params.hasOwnProperty('id') + && params.hasOwnProperty('data') + && params.hasOwnProperty('pflag') + && params.hasOwnProperty('try')) { + this.setId(params.id); + this.setData(params.data); + this.setProcessing(params.pflag); + this.setNumberTried(params.try); + } else { + var uid = 'acquia-lift-ts-' + new Date().getTime() + Math.random(); + this.setId(uid); + this.setData(params); + this.setProcessing(false); + this.setNumberTried(0); + } + }; + + Drupal.acquiaLiftUtility.QueueItem.prototype = { + constructor: Drupal.acquiaLiftUtility.QueueItem, + + /** + * Determines if QueueItem is equal to the current QueueItem. + * + * @param queueItem + * The item to check against. + * @returns + * True if equal, false if unequal. + */ + 'equals': function (queueItem) { + return (queueItem instanceof Drupal.acquiaLiftUtility.QueueItem && queueItem.getId() == this.getId()); + }, + + /** + * Resets the processing flag on this queue item. + */ + 'reset': function() { + this.setProcessing(false); + }, + + /** + * Parses the QueueItem into a simple object. + */ + 'toObject': function () { + return { + 'id': this.getId(), + 'data': this.getData(), + 'pflag': this.isProcessing(), + 'try': this.getNumberTried() + }; + } + } + + Drupal.acquiaLiftUtility.Queue = Drupal.acquiaLiftUtility.Queue || (function($) { + // @todo: Would be cool if we could swap out back-ends to local storage or + // other mechanism. + + var cookieName = 'acquiaLiftQueue', maxRetries = 5; + + /** + * Indicates if the cookie handling script handles object serialization. + * This is not available in the jquery.cookie.js version that ships with + * Drupal 7 but some installations use a later version. + * + * @return boolean + * True if cookie handles serialization, false if data must be manually + * serialized before writing. + */ + function cookieHandlesSerialization() { + return ($.cookie.json && $.cookie.json == true); + } + + /** + * Reads the queue from storage. + * + * @returns array + * An array of QueueItems. + */ + function readQueue() { + var queue = $.cookie(cookieName); + var unserialized = cookieHandlesSerialization() ? queue : $.parseJSON(queue); + return $.isArray(unserialized) ? unserialized : []; + } + + /** + * Returns a fully-parsed queue. + */ + function getAll() { + var unserialized = readQueue(), i, num = unserialized.length, queue = []; + for (i = 0; i < num; i++) { + queue.push(new Drupal.acquiaLiftUtility.QueueItem(unserialized[i])); + } + return queue; + } + + /** + * Returns the first unprocessed QueueItem. + */ + function getFirstUnprocessed() { + var unserialized = readQueue(), i, num = unserialized.length, item; + for (i = 0; i < num; i++) { + item = new Drupal.acquiaLiftUtility.QueueItem(unserialized[i]); + if (!item.isProcessing()) { + return item; + } + } + return null; + } + + /** + * Find index of a QueueItem within the Queue. + * + * @param queue + * An instance of the queue to search. + * @param item + * The QueueItem to find within the queue. + * @return int + * The index of the item in the queue or -1 if not found. + */ + function indexOf(queue, item) { + var i, + num = queue.length, + test; + // Only initialize as many as we have to in order to find a match. + for (i = 0; i < num; i++) { + test = new Drupal.acquiaLiftUtility.QueueItem(queue[i]); + if (test.equals(item)) { + return i; + } + } + return -1; + } + + + /** + * Writes the queue to storage. + * + * @param array + * The queue as an array. + */ + function writeQueue(queue) { + var queueData = [], i, num = queue.length; + + // Prepare the queue by making sure all items to save are simple objects. + for (i = 0; i < num; i++) { + if (queue[i] instanceof Drupal.acquiaLiftUtility.QueueItem) { + queueData.push(queue[i].toObject()) + } else { + queueData.push(queue[i]); + } + } + // Serialize if necessary. + if (!cookieHandlesSerialization()) { + queueData = JSON.stringify(queueData); + } + // Write to the cookie. + $.cookie(cookieName, queueData); + } + + /** + * Adds an existing QueueItem back to the queue for re-processing. + * + * @param queueItem + * The item to add back into the queue. + * @param reset + * Boolean indicates if the processing flag should be reset, defaults + * false. + */ + function addBack(queueItem, reset) { + var queue = readQueue(); + var index = indexOf(queue, queueItem); + + if (reset && reset == true) { + queueItem.reset(); + queueItem.incrementTries(); + } + if (queueItem.getNumberTried() >= maxRetries) { + // This item is beyond the maximum number of tries and should be + // removed from the queue so don't add it back. + Drupal.acquiaLiftUtility.Queue.remove(queueItem); + return; + } + if (index >= 0) { + queue.splice(index, 1, queueItem); + } else { + queue.push(queueItem); + } + writeQueue(queue); + }; + + /** + * Publicly accessible queue methods. + */ + return { + /** + * Adds a QueueItem to the queue. + * + * The item can be new data to add, a new QueueItem to add, or an + * existing QueueItem to return to the queue for re-processing. + * + * @param data + * Data or a QueueItem to add to the queue. + * @param reset + * Indicates if the processing should be reset (defaults to true). + */ + 'add': function (data, reset) { + reset = reset == undefined ? true : reset; + + if (data instanceof Drupal.acquiaLiftUtility.QueueItem) { + addBack(data, reset); + return; + } + var queue = readQueue(); + queue.push(new Drupal.acquiaLiftUtility.QueueItem(data)); + writeQueue(queue); + }, + + /** + * Gets the next unprocessed item in the queue for processing. + * @returns a queueItem or null; + * The queueItem. + */ + 'getNext': function () { + var item = getFirstUnprocessed(); + if (item) { + item.setProcessing(true); + // Save the updated item back into the queue (will overwrite). + this.add(item, false); + } + return item; + }, + + /** + * Removes a queueItem from the processing queue. + * + * @param queueItem + * The item to remove. + * @returns + * True if the item was found to remove, false if not found. + */ + 'remove': function (queueItem) { + var queue = readQueue(); + var index = indexOf(queue, queueItem); + if (index >= 0) { + queue.splice(index, 1); + writeQueue(queue); + return true; + } + return false; + }, + + /** + * Resets the processing status on all items in the queue. + */ + 'reset': function () { + var i, + queue = getAll(), + num = queue.length; + for (i = 0; i < num; i++) { + queue[i].reset(); + } + writeQueue(queue); + }, + + /** + * Empties the queue of all options (typcially used for testing purposes). + */ + 'empty': function () { + writeQueue([]); + } + } + }($)); + +}(Drupal.jQuery, Drupal)); diff --git a/pool/shard001/JavaScript/0010276_app.js b/pool/shard001/JavaScript/0010276_app.js new file mode 100644 index 0000000000000000000000000000000000000000..83cb326f596cb089fb0b2fb0fba4c7c95c8ba0c9 --- /dev/null +++ b/pool/shard001/JavaScript/0010276_app.js @@ -0,0 +1,52 @@ +var config = require('./conf/config.js'); +var express = require('express'); +var path = require('path'); +var fs = require('fs'); +var moment = require('moment'); +// var favicon = require('express-favicon'); +// var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var useragent = require('express-useragent'); +var router_api = require('./routes/api'); +var login = require('./lib/login'); +var app = express(); + +app.set('port', process.env.PORT || 3000); +app.set('views', path.join(__dirname, 'templates')); +app.set('view engine', 'html'); +app.engine('html', require('hbs').__express); +app.use('/pub_res', express.static(path.join(__dirname, 'pub_res'))); +// app.use(favicon(path.join(__dirname, 'pub_res/favicon.ico'))); +// app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ + extended: false +})); +app.use(cookieParser()); +app.use(useragent.express());//User Agent解析,判断是否是手机,爬虫等 + +/*登录*/ +// app.use(function(req, res, next) { +// login.restrict(req, res, next); +// }); + +/*Router*/ +app.use('/', router_api); + +/* Server debug*/ +app.use(function(err, req, res, next) { + console.error(err.stack); + res.status(500).send('Something broke!'); +}); + +/*404 debug*/ +app.use(function(req, res, next) { + res.status(404).send('Sorry cant find that!'); +}); + +server = app.listen(app.get('port'), function() { + console.log('%s Listening on port %d', moment().format('YYYY-MM-DD HH:mm:ss'), server.address().port); +}); + +module.exports = app; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010280_ppaDropbox.js b/pool/shard001/JavaScript/0010280_ppaDropbox.js new file mode 100644 index 0000000000000000000000000000000000000000..eeee65d7e5299893769416191e00262ca77e8cda --- /dev/null +++ b/pool/shard001/JavaScript/0010280_ppaDropbox.js @@ -0,0 +1,26 @@ +angular.module('ppaComponents') + .directive('ppaDropbox', function() { + return { + restrict: 'E', + template: + '' + + '' + + '', + transclude: true, + scope: { + types: '@', + onDataDrop: '&' + }, + link: function(scope, iElement, iAttrs) { + var types = angular.fromJson(scope.types) || []; + // it assumes jqLite instead of jQuery + var appDropbox = angular.element(iElement.children()[0])[0]; + appDropbox.setAttribute('types', scope.types); + appDropbox.addEventListener('data-drop', function(event) { + scope.$apply(function() { + scope.onDataDrop({event: event}); + }); + }); + } + }; + }); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010281_edit.js b/pool/shard001/JavaScript/0010281_edit.js new file mode 100644 index 0000000000000000000000000000000000000000..4e974f2e9e5313e97b95753e7ade9c4751578cc6 --- /dev/null +++ b/pool/shard001/JavaScript/0010281_edit.js @@ -0,0 +1,26 @@ +import React from 'react'; +import { Container, Header, Divider } from 'semantic-ui-react'; +import Router from 'next/router'; +import App from '../../../components/AppContainer'; +import FormSpecification from '../../../components/admin/FormSpecificationContainer'; +import ButtonDeleteSpecification from '../../../components/admin/ButtonDeleteSpecificationContainer'; + +const updatedSuccessfully = () => { + alert('Pflichtenheft aktualisiert'); +}; + +const deletedSuccessfully = () => { + alert('Pflichtenheft gelöscht'); + return Router.replace({ pathname: '/admin/specifications' }); +}; + +export default ({ url, ...rest }) => ( + + +
Pflichtenheft editieren
+ + + +
+
+); diff --git a/pool/shard001/JavaScript/0010287_data-store.js b/pool/shard001/JavaScript/0010287_data-store.js new file mode 100644 index 0000000000000000000000000000000000000000..a31d80edf1764fd22132f70d4db73c2307f9ccfb --- /dev/null +++ b/pool/shard001/JavaScript/0010287_data-store.js @@ -0,0 +1,26 @@ +export default class DataStore{ + constructor(){ + this._data = this._init() || {} // we dont want data to be null or even undefined + } + + get(key){ + return this._data[key] + } + + getAll(){ + return this._data + } + + set(key, value){ + this._data[key] = value + } + + persist(data){ + this._data = data + this._persist(this._data) + } + + wipe() { + this._wipe() + } +} diff --git a/pool/shard001/JavaScript/0010290_errorHandler.js b/pool/shard001/JavaScript/0010290_errorHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..04d4698e901097cacf9c424c6a114f7c1dda7bd3 --- /dev/null +++ b/pool/shard001/JavaScript/0010290_errorHandler.js @@ -0,0 +1,38 @@ +'use strict'; + +// Dependencies: +var log = require('./logger'); +var util = require('gulp-util'); + +module.exports = createHandler; + +function createHandler (reportTaskDone) { + return function (error) { + if (error) { + var message = createMessage(error); + log.error(message); + if (reportTaskDone) { + reportTaskDone(new Error(message)); + } else if (util.env.dist) { + throw new Error(message); + } + } + }; +} + +function createMessage (error) { + var message = ''; + if (error.task) { + message += ' Task: ' + error.task; + } + if (error.err && error.err.plugin) { + message += ' Plugin: ' + error.err.plugin; + } + if (error.message) { + message += ' ' + error.message; + } + if (error.err && error.err.message) { + message += ' ' + error.err.message; + } + return message; +} diff --git a/pool/shard001/JavaScript/0010292_server.js b/pool/shard001/JavaScript/0010292_server.js new file mode 100644 index 0000000000000000000000000000000000000000..c0ee65c1b5e2a1180efede3b4066583dfe0fecd1 --- /dev/null +++ b/pool/shard001/JavaScript/0010292_server.js @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2011 Vinay Pulim + * MIT Licensed + */ + +function findKey(obj, val) { + for (var n in obj) if (obj[n] === val) return n; +} + +var url = require('url'), + compress = null; + +try { compress = require("compress"); } catch(e) {} + +var Server = function(server, path, services, wsdl) { + var self = this, + listeners = server.listeners('request'); + + this.services = services; + this.wsdl = wsdl; + + if (path[path.length-1] != '/') path += '/'; + wsdl.onReady(function(err) { + server.removeAllListeners('request'); + server.addListener('request', function(req, res) { + if (typeof self.authorizeConnection === 'function') { + if (!self.authorizeConnection(req.connection.remoteAddress)) { + res.end(); + return; + } + } + var reqPath = url.parse(req.url).pathname; + if (reqPath[reqPath.length-1] != '/') reqPath += '/'; + if (path === reqPath) { + self._requestListener(req, res); + } + else { + for (var i = 0, len = listeners.length; i < len; i++){ + listeners[i].call(this, req, res); + } + } + }); + }) +} + +Server.prototype._requestListener = function(req, res) { + var self = this; + if (req.method === 'GET') { + var search = url.parse(req.url).search; + if (search && search.toLowerCase() === '?wsdl') { + res.setHeader("Content-Type", "application/xml"); + res.write(self.wsdl.toXML()); + } + res.end(); + } + else if (req.method === 'POST') { + res.setHeader('Content-Type', req.headers['content-type']); + var chunks = [], gunzip; + if (compress && req.headers["content-encoding"] == "gzip") { + gunzip = new compress.Gunzip; + gunzip.init(); + } + req.on('data', function(chunk) { + if (gunzip) chunk = gunzip.inflate(chunk, "binary"); + chunks.push(chunk); + }) + req.on('end', function() { + var xml = chunks.join(''), result; + if (gunzip) { + gunzip.end(); + gunzip = null + } + try { + self._process(xml, req.url, function(result) { + res.write(result); + res.end(); + if (typeof self.log === 'function') { + self.log("received", xml); + self.log("replied", result); + } + }); + } + catch(err) { + err = err.stack || err; + res.write(err); + res.end(); + if (typeof self.log === 'function') { + self.log("error", err); + } + } + }); + } + else { + res.end(); + } +} + +Server.prototype._process = function(input, URL, callback) { + var self = this, + pathname = url.parse(URL).pathname.replace(/\/$/,''), + obj = this.wsdl.xmlToObject(input), + body = obj.Body, + bindings = this.wsdl.definitions.bindings, binding, + methods, method, methodName, + serviceName, portName; + + if (typeof self.authenticate === 'function') { + if (obj.Header == null || obj.Header.Security == null) { + throw new Error('No security header'); + } + if (!self.authenticate(obj.Header.Security)) { + throw new Error('Invalid username or password'); + } + } + + // use port.location and current url to find the right binding + binding = (function(self){ + var services = self.wsdl.definitions.services; + for(serviceName in services ) { + var service = services[serviceName]; + var ports = service.ports; + for(portName in ports) { + var port = ports[portName]; + var portPathname = url.parse(port.location).pathname.replace(/\/$/,''); + if(portPathname===pathname) + return port.binding; + } + } + })(this); + + methods = binding.methods; + + if(binding.style === 'rpc') { + methodName = Object.keys(body)[0]; + self._executeMethod({ + serviceName: serviceName, + portName: portName, + methodName: methodName, + outputName: methodName + 'Response', + args: body[methodName], + style: 'rpc' + }, callback); + } else { + var messageElemName = Object.keys(body)[0]; + var pair = binding.topElements[messageElemName]; + self._executeMethod({ + serviceName: serviceName, + portName: portName, + methodName: pair.methodName, + outputName: pair.outputName, + args: body[messageElemName], + style: 'document' + }, callback); + } +} + +Server.prototype._executeMethod = function(options, callback) { + options = options || {}; + var self = this, + method, body, + serviceName = options.serviceName, + portName = options.portName, + methodName = options.methodName, + outputName = options.outputName, + args = options.args, + style = options.style, + handled = false; + + try { + method = this.services[serviceName][portName][methodName]; + } catch(e) { + return callback(this._envelope('')); + } + + function handleResult(result) { + if (handled) return; + handled = true; + + if(style==='rpc') { + body = self.wsdl.objectToRpcXML(outputName, result, '', self.wsdl.definitions.$targetNamespace); + } else { + var element = self.wsdl.definitions.services[serviceName].ports[portName].binding.methods[methodName].output; + body = self.wsdl.objectToDocumentXML(outputName, result, element.targetNSAlias, element.targetNamespace); + } + callback(self._envelope(body)); + } + + var result = method(args, handleResult); + if (typeof result !== 'undefined') { + handleResult(result); + } +} + +Server.prototype._envelope = function(body) { + var defs = this.wsdl.definitions, + ns = defs.$targetNamespace, + encoding = '', + alias = findKey(defs.xmlns, ns); + var xml = "" + + "' + + "" + + body + + "" + + ""; + return xml; +} + +exports.Server = Server; diff --git a/pool/shard001/JavaScript/0010293_main.js b/pool/shard001/JavaScript/0010293_main.js new file mode 100644 index 0000000000000000000000000000000000000000..ab6e6587c34a6083f47036545e6151d94e2659b9 --- /dev/null +++ b/pool/shard001/JavaScript/0010293_main.js @@ -0,0 +1,222 @@ +/** + * Chrome-Extension-Template v1.0 + * + * @author Dustin Breuer + * @version 1.0 + * @category chrome-extension + * @licence MIT http://opensource.org/licenses/MIT + */ + +document.addEventListener("DOMContentLoaded", function () { + + /** + * + * @type {EasyStorage} + * @private + */ + var _oOptionsStorage = new EasyStorage(); + + document.forms[0].addEventListener("submit", function (oEvent) { + oEvent.preventDefault(); + + _oOptionsStorage.set(serializeForm(this), function () { + if (chrome.runtime.lastError) { + console.error(chrome.runtime.lastError.message); + } else { + console.info("%O saved", this); + } + }); + }); + + _oOptionsStorage.getEntireStorage(setFormValues); + + /** + * Set the option-values by passing an key-values Object + * + * @param {Object.} oItems + */ + function setFormValues(oItems){ + var _mValue, _aElements; + + for(var _sKey in oItems){ + _mValue = oItems[_sKey]; + _aElements = toArray(document.getElementsByName(_sKey)); + + if(typeof _mValue !== "object"){ + if(_aElements.length === 1){ + var _oNode = _aElements[0]; + + if(_oNode instanceof HTMLInputElement && (_oNode.type === "checkbox" || _oNode.type === "radio")){ + _oNode.checked = true; + } else { + _oNode.value = _mValue; + } + } else if(_aElements.length > 1) { + // radio + (_aElements.filter(function(oNode){ + return (_mValue.indexOf(oNode.value) !== -1); + })[0] || {}).checked = true; + } else { + console.info("No input[name=%s] found", _sKey); + } + } else if(_mValue instanceof Array){ + console.log("Set value %O for element with the name %s", _mValue, _sKey); + + if(_aElements.length === 1){ + // select + toArray(_aElements[0].options).filter(function(oNode){ + return (_mValue.indexOf(oNode.value) !== -1); + }).forEach(function (oNode) { + oNode.selected = true; + }); + + } else if(_aElements.length > 1){ + // checkbox + + _aElements.filter(function(oNode){ + return (_mValue.indexOf(oNode.value) !== -1); + }).forEach(function (oNode) { + oNode.checked = true; + }); + + } else { + console.info("%O for key %s is of unknown type", _aElements, _sKey); + } + + } else { + setFormValues(_mValue); + } + } + } + + /** + * Transform a NodeList, Collection or something else "Array-like" to an real Array + * + * @param {Object} oArrayLikeObject + * + * @returns {Array} + */ + function toArray(oArrayLikeObject) { + return Array.prototype.slice.call(oArrayLikeObject); + } + + /** + * Return the value of the node oNode. + * This function return an Array for a select-node, otherwise a simple value + * + * @param {HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement} oNode + * + * @returns {String|String[]|null} + * + * @see getSimpleValue + */ + function getValueByNode(oNode) { + if (!oNode.multiple) { + return oNode.value; + } else { + return toArray(oNode.options).filter(isSelected).map(getSimpleValue); + } + } + + /** + * Check if the node oNode is checked + * + * @param {HTMLInputElement} oNode + * + * @returns {boolean} + */ + function isChecked(oNode) { + return !!oNode.checked; + } + + /** + * Check if the node oNode is selected + * + * @param {HTMLOptionElement} oNode + * + * @returns {boolean} + */ + function isSelected(oNode) { + return !!oNode.selected; + } + + /** + * Return the simple value of the node oNode + * + * @param {HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement} oNode + * + * @returns {String} + */ + function getSimpleValue(oNode) { + return oNode.value; + } + + /** + * Serialize a form and use all name-attributes + * + * @param {HTMLFormElement} oForm + * + * @returns {Object.} + */ + function serializeForm(oForm) { + var _oRet = {}, + _aElements = toArray(oForm.querySelectorAll("input,select,textarea")); + + _aElements.forEach(function (oNode) { + var _oParent = oNode.parentNode, + _aKeys = [], + _bIsInput = oNode instanceof HTMLInputElement; + + if (_bIsInput && oNode.type.toLowerCase() === "radio" && !oNode.checked) { + // Not checked - next! + return; + } + + while (_oParent !== oForm) { + if (_oParent.name) { + _aKeys.unshift(_oParent.name); + } + + _oParent = _oParent.parentNode; + } + + if (oForm.name) { + _aKeys.unshift(oForm.name); + } + + var _oTarget = _oRet; + for (var i = 0; i < _aKeys.length; i++) { + if (!_oTarget[_aKeys[i]]) { + _oTarget[_aKeys[i]] = {}; + } + + _oTarget = _oTarget[_aKeys[i]]; + } + + if (!_bIsInput || oNode.type.toLowerCase() !== "checkbox") { + _oTarget[oNode.name] = getValueByNode(oNode); + + } else if (!_oTarget[oNode.name]) { + var _oClosestNamedParent = oNode.parentNode, _aOtherCheckboxen; + + while (!_oClosestNamedParent.name && _oClosestNamedParent.parentNode) { + _oClosestNamedParent = _oClosestNamedParent.parentNode; + } + + _aOtherCheckboxen = toArray(_oClosestNamedParent.querySelectorAll('input[type="checkbox"][name="' + oNode.name + '"]')); + + if (_aOtherCheckboxen.length === 1) { + // The one checkbox to rule them all + if (isChecked(oNode)) { + _oTarget[oNode.name] = getSimpleValue(oNode); + } + } else { + _oTarget[oNode.name] = _aOtherCheckboxen.filter(isChecked).map(getSimpleValue); + } + } + }); + + return _oRet; + } + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010296_LoanContainer.js b/pool/shard001/JavaScript/0010296_LoanContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..bd2aee41b9a58a0fe80728d5b667f2d4d934fd4e --- /dev/null +++ b/pool/shard001/JavaScript/0010296_LoanContainer.js @@ -0,0 +1,16 @@ +import { connect } from 'react-redux'; +import { setActiveLoan, getLoanTransactionHistory } from '../modules/loans' +import { linkTo } from '../../../modules/banking' +import Loan from '../components/Loan'; + +const mapStateToProps = (state) => ({ + language: state.root.language +}); + +const mapActionCreators = { + setActiveLoan: (loan) => setActiveLoan(loan), + getLoanTransactionHistory: (loanId) => getLoanTransactionHistory(loanId), + linkTo: (route) => linkTo(route) +}; + +export default connect(mapStateToProps, mapActionCreators)(Loan); diff --git a/pool/shard001/JavaScript/0010298_PdkInputComponent.js b/pool/shard001/JavaScript/0010298_PdkInputComponent.js new file mode 100644 index 0000000000000000000000000000000000000000..728757f5f63a1da7d57aff15cf4903f2f5fcaf5d --- /dev/null +++ b/pool/shard001/JavaScript/0010298_PdkInputComponent.js @@ -0,0 +1,22 @@ +'use strict'; +var React = require('react'); +var InputComponent = require('./InputComponent.js'); +module.exports = React.createClass({ + + control:{ + id: 'pdk_input', + name: 'ПДК', + value: 0, + description:'ПДК', + measure:'' + }, + handleChange:function(e){ + this.props.onUpdate(this.control.id, event.target.value); + }, + render: function(){ + + return( + + ) + } + }); diff --git a/pool/shard001/JavaScript/0010300_decoder.js b/pool/shard001/JavaScript/0010300_decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..e05b06cb1bdba906a38334e0e5461423caef5e2a --- /dev/null +++ b/pool/shard001/JavaScript/0010300_decoder.js @@ -0,0 +1,104 @@ + +var fs = require('fs'); +var path = require('path'); +var lame = require('../'); +var assert = require('assert'); +var fixtures = path.resolve(__dirname, 'fixtures'); + +describe('Decoder', function () { + + describe('pipershut_lo.mp3', function () { + var title = 'The Burning of the Piper\'s Hut'; + var artist = 'Tony Cuffe & Billy Jackson'; + var album = 'Sae Will We Yet'; + var year = '2003'; + var comment = 'sample of full track'; + var trackNumber = 8; + var genre = 88; + var filename = path.resolve(fixtures, 'pipershut_lo.mp3'); + + it('should emit "readable" events', function (done) { + var file = fs.createReadStream(filename); + var count = 0; + var decoder = new lame.Decoder(); + decoder.on('readable', function () { + count++; + var b; + while (null != (b = decoder.read())); + }); + decoder.on('finish', function () { + assert(count > 0); + done(); + }); + file.pipe(decoder); + }); + + it('should emit a single "format" event', function (done) { + var file = fs.createReadStream(filename); + var decoder = new lame.Decoder(); + decoder.on('format', function (format) { + assert(format); + done(); + }); + file.pipe(decoder); + }); + + it('should emit a single "finish" event', function (done) { + var file = fs.createReadStream(filename); + var decoder = new lame.Decoder(); + decoder.on('finish', done); + file.pipe(decoder); + + // enable "flow" + decoder.resume(); + }); + + it('should emit a single "end" event', function (done) { + var file = fs.createReadStream(filename); + var decoder = new lame.Decoder(); + decoder.on('end', done); + file.pipe(decoder); + + // enable "flow" + decoder.resume(); + }); + + it('should emit a single "id3v1" event', function (done) { + var file = fs.createReadStream(filename); + var decoder = new lame.Decoder(); + decoder.on('id3v1', function (id3) { + assert.equal(title, id3.title.replace(/\0*$/, '')); + assert.equal(artist, id3.artist.replace(/\0*$/, '')); + assert.equal(album, id3.album.replace(/\0*$/, '')); + assert.equal(year, id3.year.replace(/\0*$/, '')); + assert.equal(comment, id3.comment.replace(/\0*$/, '')); + assert.equal(trackNumber, id3.trackNumber); + assert.equal(genre, id3.genre); + done(); + }); + file.pipe(decoder); + + // enable "flow" + decoder.resume(); + }); + + it('should emit a single "id3v2" event', function (done) { + var file = fs.createReadStream(filename); + var decoder = new lame.Decoder(); + decoder.on('id3v2', function (id3) { + assert.equal(title, id3.title.replace(/\0*$/, '')); + assert.equal(artist, id3.artist.replace(/\0*$/, '')); + assert.equal(album, id3.album.replace(/\0*$/, '')); + assert.equal(year, id3.year.replace(/\0*$/, '')); + assert.equal(comment, id3.comment.replace(/\0*$/, '')); + done(); + }); + file.pipe(decoder); + + // enable "flow" + decoder.resume(); + }); + + }); + +}); diff --git a/pool/shard001/JavaScript/0010302_validate-latest-versions.js b/pool/shard001/JavaScript/0010302_validate-latest-versions.js new file mode 100644 index 0000000000000000000000000000000000000000..6788afd5ae0867de3d7f1ccc7c79a5bf4329dd5f --- /dev/null +++ b/pool/shard001/JavaScript/0010302_validate-latest-versions.js @@ -0,0 +1,46 @@ +import { CHANNEL_PRE_RELEASE, CHANNEL_STABLE, PLATFORM_LINUX, PLATFORM_MACOS, PLATFORM_WINDOWS } from './constants' + +import { URL } from 'url' +import { valid } from 'semver' + +const validate = (latestVersions) => { + if (typeof latestVersions !== 'object') { + throw new TypeError('Argument must be an object.') + } + validateChannel(latestVersions, CHANNEL_STABLE) + validateChannel(latestVersions, CHANNEL_PRE_RELEASE) +} + +const validateChannel = (latestVersions, name) => { + const channel = latestVersions[name] + if (channel === undefined) { + throw new TypeError('Missing channel: ' + name) + } + if (typeof channel !== 'object') { + throw new TypeError('Channel must be an object.') + } + validatePlatform(channel, PLATFORM_LINUX) + validatePlatform(channel, PLATFORM_MACOS) + validatePlatform(channel, PLATFORM_WINDOWS) +} + +const validatePlatform = (channel, name) => { + const platform = channel[name] + if (platform === undefined) { + throw new TypeError('Missing platform: ' + name) + } + if (typeof platform !== 'object') { + throw new TypeError('Platform must be an object.') + } + if (platform.version === undefined) { + throw new TypeError('Missing version.') + } + if (valid(platform.version) === null) { + throw new TypeError('Invalid version: ' + platform.version) + } + if (platform.url === undefined || new URL(platform.url) === null) { + throw new TypeError('Missing URL.') + } +} + +export default validate diff --git a/pool/shard001/JavaScript/0010303_app.js b/pool/shard001/JavaScript/0010303_app.js new file mode 100644 index 0000000000000000000000000000000000000000..0735beaaea85f80d000261e390dd4e797c72147f --- /dev/null +++ b/pool/shard001/JavaScript/0010303_app.js @@ -0,0 +1,86 @@ +/* Loaded modules -- start */ +const cookieParser = require('cookie-parser') +const express = require('express') +const logger = require('morgan') +const e = require('allhttperrors') +const path = require('path') +/* Loaded modules -- end */ + +/* Loaded modules -- start */ +const errorPageRoute = require('./routes/errorPage') +const vars = require('./vars.js') /* eslint-disable-line */ +const maybeRedirectToHttps = require('./routes/maybeRedirectToHttps') +const asyncMiddleware = require('./lib/asyncMiddleware') +const moduleMiddleware = require('es6-dev-server').moduleMiddleware +const alwaysIndex = require('./routes/alwaysIndex') +/* Loaded modules -- end */ + +// Print unhandled exception if it happens. This will prevent unmanaged +// errors going silent +process.on('unhandledRejection', (err, p) => { + console.log('UNHANDLED REJECTION!', err, 'PROMISE:', p) +}) + +/* Before app is created -- start */ +/* Before app is created -- end */ + +const app = express() // Create the express app + +/* After app is created -- start */ +/* After app is created -- end */ + +// Ready checker. This allows app.js (this file) to complete async work +// before the server is actually started (in ./www) +app._readyChecker = async () => { + /* Ready checker -- start */ + /* Ready checker -- end */ + return true +} + +/* Express essentials -- start */ +app.use(maybeRedirectToHttps) // Redirect to HTTPS for production +logger.token('headers', function (req) { return JSON.stringify(req.headers) }) +logger.token('body', function (req) { return JSON.stringify(req.body) }) +app.use(logger(':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms :headers :body')) // Enable the logger +app.use(express.json({ limit: '4mb' })) // Make up request.body, json +app.use(express.urlencoded({ limit: '4mb', extended: false })) // // Make up request.body, urlencoded +app.use(cookieParser()) // Cookie parser +/* Express essentials -- end */ + +/* Before serving static files -- start */ +/* Before serving static files -- end */ + +// Important server variables +const serveBuilt = process.env.SERVE_BUILT +const env = process.env.NODE_ENV || 'development' +const root = serveBuilt ? 'server/dist' : path.join(__dirname, '..') + +// Run module resolution for local (unbuilt) files +// (Unless it's set to serve the built version, which would render this useless) +if (!serveBuilt) app.use(moduleMiddleware({ root })) + +// Serve static files +app.use(express.static(root)) + +/* After static files -- start */ +/* After static files -- end */ + +/* App routes -- start */ +/* App routes -- 1 */ +/* App routes -- 2 */ +/* App routes -- 3 */ +/* App routes -- end */ + +// Always serve index.html +app.use(alwaysIndex(root)) + +// Artificially call the errorPageRoute as "not found" +// This will never happen for GET or HEAD, but might happen for the +// rest of it +app.use((req, res) => errorPageRoute(new e.NotFoundError(), req, res)) + +// Error handler page. Express will route here when there is an error, +// since errorPageRoute has 4 parameters (err, req, res, next) +app.use(errorPageRoute) + +module.exports = app diff --git a/pool/shard001/JavaScript/0010304_graph.js b/pool/shard001/JavaScript/0010304_graph.js new file mode 100644 index 0000000000000000000000000000000000000000..3c1ae69153b26b6eba5a75f6ebd0f8f5c8aa9a65 --- /dev/null +++ b/pool/shard001/JavaScript/0010304_graph.js @@ -0,0 +1,90 @@ +'use strict'; +(function () { + + angular.module('main') + .factory('st2GraphGraph', ['st2GraphLayer', + function (Layer) { + var Graph = function (scope, options) { + var self = scope.$new(); + + self.opts = _.defaults(options || {}, { + title: null, + xAxis: true, + yAxis: true, + style: null + }); + self.layers = {}; + + self.addLayer = function (channel, options) { + channel = channel.split('/').concat(channel[channel.length - 1] !== '/' ? '' : []).join('/'); + if (!self.layers[channel]) { + self.layers[channel] = new Layer(self, channel, options); + self.$$phase || self.$apply(); + return self; + } else { + throw new Error('There should be only one layer per channel'); + } + }; + + self.removeLayer = function (layer) { + if (layer.channel) { + layer = layer.channel; + } + + self.layers[layer].remove(); + + delete self.layers[layer]; + + // Not that it's completely necessary to $apply here since layer can only be removed by + // clicking the button, still i'll leave it for now. + self.$$phase || self.$apply(); + return self; + }; + + self.get = function (time) { + return _.zipObject(_.keys(self.layers), _.map(self.layers, function (layer) { + return layer.get(time); + })); + }; + + // Versatile function to produce extrema getters + function getExtrema(type, extremum) { + return _(self.layers).filter(function (l) { + return !l.error; + }).map(function (l) { + return l.values.length && (type ? + _[extremum](l.values, function (e) { return e[type]; })[type] : + l.values[extremum === 'max' ? l.values.length - 1 : 0][0]); + })[extremum]().value(); + } + + self.getMinTime = _.partial(getExtrema, 0, 'min'); + self.getMaxTime = _.partial(getExtrema, 0, 'max'); + self.getMinValue = _.partial(getExtrema, 1, 'min'); + self.getMaxValue = _.partial(getExtrema, 1, 'max'); + + self.remove = function () { + _.each(self.layers, function (e) { + self.removeLayer(e); + }); + }; + + self.clone = function () { + var clone = new Graph(scope, _.clone(self.opts)); + + _.each(self.layers, function (e, k) { + clone.addLayer(k, e.opts); + }); + + clone.$proto = self; + + return clone; + }; + + return self; + }; + + return Graph; + }]); + +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010306_deleteModel.js b/pool/shard001/JavaScript/0010306_deleteModel.js new file mode 100644 index 0000000000000000000000000000000000000000..1cf12082b445380b11bdbf3eb3c288c75e40d238 --- /dev/null +++ b/pool/shard001/JavaScript/0010306_deleteModel.js @@ -0,0 +1,23 @@ +import $ from 'jquery'; +import { clearDialog, setBusy, clearBusy } from '../utils/dialog'; + +export default (Collection, element) => + (event) => { + const target = event.currentTarget; + + setBusy(target); + + const instanceId = $(`#${element}_id`).val(); + const instance = Collection.get(instanceId); + + instance.destroy({ + wait: true, + success: () => { + clearDialog(target); + clearBusy(target, 'trash'); + }, + error: () => { + clearBusy(target, 'trash'); + }, + }); + }; diff --git a/pool/shard001/JavaScript/0010308_AnimatedValue.js b/pool/shard001/JavaScript/0010308_AnimatedValue.js new file mode 100644 index 0000000000000000000000000000000000000000..3baf5f473df95456a54134c3696d7b716e3a28c7 --- /dev/null +++ b/pool/shard001/JavaScript/0010308_AnimatedValue.js @@ -0,0 +1,300 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @format + */ +'use strict'; + +exports.__esModule = true; +exports.default = void 0; + +var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation")); + +var _AnimatedWithChildren2 = _interopRequireDefault(require("./AnimatedWithChildren")); + +var _InteractionManager = _interopRequireDefault(require("../../../../exports/InteractionManager")); + +var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var NativeAnimatedAPI = _NativeAnimatedHelper.default.API; +/** + * Animated works by building a directed acyclic graph of dependencies + * transparently when you render your Animated components. + * + * new Animated.Value(0) + * .interpolate() .interpolate() new Animated.Value(1) + * opacity translateY scale + * style transform + * View#234 style + * View#123 + * + * A) Top Down phase + * When an Animated.Value is updated, we recursively go down through this + * graph in order to find leaf nodes: the views that we flag as needing + * an update. + * + * B) Bottom Up phase + * When a view is flagged as needing an update, we recursively go back up + * in order to build the new value that it needs. The reason why we need + * this two-phases process is to deal with composite props such as + * transform which can receive values from multiple parents. + */ + +function _flush(rootNode) { + var animatedStyles = new Set(); + + function findAnimatedStyles(node) { + /* $FlowFixMe(>=0.68.0 site=react_native_fb) This comment suppresses an + * error found when Flow v0.68 was deployed. To see the error delete this + * comment and run Flow. */ + if (typeof node.update === 'function') { + animatedStyles.add(node); + } else { + node.__getChildren().forEach(findAnimatedStyles); + } + } + + findAnimatedStyles(rootNode); + /* $FlowFixMe */ + + animatedStyles.forEach(function (animatedStyle) { + return animatedStyle.update(); + }); +} +/** + * Standard value for driving animations. One `Animated.Value` can drive + * multiple properties in a synchronized fashion, but can only be driven by one + * mechanism at a time. Using a new mechanism (e.g. starting a new animation, + * or calling `setValue`) will stop any previous ones. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html + */ + + +var AnimatedValue = +/*#__PURE__*/ +function (_AnimatedWithChildren) { + _inheritsLoose(AnimatedValue, _AnimatedWithChildren); + + function AnimatedValue(value) { + var _this; + + _this = _AnimatedWithChildren.call(this) || this; + _this._startingValue = _this._value = value; + _this._offset = 0; + _this._animation = null; + return _this; + } + + var _proto = AnimatedValue.prototype; + + _proto.__detach = function __detach() { + this.stopAnimation(); + + _AnimatedWithChildren.prototype.__detach.call(this); + }; + + _proto.__getValue = function __getValue() { + return this._value + this._offset; + } + /** + * Directly set the value. This will stop any animations running on the value + * and update all the bound properties. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#setvalue + */ + ; + + _proto.setValue = function setValue(value) { + if (this._animation) { + this._animation.stop(); + + this._animation = null; + } + + this._updateValue(value, !this.__isNative + /* don't perform a flush for natively driven values */ + ); + + if (this.__isNative) { + NativeAnimatedAPI.setAnimatedNodeValue(this.__getNativeTag(), value); + } + } + /** + * Sets an offset that is applied on top of whatever value is set, whether via + * `setValue`, an animation, or `Animated.event`. Useful for compensating + * things like the start of a pan gesture. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#setoffset + */ + ; + + _proto.setOffset = function setOffset(offset) { + this._offset = offset; + + if (this.__isNative) { + NativeAnimatedAPI.setAnimatedNodeOffset(this.__getNativeTag(), offset); + } + } + /** + * Merges the offset value into the base value and resets the offset to zero. + * The final output of the value is unchanged. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#flattenoffset + */ + ; + + _proto.flattenOffset = function flattenOffset() { + this._value += this._offset; + this._offset = 0; + + if (this.__isNative) { + NativeAnimatedAPI.flattenAnimatedNodeOffset(this.__getNativeTag()); + } + } + /** + * Sets the offset value to the base value, and resets the base value to zero. + * The final output of the value is unchanged. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#extractoffset + */ + ; + + _proto.extractOffset = function extractOffset() { + this._offset += this._value; + this._value = 0; + + if (this.__isNative) { + NativeAnimatedAPI.extractAnimatedNodeOffset(this.__getNativeTag()); + } + } + /** + * Stops any running animation or tracking. `callback` is invoked with the + * final value after stopping the animation, which is useful for updating + * state to match the animation position with layout. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#stopanimation + */ + ; + + _proto.stopAnimation = function stopAnimation(callback) { + this.stopTracking(); + this._animation && this._animation.stop(); + this._animation = null; + callback && callback(this.__getValue()); + } + /** + * Stops any animation and resets the value to its original. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#resetanimation + */ + ; + + _proto.resetAnimation = function resetAnimation(callback) { + this.stopAnimation(callback); + this._value = this._startingValue; + }; + + _proto._onAnimatedValueUpdateReceived = function _onAnimatedValueUpdateReceived(value) { + this._updateValue(value, false + /*flush*/ + ); + } + /** + * Interpolates the value before updating the property, e.g. mapping 0-1 to + * 0-10. + */ + ; + + _proto.interpolate = function interpolate(config) { + return new _AnimatedInterpolation.default(this, config); + } + /** + * Typically only used internally, but could be used by a custom Animation + * class. + * + * See http://facebook.github.io/react-native/docs/animatedvalue.html#animate + */ + ; + + _proto.animate = function animate(animation, callback) { + var _this2 = this; + + var handle = null; + + if (animation.__isInteraction) { + handle = _InteractionManager.default.createInteractionHandle(); + } + + var previousAnimation = this._animation; + this._animation && this._animation.stop(); + this._animation = animation; + animation.start(this._value, function (value) { + // Natively driven animations will never call into that callback, therefore we can always + // pass flush = true to allow the updated value to propagate to native with setNativeProps + _this2._updateValue(value, true + /* flush */ + ); + }, function (result) { + _this2._animation = null; + + if (handle !== null) { + _InteractionManager.default.clearInteractionHandle(handle); + } + + callback && callback(result); + }, previousAnimation, this); + } + /** + * Typically only used internally. + */ + ; + + _proto.stopTracking = function stopTracking() { + this._tracking && this._tracking.__detach(); + this._tracking = null; + } + /** + * Typically only used internally. + */ + ; + + _proto.track = function track(tracking) { + this.stopTracking(); + this._tracking = tracking; + }; + + _proto._updateValue = function _updateValue(value, flush) { + this._value = value; + + if (flush) { + _flush(this); + } + + _AnimatedWithChildren.prototype.__callListeners.call(this, this.__getValue()); + }; + + _proto.__getNativeConfig = function __getNativeConfig() { + return { + type: 'value', + value: this._value, + offset: this._offset + }; + }; + + return AnimatedValue; +}(_AnimatedWithChildren2.default); + +var _default = AnimatedValue; +exports.default = _default; +module.exports = exports.default; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010313_checkbox.js b/pool/shard001/JavaScript/0010313_checkbox.js new file mode 100644 index 0000000000000000000000000000000000000000..d1ee237758848cc3815ec29cf2b5dace8a381553 --- /dev/null +++ b/pool/shard001/JavaScript/0010313_checkbox.js @@ -0,0 +1,37 @@ +'use strict'; + +const _ = require('lodash'); +const React = require('react'); + +class Checkbox extends React.Component { + + renderNote(){ + const { note } = this.props; + + if(note){ + return ( +

+ {note} +

+ ); + } + } + + render(){ + const { children } = this.props; + + const extraProps = _.omit(this.props, ['note', 'children']); + + return ( +
+ + {this.renderNote()} +
+ ); + } +} + +module.exports = Checkbox; diff --git a/pool/shard001/JavaScript/0010315_task-form.js b/pool/shard001/JavaScript/0010315_task-form.js new file mode 100644 index 0000000000000000000000000000000000000000..ec6a77bab8f9f99508bdb0bb057275b95c3ed19a --- /dev/null +++ b/pool/shard001/JavaScript/0010315_task-form.js @@ -0,0 +1,110 @@ +"use strict"; + +import React from "react"; +import taskActions from "../actions/task-actions"; +import taskStore from "../stores/task-store"; +import TaskItem from "./task-item"; + +function uid() { + return Math.random().toString(36).substr(9); +} + +function getClass(visibilityFilter, status) { + return visibilityFilter === status.toUpperCase() ? "selected" : ""; +} + +const TaskForm = React.createClass({ + displayName: "TaskForm", + getInitialState() { + return taskStore.getState(); + }, + componentDidMount() { + taskStore.listen(this.handleUpdate); + }, + componentWillUnmount() { + taskStore.unlisten(this.handleUpdate); + }, + handleUpdate() { + this.setState(this.getInitialState()); + }, + handleKeyPress(event) { + if (event.keyCode === 13) { + let task = this.input.value; + + taskActions.addTask({task, done: false, id: uid()}); + this.input.value = ""; + } + }, + handleFilter(e, status) { + e.preventDefault(); + taskActions.setVisibilityFilter(status.toUpperCase()); + }, + handleClear() { + taskActions.clearCompleted(); + }, + handleToggleAll(e) { + taskActions.toggleAll(e.target.checked); + }, + render() { + let { tasks, visibilityFilter } = this.state, + filteredTasks = tasks, + tasksLeft = tasks.filter((t) => !t.done).length; + + if (visibilityFilter === "ACTIVE") { + filteredTasks = filteredTasks.filter((t) => !t.done); + } else if (visibilityFilter === "COMPLETED") { + filteredTasks = filteredTasks.filter((t) => t.done); + } + + return ( +
+ ); + } +}); + +export default TaskForm; diff --git a/pool/shard001/JavaScript/0010323_scripts.js b/pool/shard001/JavaScript/0010323_scripts.js new file mode 100644 index 0000000000000000000000000000000000000000..3647169153ff227cce4239ae6340b3508886213c --- /dev/null +++ b/pool/shard001/JavaScript/0010323_scripts.js @@ -0,0 +1,56 @@ +function click_send(page){ + // var competition = document.getElementByName('competition').value; + var competitions = document.getElementsByName('competition'); + var competition ='none'; + for (i in competitions){ + if (competitions[i].checked){ + competition = competitions[i].value + break; + } + } + if (competition == 'none'){ + alert('please choose a competition'); + } + else{ + parent.location = page + '?competition=' + competition; + } +} + +function maybe_submit(check){ + var form = document.getElementById('table_form'); + if (check == 'False') form.submit(); + else{ + var fence = document.getElementById('fence').value; + if (fence == 'none') alert('please choose a fence'); + else form.submit(); + } +} + +var t = 5; +var stopper; + +// if (parent.location.pathname.indexOf('submit') != -1){ + // document.addEventListener('DOMContentLoaded', redirect_slow); +// } + +function redirect_slow(){ + redirect_write(); + stopper = setInterval(redirect_write, 1000); +} + +function redirect_write(){ + if (t <= 0){ + clearInterval(stopper); + parent.location = '/'; + return; + } + else{ + document.getElementById('redirect_msg').innerHTML = 'Redirecting to home in ' + t + '.'; + t -= 1; + } +} + +function stop(){ + clearInterval(stopper); + document.getElementById('redirect_msg').innerHTML = ''; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010324_umd.js b/pool/shard001/JavaScript/0010324_umd.js new file mode 100644 index 0000000000000000000000000000000000000000..68ba42440622a622c41691f2af092e01a6929f73 --- /dev/null +++ b/pool/shard001/JavaScript/0010324_umd.js @@ -0,0 +1,19 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory() : + typeof define === 'function' && define.amd ? define(factory) : + (factory()); +}(this, (function () { 'use strict'; + + const effectY = () => { + console.log('effect'); + return 'y'; + }; + + const x = {y: 1}; + x[effectY()]++; + + let foo = {bar: {}}; + foo++; + foo.bar.baz = 1; + +}))); diff --git a/pool/shard001/JavaScript/0010325_TweetsSteps.js b/pool/shard001/JavaScript/0010325_TweetsSteps.js new file mode 100644 index 0000000000000000000000000000000000000000..79dd0078e2b65231707176ebcc991f5575a53d2a --- /dev/null +++ b/pool/shard001/JavaScript/0010325_TweetsSteps.js @@ -0,0 +1,34 @@ +module.exports = function () { + this.World = require("../support/ZombieWorld.js").World; + + this.Given("I have signed up", function(callback) { + this.generateUser(this.fixtures.users.Joe, callback); + }); + + this.When("I enter my credentials", function(callback) { + this.authenticateUser(this.fixtures.users.Joe, callback); + }); + + this.When("I tweet something less than 140 characters", function(callback) { + this.tweet("My cool message!", callback); + }); + + this.When("I tweet something longer than 140 characters", function(callback) { + this.tweet( + "My message is really really really really really really really really " + + "really really really really really really really really really really long!", + callback); + }); + + this.Then("I should see the message", function(callback) { + this.userTweeted(this.fixtures.users.Joe, "My cool message!", callback); + }); + + this.Then("I should not see the message", function(callback) { + this.userNotTweeted(this.fixtures.users.Joe, + "My message is really really really really really really really really " + + "really really really really really really really really really really long!", + callback); + }); +}; + diff --git a/pool/shard001/JavaScript/0010327_popup.js b/pool/shard001/JavaScript/0010327_popup.js new file mode 100644 index 0000000000000000000000000000000000000000..0bef2cd6531f153b38009e7e6158e201fcea48e2 --- /dev/null +++ b/pool/shard001/JavaScript/0010327_popup.js @@ -0,0 +1,193 @@ +var dialogs = [], $dcon; + +$(function() { + $dcon = $('#modalDialogContainer'); + init(); +}); + +/** + * メニュー初期化 + */ +function init() { + const $service = $('#service').click(() => openKTR()); + $('#options').click(() => window.open('/html/options.html', '_blank')); + + // 認証情報があれば出社、退社を表示 + if (KTR.credential.valid()) { + $('.inout-block').css('display', 'table'); + } + + // メニューを追加 + addMenus($service); + + // 状態による内容の更新 + KTR.status.update((status) => { + // 出社、退社 + updateMenu(status); + + // メニュー + addMenus($service); + + // お知らせ + if (status.information.recent) { + $service.text('新しいお知らせ').addClass('attention'); + } + }); + + /** + * ログインしており、かつ勤務状況機能を利用する場合に勤務テーブルを表示する + */ + if (KTR.credential.valid() && KTR.enableWorkInfo.get() === 'enable') { + document.querySelector('#time-table').style.display = 'block'; + // TODO: @tosite0345 リファクタリング + KTR.service._request( + {method: 'GET'}, + '?module=timesheet&action=browse', + (html) => { + const workInfo = KTR.workInfo.fetchWorkingInfoFromHtml(html); + const workTimes = KTR.workInfo.calcWorkTimes(workInfo); + KTR.workInfo.setTimesToTable(workTimes.days, workTimes.times); + if (KTR.worktype.get() === 'flex') { $('.is-flex').show(); } + } + ); + } +} + +/** + * 出社時刻、退社時刻の更新 + */ +function updateMenu(status) { + if (status.code === KTR.STATUS.UNKNOWN) { + return; + } + + if (status.start) { + $('#action1').text('出社 ' + status.start).removeClass('enabled').unbind('click', startWork); + } else { + $('#action1').addClass('enabled').click(startWork); + } + + if (status.leave) { + $('#action2').text('退社 ' + status.leave).removeClass('enabled').unbind('click', leaveWork); + } else { + $('#action2').addClass('enabled').click(leaveWork); + } +} + +/** + * メニューを追加 + */ +function addMenus($service) { + if ($service.parent().find('.menu').length === 0) { + KTR.menuList.get((menus) => { + menus.forEach((menu) => { + $(`
' + + '
' + + '' + jQuery('.sic-code-row').last().after(html) + jQuery('.sic-code-' + idCount).val('') + }, + reindexRows: function (rowSelector) { + jQuery(rowSelector + ' [name]').each(function () { + var inst = jQuery(this) + if (inst.prop('name').indexOf('[') !== -1) { + var thisIndex = inst.closest(rowSelector).index(rowSelector) + var oldAttr = inst.attr('name') + var oldAttrName = oldAttr.split('[')[0] + var oldAttrElement = oldAttr.split(']')[1] + inst.prop('name', oldAttrName + '[' + thisIndex + ']' + oldAttrElement) + } + }) + jQuery(rowSelector + ' [data-remove-row-man]').each(function () { + var inst = jQuery(this) + var thisIndex = inst.closest(rowSelector).index(rowSelector) + inst.val(thisIndex) + }) + }, + addExecOfficer: function () { + var idCount = 0 + if (jQuery('.exec-officer-row').length) { + idCount = parseInt(jQuery('.exec-officer-row[id^=exec-officer-row-]').last().attr('id').split('exec-officer-row-')[1], 10) + 1 + } + var html = '
' + + '
' + + '
' + + '' + + '' + + '' + + '' + + '
' + + '
' + + '
' + jQuery('.exec-officer-row').last().after(html) + jQuery('.exec-officer-' + idCount).val('') + } + } +})() diff --git a/pool/shard001/JavaScript/0010606_initLayer.js b/pool/shard001/JavaScript/0010606_initLayer.js new file mode 100644 index 0000000000000000000000000000000000000000..d15ae75f67fe2f0cc3cc125f3e5b042e8cf99054 --- /dev/null +++ b/pool/shard001/JavaScript/0010606_initLayer.js @@ -0,0 +1,52 @@ +/** + * @file Editor的layer初始化 + * @author mengke01(kekee000@gmail.com) + */ + + +define( + function (require) { + var lang = require('common/lang'); + + /** + * 初始化层 + */ + function initLayer() { + + this.axisLayer = this.render.addLayer('axis', { + level: 10, + fill: false + }); + + this.fontLayer = this.render.addLayer('font', lang.extend({ + level: 20, + lineWidth: 1, + strokeColor: '#999', + fillColor: '#555', + strokeSeparate: false + }, this.options.fontLayer)); + + this.coverLayer = this.render.addLayer('cover', lang.extend({ + level: 30, + fill: false, + strokeColor: this.options.coverLayer.strokeColor, + fillColor: this.options.coverLayer.fillColor + }, this.options.coverLayer)); + + this.referenceLineLayer = this.render.addLayer('referenceline', { + level: 40, + fill: false, + strokeColor: this.options.referenceline.style.strokeColor + }); + + + this.graduationLayer = this.render.addLayer('graduation', { + level: 50, + fill: false, + disabled: true + }); + } + + return initLayer; + } +); diff --git a/pool/shard001/JavaScript/0010608_legacy_view_support.js b/pool/shard001/JavaScript/0010608_legacy_view_support.js new file mode 100644 index 0000000000000000000000000000000000000000..7b1a9bfd350f14f3aaa216fd88a05136e95fdf4d --- /dev/null +++ b/pool/shard001/JavaScript/0010608_legacy_view_support.js @@ -0,0 +1,66 @@ +/** +@module ember +@submodule ember-views +*/ +import { deprecate } from 'ember-metal/debug'; +import { Mixin } from 'ember-metal/mixin'; +import { get } from 'ember-metal/property_get'; + +/** + @class LegacyViewSupport + @namespace Ember + @private +*/ +var LegacyViewSupport = Mixin.create({ + /** + Return the nearest ancestor whose parent is an instance of + `klass`. + + @method nearestChildOf + @param {Class} klass Subclass of Ember.View (or Ember.View itself) + @return Ember.View + @deprecated + @private + */ + nearestChildOf(klass) { + deprecate( + 'nearestChildOf has been deprecated.', + false, + { id: 'ember-views.nearest-child-of', until: '3.0.0' } + ); + + var view = get(this, 'parentView'); + + while (view) { + if (get(view, 'parentView') instanceof klass) { return view; } + view = get(view, 'parentView'); + } + }, + + /** + Return the nearest ancestor that is an instance of the provided + class. + + @method nearestInstanceOf + @param {Class} klass Subclass of Ember.View (or Ember.View itself) + @return Ember.View + @deprecated + @private + */ + nearestInstanceOf(klass) { + deprecate( + 'nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType.', + false, + { id: 'ember-views.nearest-instance-of', until: '3.0.0' } + ); + + var view = get(this, 'parentView'); + + while (view) { + if (view instanceof klass) { return view; } + view = get(view, 'parentView'); + } + } +}); + +export default LegacyViewSupport; diff --git a/pool/shard001/JavaScript/0010609_alg-iron-checked-element-mixin.js b/pool/shard001/JavaScript/0010609_alg-iron-checked-element-mixin.js new file mode 100644 index 0000000000000000000000000000000000000000..f7231ef6833c40b54ed3331e853d5838daadedc6 --- /dev/null +++ b/pool/shard001/JavaScript/0010609_alg-iron-checked-element-mixin.js @@ -0,0 +1,73 @@ +// @copyright @polymer\iron-checked-element-behavior\iron-checked-element-behavior.js +// @copyright 2017-2018 adalberto.lacruz@gmail.com + +import { TYPE_BOOL, TYPE_STRING } from '../util/constants.js'; + +// TODO: validate, form. Review active/check relation +/** + * [checked ⛳] + * [required ⛳aria-required] + * [toggles ⛳] + * [value 💰on] + * + * Requires: + * AlgIronButtonStateMixin + * AlgIronValidatableMixin + * + * @param {*} base + */ +export const AlgIronCheckedElementMixin = (base) => class extends base { + /** @override */ + deferredConstructor() { + super.deferredConstructor(); + + this.attributeManager + .define('aria-required', TYPE_BOOL) + .reflect({ type: 'true-remove'}) + + .define('checked', TYPE_BOOL) + .onChangeModify('active') + .reflect() + .on((value) => { + if (!value && this.hasAttribute('frozen')) this.removeAttribute('frozen'); + }) + .store((entry$) => { this.checked$ = entry$; }) + + .define('required', TYPE_BOOL) + .onChangeModify('aria-required') + .store((entry$) => { this.required$ = entry$; }) + + .define('toggles', TYPE_BOOL, { value: true}) // yet defined else + .reflect() + .autoDispatch() + + .define('value', TYPE_STRING) + .setTransformer((value) => value == null ? 'on' : value); // onNullSet('on'); + + // Duplicate from active definition? + this.messageManager + .define('change', { toAttribute: 'active' }); // message: true/false + } + + /** + * Attributes managed by the component + * @override + * @type {Array} + */ + static get observedAttributes() { + return super.observedAttributes.concat(['checked', 'on-change', 'required']); + } + + /** @type {String} */ + get value() { return this.attributeManager.getValue('value'); } + + /** + * Returns false if the element is required and not checked, and true otherwise. + * @override + * @param {*} _value Ignored. + * @return {boolean} true if `required` is false or if `checked` is true. + */ + _getValidity(_value = null) { + return this.disabled$.value || !this.required$.value || this.checked$.value; + } +}; diff --git a/pool/shard001/JavaScript/0010610_index.js b/pool/shard001/JavaScript/0010610_index.js new file mode 100644 index 0000000000000000000000000000000000000000..500958f9790406b2c9af618007db3dfa1dad58b0 --- /dev/null +++ b/pool/shard001/JavaScript/0010610_index.js @@ -0,0 +1,46 @@ +import _ from 'lodash'; +import Emitter from 'eventemitter2'; + +import Report from './report'; +import Receiver from './receiver'; +import defaultOptions from '../shared/default'; + + +class API { + + constructor(options = {}) { + this._options = {}; + _.defaultsDeep(this._options, options, defaultOptions); + + this._report = new Report(); + this._eventBus = new Emitter.EventEmitter2(); + + this._receiver = new Receiver(this._options); + this._receiver.onDataReceived((data) => { + if (this._report.update(data)) { + this._eventBus.emit('report', this._report); + } + }); + } + + start() { + this._receiver.start(); + } + + stop() { + if (this._receiver) { + this._receiver.stop(); + } + } + + onReportChange(listener) { + this._eventBus.on('report', listener); + } + + onConnectionChange(listener) { + this._receiver.onConnectionChange(listener); + } +} + + +export default API; diff --git a/pool/shard001/JavaScript/0010614_resource.js b/pool/shard001/JavaScript/0010614_resource.js new file mode 100644 index 0000000000000000000000000000000000000000..e50ca030f35ee04c56041c9bf004d68debdf1834 --- /dev/null +++ b/pool/shard001/JavaScript/0010614_resource.js @@ -0,0 +1,57 @@ +'use strict'; + +var + Q = require('q'), + _ = require('lodash'), + express = require('express'), + errors = require('./errors'), + debug = require('debug')('express-toybox:resource'), + DEBUG = debug.enabled; + +var + PARAM_REGEXP = new RegExp('/:[^/]+$'), + HANDLERS = { + index: { + method: 'get' + }, + create: { + method: 'post' + }, + show: { + method: 'get', + param: true + }, + update: { + method: 'put', + param: true + }, + destroy: { + method: 'delete', + param: true + } + }; + +function configureResource(app, path, module) { + DEBUG && debug('configure RESTful resource on ', path); + + Object.keys(HANDLERS).forEach(function (handlerName) { + var handlerFunc = module[handlerName]; + if (typeof handlerFunc === 'function') { + var handlerInfo = HANDLERS[handlerName]; + app[handlerInfo.method](handlerInfo.param ? path : path.replace(PARAM_REGEXP, ''), handlerFunc); + } + }); + return app; +} + +// +// mixin to express proto. +// + +express.application.useResource = express.Router.useResource = function (name, module) { + return configureResource(this, name, module); +}; + +module.exports = { + configureResource: configureResource +}; diff --git a/pool/shard001/JavaScript/0010615_Select.js b/pool/shard001/JavaScript/0010615_Select.js new file mode 100644 index 0000000000000000000000000000000000000000..e29a0e949a7dc792b18b683b788f98687d9342e9 --- /dev/null +++ b/pool/shard001/JavaScript/0010615_Select.js @@ -0,0 +1,86 @@ +import React from "react"; +import PropTypes from "prop-types"; + +import Dropdown from "../Dropdown/Dropdown"; +import DropdownListTrigger from "../Dropdown/DropdownListTrigger"; + +export default class Select extends React.Component { + constructor() { + super(); + this.input = React.createRef(); + } + buildItemsArray() { + return React.Children.map(this.props.children, child => { + return { + html: child, + id: child.props.value, + selectedHtml: child.props.label || child.props.value, + selectable: !child.props.disabled + }; + }); + } + + handleInputChange(event) { + this.props.onChange(event); + } + + handleDropdownChange(selectedOption) { + const nativeInputValueSetter = Object.getOwnPropertyDescriptor( + window.HTMLInputElement.prototype, + "value" + ).set; + + if (this.input && this.input.current) { + nativeInputValueSetter.call(this.input.current, selectedOption.id); + this.input.current.dispatchEvent(new Event("input", { bubbles: true })); + } + } + + render() { + return ( +
+ + } + /> +
+ ); + } +} + +Select.defaultProps = { + className: "dropdown-select", + onChange() {}, + name: null, + placeholder: "", + value: "" +}; + +Select.propTypes = { + className: PropTypes.string, + onChange: PropTypes.func, + name: PropTypes.string, + placeholder: PropTypes.string, + value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) +}; diff --git a/pool/shard001/JavaScript/0010616_template-compiler.js b/pool/shard001/JavaScript/0010616_template-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..33dc2d42ecc2ef06b9a1260d594d580363cd7f8f --- /dev/null +++ b/pool/shard001/JavaScript/0010616_template-compiler.js @@ -0,0 +1,93 @@ +let compileFlags = null; + +function ConditionalTemplateCompiler() { +} + +ConditionalTemplateCompiler.prototype.transform = function(ast) { + let pluginContext = this; + let walker = new this.syntax.Walker(); + + walker.visit(ast, function(node) { + if (!pluginContext.validate(node)) { + return; + } + + pluginContext.processParams(node); + }); + + return ast; +}; + +ConditionalTemplateCompiler.prototype.mungeNode = function(node, flag, unless) { + let b = this.syntax.builders; + + if (!unless) { + node.path = b.path('if'); + } else { + node.path = b.path('unless'); + } + + let flagEnabled = compileFlags[flag]; + + node.params = [b.boolean(flagEnabled)]; + + if (unless) { + flagEnabled = !flagEnabled; + } + + if (flagEnabled && node.inverse) { + node.inverse = b.program(false, false, node.inverse.loc); + } else if (!flagEnabled && node.program) { + node.program = b.program(false, false, node.program.loc); + } +}; + +ConditionalTemplateCompiler.prototype.mungePlainHelperNode = function(node, unless) { + let compileFlag = node.params[0]['original']; + + if (!(compileFlag in compileFlags)) { + throw 'No compile flag found for ' + compileFlag; + } + + this.mungeNode(node, compileFlag, unless); +}; + +ConditionalTemplateCompiler.prototype.processParams = function(node) { + for (let flag in compileFlags) { + if (node.path.original === 'if-flag-' + flag) { + this.mungeNode(node, flag, false); + } + + if (node.path.original === 'unless-flag-' + flag) { + this.mungeNode(node, flag, true); + } + } + + if (node.path.original === 'if-flag') { + this.mungePlainHelperNode(node, false); + } + + if (node.path.original === 'unless-flag') { + this.mungePlainHelperNode(node, true); + } +}; + +ConditionalTemplateCompiler.prototype.validate = function(node) { + let nodeType = (node.type === 'BlockStatement' || node.type === 'MustacheStatement'); + + if (!nodeType) { + return false; + } + + return ( + node.path && ( + node.path.original.startsWith('if-flag') || + node.path.original.startsWith('unless-flag') + ) + ); +}; + +module.exports = function(flags) { + compileFlags = flags; + return ConditionalTemplateCompiler; +}; diff --git a/pool/shard001/JavaScript/0010618_api3.socket.test.js b/pool/shard001/JavaScript/0010618_api3.socket.test.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2a5cf6461558abb0fe02caee46233ef67c73b4 --- /dev/null +++ b/pool/shard001/JavaScript/0010618_api3.socket.test.js @@ -0,0 +1,178 @@ +/* eslint require-atomic-updates: 0 */ +/* global should */ +'use strict'; + +require('should'); + +describe('Socket.IO in REST API3', function() { + const self = this + , testConst = require('./fixtures/api3/const.json') + , apiConst = require('../lib/api3/const.json') + , instance = require('./fixtures/api3/instance') + , authSubject = require('./fixtures/api3/authSubject') + , utils = require('./fixtures/api3/utils') + ; + + self.identifier = utils.randomString('32', 'aA#'); // let's have a brand new identifier for your testing document + + self.docOriginal = { + identifier: self.identifier, + eventType: 'Correction Bolus', + insulin: 1, + date: (new Date()).getTime(), + app: testConst.TEST_APP + }; + + this.timeout(30000); + + before(async () => { + self.instance = await instance.create({ + storageSocket: true + }); + + self.app = self.instance.app; + self.env = self.instance.env; + self.colName = 'treatments'; + self.urlCol = `/api/v3/${self.colName}`; + self.urlResource = self.urlCol + '/' + self.identifier; + self.urlHistory = self.urlCol + '/history'; + + let authResult = await authSubject(self.instance.ctx.authorization.storage); + + self.subject = authResult.subject; + self.token = authResult.token; + self.socket = self.instance.clientSocket; + }); + + + after(() => { + if(self.instance && self.instance.clientSocket && self.instance.clientSocket.connected) { + self.instance.clientSocket.disconnect(); + } + self.instance.server.close(); + }); + + + it('should not subscribe without accessToken', done => { + self.socket.emit('subscribe', { }, function (data) { + data.success.should.not.equal(true); + data.message.should.equal(apiConst.MSG.SOCKET_MISSING_OR_BAD_ACCESS_TOKEN); + done(); + }); + }); + + + it('should not subscribe by invalid accessToken', done => { + self.socket.emit('subscribe', { accessToken: 'INVALID' }, function (data) { + data.success.should.not.equal(true); + data.message.should.equal(apiConst.MSG.SOCKET_MISSING_OR_BAD_ACCESS_TOKEN); + done(); + }); + }); + + + it('should not subscribe by subject with no rights', done => { + self.socket.emit('subscribe', { accessToken: self.token.denied }, function (data) { + data.success.should.not.equal(true); + data.message.should.equal(apiConst.MSG.SOCKET_UNAUTHORIZED_TO_ANY); + done(); + }); + }); + + + it('should subscribe by valid accessToken', done => { + const cols = ['entries', 'treatments']; + + self.socket.emit('subscribe', { + accessToken: self.token.all, + collections: cols + }, function (data) { + data.success.should.equal(true); + should(data.collections.sort()).be.eql(cols); + done(); + }); + }); + + + it('should emit create event on CREATE', done => { + + self.socket.once('create', (event) => { + event.colName.should.equal(self.colName); + event.doc.should.containEql(self.docOriginal); + delete event.doc.subject; + self.docActual = event.doc; + done(); + }); + + self.instance.post(`${self.urlCol}?token=${self.token.create}`) + .send(self.docOriginal) + .expect(201) + .end((err) => { + should.not.exist(err); + }); + }); + + + it('should emit update event on UPDATE', done => { + + self.docActual.insulin = 0.5; + + self.socket.once('update', (event) => { + delete self.docActual.srvModified; + event.colName.should.equal(self.colName); + event.doc.should.containEql(self.docActual); + delete event.doc.subject; + self.docActual = event.doc; + done(); + }); + + self.instance.put(`${self.urlResource}?token=${self.token.update}`) + .send(self.docActual) + .expect(204) + .end((err) => { + should.not.exist(err); + self.docActual.subject = self.subject.apiUpdate.name; + }); + }); + + + it('should emit update event on PATCH', done => { + + self.docActual.carbs = 5; + self.docActual.insulin = 0.4; + + self.socket.once('update', (event) => { + delete self.docActual.srvModified; + event.colName.should.equal(self.colName); + event.doc.should.containEql(self.docActual); + delete event.doc.subject; + self.docActual = event.doc; + done(); + }); + + self.instance.patch(`${self.urlResource}?token=${self.token.update}`) + .send({ 'carbs': self.docActual.carbs, 'insulin': self.docActual.insulin }) + .expect(204) + .end((err) => { + should.not.exist(err); + }); + }); + + + it('should emit delete event on DELETE', done => { + + self.socket.once('delete', (event) => { + event.colName.should.equal(self.colName); + event.identifier.should.equal(self.identifier); + done(); + }); + + self.instance.delete(`${self.urlResource}?token=${self.token.delete}`) + .expect(204) + .end((err) => { + should.not.exist(err); + }); + }); + +}); + diff --git a/pool/shard001/JavaScript/0010641_float64array-store-div.js b/pool/shard001/JavaScript/0010641_float64array-store-div.js new file mode 100644 index 0000000000000000000000000000000000000000..10b0011fbc41c083af0144deda068f576f074a5b --- /dev/null +++ b/pool/shard001/JavaScript/0010641_float64array-store-div.js @@ -0,0 +1,16 @@ +// Copyright 2014 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +function Module(stdlib, foreign, heap) { + "use asm"; + var MEM64 = new stdlib.Float64Array(heap); + function foo(i) { + MEM64[0] = (i >>> 0) / 2; + return MEM64[0]; + } + return { foo: foo }; +} + +var foo = Module(this, {}, new ArrayBuffer(64 * 1024)).foo; +assertEquals(0.5, foo(1)); diff --git a/pool/shard001/JavaScript/0010645_gmaps.js b/pool/shard001/JavaScript/0010645_gmaps.js new file mode 100644 index 0000000000000000000000000000000000000000..9b8e5a0a5c2857f763b7a4bde1f132c4dccdf3b8 --- /dev/null +++ b/pool/shard001/JavaScript/0010645_gmaps.js @@ -0,0 +1,143 @@ +var extendObject = function(obj, new_obj) { + if (obj === new_obj) { + return obj; + } + + for (var name in new_obj) { + obj[name] = new_obj[name]; + } + return obj; +}; + +var coordinatesToLatlng = function(coordinates) { + var lat = coordinates[0], + lng = coordinates[1]; + return new google.maps.LatLng(lat, lng); +}; + +var getElementById = function(id) { + id = id.replace('#', ''); + return document.getElementById(id); +}; + +var getDataAttribute = function(elem, key) { + var data = elem.getAttribute('data-' + key); + return window.JSON.parse(data); +}; + +var GMaps = function(options) { + options.mapType = options.mapType || 'roadmap'; + + var that = this, + container_id = options.el || options.div, + mapCenter = new google.maps.LatLng(37.4419, -122.1419), + el = typeof container_id == 'string' ? getElementById(container_id) : container_id, + locations = options.locations, + markers = []; + + + var fitZoom = function() { + var latLngs = []; + for (var i = 0; i < markers.length; i++) { + if (typeof(markers[i].visible) === 'boolean' && markers[i].visible) { + latLngs.push(markers[i].getPosition()); + } + } + + fitLatLngBounds(latLngs); + }; + + var fitLatLngBounds = function(latLngs) { + var total = latLngs.length; + var bounds = new google.maps.LatLngBounds(); + + for (var i = 0; i < total; i++) { + bounds.extend(latLngs[i]); + } + + map.fitBounds(bounds); + }; + + var setCenter = function(lat, lng) { + map.panTo(new google.maps.LatLng(lat, lng)); + }; + + var hideInfoWindows = function() { + for (var i = 0; i < markers.length; i++){ + if (markers[i].infoWindow) { + markers[i].infoWindow.close(); + } + }; + }; + + var addMarker = function(options) { + var markerOptions = { + position: coordinatesToLatlng(options.coordinates), + title: options.address, + animation: google.maps.Animation.DROP, + map: null, + icon: options.icon + }; + + var marker = new google.maps.Marker(markerOptions); + + if (options.infoWindow) { + marker.infoWindow = new google.maps.InfoWindow({ + content: options.infoWindow.content, + maxWidth: options.infoWindow.maxWidth + }); + google.maps.event.addListener(marker, 'click', function() { + hideInfoWindows(); + marker.infoWindow.open(map, marker); + }); + }; + markers.push(marker); + marker.setMap(map); + }; + + if (typeof(el) === 'undefined' || el === null) { + throw 'Map error: Can\'t find map container.'; + } + + if (options.locations.length > 0) { + mapCenter = coordinatesToLatlng(locations[0].coordinates); + } + + var mapOptions = { + center: mapCenter, + disableDoubleClickZoom: options.disableDoubleClickZoom, + draggable: options.draggable, + keyboardShortcuts: options.keyboardShortcuts, + mapTypeControl: options.mapTypeControl, + mapTypeId: google.maps.MapTypeId[options.mapType.toUpperCase()], + panControl: options.panControl , + scrollwheel: options.scrollwheel, + streetViewControl: options.streetViewControl, + styles: options.styles, + zoom: options.zoom, + zoomControl: options.zoomControl + }; + + el.style.width = options.width; + el.style.height = options.height; + + var map = new google.maps.Map(el, mapOptions); + + for (var i = 0; i < locations.length; i++) { + addMarker(locations[i]); + } + if (locations.length > 1){ + fitZoom(); + } +}; + +function initMap() { + var maps = document.getElementsByClassName('djangocms_gmaps'); + for (var i = 0; i < maps.length; i++) { + var mapOptions = { + div: maps[i] + }; + mapOptions = extendObject(mapOptions, getDataAttribute(maps[i], 'options')); + new GMaps(mapOptions); + } +}; diff --git a/pool/shard001/JavaScript/0010648_methods.js b/pool/shard001/JavaScript/0010648_methods.js new file mode 100644 index 0000000000000000000000000000000000000000..c7a0919bd611228b877956bba8674b902eb437ec --- /dev/null +++ b/pool/shard001/JavaScript/0010648_methods.js @@ -0,0 +1,124 @@ +// ========================================================================== +// Project: SproutCore - JavaScript Application Framework +// Copyright: ©2006-2010 Apple Inc. and contributors. +// License: Licensed under MIT license (see license.js) +// ========================================================================== +var b, counter; + +module("SC.ButtonView#actions", { + setup: function() { + b = SC.ButtonView.create(); + } +}); + +test("Emulate mouse click to verify if the button activates", function() { + b.triggerAction(); + equals(b.get('isActive'), YES, "the should be active for 200ms"); + +}); + + +test("Test different moused states", function() { + b.set('isEnabled', YES); + b.mouseDown(); + equals(b.get('isActive'), YES, "the button should be active after a mouseDown event"); + b.mouseExited(); + equals(b.get('isActive'), NO, "the button should be active after a mouseDown event"); + b.mouseEntered(); + equals(b.get('isActive'), b._isMouseDown, "the button should be active after a mouseDown event"); +// b.mouseUp(); +// equals(b.get('isActive'), NO, "the button should be inactive after a mouseUP event"); + + b.set('buttonBehavior', SC.TOGGLE_BEHAVIOR); + b._action(); + equals(b.get('value'), b.get('toggleOnValue'), "the value should be the same as the toggle value"); + + b.set('buttonBehavior', SC.TOGGLE_ON_BEHAVIOR); + b._action(); + equals(b.get('value'), b.get('toggleOnValue'), "the value should be the same as the toggle value"); + + b.set('buttonBehavior', SC.TOGGLE_OFF_BEHAVIOR); + b._action(); + equals(b.get('value'), b.get('toggleOffValue'), "the value should be the same as the toggle value"); +}); + + +module("SC.ButtonView#actions - SC.HOLD_BEHAVIOR", { + setup: function() { + counter = SC.Object.create({ + value: 0, + increment: function(){ + this.set('value', this.get('value') + 1); + } + }); + + b = SC.ButtonView.create({ + buttonBehavior: SC.HOLD_BEHAVIOR, + holdInterval: 5, + target: counter, + action: 'increment', + + // Is it a bad idea to stub like this? If we don't do it this way, we need to set up a Pane + _runAction: function(evt) { + var action = this.get('action'), + target = this.get('target') || null; + + target[action](); + } + }); + } +}); + +test('Test triggerAction only happens once', function(){ + b.triggerAction(); + SC.RunLoop.begin().end(); + var assertions = function(){ + equals(counter.get('value'), 1, "should only run action once"); + start(); + }; + + stop(); + setTimeout(assertions, 300); +}); + +// This test is not nearly reliable enough +test("Test action repeats while active", function(){ + b.set('isActive', YES); + b._action(); + + var assertions = function(){ + // The actual number of times in not entirely predictable since there can be delays beyond the holdInterval + ok(counter.get('value') > 2, "should have run more than 2 times"); + b.set('isActive', NO); // Stops triggering + start(); + }; + + stop(); + setTimeout(assertions, 300); +}); + +test("Test action happens on mouseDown", function(){ + b.mouseDown(); + equals(counter.get('value'), 1, "should have run once"); + b.set('isActive', NO); // Stops triggering +}); + +test("Test action does not happen on mouseUp", function(){ + b._isMouseDown = YES; + b.mouseUp(); + equals(counter.get('value'), 0, "should not have run"); +}); + +test("Should stop when inactive", function(){ + b.set('isActive', YES); + b._action(); + b.set('isActive', NO); + + var assertions = function(){ + equals(counter.get('value'), 1, "should only run action once"); + start(); + }; + + stop(); + setTimeout(assertions, 10); +}); diff --git a/pool/shard001/JavaScript/0010650_get-age.js b/pool/shard001/JavaScript/0010650_get-age.js new file mode 100644 index 0000000000000000000000000000000000000000..d160032e3d82f44aa23ef5608ac60639461734e3 --- /dev/null +++ b/pool/shard001/JavaScript/0010650_get-age.js @@ -0,0 +1,21 @@ +import getAge from '../get-age' + +test('returns null if the person has no age', () => { + const person = {} + const result = getAge(person) + expect(result).toBe(null) +}) + +test(`can get a person's age`, () => { + const age = 23 + const person = {age} + const result = getAge(person) + expect(result).toBe(age) +}) + +test(`returns 0 if the person's age is 0`, () => { + const age = 0 + const person = {age} + const result = getAge(person) + expect(result).toBe(age) +}) diff --git a/pool/shard001/JavaScript/0010653_Class.js b/pool/shard001/JavaScript/0010653_Class.js new file mode 100644 index 0000000000000000000000000000000000000000..7b9544bf79810d05e8a66d5545e31f1f52ae3233 --- /dev/null +++ b/pool/shard001/JavaScript/0010653_Class.js @@ -0,0 +1,82 @@ +"use strict"; + +define([ + 'lodash', + 'events' +], function(_, Events) { + + var Class = {}; + + // `ctor` and `inherits` are from Backbone (with some modifications): + // http://documentcloud.github.com/backbone/ + + // Shared empty constructor function to aid in prototype-chain creation. + var ctor = function () {}; + + // Helper function to correctly set up the prototype chain, for subclasses. + // Similar to `goog.inherits`, but uses a hash of prototype properties and + // class properties to be extended. + var inherits = function (parent, protoProps, staticProps) { + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call `super()`. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + child = function () { return parent.apply(this, arguments); }; + } + + // Inherit class (static) properties from parent. + _.extend(child, parent); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) _.extend(child.prototype, protoProps); + + if (protoProps) _.extend(child.prototype, Events); + + // Add static properties to the constructor function, if supplied. + if (staticProps) _.extend(child, staticProps); + + // Correctly set child's `prototype.constructor`. + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is needed later. + child.__super__ = parent.prototype; + + return child; + }; + + // Self-propagating extend function. + // Create a new class that inherits from the class found in the `this` context object. + // This function is meant to be called in the context of a constructor function. + function extendThis(protoProps, staticProps) { + var child = inherits(this, protoProps, staticProps); + child.extend = extendThis; + return child; + } + + // A primitive base class for creating subclasses. + // All subclasses will have the `extend` function. + // Example: + // var MyClass = Class.extend({ + // someProp: 'My property value', + // someMethod: function () { ... } + // }); + // var instance = new MyClass(); + Class = function () {}; + Class.extend = extendThis; + + // Inject to class events module + _.extend(Class, Events); + + // Return prepared class object + return Class; +}); diff --git a/pool/shard001/JavaScript/0010655_sketch.js b/pool/shard001/JavaScript/0010655_sketch.js new file mode 100644 index 0000000000000000000000000000000000000000..0600a3a404e6ab0da2a2f772afc035e2e0307c76 --- /dev/null +++ b/pool/shard001/JavaScript/0010655_sketch.js @@ -0,0 +1,47 @@ +// Beat Detection with offline context example by @b2renger +// Building off an example by Joe Sullivan : http://tech.beatport.com/2014/web-audio/beat-detection-using-web-audio/ +// and this example, too : https://github.com/JMPerez/beats-audio-api + + +var source_file; // sound file + + +function preload(){ + source_file = loadSound('../_files/Tripping.mp3'); // preload the sound +} + + +function setup() { + createCanvas(windowWidth, 150); + background(180); + + src_length = source_file.duration(); + source_file.playMode('restart'); + println("source duration: " +src_length); + + // find beat preprocessing the source file with lowpass + var beats = source_file.processPeaks(onComplete); + +} + +function draw() { + +} + +function onComplete(data) { + for (var i = 0; i < data.length; i++) { + // add a cue to the soundfile with a callback function + source_file.addCue(data[i], logBeat); + + // draw peaks + var xpos = map(i,0,src_length,0,width); + stroke(0); + line(xpos,0,xpos,height); + } + + source_file.play(); +} + +function logBeat() { + console.log('beat!'); +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010657_ws.js b/pool/shard001/JavaScript/0010657_ws.js new file mode 100644 index 0000000000000000000000000000000000000000..ad96d4b408f98be129af9908cd71e6987d5e51ad --- /dev/null +++ b/pool/shard001/JavaScript/0010657_ws.js @@ -0,0 +1,89 @@ +var tools = require('github.com/yobert/pkunk/js/tools'); + +function UndbSocket(store, uri) { + var ws = new WebSocket(uri); + var ws_id = 'server-ws'; + + this.sock = ws; + + var firstmessage = false; + var t = this; + + var softerror; + var do_pings = false; + + var onchange = function(op) { + if(op.changesource && op.changesource == ws_id) + return; + + var o = { + Method: op.Method, + Path: op.Path, + Id: op.Id, + Type: op.Type, + Values: op.Values + }; + var msg = JSON.stringify([o]); + //console.log('send: '+msg); + ws.send(msg); + }; + + var ping = function() { + if(do_pings) { + ws.send(JSON.stringify([])); + } + + setTimeout(ping, 1000); + }; + + ping(); + + ws.onopen = function() { + //console.log("websocket open"); + store.addListener('CHANGE', onchange); + do_pings = true; + }; + + ws.onclose = function() { + store.removeListener('CHANGE', onchange); + //console.log("websocket closed"); + if(t.onClose) + t.onClose(softerror); + + softerror = undefined; + do_pings = false; + }; + + //ws.onerror = function(err) { + // console.log("websocket error"); + //}; + + ws.onmessage = function(msg) { + //console.log('recv: '+msg.data) + + var oplist = JSON.parse(msg.data); + if(oplist && oplist.Error) { + softerror = oplist.Error; + return; + } + + var err; + for(var i in oplist) { + err = store.Exec(oplist[i], ws_id); + + if(err) + throw(err); + } + + if(!firstmessage) { + firstmessage = true; + + if(t.onFirstMessage) + t.onFirstMessage(); + } + }; +} + +module.exports = { + UndbSocket: UndbSocket +}; diff --git a/pool/shard001/JavaScript/0010660_Header.js b/pool/shard001/JavaScript/0010660_Header.js new file mode 100644 index 0000000000000000000000000000000000000000..37b76fe55ba64d12aff7d410ed0be8ab69a05295 --- /dev/null +++ b/pool/shard001/JavaScript/0010660_Header.js @@ -0,0 +1,95 @@ +import React, { Component } from 'react' +import { Link } from 'react-router-dom' +import classname from 'classnames' +import './header.less' +import githubImg from './github.png' +import logoImg from './logo.png' +import downloadImg from './download.png' +import * as globalActions from '@/actions/global' +import { bindActionCreators } from 'redux' +import { connect } from 'react-redux' +import html2canvas from 'html2canvas' + +@connect( + state => state, + dispatch => bindActionCreators(globalActions, dispatch) +) +export default class Header extends Component { + constructor(props) { + super(props) + this.state = { + hide: true, + } + //const pathname = this.props.pathname; + //this.props.currentPage(pathname); + } + + componentDidMount() { + + } + + html2ToImg(dom) { + html2canvas(dom, { + useCORS: true, + background: '#fff', + origin: 'http://echarts.baidu.com', + onrendered: (canvas) => { + const $a = document.createElement('a'); + canvas.style.backgroundColor = '#fff'; + $a.download = 'pages.jpg'; + $a.setAttribute('target', '_blank'); + $a.href = canvas.toDataURL(); + const evt = new MouseEvent('click', { + view: window, + bubbles: true, + cancelable: false + }); + $a.dispatchEvent(evt); + } + }) + } + + render() { + return ( +
+ ) + } + +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010662_twttr.js b/pool/shard001/JavaScript/0010662_twttr.js new file mode 100644 index 0000000000000000000000000000000000000000..01b5371942ac76699570c8df0d92b783eecf14ec --- /dev/null +++ b/pool/shard001/JavaScript/0010662_twttr.js @@ -0,0 +1,22 @@ +/* eslint no-underscore-dangle: 0 */ +(function () { + 'use strict'; + window.twttr = (function (d, s, id) { + var fjs = d.getElementsByTagName(s)[0]; + if (d.getElementById(id)) { + return window.twttr; + } + var js = d.createElement(s); + js.id = id; + js.src = 'https://platform.twitter.com/widgets.js'; + fjs.parentNode.insertBefore(js, fjs); + var t = { + _e: [], + ready: function (f) { + t._e.push(f); + } + }; + return window.twttr || t; + }(document, 'script', 'twitter-wjs')); + +})(); diff --git a/pool/shard001/JavaScript/0010664_load-sound.js b/pool/shard001/JavaScript/0010664_load-sound.js new file mode 100644 index 0000000000000000000000000000000000000000..639fcc2afa3b66d1efa2a71f63d6982f1635175c --- /dev/null +++ b/pool/shard001/JavaScript/0010664_load-sound.js @@ -0,0 +1,71 @@ +const StringUtil = require('../util/string-util'); +const log = require('../util/log'); + +/** + * Initialize a sound from an asset asynchronously. + * @param {!object} sound - the Scratch sound object. + * @property {string} md5 - the MD5 and extension of the sound to be loaded. + * @property {Buffer} data - sound data will be written here once loaded. + * @param {!Asset} soundAsset - the asset loaded from storage. + * @param {!Runtime} runtime - Scratch runtime, used to access the storage module. + * @param {SoundBank} soundBank - Scratch Audio SoundBank to add sounds to. + * @returns {!Promise} - a promise which will resolve to the sound when ready. + */ +const loadSoundFromAsset = function (sound, soundAsset, runtime, soundBank) { + sound.assetId = soundAsset.assetId; + if (!runtime.audioEngine) { + log.error('No audio engine present; cannot load sound asset: ', sound.md5); + return Promise.resolve(sound); + } + return runtime.audioEngine.decodeSoundPlayer(Object.assign( + {}, + sound, + {data: soundAsset.data} + )).then(soundPlayer => { + sound.soundId = soundPlayer.id; + // Set the sound sample rate and sample count based on the + // the audio buffer from the audio engine since the sound + // gets resampled by the audio engine + const soundBuffer = soundPlayer.buffer; + sound.rate = soundBuffer.sampleRate; + sound.sampleCount = soundBuffer.length; + + if (soundBank !== null) { + soundBank.addSoundPlayer(soundPlayer); + } + + return sound; + }); +}; + +/** + * Load a sound's asset into memory asynchronously. + * @param {!object} sound - the Scratch sound object. + * @property {string} md5 - the MD5 and extension of the sound to be loaded. + * @property {Buffer} data - sound data will be written here once loaded. + * @param {!Runtime} runtime - Scratch runtime, used to access the storage module. + * @param {SoundBank} soundBank - Scratch Audio SoundBank to add sounds to. + * @returns {!Promise} - a promise which will resolve to the sound when ready. + */ +const loadSound = function (sound, runtime, soundBank) { + if (!runtime.storage) { + log.error('No storage module present; cannot load sound asset: ', sound.md5); + return Promise.resolve(sound); + } + const idParts = StringUtil.splitFirst(sound.md5, '.'); + const md5 = idParts[0]; + const ext = idParts[1].toLowerCase(); + sound.dataFormat = ext; + return ( + (sound.asset && Promise.resolve(sound.asset)) || + runtime.storage.load(runtime.storage.AssetType.Sound, md5, ext) + ).then(soundAsset => { + sound.asset = soundAsset; + return loadSoundFromAsset(sound, soundAsset, runtime, soundBank); + }); +}; + +module.exports = { + loadSound, + loadSoundFromAsset +}; diff --git a/pool/shard001/JavaScript/0010665_Promise.js b/pool/shard001/JavaScript/0010665_Promise.js new file mode 100644 index 0000000000000000000000000000000000000000..631ca15884be056e5c518e8f41602a12bb3d6655 --- /dev/null +++ b/pool/shard001/JavaScript/0010665_Promise.js @@ -0,0 +1,27 @@ +ScalaJS.is.scala_concurrent_Promise = (function(obj) { + return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_concurrent_Promise))) +}); +ScalaJS.as.scala_concurrent_Promise = (function(obj) { + if ((ScalaJS.is.scala_concurrent_Promise(obj) || (obj === null))) { + return obj + } else { + ScalaJS.throwClassCastException(obj, "scala.concurrent.Promise") + } +}); +ScalaJS.isArrayOf.scala_concurrent_Promise = (function(obj, depth) { + return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_concurrent_Promise))) +}); +ScalaJS.asArrayOf.scala_concurrent_Promise = (function(obj, depth) { + if ((ScalaJS.isArrayOf.scala_concurrent_Promise(obj, depth) || (obj === null))) { + return obj + } else { + ScalaJS.throwArrayCastException(obj, "Lscala.concurrent.Promise;", depth) + } +}); +ScalaJS.data.scala_concurrent_Promise = new ScalaJS.ClassTypeData({ + scala_concurrent_Promise: 0 +}, true, "scala.concurrent.Promise", undefined, { + scala_concurrent_Promise: 1, + java_lang_Object: 1 +}); +//@ sourceMappingURL=Promise.js.map diff --git a/pool/shard001/JavaScript/0010672_save.js b/pool/shard001/JavaScript/0010672_save.js new file mode 100644 index 0000000000000000000000000000000000000000..4910e89ab4e820735526bc20348e1f2f8d56fb72 --- /dev/null +++ b/pool/shard001/JavaScript/0010672_save.js @@ -0,0 +1,19 @@ +const fs = require("fs"); +const path = require("path"); +const util = require("util"); +const game = require("../../src/game"); + +const writeFileAsync = util.promisify(fs.writeFile); +const stringify = (object) => JSON.stringify(object, null, " "); + +module.exports = async function saveWorld() { + for (let area of game.world.areas.values()) { + let areaPath = path.join(__dirname, "../../areas", area.folderName); + + await [ + writeFileAsync(path.join(areaPath, "area.json"), stringify(area.serialize())), + writeFileAsync(path.join(areaPath, "rooms.json"), stringify([...area.rooms.values()].map((room) => room.serialize()))), + writeFileAsync(path.join(areaPath, "map.json"), stringify(area.map.map((cell) => cell.serialize()))) + ]; + } +} diff --git a/pool/shard001/JavaScript/0010674_test_issue_931.js b/pool/shard001/JavaScript/0010674_test_issue_931.js new file mode 100644 index 0000000000000000000000000000000000000000..357a7c65430d10461b84153998c4faba2b8e0996 --- /dev/null +++ b/pool/shard001/JavaScript/0010674_test_issue_931.js @@ -0,0 +1,117 @@ +const os = require("os"); +const { make_debugLog } = require("node-opcua-debug"); +const { OPCUAClient, MessageSecurityMode, SecurityPolicy } = require(".."); + +const debugLog = make_debugLog("TEST"); + +// eslint-disable-next-line import/order +const describe = require("node-opcua-leak-detector").describeWithLeakDetector; +describe("issue #931 investigation", function () { + this.timeout(30000); + async function wait(t) { + return await new Promise((resolve) => setTimeout(resolve, t)); + } + + async function doTest(options, host) { + const client = OPCUAClient.create(options); + + let backoffCount = 0; + client.on("backoff", (retry, next) => { + backoffCount++; + debugLog("backoff", retry, next); + }); + + debugLog("Before Connect"); + client.connect(`opc.tcp://${host}:20000`).catch((err) => { + debugLog("connection failed !", err.message); + }); + debugLog("Connect in progress"); + await wait(3000); + + backoffCount.should.be.aboveOrEqual(0); + + const refBackoffCount = backoffCount; + + debugLog("now disconnecting"); + await client.disconnect(); + await wait(1000); + backoffCount.should.eql( + refBackoffCount, + "Backoff should stops when disconnect is called while connection is still in progress" + ); + } + it("931-A should be able to disconnect when the client is trying to initially connect to a server - No Security - Localhost", async () => { + const options = { + connectionStrategy: { + maxRetry: 100, + initialDelay: 100, + maxDelay: 200 + } + }; + await doTest(options, "localhost"); + }); + it("931-A should be able to disconnect when the client is trying to initially connect to a server - No Security - hostname", async () => { + const options = { + connectionStrategy: { + maxRetry: 100, + initialDelay: 100, + maxDelay: 200 + } + }; + await doTest(options, os.hostname()); + }); + it("931-B should be able to disconnect when the client is trying to initially connect to a server - With Security - localhost", async () => { + const options = { + connectionStrategy: { + maxRetry: 100, + initialDelay: 100, + maxDelay: 200 + }, + securityMode: MessageSecurityMode.SignAndEncrypt, + securityPolicy: SecurityPolicy.Basic256Sha256 + }; + await doTest(options, "localhost"); + }); + it("931-B should be able to disconnect when the client is trying to initially connect to a server - With Security - hostname", async () => { + const options = { + connectionStrategy: { + maxRetry: 100, + initialDelay: 100, + maxDelay: 200 + }, + securityMode: MessageSecurityMode.SignAndEncrypt, + securityPolicy: SecurityPolicy.Basic256Sha256 + }; + await doTest(options, os.hostname()); + }); + + it("931-Z connect disconnect no wait ", async () => { + const host = os.hostname(); + const options = { + connectionStrategy: { + maxRetry: 100, + initialDelay: 100, + maxDelay: 200 + }, + securityMode: MessageSecurityMode.SignAndEncrypt, + securityPolicy: SecurityPolicy.Basic256Sha256 + }; + const client = OPCUAClient.create(options); + + let backoffCount = 0; + client.on("backoff", (retry, next) => { + backoffCount++; + debugLog("backoff", retry, next); + }); + + debugLog("Before Connect"); + client.connect(`opc.tcp://${host}:20000`).catch((err) => { + debugLog("connection failed !", err.message); + }); + debugLog("Connect in progress"); + debugLog("now disconnecting"); + await client.disconnect(); + await wait(2000); + backoffCount.should.eql(0, "Backoff should stops when disconnect is called while connection is still in progress"); + }); +}); diff --git a/pool/shard001/JavaScript/0010679_window-frame-test.js b/pool/shard001/JavaScript/0010679_window-frame-test.js new file mode 100644 index 0000000000000000000000000000000000000000..e378c7f5478dd6c879f572b926867c12819793b3 --- /dev/null +++ b/pool/shard001/JavaScript/0010679_window-frame-test.js @@ -0,0 +1,18 @@ +/*global describe,before,it,after */ +var desired, remoteWdConfig, test, _ref; + +_ref = require('./config'); +desired = _ref.desired; +remoteWdConfig = _ref.remoteWdConfig; + +test = require('../common/window-frame-test-base').test; + +describe("wd", function() { + describe("ghostdriver", function() { + describe("window frame test", function() { + describe("using ghostdriver", function() { + test(remoteWdConfig, desired); + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010687_ripple-effects.js b/pool/shard001/JavaScript/0010687_ripple-effects.js new file mode 100644 index 0000000000000000000000000000000000000000..14e2913dd988de12cb6922c5e3dab751d31096b5 --- /dev/null +++ b/pool/shard001/JavaScript/0010687_ripple-effects.js @@ -0,0 +1,75 @@ +/** + * @author xingo + * @date 2016-03-07 version 0.2 + * @description ripple effects for tips-box and mobile-sidebar + * @update add effects to mobile-sidebar & more moudler + * + */ +define(['jquery'], function($) { + + var $rippleRemove; + //pc + var addRippleEffectHandler = function(event) { + if ($rippleRemove) { + var $rippleDivRemoveVar = $rippleRemove; + setTimeout(function() { + $rippleDivRemoveVar.removeClass('ripple-selecting'); + setTimeout(function() { + $rippleDivRemoveVar.remove(); + }, 750); + }, 750); + } + $itemClicked = $(this); + var offset = $itemClicked.offset(); + var top = offset.top; + var left = offset.left; + if (event.data == "pc") { + var offsetX = event.pageX - left; + var offsetY = event.pageY - top; + } else { + console.log(event.originalEvent); + top = top - $(document).scrollTop(); + var offsetX = event.clientX - left; + var offsetY = event.clientY - top; + } + + var radius = Math.max($itemClicked.innerHeight(), $itemClicked.innerWidth()); + + var $rippleDiv = $('
'); + $rippleDiv + .css('width', radius + 'px') + .css('height', radius + 'px') + .css('left', (offsetX - radius / 2) + 'px') + .css('top', (offsetY - radius / 2) + 'px'); + $itemClicked.append($rippleDiv); + $rippleRemove = $rippleDiv; + event.stopPropagation(); + }; + var removeRippleEffectHandler = function() { + if (!$rippleRemove) { + return; + } + var $rippleDiv = $rippleRemove; + setTimeout(function() { + $rippleDiv.removeClass('ripple-selecting'); + setTimeout(function() { + $rippleDiv.remove(); + }, 750); + }, 750); + }; + + + + return { + init: function() { + $('.tips-inner li') //TODO desktop touch + //when bind mousedown and up,Firefox won't execute click event + .on('mousedown', null, "pc", addRippleEffectHandler) + .on('mouseup', null, "pc", removeRippleEffectHandler); + $('#viewer-box .viewer-box-l .viewer-box-wrap>.viewer-title,#viewer-box .viewer-box-l .viewer-box-wrap li') //should investgate why touchstart and end didn't let click happen; + .on('mousedown', null, "mobile", addRippleEffectHandler) + .on('mouseup', null, "mobile", removeRippleEffectHandler); + } + }; + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010688_errors.js b/pool/shard001/JavaScript/0010688_errors.js new file mode 100644 index 0000000000000000000000000000000000000000..12f5a761f114783abab616e082b67fe08367d175 --- /dev/null +++ b/pool/shard001/JavaScript/0010688_errors.js @@ -0,0 +1,19 @@ +/** + * A class that represents an invalid validation rule pareameter + * + * @constructor + * @author Sendy Halim + * @param message - The error message. + */ +function InvalidValidationRuleParameter(ruleParameter, reason) { + var defaultMessage = ruleParameter + ' is not a valid rule parameter.'; + this.message = reason ? defaultMessage + '. ' + reason : defaultMessage; + this.name = 'InvalidValidationRuleParameter'; + + Error.captureStackTrace(this, InvalidValidationRuleParameter); +} + +InvalidValidationRuleParameter.prototype = Object.create(Error.prototype); +InvalidValidationRuleParameter.prototype.constructor = InvalidValidationRuleParameter; + +export {InvalidValidationRuleParameter}; diff --git a/pool/shard001/JavaScript/0010689_VindictiveRanger.js b/pool/shard001/JavaScript/0010689_VindictiveRanger.js new file mode 100644 index 0000000000000000000000000000000000000000..57ea93494b65713eb3ca17d796566c8bd91dd17a --- /dev/null +++ b/pool/shard001/JavaScript/0010689_VindictiveRanger.js @@ -0,0 +1,27 @@ +const DrawCard = require('../../drawcard'); + +class VindictiveRanger extends DrawCard { + setupCardAbilities() { + this.reaction({ + when: { + afterChallenge: event => event.challenge.isMatch({ loser: this.controller, defendingPlayer: this.controller }) + }, + handler: context => { + this.game.promptForIcon(context.player, this, icon => { + this.game.addMessage('{0} uses {1} to gain stealth and {2} {3} icon', context.player, this, icon === 'intrigue' ? 'an' : 'a', icon); + this.untilEndOfPhase(ability => ({ + match: this, + effect: [ + ability.effects.addIcon(icon), + ability.effects.addKeyword('Stealth') + ] + })); + }); + } + }); + } +} + +VindictiveRanger.code = '12031'; + +module.exports = VindictiveRanger; diff --git a/pool/shard001/JavaScript/0010693_main.js b/pool/shard001/JavaScript/0010693_main.js new file mode 100644 index 0000000000000000000000000000000000000000..3d145b71ede1731d6c973ba1a657eaac9acdbed2 --- /dev/null +++ b/pool/shard001/JavaScript/0010693_main.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * @ngdoc function + * @name yeomanFunApp.controller:MainCtrl + * @description + * # MainCtrl + * Controller of the yeomanFunApp + */ +angular.module('simpleScheduleApp') + .controller('MainCtrl', function ($scope, calendar) { + + + $scope.calendar = calendar; //Add the calendar to our controller scope + + //When Add is clicked call this function + $scope.addEvent = function () { + + calendar.addEvent( + $scope.startTime, + $scope.endTime, + $scope.calendarinput.scheduleEventName, + $scope.calendarinput.scheduleOption + ); + + $scope.calendar.rowCollection = calendar.rowCollection; + }; + + $scope.removeEvent = function (index) { + calendar.removeEvent(index); + $scope.calendar.rowCollection = calendar.rowCollection; + }; +}); + + diff --git a/pool/shard001/JavaScript/0010699_empire.js b/pool/shard001/JavaScript/0010699_empire.js new file mode 100644 index 0000000000000000000000000000000000000000..4d76bf0fb149e36cfc20c965aa4ddc706a520df9 --- /dev/null +++ b/pool/shard001/JavaScript/0010699_empire.js @@ -0,0 +1,30 @@ +/*********************************************************************************************************************** + * + * gameEmpireController + * + **********************************************************************************************************************/ +const fs = require("fs"); // https://nodejs.org/api/fs.html +const path = require("path"); // https://nodejs.org/api/path.html +const i18n = require("i18n"); // https://github.com/mashpie/i18n-node +const moment = require("moment"); // https://momentjs.com/ +const apiEmpireGameDataController = require("../api/gameData/empire"); +const cfg = require("../../config"); + +/* + * show game empire screen ============================================================================================= + * @param {ExpressHTTPRequest} req + * @param {ExpressHTTPResponse} res + */ +exports.showIndex = async (req, res) => { + const pathArea = path.join(cfg.app.projectDir, "client", "lang", req.user.locale, "empire.json"); + const pathCommon = path.join(cfg.app.projectDir, "client", "lang", req.user.locale, "common.json"); + const areaTime = fs.statSync(pathArea).mtime; + const commonTime = fs.statSync(pathCommon).mtime; + const gameData = await apiEmpireGameDataController.fetch(req.user.selectedPlayer); + res.render("game/empire", { + title: i18n.__("GAME.EMPIRE.LABEL"), + session: req.session, + textVersion: moment(areaTime).diff(commonTime) > 0 ? areaTime : commonTime, + gameData + }); +}; diff --git a/pool/shard001/JavaScript/0010701_podpress_jquery_ui_widgetssettings.js b/pool/shard001/JavaScript/0010701_podpress_jquery_ui_widgetssettings.js new file mode 100644 index 0000000000000000000000000000000000000000..20557fd81a14cde7f0c21dd7938ce020bbbb089a --- /dev/null +++ b/pool/shard001/JavaScript/0010701_podpress_jquery_ui_widgetssettings.js @@ -0,0 +1,41 @@ +podPress_jQuery(document).ready(function() { + // Widget Settings Accordion (on page loading) + podPress_jQuery( '.podpress_widget_accordion' ).accordion({ + header: 'h5', + autoHeight: false + }); + + // bind the Accordion effect after saving the widgets settings (WP >= 2.9) + podPress_jQuery('input.widget-control-save').live('click', function() { + var podpress_a_widget_id = podPress_jQuery(this).closest('div.widget').attr('id'); + if ( podpress_a_widget_id.search(/podpress_feedbuttons/i) != -1 ) { + jQuery('#'+podpress_a_widget_id).ajaxComplete( function(event, request, settings) { + if ( settings.data.search(/action=save-widget/i) != -1 && settings.data.search(/delete_widget=1/i) == -1 ) { + podPress_jQuery( '.podpress_widget_accordion' ).accordion({ + header: 'h5', + autoHeight: false + }); + //alert('live\n' + settings.data); + } + }); + } + }); + + // bind the Accordion effect after adding the widget to a sidebar in a WP >= 2.9 sidebar + jQuery('div.widgets-sortables').bind( 'sortstop', function(e, ui) { + // the sidebar element is a jQuery Sortable list. After you drop a widget on a sidebar (or when you change the order of the list elements) this event happens. + var podpress_a_widget_id = ui.item.find('a.widget-action').closest('div.widget').attr('id'); + var podpress_fbw_status = 'notloaded'; + if ( podpress_a_widget_id.search(/podpress_feedbuttons/i) != -1 ) { + jQuery('#'+podpress_a_widget_id).ajaxComplete( function(event, request, settings) { + if ( podpress_fbw_status == 'notloaded' && settings.data.search(/action=save-widget/i) != -1 && settings.data.search(/delete_widget=1/i) == -1 ) { + podPress_jQuery( '.podpress_widget_accordion' ).accordion({ + header: 'h5', + autoHeight: false + }); + podpress_fbw_status = 'loaded'; + } + }); + } + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010705_actions.js b/pool/shard001/JavaScript/0010705_actions.js new file mode 100644 index 0000000000000000000000000000000000000000..e8a5967b1c5f3f67a54e6627a500b5968d0621dd --- /dev/null +++ b/pool/shard001/JavaScript/0010705_actions.js @@ -0,0 +1,101 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +import FauxtonAPI from "../../core/api"; +import Constants from "./constants"; +import VerifyInstall from "./resources"; +import ActionTypes from "./actiontypes"; + + +// helper function to publish success/fail result of a single test having been ran +const testPassed = function (test, dispatch) { + return function () { + dispatch({ + type: ActionTypes.VERIFY_INSTALL_SINGLE_TEST_COMPLETE, + test: test, + success: true + }); + }; +}; + +let allTestsPassed = true; +const testFailed = function (test, dispatch) { + return function (xhr) { + allTestsPassed = false; + if (!xhr) { return; } + + dispatch({ + type: ActionTypes.VERIFY_INSTALL_SINGLE_TEST_COMPLETE, + test: test, + success: false + }); + let reason = 'n/a'; + if (xhr.responseText) { + reason = JSON.parse(xhr.responseText).reason; + } else if (xhr.message) { + reason = xhr.message; + } + FauxtonAPI.addNotification({ + msg: 'Error: ' + reason, + type: 'error' + }); + }; +}; + + +export const resetTests = () => (dispatch) => { + dispatch({ type: ActionTypes.VERIFY_INSTALL_RESET }); +}; + +export const startVerification = () => (dispatch) => { + // announce that we're starting the verification tests + dispatch({ type: ActionTypes.VERIFY_INSTALL_START }); + + const testProcess = VerifyInstall.testProcess; + testProcess.setup() + .then(() => { + return testProcess.saveDB().then(testPassed(Constants.TESTS.CREATE_DATABASE, dispatch)); + }, testFailed(Constants.TESTS.CREATE_DATABASE, dispatch)) + .then(() => { + return testProcess.saveDoc().then(testPassed(Constants.TESTS.CREATE_DOCUMENT, dispatch)); + }, testFailed(Constants.TESTS.CREATE_DATABASE, dispatch)) + .then(() => { + return testProcess.updateDoc().then(testPassed(Constants.TESTS.UPDATE_DOCUMENT, dispatch)); + }, testFailed(Constants.TESTS.CREATE_DOCUMENT, dispatch)) + .then(() => { + return testProcess.destroyDoc().then(testPassed(Constants.TESTS.DELETE_DOCUMENT, dispatch)); + }, testFailed(Constants.TESTS.UPDATE_DOCUMENT, dispatch)) + .then(() => { + return testProcess.setupView().then(() => { + return testProcess.testView().then(testPassed(Constants.TESTS.CREATE_VIEW, dispatch)); + }); + }, testFailed(Constants.TESTS.DELETE_DOCUMENT, dispatch)) + .then(() => { + return testProcess.setupReplicate().then(() => { + return testProcess.testReplicate().then(testPassed(Constants.TESTS.REPLICATION, dispatch)); + }); + }, testFailed(Constants.TESTS.CREATE_VIEW, dispatch)) + .then(() => {}, testFailed(Constants.TESTS.REPLICATION, dispatch)) + .then(() => { + // now announce the tests have been ran + dispatch({ type: ActionTypes.VERIFY_INSTALL_ALL_TESTS_COMPLETE }); + + if (allTestsPassed) { + FauxtonAPI.addNotification({ + msg: 'Success! Your CouchDB installation is working. Time to Relax.', + type: 'success' + }); + } + + testProcess.removeDBs(); + }); +}; diff --git a/pool/shard001/JavaScript/0010706_app.js b/pool/shard001/JavaScript/0010706_app.js new file mode 100644 index 0000000000000000000000000000000000000000..295c87693bea098f7e530514f7a14463ee381eba --- /dev/null +++ b/pool/shard001/JavaScript/0010706_app.js @@ -0,0 +1,219 @@ +function pad(n, width, z) { + z = z || '0'; + n = n + ''; + return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; +} + +function formatTime(dTms){ + ms = dTms % 60; + s = Math.floor(dTms / 1000) % 60; + m = Math.floor(dTms / (1000 * 60)) % 60; + return (pad(m,2) + ":" + pad(s,2) + "." + pad(ms,2)) +} + + + + +function MakerFaireColorApp(){ + this.timer = new MakerFaireColorTimer("#challenge-window"); + this.timer.setupHandlers(this.onNewScore.bind(this)); + + this.$leaderBoard = $(".leader-board .board"); + this.$clearLeaderBoardBtn = $(".leader-board .clear"); + + this.scores = []; + this.loadScores(); + + this.$clearLeaderBoardBtn.click(this.clearScores.bind(this)); + +} + +MakerFaireColorApp.prototype.onNewScore = function(name,time){ + if(name.length === 0) + return; + + var scoreObj = { + date : new Date(), + name : name, + time : time + }; + + this.scores.push(scoreObj); + this.sortScores(); + this.saveScores(); +} + +MakerFaireColorApp.prototype.saveScores = function(obj){ + localStorage["scores"] = JSON.stringify(this.scores); + this.drawLeaderBoard(); +} + +MakerFaireColorApp.prototype.loadScores = function(name,time){ + this.scores = JSON.parse(localStorage["scores"]) || []; + this.sortScores(); + this.drawLeaderBoard(); +} + +MakerFaireColorApp.prototype.sortScores = function(){ + this.scores.sort(function(a,b){return a.time - b.time}); +} +MakerFaireColorApp.prototype.formatLeaderBoardEntry = function(idx,obj){ + return "
  • #" + (idx+1) + " " + formatTime(obj.time) + " " + obj.name + "
  • "; +} + +MakerFaireColorApp.prototype.drawLeaderBoard = function(){ + var that = this; + that.$leaderBoard.html(""); + $(this.scores).each(function(idx){ + that.$leaderBoard.append(that.formatLeaderBoardEntry(idx,this)); + if(idx >= 9) + return; + }); +} +MakerFaireColorApp.prototype.clearScores = function(){ + this.scores = []; + this.saveScores(); + this.drawLeaderBoard(); +} + + + +function MakerFaireColorTimer(elem){ + var that = this; + this.elem = elem; + this.$startButton = $("#go-btn",this.elem); + this.$stopButton = $("#stop-btn",this.elem); + this.$closeModalButton = $("#close-btn",this.elem); + this.$clock = $(".clock .time",this.elem); + this.$nameEntry = $('.name-entry',this.elem); + this.$nameEntryInput = $('.name-entry input',this.elem); + + this.$colors = []; + $('.colors .color',this.elem).each(function(idx){ + that.$colors.push(this); + }); + + this.Colors = ["#FF0000","#00FF00","#0000FF","#FFFF00"]; + + this.timer = { + sTime : null, + eTime : null, + displayTimer : null + }; + + this.States = { + WAITING_TO_START : 0, + RUNNING : 1, + WAITING_TO_RESET : 2 + } + + this.state = 0; + + this.newScoreCallback = null; + +} + +MakerFaireColorTimer.prototype.setupHandlers = function(newScoreCallback) { + this.$startButton.click(this.startTimer.bind(this)); + this.$stopButton.click(this.stopTimer.bind(this)); + this.$closeModalButton.click(this.reset.bind(this)); + this.setState(this.States.WAITING_TO_START); + + this.newScoreCallback = newScoreCallback; +}; + +MakerFaireColorTimer.prototype.startTimer = function() { + this.setState(this.States.RUNNING); + this.timer.sTime = new Date().getTime(); + + this.generateRandomColors(); + + clearInterval(this.timer.displayTimer); + this.timer.displayTimer = setInterval(this.updateClock.bind(this),100); +} + +MakerFaireColorTimer.prototype.stopTimer = function() { + this.setState(this.States.WAITING_TO_RESET); + this.timer.eTime = new Date().getTime(); + clearInterval(this.timer.displayTimer); +} + +MakerFaireColorTimer.prototype.reset = function() { + this.newScoreCallback(this.$nameEntryInput.val(),(this.timer.eTime-this.timer.sTime)); + + this.setState(this.States.WAITING_TO_START); + this.timer.eTime = null; + this.timer.eTime = null; +} + +MakerFaireColorTimer.prototype.setState = function(state){ + this.state = state; + + switch(this.state){ + case this.States.WAITING_TO_START: + this.$startButton.show(); + this.$stopButton.hide(); + this.$closeModalButton.hide(); + this.$nameEntry.hide(); + this.$nameEntryInput.val(""); + this.$clock.text("00:00.00"); + $(this.$colors).each(function(){ $(this).css('background-color',"#FFFFFF"); }); + break; + case this.States.RUNNING: + this.$startButton.hide(); + this.$stopButton.show(); + this.$closeModalButton.hide(); + this.$nameEntry.hide(); + break; + case this.States.WAITING_TO_RESET: + this.$startButton.hide(); + this.$stopButton.hide(); + this.$closeModalButton.show(); + this.$nameEntry.show(); + break; + } +} + + +MakerFaireColorTimer.prototype.generateRandomColors = function() { + var that = this; + + function getRandomColor(){ + return that.Colors[Math.floor(Math.random() * (that.Colors.length - 0) + 0)]; + } + + function loopColors(){ + $(that.$colors).each(function(){ + $(this).css('background-color',getRandomColor()); + }); + } + + function pickFinal(){ + var colorOrder = []; + $(that.$colors).each(function(idx){ + var c = getRandomColor(); + do { + c = getRandomColor(); + }while(idx !== 0 && colorOrder[idx-1] === c); + colorOrder.push(c); + $(this).css('background-color',c); + }); + } + + var t = setInterval(loopColors,150); + setTimeout(function(){ + pickFinal(); + clearInterval(t); + },3000); + +} + +MakerFaireColorTimer.prototype.updateClock = function() { + var dTms = (new Date().getTime() - this.timer.sTime); + this.$clock.text( formatTime(dTms) ); +} + + +$(document).ready(function onDocumentReady(){ + var app = new MakerFaireColorApp(); +}); diff --git a/pool/shard001/JavaScript/0010709_transition-test-attrTween.js b/pool/shard001/JavaScript/0010709_transition-test-attrTween.js new file mode 100644 index 0000000000000000000000000000000000000000..135a38a241c8fe182721ad31b837fc234144c817 --- /dev/null +++ b/pool/shard001/JavaScript/0010709_transition-test-attrTween.js @@ -0,0 +1,61 @@ +define("d3/test/transition/transition-test-attrTween", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ +var assert = require("../assert"), + _ = require("../../"); + +module.exports = { + topic: function(d3) { + var callback = this.callback, + dd = [], + ii = [], + tt = [], + vv = []; + + var s = d3.select("body").html("").append("div").selectAll("div") + .data(["red", "green"]) + .enter().append("div") + .attr("color", function(d, i) { return i ? "#008000" : "#ff0000"; }); + + var t = s.transition() + .attrTween("color", tween); + + function tween(d, i, v) { + dd.push(d); + ii.push(i); + vv.push(v); + if (tt.push(this) >= 2) callback(null, { + selection: s, + transition: t, + data: dd, + index: ii, + value: vv, + context: tt + }); + return i && _.interpolateHsl(v, "blue"); + } + }, + + "defines the corresponding attr tween": function(result) { + assert.typeOf(result.transition.tween("attr.color"), "function"); + }, + "invokes the tween function": function(result) { + assert.deepEqual(result.data, ["red", "green"], "expected data, got {actual}"); + assert.deepEqual(result.index, [0, 1], "expected data, got {actual}"); + assert.deepEqual(result.value, ["#ff0000", "#008000"], "expected value, got {actual}"); + assert.domEqual(result.context[0], result.selection[0][0], "expected this, got {actual}"); + assert.domEqual(result.context[1], result.selection[0][1], "expected this, got {actual}"); + }, + + "end": { + topic: function(result) { + var callback = this.callback; + result.transition.each("end", function(d, i) { if (i >= 1) callback(null, result); }); + }, + "uses the returned interpolator": function(result) { + assert.equal(result.selection[0][1].getAttribute("color"), "#0000ff"); + }, + "does nothing if the interpolator is falsey": function(result) { + assert.equal(result.selection[0][0].getAttribute("color"), "#ff0000"); + } + } +}; +}); diff --git a/pool/shard001/JavaScript/0010714_cli-optimize.js b/pool/shard001/JavaScript/0010714_cli-optimize.js new file mode 100644 index 0000000000000000000000000000000000000000..9e80adeab1a34f5a0f2805203505b48fa2fbbd8b --- /dev/null +++ b/pool/shard001/JavaScript/0010714_cli-optimize.js @@ -0,0 +1,115 @@ +var relative = require('path').relative +var join = require('path').join + +var Bluebird = require('bluebird') +var promisify = Bluebird.promisify +var mkdirp = promisify(require('mkdirp')) +var rimraf = promisify(require('rimraf')) + +var test = require('tap').test + +var cli = require('./lib/cli.js') +var metadata = require('./lib/metadata.js') + +var p = join(__dirname, '../lib/cli.js') +var r = relative(process.cwd(), p) + +var lines = function () { /* + +Options: + -S, --save-config save this run's configuration to ~/.packardrc + [boolean] [default: false] + --loglevel logging level [default: "info"] + -h, --help Show help [boolean] + --version Show version number [boolean] + -B, --block-size size of blocks on target volume [default: 512] + -O, --optimal-capacity size of target volume, in blocks [required] + -R, --root directory root for an Artist/Album tree [array] + +Missing required argument: O +- Must have a target to optimize towards. +*/ }.toString().split('\n').slice(1, -1) + +var prolog = 'Usage: ' + r + ' [options] optimize -O blocks [-R dir [file...]]' + +var root = join(__dirname, 'cli-optimize') +var flacRoot = join(root, 'flac') +var albumRoot = join(flacRoot, 'Gary Beck') + +test('setup', function (t) { + rimraf(root).then(function () { + return mkdirp(root) + }).then(function () { + t.end() + }) +}) + +test('packard optimize', function (t) { + var expected = [prolog].concat(lines).join('\n') + cli.pnixt() + .run('node ' + p + ' optimize') + .expect(function (r) { + var trimmed = r.stderr + .split('\n') + .map(function (l) { return l.replace(/\s+$/, '') }) + .join('\n') + t.equal(trimmed, expected, '"packard" is missing a required parameter') + }) + .code(1) + .end(function (e) { + t.ifError(e, 'no error on exit') + t.end() + }) +}) + +test('packard optimize -O 190 -R ' + root, function (t) { + rimraf(root).then(function () { + return metadata.makeAlbum( + join(albumRoot, 'Algoreal 12 inch mix Naptha'), + '2012', + 'Gary Beck', + 'Algoreal 12 inch mix / Naptha', + [ + { name: 'Algoreal [12" mix"]' }, + { name: 'Naptha' } + ] + ) + }).then(function () { + return metadata.makeAlbum( + join(albumRoot, 'Bring a Friend'), + '2012', + 'Gary Beck', + 'Bring a Friend', + [ + { name: 'I Read About You' }, + { name: 'Algoreal' }, + { name: 'D51' }, + { name: 'Before the Crash' }, + { name: 'Unaware' }, + { name: 'Skiver' }, + { name: 'Hopkin' }, + { name: 'Little Moon' }, + { name: 'Bring a Friend' }, + { name: 'Operation' } + ] + ) + }).then(function () { + cli.pnixt() + .run('node ' + p + ' optimize -O 190 -R "' + root + '"') + .expect(function (r) { + t.equal(r.stderr, '', '"packard optimize" ran without errors') + t.match(r.stdout, /included:[\s\S]+TOTAL: \d+ .+ \(of 190 block capacity\)[\s\S]+left out:/gm) + }) + .code(0) + .end(function (e) { + t.ifError(e, 'no error on exit') + t.end() + }) + }) +}) + +test('cleanup', function (t) { + rimraf(root).then(function () { + t.end() + }) +}) diff --git a/pool/shard001/JavaScript/0010718_validate.js b/pool/shard001/JavaScript/0010718_validate.js new file mode 100644 index 0000000000000000000000000000000000000000..bd002c8d470ba0fae896a6d0ebd749fad0593171 --- /dev/null +++ b/pool/shard001/JavaScript/0010718_validate.js @@ -0,0 +1,166 @@ +// JayData 1.3.4 +// Dual licensed under MIT and GPL v2 +// Copyright JayStack Technologies (http://jaydata.org/licensing) +// +// JayData is a standards-based, cross-platform Javascript library and a set of +// practices to access and manipulate data from various online and offline sources. +// +// Credits: +// Hajnalka Battancs, Dániel József, János Roden, László Horváth, Péter Nochta +// Péter Zentai, Róbert Bónay, Szabolcs Czinege, Viktor Borza, Viktor Lázár, +// Zoltán Gyebrovszki, Gábor Dolla +// +// More info: http://jaydata.org + +(function ($data, $) { + + var entityValidator = $data.Validation.Entity; + var dateConverter = function (stringDate) { + try { + return new Date(Date.parse(stringDate)); + } catch (e) { + return new Date(0); + } + }; + + var validationMapping = { + required: { key: 'required' }, + minValue: { key: 'min', validateMethod: true, converter: dateConverter }, + maxValue: { key: 'max', validateMethod: true, converter: dateConverter }, + length: { key: 'length' }, + minLength: { key: 'minlength' }, + maxLength: { key: 'maxlength' }, + regex: { key: 'regex', validateMethod: true }, + customValidator: { key: 'customValidator', validateMethod: true } + }; + + var defaultValidationOption = { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true } + }; + + var numberValidationOption = { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + minValue: { key: 'min' }, + maxValue: { key: 'max' } + }; + + var supportedValidations = { + '$data.Number': numberValidationOption, + '$data.Float': numberValidationOption, + '$data.Decimal': numberValidationOption, + '$data.Integer': numberValidationOption, + '$data.Int16': numberValidationOption, + '$data.Int32': numberValidationOption, + '$data.Int64': numberValidationOption, + '$data.Byte': numberValidationOption, + '$data.SByte': numberValidationOption, + '$data.String': { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + minLength: { key: 'minlength' }, + maxLength: { key: 'maxlength' }, + length: { key: 'length' }, + regex: { key: 'regex', validateMethod: true } + }, + '$data.Date': { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + minValue: { key: 'min', validateMethod: true, converter: dateConverter }, + maxValue: { key: 'max', validateMethod: true, converter: dateConverter } + }, + '$data.DateTimeOffset': { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + minValue: { key: 'min', validateMethod: true, converter: dateConverter }, + maxValue: { key: 'max', validateMethod: true, converter: dateConverter } + }, + '$data.Time': { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + minValue: { key: 'min' }, + maxValue: { key: 'max' } + }, + '$data.Array': { + required: { key: 'required' }, + customValidator: { key: 'customValidator', validateMethod: true }, + length: { key: 'length', validateMethod: true } + }, + '$data.Boolean': defaultValidationOption, + '$data.Object': defaultValidationOption + }; + + var createValidationItem = function (memDef, rule, typeName, result) { + if (memDef[rule]) { + var validation = supportedValidations[typeName][rule]; + var ruleName = validation.key; + var ruleValue = entityValidator.getValidationValue(memDef, rule); + if (validation.validateMethod === true) { + ruleName = memDef.name + '_' + ruleName; + $.validator.addMethod(ruleName, function (value, element) { + if (!value) + value = undefined; + + if (value && validation.converter && typeof validation.converter == "function") + value = validation.converter(value); + + return entityValidator.supportedValidations[typeName][rule](value, ruleValue); + }, entityValidator.getValidationMessage(memDef, rule, 'Validation Error!')); + result.rules[memDef.name] = result.rules[memDef.name] || {}; + result.rules[memDef.name][ruleName] = true; + return; + } + else { + result.rules[memDef.name] = result.rules[memDef.name] || {}; + result.rules[memDef.name][ruleName] = ruleValue; + } + + var message = entityValidator.getValidationMessage(memDef, rule); + if (message) { + result.messages[memDef.name] = result.messages[memDef.name] || {}; + result.messages[memDef.name][ruleName] = message; + } + + } + }; + + var buildValidationModel = function (type, result) { + type.memberDefinitions.getPublicMappedProperties().forEach(function (memDef) { + var typeName = Container.resolveName(Container.resolveType(memDef.dataType)); + if (supportedValidations[typeName]) { + var validations = Object.keys(supportedValidations[typeName]); + validations.forEach(function (validation) { + createValidationItem(memDef, validation, typeName, result); + }); + } + }); + }; + + + $data.Entity.prototype.toJQueryValidate = function (callBack) { + if (typeof $ === 'undefined' || typeof $.validator === 'undefined') { + Guard.raise(new Exception('jQuery and jQuery validator plugin is required', 'Not Found!')); + } + var model = this; + + var validateResult = { rules: {}, messages: {} }; + buildValidationModel(model.getType(), validateResult); + + callBack = $data.typeSystem.createCallbackSetting(callBack, {}); + if (callBack.success) { + var origCallback = callBack.success; + callBack.success = function (form, event) { + if ($.fn.formBinder) + $(form).formBinder(model, false); + origCallback.apply(this, [model, form, event]); + }; + } + if (typeof callBack.success == "function") + validateResult.submitHandler = callBack.success; + if (typeof callBack.error == "function") + validateResult.invalidHandler = callBack.error; + return validateResult; + }; + +})($data, jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010719_test-defaults.js b/pool/shard001/JavaScript/0010719_test-defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..19844085d8b29fad632b0697a665be4970dbfacf --- /dev/null +++ b/pool/shard001/JavaScript/0010719_test-defaults.js @@ -0,0 +1,219 @@ +var server = require('./server') + , assert = require('assert') + , request = require('../index') + ; + +var s = server.createServer(); + +s.listen(s.port, function () { + var counter = 0; + s.on('/get', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.method, 'GET') + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end('TESTING!'); + }); + + // test get(string, function) + request.defaults({headers:{foo:"bar"}})(s.url + '/get', function (e, r, b){ + if (e) throw e; + assert.deepEqual("TESTING!", b); + counter += 1; + }); + + s.on('/merge-headers', function (req, resp) { + assert.equal(req.headers.foo, 'bar') + assert.equal(req.headers.merged, 'yes') + resp.writeHead(200) + resp.end() + }); + + request.defaults({ + headers:{foo:"bar", merged:"no"} + })(s.url + '/merge-headers', { + headers:{merged:"yes"} + }, function (e, r, b){ + if (e) throw e + assert.equal(r.statusCode, 200) + counter += 1 + }); + + s.on('/post', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.headers['content-type'], null); + assert.equal(req.method, 'POST') + resp.writeHead(200, {'Content-Type': 'application/json'}); + resp.end(JSON.stringify({foo:'bar'})); + }); + + // test post(string, object, function) + request.defaults({headers:{foo:"bar"}}).post(s.url + '/post', {json: true}, function (e, r, b){ + if (e) throw e; + assert.deepEqual('bar', b.foo); + counter += 1; + }); + + s.on('/patch', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.headers['content-type'], null); + assert.equal(req.method, 'PATCH') + resp.writeHead(200, {'Content-Type': 'application/json'}); + resp.end(JSON.stringify({foo:'bar'})); + }); + + // test post(string, object, function) + request.defaults({headers:{foo:"bar"}}).patch(s.url + '/patch', {json: true}, function (e, r, b){ + if (e) throw e; + assert.deepEqual('bar', b.foo); + counter += 1; + }); + + s.on('/post-body', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.headers['content-type'], 'application/json'); + assert.equal(req.method, 'POST') + resp.writeHead(200, {'Content-Type': 'application/json'}); + resp.end(JSON.stringify({foo:'bar'})); + }); + + // test post(string, object, function) with body + request.defaults({headers:{foo:"bar"}}).post(s.url + '/post-body', {json: true, body:{bar:"baz"}}, function (e, r, b){ + if (e) throw e; + assert.deepEqual('bar', b.foo); + counter += 1; + }); + + s.on('/del', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.method, 'DELETE') + resp.writeHead(200, {'Content-Type': 'application/json'}); + resp.end(JSON.stringify({foo:'bar'})); + }); + + // test .del(string, function) + request.defaults({headers:{foo:"bar"}, json:true}).del(s.url + '/del', function (e, r, b){ + if (e) throw e; + assert.deepEqual('bar', b.foo); + counter += 1; + }); + + s.on('/head', function (req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.method, 'HEAD') + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end(); + }); + + // test head.(object, function) + request.defaults({headers:{foo:"bar"}}).head({uri: s.url + '/head'}, function (e, r, b){ + if (e) throw e; + counter += 1; + }); + + s.on('/get_recursive1', function (req, resp) { + assert.equal(req.headers.foo, 'bar1'); + assert.equal(req.method, 'GET'); + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end('TESTING!'); + }); + + s.on('/get_recursive2', function (req, resp) { + assert.equal(req.headers.foo, 'bar1'); + assert.equal(req.headers.baz, 'bar2'); + assert.equal(req.method, 'GET'); + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end('TESTING!'); + }); + + // test recursive defaults (string, function) + var defaultsOne = request.defaults({headers:{foo:"bar1"}}); + var defaultsTwo = defaultsOne.defaults({headers:{baz:"bar2"}}); + var defaultsThree = defaultsTwo.defaults({}, function(options, callback){ + options.headers = { + foo: 'bar3' + }; + defaultsTwo(options, callback); + }); + + defaultsOne(s.url + '/get_recursive1', function (e, r, b){ + if (e) throw e; + assert.deepEqual("TESTING!", b); + counter += 1; + }); + + defaultsTwo(s.url + '/get_recursive2', function (e, r, b){ + if (e) throw e; + assert.deepEqual("TESTING!", b); + counter += 1; + }); + + s.on('/get_recursive3', function (req, resp) { + assert.equal(req.headers.foo, 'bar3'); + assert.equal(req.headers.baz, 'bar2'); + assert.equal(req.method, 'GET'); + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end('TESTING!'); + }); + + //test that you can set a requester function on recursive defaults + defaultsThree(s.url + '/get_recursive3', function (e, r, b){ + if (e) throw e; + assert.deepEqual("TESTING!", b); + counter += 1; + }); + + s.on('/get_custom', function(req, resp) { + assert.equal(req.headers.foo, 'bar'); + assert.equal(req.headers.x, 'y'); + resp.writeHead(200, {'Content-Type': 'text/plain'}); + resp.end(); + }); + + // test custom request handler function + var defaultRequest = request.defaults({ + headers:{foo:"bar"} + , body: 'TESTING!' + }, function(uri, options, callback) { + var params = request.initParams(uri, options, callback); + options = params.options; + options.headers.x = 'y'; + + return request(params.uri, params.options, params.callback); + }); + + s.on('/set-undefined', function (req, resp) { + assert.equal(req.method, 'POST') + assert.equal(req.headers['content-type'], 'application/json'); + assert.equal(req.headers['x-foo'], 'baz'); + var data = ''; + req.on('data', function(d) { + data += d; + }); + req.on('end', function() { + resp.writeHead(200, {'Content-Type': 'application/json'}); + resp.end(data); + }); + }); + + // test only setting undefined properties + request.defaults({method:'post',json:true,headers:{'x-foo':'bar'}})({uri:s.url + '/set-undefined',json:{foo:'bar'},headers:{'x-foo':'baz'}}, function (e, r, b){ + if (e) throw e; + assert.deepEqual({foo:'bar'}, b); + counter += 1; + }); + + var msg = 'defaults test failed. head request should throw earlier'; + assert.throws(function() { + defaultRequest.head(s.url + '/get_custom', function(e, r, b) { + throw new Error(msg); + }); + counter+=1; + }, msg); + + defaultRequest.get(s.url + '/get_custom', function(e, r, b) { + if(e) throw e; + counter += 1; + console.log(counter.toString() + " tests passed."); + s.close(); + }); +}) diff --git a/pool/shard001/JavaScript/0010726_KappaChan.js b/pool/shard001/JavaScript/0010726_KappaChan.js new file mode 100644 index 0000000000000000000000000000000000000000..dea776b7af7f63afd04d91979dd142edc4e25573 --- /dev/null +++ b/pool/shard001/JavaScript/0010726_KappaChan.js @@ -0,0 +1,78 @@ +'use strict'; + +GLOBAL.App = {}; + +const Eris = require('eris'); +const fs = require('fs'); +const EmoteRequest = require('./src/emotes'); +const Commands = require('./src/commands'); +const Stats = require('./src/stats'); +const Streamreporter = require('./src/streamreporter'); +const DatabaseHandler = require('./src/databasehandler'); +const Streamsearch = require('./src/streamsearch'); +const Channelsearch = require('./src/channelsearch'); +const Logger = require('./src/logger'); + +App.config = JSON.parse(fs.readFileSync('config.cf', 'utf8')); +App.Logger = new Logger(); +App.client = new Eris(App.config.token); +App.EmoteRequest = new EmoteRequest(); +App.Commands = new Commands(); +App.Streamsearch = new Streamsearch(); +App.Channelsearch = new Channelsearch(); +App.DatabaseHandler = new DatabaseHandler(); +App.Streamreporter = new Streamreporter(); +App.Stats = new Stats(); + +App.bMuted = false; + +process.on('uncaughtException', err => { + App.Logger.log(err.message + '\n' + err.stack, 0); + + // Leave some time for the ws to finnish sending. + setTimeout(process.exit.bind(1), 3000); +}); + + +App.client.on('ready', () => { + App.Logger.log('READY', 2); +}); + +App.client.on('guildCreate', g => { + var res = '```Hello ' + g.name + '! Thanks for using me. \n\n' + + 'Use &help for a list of commands.```'; + + // App.client.createMessage(g.defaultChannel.id, res); + App.Stats.update(); +}); + +App.client.on('error', (e) => { + App.Logger.log(e, 0); +}); + +App.client.on('debug', (d) => { + App.Logger.log(d, 2); +}); + +App.client.on('warn', (d) => { + App.Logger.log(d, 2); +}); + +App.client.on('messageCreate', m => { + if (!m.channel.guild) return; + var split = m.content.split(' '); + var command = split.shift(); + + var payload = { + command: command, + parameter: split.join(' '), + message: m + }; + + if (App.Stats) + App.Stats.messages++; + + App.Commands.onMessage(payload); +}); + +App.client.connect(); diff --git a/pool/shard001/JavaScript/0010728_FloatingHelper.visual.js b/pool/shard001/JavaScript/0010728_FloatingHelper.visual.js new file mode 100644 index 0000000000000000000000000000000000000000..7e6745c1e33fff250302ead7ddfc4073d5dc34f4 --- /dev/null +++ b/pool/shard001/JavaScript/0010728_FloatingHelper.visual.js @@ -0,0 +1,84 @@ +import React from 'react'; +import { storiesOf } from '@storybook/react'; +import FloatingHelper from '../FloatingHelper'; +import Box from '../../Box'; + +import { + floatingHelperAppearance, + appendToOptions, + placementOptions, +} from '../constants'; + +const body = + 'In order to sell your music you need to choose a payment method. '; + +const requiredProps = { + content: , + target: I am a FloatingHelper target, + placement: placementOptions.right, +}; + +const defaultProps = { + appearance: floatingHelperAppearance.dark, + appendTo: appendToOptions.window, + initiallyOpened: true, + width: '444px', +}; + +const appearances = Object.values(floatingHelperAppearance); + +const tests = [ + { + describe: 'sanity', + its: [ + { + it: 'default', + props: {}, + }, + ], + }, + { + describe: 'appearance', + its: appearances.map(appearance => ({ + it: appearance, + props: { appearance }, + })), + }, + { + describe: 'initiallyOpened', + its: [true, false].map(initiallyOpened => ({ + it: initiallyOpened.toString(), + props: { initiallyOpened }, + })), + }, + { + describe: 'width', + its: [ + { + it: 'default', + props: {}, + }, + { + it: 'number', + props: { width: 500 }, + }, + { + it: 'string', + props: { width: '550px' }, + }, + ], + }, +]; + +tests.forEach(({ describe, its }) => { + its.forEach(({ it, props }) => { + storiesOf(`FloatingHelper${describe ? '/' + describe : ''}`, module).add( + it, + () => ( + + + + ), + ); + }); +}); diff --git a/pool/shard001/JavaScript/0010729_specCollectorSpec.js b/pool/shard001/JavaScript/0010729_specCollectorSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..6c5bf782b82814266bcf99942f0dcd7e18507398 --- /dev/null +++ b/pool/shard001/JavaScript/0010729_specCollectorSpec.js @@ -0,0 +1,144 @@ +var assert = require('assert'), + mockery = require('mockery'), + sinon = require('sinon'); + + + +describe("Spec collector", function() { + var calls = [], + transformerSpy, + globStub, + specCollector, + i; + + beforeEach(function() { + i = 0; + var object, + transformer = function (file, tags, callback) { + i++; + object = {}; + object['some data' + i] = 'some value'; + callback(JSON.stringify(object)); + } + mockery.enable(); + mockery.warnOnReplace(false); + mockery.warnOnUnregistered(false); + transformerSpy = sinon.spy(transformer); + + + globStub = function(glob, options, callback) { + callback(null,[1,2,3]); + }; + mockery.registerMock('./featureTransformer', transformerSpy); + mockery.registerMock('glob', globStub); + specCollector = require('../lib/specCollector'); + + }); + + afterEach(function() { + calls = []; + mockery.disable(); + }); + + it("resolves the glob and calls the feature transformer for each file", function() { + + specCollector('test/fixtures/markdown/*.md', [], function(){}); + assert.equal(transformerSpy.callCount, 3); + }); + + it("should fire a callback passing in an object made up of merged objects", function(done) { + specCollector('test/fixtures/markdown/*.md', [], function(data) { + assert.equal(JSON.stringify(data), JSON.stringify({ + 'some data1': 'some value', + 'some data2': 'some value', + 'some data3': 'some value' + })); + done(); + }); + + }); +}); + +describe("Spec collector", function() { + var calls = [], transformerSpy, globStub, specCollector, i; + + beforeEach(function() { + i = 0; + var object, transformer = function(file, tags, callback) { + i++; + switch(i) { + case 1: + object = { + "top middle bottom": { + "_parents": ["top", "middle", "bottom"], "specs": { + "should bottom 1": "test/fixtures/markdown/describe.md:2", + "should bottom 2": "test/fixtures/markdown/describe.md:3" + } + } + }; + break; + case 2: + object = { + "top middle": { + "_parents": ["top", "middle"], "specs": { + "should middle": "test/fixtures/markdown/describe.md:2", + "should middle 2": "test/fixtures/markdown/describe.md:3" + } + } + }; + break; + case 3: + object = { + "top middle": { + "_parents": ["top", "middle"], "specs": { + "should middle 3": "test/fixtures/markdown/describe2.md:3", + "should middle 4": "test/fixtures/markdown/describe2.md:4" + } + } + }; + break; + } + + callback(JSON.stringify(object)); + } + mockery.enable(); + mockery.warnOnReplace(false); + mockery.warnOnUnregistered(false); + transformerSpy = sinon.spy(transformer); + + globStub = function(glob, options, callback) { + callback(null, [1, 2, 3]); + }; + mockery.registerMock('./featureTransformer', transformerSpy); + mockery.registerMock('glob', globStub); + specCollector = require('../lib/specCollector'); + + }); + + afterEach(function() { + calls = []; + mockery.disable(); + }); + + it("should merge structures", function(done) { + specCollector('test/fixtures/markdown/*.md', [], function(data) { + assert.equal(JSON.stringify(data), JSON.stringify({ + "top middle bottom": { + "_parents": ["top", "middle", "bottom"], "specs": { + "should bottom 1": "test/fixtures/markdown/describe.md:2", + "should bottom 2": "test/fixtures/markdown/describe.md:3" + } + }, "top middle": { + "_parents": ["top", "middle"], "specs": { + "should middle": "test/fixtures/markdown/describe.md:2", + "should middle 2": "test/fixtures/markdown/describe.md:3", + "should middle 3": "test/fixtures/markdown/describe2.md:3", + "should middle 4": "test/fixtures/markdown/describe2.md:4" + } + } + })); + done(); + }); + + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010731_EnableMethodEventInterceptorTest.js b/pool/shard001/JavaScript/0010731_EnableMethodEventInterceptorTest.js new file mode 100644 index 0000000000000000000000000000000000000000..b96d403833cd86226b25aaa6ba253b3e92834fbb --- /dev/null +++ b/pool/shard001/JavaScript/0010731_EnableMethodEventInterceptorTest.js @@ -0,0 +1,125 @@ +/* + * Copyright 2012 Amadeus s.a.s. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * EnableMethodEventInterceptorTest Controller test class + */ +Aria.classDefinition({ + $classpath : 'test.aria.templates.EnableMethodEventInterceptorTest', + $extends : 'aria.jsunit.TestCase', + $dependencies : ['aria.templates.ModuleCtrlFactory'], + $constructor : function () { + this.$TestCase.constructor.call(this); + this.defaultTestTimeout = 2000; + }, + $prototype : { + + testAsyncDefaultInterceptor : function () { + aria.templates.ModuleCtrlFactory.createModuleCtrl({ + classpath : "test.aria.templates.test.SampleModuleCtrl" + }, { + fn : this._testAsyncDefaultInterceptorCb, + scope : this + }); + }, + + _testAsyncDefaultInterceptorCb : function (res) { + try { + var mc = res.moduleCtrlPrivate; + this.assertTrue(mc.__$interceptors != null); + mc.incrementCount(); + aria.core.Timer.addCallback({ + fn : this._endTestAsyncDisableInterceptor, + scope : this, + args : { + "mc" : mc, + "testName" : "testAsyncDefaultInterceptor" + }, + delay : 16 + }); + } catch (ex) { + this.handleAsyncTestError(ex); + } + }, + + testAsyncDisableInterceptor : function () { + aria.templates.ModuleCtrlFactory.createModuleCtrl({ + classpath : "test.aria.templates.test.DisableMethodEventsModuleCtrl" + }, { + fn : this._testAsyncDisableInterceptorCb, + scope : this + }); + }, + + _testAsyncDisableInterceptorCb : function (res) { + try { + var mc = res.moduleCtrlPrivate; + this.assertTrue(!mc.__$interceptors); + mc.testMethod(); + aria.core.Timer.addCallback({ + fn : this._endTestAsyncDisableInterceptor, + scope : this, + args : { + "mc" : mc + }, + delay : 16 + }); + } catch (ex) { + this.handleAsyncTestError(ex); + } + }, + _endTestAsyncDisableInterceptor : function (args) { + this.assertFalse(args.mc.eventCallBeginRaised); + this.assertFalse(args.mc.eventCallEndRaised); + args.mc.$dispose(); + this.notifyTestEnd("testAsyncDisableInterceptor"); + }, + + testAsyncEnableInterceptor : function () { + aria.templates.ModuleCtrlFactory.createModuleCtrl({ + classpath : "test.aria.templates.test.EnableMethodEventsModuleCtrl" + }, { + fn : this._testAsyncEnableInterceptorCb, + scope : this + }); + }, + + _testAsyncEnableInterceptorCb : function (res) { + try { + var mc = res.moduleCtrlPrivate; + this.assertTrue(mc.__$interceptors != null); + mc.testMethod(); + aria.core.Timer.addCallback({ + fn : this._endTestAsyncEnableInterceptor, + scope : this, + args : { + "mc" : mc, + "testName" : "testAsyncEnableInterceptor" + }, + delay : 16 + }); + } catch (ex) { + this.handleAsyncTestError(ex); + } + }, + _endTestAsyncEnableInterceptor : function (args) { + this.assertTrue(args.mc.eventCallBeginRaised); + this.assertTrue(args.mc.eventCallEndRaised); + args.mc.$dispose(); + this.notifyTestEnd(args.testName); + } + + } +}); diff --git a/pool/shard001/JavaScript/0010738_fallDown.spec.js b/pool/shard001/JavaScript/0010738_fallDown.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9d043ca5709b846dd58f3134f08d7b69414b5bf4 --- /dev/null +++ b/pool/shard001/JavaScript/0010738_fallDown.spec.js @@ -0,0 +1,70 @@ +'use strict'; + +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; +import { expect } from 'chai'; +import createShallowComponent from './utils/createShallowComponent'; +import BurgerMenu from '../lib/BurgerMenu'; +const Menu = BurgerMenu.fallDown; + +describe('fallDown', () => { + + let component, menuWrap, menu, itemList, firstItem; + + function addWrapperElementsToDOM() { + let outerContainer = document.createElement('div'); + outerContainer.setAttribute('id', 'outer-container'); + let pageWrap = document.createElement('div'); + pageWrap.setAttribute('id', 'page-wrap'); + outerContainer.appendChild(pageWrap); + document.body.appendChild(outerContainer); + } + + function removeWrapperElementsFromDOM() { + let outerContainer = document.getElementById('outer-container'); + document.body.removeChild(outerContainer); + } + + beforeEach(() => { + addWrapperElementsToDOM(); + }); + + afterEach(() => { + removeWrapperElementsFromDOM(); + }); + + it('has correct menuWrap styles', () => { + component = createShallowComponent(
    An item
    ); + menuWrap = component.props.children[1]; + expect(menuWrap.props.style.position).to.equal('fixed'); + expect(menuWrap.props.style.zIndex).to.equal(2); + expect(menuWrap.props.style.width).to.equal(300); + expect(menuWrap.props.style.height).to.equal('100%'); + }); + + it('has correct menu styles', () => { + component = TestUtils.renderIntoDocument(
    An item
    ); + menu = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu'); + expect(menu.style.height).to.equal('100%'); + expect(menu.style.boxSizing).to.equal('border-box'); + }); + + it('has correct itemList styles', () => { + component = TestUtils.renderIntoDocument(
    An item
    ); + itemList = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list'); + expect(itemList.style.height).to.equal('100%'); + }); + + it('has correct item styles', () => { + component = TestUtils.renderIntoDocument(
    An item
    ); + firstItem = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list').children[0]; + expect(firstItem.style.display).to.equal('block'); + expect(firstItem.style.outline).to.equal('none'); + }); + + it('can be positioned on the right', () => { + component = TestUtils.renderIntoDocument(
    An item
    ); + menuWrap = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu-wrap'); + expect(menuWrap.style.right).to.equal('0px'); + }); +}); diff --git a/pool/shard001/JavaScript/0010743_tests.js b/pool/shard001/JavaScript/0010743_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..f7215646047dc9df6a3bc716bbb8939b47ff1add --- /dev/null +++ b/pool/shard001/JavaScript/0010743_tests.js @@ -0,0 +1,134 @@ +(function($) { + + module('jQuery#placeholder'); + + test('caches results of feature tests', function() { + strictEqual(typeof $.fn.placeholder.input, 'boolean', '$.fn.placeholder.input'); + strictEqual(typeof $.fn.placeholder.textarea, 'boolean', '$.fn.placeholder.textarea'); + }); + + if ($.fn.placeholder.input && $.fn.placeholder.textarea) { + return; + } + + var testElement = function($el) { + + var el = $el[0]; + var placeholder = el.getAttribute('placeholder'); + + strictEqual($el.placeholder(), $el, 'should be chainable'); + + strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // test on focus + $el.focus(); + strictEqual(el.value, '', '`value` should be the empty string on focus'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok(!$el.hasClass('placeholder'), 'should not have `placeholder` class on focus'); + + // and unfocus (blur) again + $el.blur(); + + strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // change the value + $el.val('lorem ipsum'); + strictEqual($el.prop('value'), 'lorem ipsum', '`$el.val(string)` should change the `value` property'); + strictEqual(el.value, 'lorem ipsum', '`$el.val(string)` should change the `value` attribute'); + ok(!$el.hasClass('placeholder'), '`$el.val(string)` should remove `placeholder` class'); + + // and clear it again + $el.val(''); + strictEqual($el.prop('value'), '', '`$el.val("")` should change the `value` property'); + strictEqual(el.value, placeholder, '`$el.val("")` should change the `value` attribute'); + ok($el.hasClass('placeholder'), '`$el.val("")` should re-enable `placeholder` class'); + + // make sure the placeholder property works as expected. + strictEqual($el.prop('placeholder'), placeholder, '$el.prop(`placeholder`) should return the placeholder value'); + $el.prop('placeholder', 'new placeholder'); + strictEqual($el.prop('placeholder'), 'new placeholder', '$el.prop(`placeholder`, ) should set the placeholder value'); + strictEqual($el.value, 'new placeholder', '$el.prop(`placeholder`, ) should update the displayed placeholder value'); + $el.prop('placeholder', placeholder); + }; + + test('emulates placeholder for ', function() { + testElement( $('#input-type-text') ); + }); + + test('emulates placeholder for ', function() { + testElement( $('#input-type-search') ); + }); + + test('emulates placeholder for ', function() { + testElement( $('#input-type-email') ); + }); + + test('emulates placeholder for ', function() { + testElement( $('#input-type-url') ); + }); + + test('emulates placeholder for ', function() { + testElement( $('#input-type-tel') ); + }); + + test('emulates placeholder for ', function() { + testElement( $('#input-type-tel') ); + }); + + test('emulates placeholder for ', function() { + var selector = '#input-type-password'; + + var $el = $(selector); + var el = $el[0]; + + var placeholder = el.getAttribute('placeholder'); + + strictEqual($el.placeholder(), $el, 'should be chainable'); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + // test on focus + $el.focus(); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + strictEqual(el.value, '', '`value` should be the empty string on focus'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok(!$el.hasClass('placeholder'), 'should not have `placeholder` class on focus'); + + // and unfocus (blur) again + $el.blur(); + + // Re-select the element, as it gets replaced by another one in some browsers + $el = $(selector); + el = $el[0]; + + strictEqual(el.value, placeholder, 'should set `placeholder` text as `value`'); + strictEqual($el.prop('value'), '', 'propHooks works properly'); + strictEqual($el.val(), '', 'valHooks works properly'); + ok($el.hasClass('placeholder'), 'should have `placeholder` class'); + + }); + + test('emulates placeholder for ', function() { + testElement( $('#textarea') ); + }); + +}(jQuery)); diff --git a/pool/shard001/JavaScript/0010746_isDisabled.js b/pool/shard001/JavaScript/0010746_isDisabled.js new file mode 100644 index 0000000000000000000000000000000000000000..0ecc02377dbb6f4f4914dc2646294025263baac8 --- /dev/null +++ b/pool/shard001/JavaScript/0010746_isDisabled.js @@ -0,0 +1,20 @@ +"use strict"; + +exports.__esModule = true; +exports.default = void 0; + +/** + * Copyright (c) Nicolas Gallagher. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ +var isDisabled = function isDisabled(props) { + return props.disabled || Array.isArray(props.accessibilityStates) && props.accessibilityStates.indexOf('disabled') > -1; +}; + +var _default = isDisabled; +exports.default = _default; +module.exports = exports.default; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010755_neo4j.js b/pool/shard001/JavaScript/0010755_neo4j.js new file mode 100644 index 0000000000000000000000000000000000000000..18ad7163fec5a6a4536b20f190ec45a6270bbebd --- /dev/null +++ b/pool/shard001/JavaScript/0010755_neo4j.js @@ -0,0 +1,18 @@ +import neo4j from 'neo4j-driver' + +let driver + +const defaultOptions = { + uri: process.env.NEO4J_URI, + username: process.env.NEO4J_USER, + password: process.env.NEO4J_PASSWORD, +} + +export default function getDriver() { + const { uri, username, password } = defaultOptions + if (!driver) { + driver = neo4j.driver(uri, neo4j.auth.basic(username, password)) + } + + return driver +} diff --git a/pool/shard001/JavaScript/0010758_TestingCollectionView.js b/pool/shard001/JavaScript/0010758_TestingCollectionView.js new file mode 100644 index 0000000000000000000000000000000000000000..b35f83ce0bf7956e3acca17ae5b94d5ad72f71dc --- /dev/null +++ b/pool/shard001/JavaScript/0010758_TestingCollectionView.js @@ -0,0 +1,25 @@ +(function() { + 'use strict'; + + var root = this; + + root.define([ + 'views/composite/TestingCollectionView' + ], + function( Testingcollectionview ) { + + describe('Testingcollectionview Compositeview', function () { + + it('should be an instance of Testingcollectionview Compositeview', function () { + var TestingCollectionView = new Testingcollectionview(); + expect( TestingCollectionView ).to.be.an.instanceof( Testingcollectionview ); + }); + + it('should have more test written', function(){ + expect( false ).to.be.ok; + }); + }); + + }); + +}).call( this ); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010762_module.js b/pool/shard001/JavaScript/0010762_module.js new file mode 100644 index 0000000000000000000000000000000000000000..dba96fd433ec1ccb084c95e48e1d070c3463ba2d --- /dev/null +++ b/pool/shard001/JavaScript/0010762_module.js @@ -0,0 +1,249 @@ +/* + + ## Map + + ### Parameters + * map :: 'world', 'us' or 'europe' + * colors :: an array of colors to use for the regions of the map. If this is a 2 + element array, jquerymap will generate shades between these colors + * size :: How big to make the facet. Higher = more countries + * exclude :: Exlude the array of counties + * spyable :: Show the 'eye' icon that reveals the last Solr query + * index_limit :: This does nothing yet. Eventually will limit the query to the first + N indices + +*/ + +define([ + 'angular', + 'app', + 'underscore', + 'jquery', + './lib/jquery.jvectormap.min' +], +function (angular, app, _, $) { + 'use strict'; + + var DEBUG = true; // DEBUG mode + + var module = angular.module('kibana.panels.map', []); + app.useModule(module); + + module.controller('map', function($scope, $rootScope, querySrv, dashboard, filterSrv) { + $scope.panelMeta = { + editorTabs : [ + {title:'Queries', src:'app/partials/querySelect.html'} + ], + modals : [ + { + description: "Inspect", + icon: "icon-info-sign", + partial: "app/partials/inspector.html", + show: $scope.panel.spyable + } + ], + status : "Stable", + description : "Displays a map of shaded regions using a field containing a 2 letter country "+ + ", or US state, code. Regions with more hit are shaded darker. Node that this does use the"+ + " Solr terms facet, so it is important that you set it to the correct field." + }; + + // Set and populate defaults + var _d = { + queries : { + mode : 'all', + ids : [], + query : '*:*', + custom : '' + }, + map : "world", + colors : ['#A0E2E2', '#265656'], + size : 100, + exclude : [], + spyable : true, + index_limit : 0 + }; + _.defaults($scope.panel,_d); + + $scope.init = function() { + $scope.$on('refresh',function(){$scope.get_data();}); + $scope.get_data(); + }; + + $scope.set_refresh = function (state) { + $scope.refresh = state; + }; + + $scope.close_edit = function() { + if ($scope.refresh) { + $scope.get_data(); + } + $scope.refresh = false; + $scope.$emit('render'); + }; + + $scope.get_data = function() { + + // Make sure we have everything for the request to complete + if(dashboard.indices.length === 0) { + return; + } + $scope.panelMeta.loading = true; + + + var request; + request = $scope.sjs.Request().indices(dashboard.indices); + + $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries); + // This could probably be changed to a BoolFilter + var boolQuery = $scope.ejs.BoolQuery(); + _.each($scope.panel.queries.ids,function(id) { + boolQuery = boolQuery.should(querySrv.getEjsObj(id)); + }); + + // Then the insert into facet and make the request + request = request + .facet($scope.ejs.TermsFacet('map') + .field($scope.panel.field) + .size($scope.panel.size) + .exclude($scope.panel.exclude) + .facetFilter($scope.ejs.QueryFilter( + $scope.ejs.FilteredQuery( + boolQuery, + filterSrv.getBoolFilter(filterSrv.ids) + )))).size(0); + + $scope.populate_modal(request); + + // Build Solr query + var fq = '&' + filterSrv.getSolrFq(); + var wt_json = '&wt=json'; + var rows_limit = '&rows=0'; // for map module, we don't display results from row, but we use facets. + var facet = '&facet=true' + + '&facet.field=' + $scope.panel.field + + '&facet.limit=' + $scope.panel.size; + + // Set the panel's query + $scope.panel.queries.query = querySrv.getQuery(0) + wt_json + fq + rows_limit + facet; + + // Set the additional custom query + if ($scope.panel.queries.custom != null) { + request = request.setQuery($scope.panel.queries.query + $scope.panel.queries.custom); + } else { + request = request.setQuery($scope.panel.queries.query); + } + + if (DEBUG) { console.debug('map: $scope.panel=',$scope.panel); } + + var results = request.doSearch(); + + // Populate scope when we have results + results.then(function(results) { + $scope.panelMeta.loading = false; + $scope.data = {}; // empty the data for new results + + if (results.response.numFound) { + $scope.hits = results.response.numFound; + } else { + // Undefined numFound or zero, clear the map. + $scope.$emit('render'); + return false; + } + + if (DEBUG) { console.debug('map: results=',results); } + + var terms = results.facet_counts.facet_fields[$scope.panel.field]; + + if ($scope.hits > 0) { + for (var i=0; i < terms.length; i += 2) { + // Skip states with zero count to make them greyed out in the map. + if (terms[i+1] > 0) { + // if $scope.data[terms] is undefined, assign the value to it + // otherwise, we will add the value. This case can happen when + // the data contains both uppercase and lowercase state letters with + // duplicate states (e.g. CA and ca). By adding the value, the map will + // show correct counts for states with mixed-case letters. + if (!$scope.data[terms[i].toUpperCase()]) { + $scope.data[terms[i].toUpperCase()] = terms[i+1]; + } else { + $scope.data[terms[i].toUpperCase()] += terms[i+1]; + } + } + }; + } + + $scope.$emit('render'); + }); + }; + + // I really don't like this function, too much dom manip. Break out into directive? + $scope.populate_modal = function(request) { + $scope.inspector = angular.toJson(JSON.parse(request.toString()),true); + }; + + $scope.build_search = function(field,value) { + // Set querystring to both uppercase and lowercase state values with double-quote around the value + // to prevent query error from state=OR (Oregon) + filterSrv.set({type:'querystring',mandate:'must',query:field+':"'+value.toUpperCase()+'" OR '+field+':"'+value.toLowerCase()+'"'}); + dashboard.refresh(); + }; + + }); + + + module.directive('map', function() { + return { + restrict: 'A', + link: function(scope, elem) { + + elem.html('
    '); + + // Receive render events + scope.$on('render',function(){ + render_panel(); + }); + + // Or if the window is resized + angular.element(window).bind('resize', function(){ + render_panel(); + }); + + function render_panel() { + elem.text(''); + $('.jvectormap-zoomin,.jvectormap-zoomout,.jvectormap-label').remove(); + require(['./panels/map/lib/map.'+scope.panel.map], function () { + elem.vectorMap({ + map: scope.panel.map, + regionStyle: {initial: {fill: '#8c8c8c'}}, + zoomOnScroll: false, + backgroundColor: null, + series: { + regions: [{ + values: scope.data, + scale: scope.panel.colors, + normalizeFunction: 'polynomial' + }] + }, + onRegionLabelShow: function(event, label, code){ + elem.children('.map-legend').show(); + var count = _.isUndefined(scope.data[code]) ? 0 : scope.data[code]; + elem.children('.map-legend').text(label.text() + ": " + count); + }, + onRegionOut: function() { + $('.map-legend').hide(); + }, + onRegionClick: function(event, code) { + var count = _.isUndefined(scope.data[code]) ? 0 : scope.data[code]; + if (count !== 0) { + scope.build_search(scope.panel.field,code); + } + } + }); + elem.prepend(''); + $('.map-legend').hide(); + }); + } + } + }; + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010764_viewModel.js b/pool/shard001/JavaScript/0010764_viewModel.js new file mode 100644 index 0000000000000000000000000000000000000000..795ceda53e4b2012e095220e9733b4b013a39309 --- /dev/null +++ b/pool/shard001/JavaScript/0010764_viewModel.js @@ -0,0 +1,82 @@ +var fourthChart = scatterChart(); + +var viewModel = { + width : ko.observable($(window).width()), + height : ko.observable($(".carousel-inner").height()), + showLegend : ko.observable(false), + showFeedback : ko.observable(false), + time : { + start : ko.observable(), + end : ko.observable(), + recent : ko.observable() + }, + toggleLegend : function() { + //console.log("toggleLegend click"); + this.showLegend() ? this.showLegend(false) : this.showLegend(true); + }, + toggleFeedback : function() { + //console.log("toggleFeedback click"); + this.showFeedback() ? this.showFeedback(false) : this.showFeedback(true); + }, + view : ko.observable("map"), + graph : ko.observable("scatter"), + hydro : function() { + this.view("hydro"); + this.graph("hydro"); + this.plotGraph(); + }, + flow : function() { + this.view("flow"); + this.graph("flow"); + this.plotGraph(); + }, + histo : function() { + this.view("histo"); + this.graph("histo"); + this.plotGraph(); + }, + scatter : function() { + this.view("scatter"); + this.graph("scatter"); + this.plotGraph(); + }, + hyeto : function() { + this.view("hyeto"); + this.graph("hyeto"); + this.plotGraph(); + }, + map : function() { + //this is only called when map button is pressed, not next and prev arrows. + fusionLayerInfoWindow.close(); + this.view("map"); + google.maps.event.trigger(map, 'resize'); + }, + slide : function() { + fusionLayerInfoWindow.close(); + }, + plotGraph : function() { + //console.log("Inside viewModel.plotGraph()"); + //console.log(this.graph()); + if (this.graph() === "flow") { + flowduration(this.siteId()); + } else if (this.graph() === "scatter") { + var graphDiv = d3.select("#graph_div"); + d3.select("#graph_div svg").remove(); + graphDiv.datum(this.dataArray()).call(fourthChart); + } else { + console.log("no option selected"); + } + }, + siteId : ko.observable(), + siteIdArray : ko.observableArray(), + siteName : ko.observable(), + siteDict : ko.observableArray(), + dataArray : ko.observableArray([]),//Initial value set to empty. + tuNexrad : ko.observable({status: "requesting data"}) +}; + + + + + + diff --git a/pool/shard001/JavaScript/0010765_app.js b/pool/shard001/JavaScript/0010765_app.js new file mode 100644 index 0000000000000000000000000000000000000000..71742e13ee1cae22cf84cf45051da36d8586bbd1 --- /dev/null +++ b/pool/shard001/JavaScript/0010765_app.js @@ -0,0 +1,58 @@ +var express = require('express'); +var os = require('os'); +var networkInterfaces = os.networkInterfaces(); +var ip = networkInterfaces['eth0'][0]['address'] +var fs = require("fs"); +var port = 8080; +var greeting = process.env.GREETING || 'Hello'; +var who = process.env.WHO || 'World'; +var healthy=true; +var app = express(); + +app.get('/hello', function (req, res) { + console.log('saying hello') + res.send(greeting + ' ' + who + ' from container ' + os.hostname() + ' with Ip address ' + ip); +}); + +app.get('/file', function(req, res) { + console.log('reading config file') + if (fs.existsSync('/tmp/hello/hello.conf')) { + var file = fs.readFileSync("/tmp/hello/hello.conf").toString();} + else { + var file = "--No config file--";} + res.send(file + " from Container " + os.hostname() + '\n'); +}); + +app.get('/imageversion', function(req, res) { + console.log('getting base image version') + if (fs.existsSync('/etc/imageversion')) { + var imageversion = fs.readFileSync("/etc/imageversion").toString();} + else { + var imageversion = 'not set';} + res.send('Image version : ' + imageversion + '\n'); +}); + +app.get('/healthz', function (req, res) { + if(healthy) + res.send('OK'); + else + res.status(404).send('NOT OK'); +}); + +app.get('/kill', function (req, res) { + console.log('setting unhealthy') + healthy=false; + res.send('Killed ' + os.hostname()); +}); + +app.get('/', function(req, res) { + res.send('/imageversion
    /healthz
    /hello
    /file
    /kill'); +}); + +app.listen(port, ip); +console.log('Server running on http://%s:%s', ip, port); + +process.on('SIGTERM', function () { + console.log('Cleanup.....'); + process.exit(); +}); diff --git a/pool/shard001/JavaScript/0010768_index.js b/pool/shard001/JavaScript/0010768_index.js new file mode 100644 index 0000000000000000000000000000000000000000..6f24bbdc16929e5d0b8b1e511d09c8d69b7782b3 --- /dev/null +++ b/pool/shard001/JavaScript/0010768_index.js @@ -0,0 +1,57 @@ +angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']); +angular.module('ui.bootstrap.demo').controller('CarouselCtrl', function ($scope) { + $scope.myInterval = 5000; + $scope.noWrapSlides = false; + var slides = $scope.slides = []; + var currIndex = 0; + + $scope.addSlide = function() { + var newWidth = 0 + slides.length + 1; + slides.push({ + image: 'images/pic' + newWidth + '.jpg', + text: ['Senior','Freshman','New','New'][slides.length % 4] + ' ' + + ['Survey', 'Survey', 'Website', 'App'][slides.length % 4], + id: currIndex++ + }); + }; + + $scope.randomize = function() { + var indexes = generateIndexesArray(); + assignNewIndexesToSlides(indexes); + }; + + for (var i = 0; i < 4; i++) { + $scope.addSlide(); + } + + // Randomize logic below + + function assignNewIndexesToSlides(indexes) { + for (var i = 0, l = slides.length; i < l; i++) { + slides[i].id = indexes.pop(); + } + } + + function generateIndexesArray() { + var indexes = []; + for (var i = 0; i < currIndex; ++i) { + indexes[i] = i; + } + return shuffle(indexes); + } + + function shuffle(array) { + var tmp, current, top = array.length; + + if (top) { + while (--top) { + current = Math.floor(Math.random() * (top + 1)); + tmp = array[current]; + array[current] = array[top]; + array[top] = tmp; + } + } + + return array; + } +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010771_segment.js b/pool/shard001/JavaScript/0010771_segment.js new file mode 100644 index 0000000000000000000000000000000000000000..af140efa6c77c89f2d72427c8a8f6fb7e55d773f --- /dev/null +++ b/pool/shard001/JavaScript/0010771_segment.js @@ -0,0 +1,104 @@ +//Quick hack before webpack fix +function extendIfNode() { + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + var isNode = false; + // Export the Underscore object for **CommonJS**, with backwards-compatibility + // for the old `require()` API. If we're not in CommonJS, add `_` to the + // global object. + if (typeof __webpack_require__ !== 'function') { + isNode = true; + + var fs = require('fs'); + + require.extensions['.txt'] = function (module, filename) { + module.exports = fs.readFileSync(filename, 'utf8'); + }; + } else { + } +} +extendIfNode(); + +// 载入模块 +var Segment = require('segment'); +// 创建实例 +var segment = new Segment(); +// 使用默认的识别模块及字典,载入字典文件需要1秒,仅初始化时执行一次即可 +segment.useDefault(); + + +segment.loadDict(require('../../dict/jieba.txt'),true); +segment.loadDict(require('../../dict/dict2.txt'),true); +segment.loadDict(require('../../dict/dict3.txt'),true); + +segment.loadStopwordDict(require('../../dict/check_stop_words.txt'),true); + +segment.use({ + + // 类型 + type: 'optimizer', + + // segment.use() 载入模块,初始化时执行 + init: function (segment) { + console.log('init Opt'); + // segment 为当前的Segment实例 + }, + + // 优化 + doOptimize: function (words) { + + //TODO dynamic algo later + // function checkSlideWindow(sw) { + // if(sw.length>=2){ + // return (sw[0].p === 0 && sw[0].w.length ===1) + // && (sw[1].p === 0 && sw[1].w.length ===1) + // } + // return false; + // + // } + // console.log('doOptimize'); + // console.log(words); + // console.log('endOptimize'); + // //get all at once + // // find consecutive single char & break again? but rest nouns also important + // var slideWindow = []; + // for(var i=0;i 47 && code < 58) && // numeric (0-9) + !(code > 64 && code < 91) && // upper alpha (A-Z) + !(code > 96 && code < 123)) { // lower alpha (a-z) + return false; + } + } + return true; +}; + +export default segment; diff --git a/pool/shard001/JavaScript/0010777_15.2.3.6-3-14.js b/pool/shard001/JavaScript/0010777_15.2.3.6-3-14.js new file mode 100644 index 0000000000000000000000000000000000000000..7d85a2f7c88d4dda84094d4e69923a62301c77a4 --- /dev/null +++ b/pool/shard001/JavaScript/0010777_15.2.3.6-3-14.js @@ -0,0 +1,29 @@ +/// Copyright (c) 2012 Ecma International. All rights reserved. +/** + * The abtract operation ToPropertyDescriptor is used to package the + * into a property desc. Step 10 of ToPropertyDescriptor throws a TypeError + * if the property desc ends up having a mix of accessor and data property elements. + * + * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-14.js + * @description Object.defineProperty throws TypeError if setter is not callable but not undefined (Object)(8.10.5 step 8.b) + */ + + +function testcase() { + var o = {}; + + // dummy getter + var setter = { a: 1 }; + var desc = { set: setter }; + + try { + Object.defineProperty(o, "foo", desc); + } + catch (e) { + if (e instanceof TypeError && + (o.hasOwnProperty("foo") === false)) { + return true; + } + } + } +runTestCase(testcase); diff --git a/pool/shard001/JavaScript/0010778_ClickLoad.js b/pool/shard001/JavaScript/0010778_ClickLoad.js new file mode 100644 index 0000000000000000000000000000000000000000..0c0975e65ad50e421f0388651012d7211308ea34 --- /dev/null +++ b/pool/shard001/JavaScript/0010778_ClickLoad.js @@ -0,0 +1,51 @@ +//ClickLoad Library +//Version 1, December 2015 +//Written by Tucker Osman +//github.com/osmiumusa/ClickLoad/ + +(function($) { + $.fn.clickload = function(options) { + $(this).click(function() { + if (options.animate !== false) { + $(this).css("-webkit-animation", "progress-bar-stripes 2s linear infinite"); + $(this).css("-o-animation", "progress-bar-stripes 2s linear infinite"); + $(this).css("animation", "progress-bar-stripes 2s linear infinite"); + $(this).addClass("progress-bar-striped"); + } + $(this).removeClass("btn-success btn-danger"); + if (options.during) $(this).text(options.during); + if (options.disable !== false) $(this).prop("disabled", true); + var thisbutton = $(this); + $.ajax({ + url: options.url, + method: options.method || "GET", + headers: options.headers || {}, + data: options.data || {}, + success: function(data, textStatus, jqXHR) { + //User supplied function returns false if actually a success + thisbutton.prop("disabled", false); + thisbutton.css("-webkit-animation", ""); + thisbutton.css("-o-animation", ""); + thisbutton.css("animation", ""); + if (!options.success || options.success(data, textStatus, jqXHR) !== false) { + thisbutton.text(options.after); + thisbutton.removeClass("progress-bar-striped").addClass("btn-success"); + } else { + if (options.error) { + thisbutton.text(options.error(jqXHR, textStatus, undefined, data)); + } else thisbutton.text("Error!"); + thisbutton.removeClass("btn-success").addClass("btn-danger"); + } + }, + error: function(jqXHR, textStatus, errorThrown) { + thisbutton.css("-webkit-animation", ""); + thisbutton.css("-o-animation", ""); + thisbutton.css("animation", ""); + thisbutton.removeClass("progress-bar-striped").removeClass("btn-success").addClass("btn-danger"); + var returned = (options.error) ? options.error(jqXHR, textStatus, errorThrown, undefined) : "Error!"; + thisbutton.text(returned); + } + }) + }); + }; +}(jQuery)); diff --git a/pool/shard001/JavaScript/0010780_walkhub_iframe.js b/pool/shard001/JavaScript/0010780_walkhub_iframe.js new file mode 100644 index 0000000000000000000000000000000000000000..5125583e43ec412b6dce3330d214bfa42f44c9b8 --- /dev/null +++ b/pool/shard001/JavaScript/0010780_walkhub_iframe.js @@ -0,0 +1,142 @@ +// Walkhub +// Copyright (C) 2015 Pronovix +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +import React from "react"; +import ReactDOM from "react-dom"; +import Modal from "components/modal"; +import {noop} from "form"; +import {t} from "t"; +import flux from "control"; +import WalkhubBackendActions from "actions/walkhub_backend"; +import Bar from "components/bar"; + +class WalkhubIframe extends React.Component { + + static defaultProps = { + src: "", + title: "", + + actionButton: null, + actionButtonClassName: "", + onActionButtonClick: noop, + recdot: false, + errors: {}, + + onClose: noop, + }; + + onChange = (event) => { + switch (event.action) { + case WalkhubBackendActions.SHOW_ERROR: { + const data = event.data[0]; + this.setError(data.id, data.error); + } + break; + case WalkhubBackendActions.SUPPRESS_ERROR: { + const data = event.data[0]; + this.clearError(data.id); + } + break; + case WalkhubBackendActions.CLEAR_ERRORS: { + this.clearErrors(); + } + break; + } + }; + + dispatcherToken = null; + + componentDidMount() { + this.dispatcherToken = flux.dispatcher.register(this.onChange); + window.addEventListener("resize", this.resize); + this.resize(null); + } + + componentWillUnmount() { + if (this.dispatcherToken) { + flux.dispatcher.unregister(this.dispatcherToken); + } + window.removeEventListener("resize", this.resize); + } + + state = { + errors: {}, + height: window.innerHeight, + }; + + clearError(id) { + let errors = this.state.errors; + delete(errors[id]); + + this.setState({ + errors: errors, + }); + } + + clearErrors() { + this.setState({errors: {}}); + } + + setError(id, error) { + let errors = this.state.errors; + errors[id] = error; + + this.setState({ + errors: errors, + }); + } + + resize = (evt) => { + const iframe = ReactDOM.findDOMNode(this.refs.contentIframe); + const top = iframe.getBoundingClientRect().top; + this.setState({ + height: window.innerHeight - top, + }); + } + + render() { + const errors = this.state.errors; + const errs = Object.keys(errors).map(function(errid) { + return ( +
  • + +
  • + ); + }); + + return ( + + + {errs} + +
    +
    + +
    +
    +
    + ); + } + +} + +export default WalkhubIframe; diff --git a/pool/shard001/JavaScript/0010781_paymentProcessor.js b/pool/shard001/JavaScript/0010781_paymentProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..f3b6a0b2bec1c58578b74af6b032c69f9251a567 --- /dev/null +++ b/pool/shard001/JavaScript/0010781_paymentProcessor.js @@ -0,0 +1,150 @@ +class PaymentProcessor { + + constructor(options) { + this._payments = new Map(); // let's do it as a map + this._options = {types: ["service", "product", "other"], precision: 2}; + this.setOptions(options); + } + + get(id){ + if(!this._payments.has(id)){ + throw new Error('ID does not exist') + } + let payment = this._payments.get(id); + return `Details about payment ID: ${payment.id}\n` + + `- Name: ${payment.name}\n` + + `- Type: ${payment.type}\n` + + `- Value: ${payment.value}` + } + + registerPayment(id, name, type, value) { + try { + this.validate(id, name, type, value); + this._payments.set(id, ({id, name, type, value: this.formatValue(value)})); + } catch (e) { + throw new Error(e); + } + } + + formatValue(val){ + return Number(val).toFixed(this._options.precision) + } + + validate(id, name, type, value) { + if ( typeof id !== 'string'){ + throw new TypeError('ID should be string') + }; + if ( id === ''){ + throw new Error('ID can not be empty') + }; + if ( typeof name !== 'string'){ + throw new TypeError(`Payment\'sname should be string`) + } + if ( name === ''){ + throw new Error(`Payment\'s name can not be empty`) + }; + if (this._options.types.indexOf(type) < 0){ + throw new Error(`Material type: ${type} is not a valid option`) + } + if ( typeof value !== 'number'){ + throw new TypeError(`Payment\'s value: ${value} should be number`) + }; + if (this._payments.has(id)) { + throw new Error(`Payment's ID: ${id} already exist`) + } + return true; + } + + + deletePayment(id) { + if(!this._payments.has(id)){ + throw new Error('ID does not exist') + } + this._payments.delete(id); + } + + setOptions(options) { + if (options === undefined || options === null || options === ''){ + //options = {types: ["service", "product", "other"], precision: 2}; + // do not change default options + return false; + } + if (options.hasOwnProperty('types')){ + this._options.types = options.types; + } + if (options.hasOwnProperty('precision')){ + this._options.precision = options.precision; + } + } + + toString() { + return `Summary:\n` + + `- Payments: ${this._payments.size}\n` + + `- Balance: ${this.formatValue([...this._payments.values()].map(v => Number(v.value)).reduce((a, b) => a + b))}` + } + +} + +// Initialize processor with default options +const generalPayments = new PaymentProcessor(); +generalPayments.registerPayment('0001', 'Microchips', 'product', 15000); +generalPayments.registerPayment('01A3', 'Biopolymer', 'product', 23000); +console.log(generalPayments.toString()); + +// Should throw an error (invalid type) +try { + generalPayments.registerPayment('E028', 'Rare-earth elements', 'materials', 8000); +} catch (e){ + console.log(e.message); +} +generalPayments.setOptions({types: ['product', 'material']}); +generalPayments.registerPayment('E028', 'Rare-earth elements', 'material', 8000); +console.log(generalPayments.get('E028')); +generalPayments.registerPayment('CF15', 'Enzymes', 'material', 55000); + +// Should throw an error (ID not found) +try{ +generalPayments.deletePayment('E027'); +} catch (e){ + console.log(e.message); +} +// Should throw an error (ID not found) +try { +generalPayments.get('E027'); +} catch (e){ + console.log(e.message); +} + +generalPayments.deletePayment('E028'); +console.log(generalPayments.toString()); + +// Initialize processor with custom types +const servicePyaments = new PaymentProcessor({types: ['service']}); +servicePyaments.registerPayment('01', 'HR Consultation', 'service', 3000); +servicePyaments.registerPayment('02', 'Discount', 'service', -1500); +console.log(servicePyaments.toString()); + +// Initialize processor with custom precision +const transactionLog = new PaymentProcessor({precision: 5}); +transactionLog.registerPayment('b5af2d02-327e-4cbf', 'Interest', 'other', 0.00153); +console.log(transactionLog.toString()); + +/* +Summary: +- Payments: 2 +- Balance: 38000.00 +Details about payment ID: E028 +- Name: Rare-earth elements +- Type: material +- Value: 8000.00 +Summary: +- Payments: 3 +- Balance: 93000.00 +Summary: +- Payments: 2 +- Balance: 1500.00 +Summary: +- Payments: 1 +- Balance: 0.00153 + + */ \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010783_spec.js b/pool/shard001/JavaScript/0010783_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..08b7691f68a9260a4324751bbf5cec56f4e30153 --- /dev/null +++ b/pool/shard001/JavaScript/0010783_spec.js @@ -0,0 +1,45 @@ +/*jshint node:true, mocha:true */ + +'use strict'; + +require('should'); + +var adapter = require('floating-adapter'); +var Decimal = require('core-arbitrary-precision')(adapter); +var binaryOpExtender = require('../src/'); + +describe('binary operation', function() { + it('should do something with two values and return a new decimal by default', function() { + binaryOpExtender(Decimal, 'plus'); + binaryOpExtender(Decimal, 'plus', '+'); + binaryOpExtender(Decimal, 'div'); + binaryOpExtender(Decimal, 'div', 0); + + new Decimal('2').plus(new Decimal('3')).toString().should.be.exactly('5'); + new Decimal('2')['+'](new Decimal('3')).toString().should.be.exactly('5'); + + new Decimal('1')[0](new Decimal('2')).toString().should.be.exactly('0.5'); + }); + + it('should be able to return the result of the operation as is', function() { + binaryOpExtender.asIs(Decimal, 'lt'); + + new Decimal('2').lt(new Decimal('3')) + .should.be.exactly(true); + }); + + it('should be able to return the result of the operation with a custom transform', function() { + binaryOpExtender.raw(function(x) { return x.toString(); }, Decimal, 'lt'); + + new Decimal('4').lt(new Decimal('3')) + .should.be.exactly('false'); + }); + + it('should throw when the given method does not exist', function() { + binaryOpExtender(Decimal, 'nonExistentMethod'); + + (function() { + new Decimal('2').nonExistentMethod(new Decimal('3')); + }).should.throw('Unsupported operation'); + }); +}); diff --git a/pool/shard001/JavaScript/0010790_prototypes.js b/pool/shard001/JavaScript/0010790_prototypes.js new file mode 100644 index 0000000000000000000000000000000000000000..5fa001ef871f29a265ebd877c490e5bc1c5cf7f2 --- /dev/null +++ b/pool/shard001/JavaScript/0010790_prototypes.js @@ -0,0 +1,156 @@ + +// run like so: +// mocha -R spec abstract/prototypes.js + +// =============================================================================== +// HUGE DISCLAIMER AND WARNING: +// Don't be an interview jerk and ask questions like "What does {} + [] returns?". +// That's just mean and completely useless. Because if they know the answer, +// they're either antisocial jerks themselves, Douglas Crockford or Nick Makarov. +// =============================================================================== + +var assert = require('assert'); +var glob = this; + +describe ('Prototypes', function () { + + describe('simple call', function () { + var Obj = function () {}; + Obj.prototype.key = 'value'; + Obj.prototype.fn = function () {return this.key;}; + var obj = new Obj(); + + it('direct vs. prototype.call', function () { + assert.equal(obj.fn(), 'value'); + assert.equal(Obj.prototype.fn.call(obj), 'value'); + }); + }); + + it('direct vs call vs apply', function () { + var f = function (a,b,c) { + return 'a:'+a+', b:'+b+', c:'+c; + }; + + var direct = f(2,4,6); + assert.equal(direct, f.call(this,2,4,6)); + assert.equal(direct, f.apply(this,[2,4,6])); + }); + + describe ('objects', function () { + + it ('inherits from Object', function () { + var obj = {a: 1}; + assert(obj instanceof Object); + }); + }); + + it ('playing with...', function () { + var P1 = function () {}; + var P2 = function () {}; + + var p1 = new P1(); + + assert.equal(p1 instanceof P1, true); + assert.equal(p1 instanceof Object, true); + + assert.equal(p1 instanceof P2, false); + + // let's build a simple chain: + P1.prototype = new P2(); + var p2 = new P1(); + assert.equal(p2 instanceof P2, true); + assert.equal(p2 instanceof P1, true); + + // these not work because `p1` is instantiated _before_ prototype chain was setup: + assert.equal(p1 instanceof P2, false); // why? + assert.equal(p1 instanceof P1, false); // why? + + // and now is ok, because `p1After` is created just now: + var p1After = new P1(); + assert.equal(p1After instanceof P1, true); + assert.equal(p1After instanceof P2, true); + + }); + + describe('Cool stuff', function () { + it('can be rounded by shift', function () { + assert.equal(123.45 >> 0, 123); + }); + it('is it array?', function () { + assert([1,3,5] instanceof Array); + }); + describe('shallow array copy', function () { + it('bad way (never do it)', function () { + var a = [1,3,5]; + var b = a; + + b[1] = 100; // modify second element + assert.equal(a[1] === 3, false); // original array modified since a and b just pointers to the same stuff + }); + it('good way', function () { + var a = [1,3,5]; + var b = a.slice(); + + b[1] = 100; // modify second element + assert.equal(a[1] === 3, true); // that works now. + }); + }); + }); + + describe('Functions', function () { + var f = function () {return this;}; + var o = {key: 'value', f: function () {return this;}}; + + // helper function + var isNodeOrIOJS = function (string) { + return !! string.match(/node|iojs/); + }; + describe('have different contexts (this)', function () { + + it('watch this crap:', function () { + // here: borrowing the function, not the context of it: + var fi = o.f; + assert.equal(isNodeOrIOJS(fi().process.title), true); + // wow + // it is because the context solely depends on how you call a function. + }); + + it ('apply/call: whatever you pass as a first arg', function () { + assert.equal(f.call(4), 4); + assert.equal(f.call('abc'), 'abc'); + }); + + it ('apply/call: global if you pass nothing', function () { + assert.equal(isNodeOrIOJS(f.call().process.title), true); + assert.equal(isNodeOrIOJS(f.call(undefined).process.title), true); + assert.equal(isNodeOrIOJS(f.call(null).process.title), true); + }); + + it('as a method: the object', function () { + assert.equal(o.f().key, 'value'); + }); + + it('standalone: global', function () { + assert.equal(isNodeOrIOJS(f().process.title), true); + }); + + it('universal solution: bind it!', function () { + var _bind = function (func, context) { + return function () { return func.apply(context, arguments); }; + }; + + var bindedF = _bind(o.f, o); + assert.equal(bindedF().key, 'value'); + }); + }); + + }); +}); + +/* +var obj1 = {a:'b'}; +// the following is identical, because `toString` works with the `this` object, which is the first parameter anyway +console.log('obj1: ' + obj1.toString()); +console.log('obj1: ' + Object.prototype.toString.call(obj1)); +*/ + diff --git a/pool/shard001/JavaScript/0010793_entry.js b/pool/shard001/JavaScript/0010793_entry.js new file mode 100644 index 0000000000000000000000000000000000000000..8045e9be3779c7777826f262d776c5ea54b9bdf9 --- /dev/null +++ b/pool/shard001/JavaScript/0010793_entry.js @@ -0,0 +1,56 @@ +'use strict'; + +module.exports = function(sequelize, DataTypes) { + var models = { + entry: sequelize.define('entry', { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + validate: { + isUUID: 4 + }, + primaryKey: true + }, + date: { + type: DataTypes.DATE, + allowNull: false, + validate: { + isDate: true, + } + }, + body: { + type: DataTypes.TEXT, + allowNull: false, + validate: { + notEmpty: true, + } + } + }, { + }), + + tag: sequelize.define('tag', { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + allowNull: false, + validate: { + isUUID: 4 + }, + primaryKey: true + }, + value: { + type: DataTypes.STRING(255), + allowNull: false, + unique: true, + validate: { + } + } + }, { + }) + }; + + models.tag.belongsToMany(models.entry, { through: 'entry_tag' }); + models.entry.belongsToMany(models.tag, { through: 'entry_tag' }); + + return models; +}; diff --git a/pool/shard001/JavaScript/0010797_first-post-as-index.js b/pool/shard001/JavaScript/0010797_first-post-as-index.js new file mode 100644 index 0000000000000000000000000000000000000000..107403809e692399f565df6b564e2f8aeb74b222 --- /dev/null +++ b/pool/shard001/JavaScript/0010797_first-post-as-index.js @@ -0,0 +1,30 @@ +/** + * Dependencies + */ +var minimatch = require('minimatch') + +/** + * Expose `firstPostAsIndex` + */ +module.exports = firstPostAsIndex + +function firstPostAsIndex (collection) { + return function (files, metalsmith, done) { + var filenames = Object.keys(files) + filenames.forEach(function (filename) { + var file = files[filename] + if ( minimatch(filename, collection + '/index.html') ) { + var first = metalsmith.metadata() + .collections[collection][0] + file['pathOriginal'] = first.pathOriginal + // file['headline'] = first.headline + file['pathContent'] = '/' + first.path + file['collection'] = collection + // file['description'] = first.description + // file['keywords'] = (file['keywords']) ? first.keywords : file['keywords'] + ',' + first.keywords + done() + } + }) + } +} + diff --git a/pool/shard001/JavaScript/0010803_visit.js b/pool/shard001/JavaScript/0010803_visit.js new file mode 100644 index 0000000000000000000000000000000000000000..d8deaf8052dbcaed7b6bfc7d35484d4ea81d7791 --- /dev/null +++ b/pool/shard001/JavaScript/0010803_visit.js @@ -0,0 +1,179 @@ +import AbstractModel from 'hospitalrun/models/abstract'; +import DS from 'ember-data'; +import Ember from 'ember'; +import moment from 'moment'; + +function dateAcceptance(object) { + if (!object.get('hasDirtyAttributes')) { + return false; + } + let startDate = object.get('startDate'); + let endDate = object.get('endDate'); + if (Ember.isEmpty(endDate) || Ember.isEmpty(startDate)) { + // Can't validate if empty + return false; + } else { + if (endDate.getTime() < startDate.getTime()) { + return true; + } + } + return false; +} + +const { computed } = Ember; + +const PAYMENT_STATES = { + CLEAR: 'clear', + PENDING: 'pending' +}; +const COMPLETED_STATUS = 'Completed'; +const FULFILLED_STATUS = 'Fulfilled'; +const REQUESTED_STATUS = 'Requested'; +const STATUS_FIELD = 'status'; + +function paymentStateAcceptance(object) { + return !Object.keys(PAYMENT_STATES) + .some((state) => PAYMENT_STATES[state] === object.get('paymentState')); +} + +export default AbstractModel.extend({ + additionalDiagnoses: DS.attr(), // Yes, the plural of diagnosis is diagnoses! + charges: DS.hasMany('proc-charge', { + async: false + }), + customForms: DS.attr('custom-forms'), + diagnoses: DS.hasMany('diagnosis', { async: false }), + dischargeInfo: DS.attr('string'), + endDate: DS.attr('date'), // if visit type is outpatient, startDate and endDate are equal + examiner: DS.attr('string'), + hasAppointment: DS.attr('boolean', { defaultValue: false }), + history: DS.attr('string'), // No longer used + historySince: DS.attr('string'), // History of the Present Illness -- no longer used + imaging: DS.hasMany('imaging', { async: true }), + labs: DS.hasMany('lab', { async: true }), + location: DS.attr('string'), + medication: DS.hasMany('medication', { async: true }), + // this field is being deprecated in favor of patient-note + notes: DS.attr('string'), + patientNotes: DS.hasMany('patient-note', { async: true }), + outPatient: DS.attr('boolean'), + patient: DS.belongsTo('patient', { + async: false + }), + paymentState: DS.attr('string', { defaultValue: PAYMENT_STATES.PENDING }), + primaryDiagnosis: DS.attr('string'), // No longer used -- diagnoses are stored in diagnoses hasMany relationship + primaryBillingDiagnosis: DS.attr('string'), // AKA final diagnosis + primaryBillingDiagnosisId: DS.attr('string'), + procedures: DS.hasMany('procedure', { async: true }), + reasonForVisit: DS.attr('string'), + startDate: DS.attr('date'), + status: DS.attr('string'), + visitType: DS.attr(), + vitals: DS.hasMany('vital', { async: true }), + reports: DS.hasMany('report', { async: true }), + + diagnosisList: computed('diagnoses.[]', function() { + let diagnoses = this.get('diagnoses'); + let diagnosisList = diagnoses.map((diagnosis) => { + return diagnosis.get('diagnosis'); + }); + return diagnosisList; + }), + + hasAppointmentLabel: computed('hasAppointment', function() { + let hasAppointment = this.get('hasAppointment'); + let i18n = this.get('i18n'); + if (hasAppointment === true) { + return i18n.t('visits.labels.haveAppointment'); + } else { + return i18n.t('visits.labels.noAppointment'); + } + }), + + hasCompletedImaging: computed('imaging.@each.status', function() { + let imaging = this.get('imaging'); + return imaging.isAny(STATUS_FIELD, COMPLETED_STATUS); + }), + + hasCompletedLabs: computed('labs.@each.status', function() { + let labs = this.get('labs'); + return labs.isAny(STATUS_FIELD, COMPLETED_STATUS); + }), + + hasCompletedMedication: computed('medication.@each.status', function() { + let medication = this.get('medication'); + return medication.isAny(STATUS_FIELD, FULFILLED_STATUS); + }), + + hasDoneOrders: computed('imaging.@each.status', 'labs.@each.status', function() { + let i18n = this.get('i18n'); + let imaging = this.get('imaging'); + let labs = this.get('labs'); + if (imaging.isAny(STATUS_FIELD, REQUESTED_STATUS) || labs.isAny(STATUS_FIELD, REQUESTED_STATUS)) { + return i18n.t('visits.labels.ordersNotDone'); + } else { + return i18n.t('visits.labels.haveDoneOrders'); + } + }), + + primaryDiagnoses: computed('diagnoses.[].secondaryDiagnosis', function() { + let diagnoses = this.get('diagnoses'); + let diagnosisList = diagnoses.filterBy('secondaryDiagnosis', false).map((diagnosis) => { + return diagnosis.get('diagnosis'); + }); + return diagnosisList.join(', '); + }), + + visitDate: function() { + let endDate = this.get('endDate'); + let startDate = moment(this.get('startDate')); + let visitDate = startDate.format('l'); + if (!Ember.isEmpty(endDate) && !startDate.isSame(endDate, 'day')) { + visitDate += ` - ${moment(endDate).format('l')}`; + } + return visitDate; + }.property('startDate', 'endDate'), + + visitDescription: function() { + let visitDate = this.get('visitDate'); + let visitType = this.get('visitType'); + return `${visitDate} (${visitType})`; + }.property('visitDate', 'visitType'), + + validations: { + endDate: { + acceptance: { + accept: true, + if: dateAcceptance, + message: 'Please select an end date later than the start date' + } + }, + patientTypeAhead: { + presence: { + if(object) { + return (object.get('checkIn') && !object.get('hidePatientSelection')); + } + } + }, + paymentState: { + acceptance: { + accept: true, + if: paymentStateAcceptance + }, + presence: true + }, + startDate: { + acceptance: { + accept: true, + if: dateAcceptance, + message: 'Please select a start date earlier than the end date' + }, + presence: true + }, + visitType: { + presence: true + } + + } + +}); diff --git a/pool/shard001/JavaScript/0010807_format.js b/pool/shard001/JavaScript/0010807_format.js new file mode 100644 index 0000000000000000000000000000000000000000..1fb0c8ed7fd2b18631365a56ab1bd574cbc2562c --- /dev/null +++ b/pool/shard001/JavaScript/0010807_format.js @@ -0,0 +1,97 @@ +// Javascript functions for Weeks course format + +M.course = M.course || {}; + +M.course.format = M.course.format || {}; + +/** + * Get sections config for this format + * + * The section structure is: + *
      + *
    • ...
    • + *
    • ...
    • + * ... + *
    + * + * @return {object} section list configuration + */ +M.course.format.get_config = function() { + return { + container_node : 'ul', + container_class : 'weeks', + section_node : 'li', + section_class : 'section' + }; +} + +/** + * Swap section + * + * @param {YUI} Y YUI3 instance + * @param {string} node1 node to swap to + * @param {string} node2 node to swap with + * @return {NodeList} section list + */ +M.course.format.swap_sections = function(Y, node1, node2) { + var CSS = { + COURSECONTENT : 'course-content', + SECTIONADDMENUS : 'section_add_menus' + }; + + var sectionlist = Y.Node.all('.'+CSS.COURSECONTENT+' '+M.course.format.get_section_selector(Y)); + // Swap menus. + sectionlist.item(node1).one('.'+CSS.SECTIONADDMENUS).swap(sectionlist.item(node2).one('.'+CSS.SECTIONADDMENUS)); +} + +/** + * Process sections after ajax response + * + * @param {YUI} Y YUI3 instance + * @param {array} response ajax response + * @param {string} sectionfrom first affected section + * @param {string} sectionto last affected section + * @return void + */ +M.course.format.process_sections = function(Y, sectionlist, response, sectionfrom, sectionto) { + var CSS = { + SECTIONNAME : 'sectionname' + }, + SELECTORS = { + SECTIONLEFTSIDE : '.left .section-handle .icon' + }; + + if (response.action == 'move') { + // If moving up swap around 'sectionfrom' and 'sectionto' so the that loop operates. + if (sectionfrom > sectionto) { + var temp = sectionto; + sectionto = sectionfrom; + sectionfrom = temp; + } + + // Update titles and move icons in all affected sections. + var ele, str, stridx, newstr; + + for (var i = sectionfrom; i <= sectionto; i++) { + // Update section title. + var content = Y.Node.create('' + response.sectiontitles[i] + ''); + sectionlist.item(i).all('.'+CSS.SECTIONNAME).setHTML(content); + + // Update move icon. + ele = sectionlist.item(i).one(SELECTORS.SECTIONLEFTSIDE); + str = ele.getAttribute('alt'); + stridx = str.lastIndexOf(' '); + newstr = str.substr(0, stridx +1) + i; + ele.setAttribute('alt', newstr); + ele.setAttribute('title', newstr); // For FireFox as 'alt' is not refreshed. + + // Remove the current class as section has been moved. + sectionlist.item(i).removeClass('current'); + } + // If there is a current section, apply corresponding class in order to highlight it. + if (response.current !== -1) { + // Add current class to the required section. + sectionlist.item(response.current).addClass('current'); + } + } +} diff --git a/pool/shard001/JavaScript/0010808_2d.fillStyle.parse.hsl-4.worker.js b/pool/shard001/JavaScript/0010808_2d.fillStyle.parse.hsl-4.worker.js new file mode 100644 index 0000000000000000000000000000000000000000..21fa84aaec92fb95805d6eabe1342848c5a48ad6 --- /dev/null +++ b/pool/shard001/JavaScript/0010808_2d.fillStyle.parse.hsl-4.worker.js @@ -0,0 +1,27 @@ +// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.fillStyle.parse.hsl-4 +// Description: +// Note:

    + +importScripts("/resources/testharness.js"); +importScripts("/html/canvas/resources/canvas-tests.js"); + +var t = async_test(""); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + + +ctx.fillStyle = '#f00'; +ctx.fillStyle = 'hsl(-360240, 100%, 50%)'; +ctx.fillRect(0, 0, 100, 50); +_assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255"); +t.done(); + +}); +done(); diff --git a/pool/shard001/JavaScript/0010809_CharacterTab.js b/pool/shard001/JavaScript/0010809_CharacterTab.js new file mode 100644 index 0000000000000000000000000000000000000000..f50f3683d261ad12bc339c520999f2a3b2533be4 --- /dev/null +++ b/pool/shard001/JavaScript/0010809_CharacterTab.js @@ -0,0 +1,63 @@ +import ArmoryIcon from 'interface/icons/Armory'; +import WoWAnalyzerIcon from 'interface/icons/WoWAnalyzer'; +import { makeCharacterUrl, makeArmoryUrl } from 'interface/makeAnalyzerUrl'; +import Combatant from 'parser/core/Combatant'; +import StatTracker from 'parser/shared/modules/StatTracker'; +import PropTypes from 'prop-types'; +import React from 'react'; +import { Link } from 'react-router-dom'; + +import './CharacterTab.css'; +import CharacterRace from './CharacterRace'; +import CharacterStats from './CharacterStats'; +import PlayerInfo from './PlayerInfo'; + +const CharacterTab = (props) => { + const { statTracker, combatant } = props; + + return ( +

    +
    +
    + +
    +
    + + + + +
    +
    +

    Other pages

    +
    +
    +
    +
    + {/* some bonus padding so it looks to be aligned with the icon for stats */} + {combatant.characterProfile ? ( + <> + + Character parses + +
    + + Armory + + + ) : ( + Unavailable because your character could not be found. + )} +
    +
    +
    +
    +
    + ); +}; + +CharacterTab.propTypes = { + statTracker: PropTypes.instanceOf(StatTracker).isRequired, + combatant: PropTypes.instanceOf(Combatant).isRequired, +}; + +export default CharacterTab; diff --git a/pool/shard001/JavaScript/0010811_https.js b/pool/shard001/JavaScript/0010811_https.js new file mode 100644 index 0000000000000000000000000000000000000000..895459aa60a6d568ec3ef9b23df3bc182c5be928 --- /dev/null +++ b/pool/shard001/JavaScript/0010811_https.js @@ -0,0 +1,21 @@ +var https = require('https'); +var fs = require('fs'); +var path = require('path'); +var static = require('node-static'), + fileServer; + +var options = { + key: fs.readFileSync(path.join(__dirname, '..', '..', 'cert/http2rulez.com.key')), + cert: fs.readFileSync(path.join(__dirname, '..', '..', 'cert/http2rulez.com.cert')) +}; + +var file = new static.Server('../public'); + +https.createServer(options, function(request, response) { + request.addListener('end', function () { + // + // Serve files! + // + file.serve(request, response); + }).resume(); +}).listen(8081); diff --git a/pool/shard001/JavaScript/0010818_amd.js b/pool/shard001/JavaScript/0010818_amd.js new file mode 100644 index 0000000000000000000000000000000000000000..af4a5b52fe88b50b0391e66054cb26e9edc86b51 --- /dev/null +++ b/pool/shard001/JavaScript/0010818_amd.js @@ -0,0 +1,21 @@ +define(function () { 'use strict'; + + function odd ( n ) { + return n !== 0 && even( n - 1 ); + } + + var counter = 0; + + // This should be in the output + var foo = odd( 12 ); + + function even ( n ) { + alert( counter++ ); + return n === 0 || odd( n - 1 ); + } + + console.log( even( 5 ) ); + + console.log( counter ); + +}); diff --git a/pool/shard001/JavaScript/0010820_Gulpfile.js b/pool/shard001/JavaScript/0010820_Gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..17da831da5c3fd99943c2338b41057e6c22e48f6 --- /dev/null +++ b/pool/shard001/JavaScript/0010820_Gulpfile.js @@ -0,0 +1,94 @@ +/** + * Gulpfile.js + */ + +/* jshint node:true */ + +'use strict'; + +// If NodeJS version is 0.10.x, use Promise polyfill to support Autoprefixer +if (/0.10/.test(process.version)) { + console.log("NodeJS 0.10.x detected; using Promise polyfill"); + require('es6-promise').polyfill(); +} + +var gulp = require('gulp'), + sass = require('gulp-sass'), + rename = require('gulp-rename'), + sourcemaps = require('gulp-sourcemaps'); + +var folders = { + globals: 'src/components/', + dist: 'dist/' +}; + + +// +// node-sass functions +// +// Experimental according to documentation but that doesn't prevent it +// from working + +var functions = { + // Turns SVG Code into a base64 data URI + // Used in _icons.scss + // + // @param $svg A valid SVG document + // @return A data URI of the base64 encoded representation of the given + // SVG document + + 'svg_to_base64($svg)': function svg_to_base64(svg, done) { + var String = require('node-sass').types.String, + src = svg.getValue(), + base64; + src = src.replace(/[\s\\a]+(?=<)/g, ''); + + base64 = new Buffer(src).toString('base64'); + + done(new String('data:image/svg+xml;base64,' + base64)); + } +}; + + +// +// Gulp Tasks +// + +// Core building +gulp.task('build:sass', function () { + return gulp.src('src/main.scss') + .pipe(sourcemaps.init()) + .pipe(sass({ + sourcemap: true, + outputStyle: 'expanded', + functions: functions + }).on('error', sass.logError)) + .pipe(rename({basename: 'city'})) + .pipe(sourcemaps.write('./', {sourceRoot: './'})) + .pipe(gulp.dest(folders.dist)); +}); + +// Production +gulp.task('production', ['build:sass'], function () { + // We use Autoprefixer and cssnano *only* when building for production, thus these "require" + // statements are separate from the others + var autoprefixer = require('gulp-autoprefixer'), + cssnano = require('gulp-cssnano'); + + return gulp.src(folders.dist + 'city.css') + .pipe(autoprefixer({browsers: ['last 2 versions']})) + // normal version + .pipe(gulp.dest(folders.dist)) + // minified version + .pipe(rename({suffix: '.min'})) + .pipe(cssnano()) + .pipe(gulp.dest(folders.dist)); +}); + +// Default task +gulp.task('default', ['build:sass', 'watch']); + +// Watch files +gulp.task('watch', function () { + gulp.watch(['src/**/*.scss', 'src/main.scss'], ['build:sass']); +}); diff --git a/pool/shard001/JavaScript/0010822_CssBaseline.js b/pool/shard001/JavaScript/0010822_CssBaseline.js new file mode 100644 index 0000000000000000000000000000000000000000..47b74a8ffcddabc03b4b4bd1e3bff5c71822dbe9 --- /dev/null +++ b/pool/shard001/JavaScript/0010822_CssBaseline.js @@ -0,0 +1,92 @@ +import _extends from "@babel/runtime/helpers/esm/extends"; + +var _GlobalStyles; + +import * as React from 'react'; +import PropTypes from 'prop-types'; +import useThemeProps from '../styles/useThemeProps'; +import GlobalStyles from '../GlobalStyles'; +import { jsx as _jsx } from "react/jsx-runtime"; +import { jsxs as _jsxs } from "react/jsx-runtime"; +export var html = { + WebkitFontSmoothing: 'antialiased', + // Antialiasing. + MozOsxFontSmoothing: 'grayscale', + // Antialiasing. + // Change from `box-sizing: content-box` so that `width` + // is not affected by `padding` or `border`. + boxSizing: 'border-box', + // Fix font resize problem in iOS + WebkitTextSizeAdjust: '100%' +}; +export var body = function body(theme) { + return _extends({ + color: theme.palette.text.primary + }, theme.typography.body1, { + backgroundColor: theme.palette.background.default, + '@media print': { + // Save printer ink. + backgroundColor: theme.palette.common.white + } + }); +}; +export var styles = function styles(theme) { + var _theme$components, _theme$components$Mui; + + var defaultStyles = { + html: html, + '*, *::before, *::after': { + boxSizing: 'inherit' + }, + 'strong, b': { + fontWeight: theme.typography.fontWeightBold + }, + body: _extends({ + margin: 0 + }, body(theme), { + // Add support for document.body.requestFullScreen(). + // Other elements, if background transparent, are not supported. + '&::backdrop': { + backgroundColor: theme.palette.background.default + } + }) + }; + var themeOverrides = (_theme$components = theme.components) == null ? void 0 : (_theme$components$Mui = _theme$components.MuiCssBaseline) == null ? void 0 : _theme$components$Mui.styleOverrides; + + if (themeOverrides) { + defaultStyles = [defaultStyles, themeOverrides]; + } + + return defaultStyles; +}; +/** + * Kickstart an elegant, consistent, and simple baseline to build upon. + */ + +function CssBaseline(inProps) { + var props = useThemeProps({ + props: inProps, + name: 'MuiCssBaseline' + }); + var children = props.children; + return /*#__PURE__*/_jsxs(React.Fragment, { + children: [_GlobalStyles || (_GlobalStyles = /*#__PURE__*/_jsx(GlobalStyles, { + styles: styles + })), children] + }); +} + +process.env.NODE_ENV !== "production" ? CssBaseline.propTypes +/* remove-proptypes */ += { + // ----------------------------- Warning -------------------------------- + // | These PropTypes are generated from the TypeScript type definitions | + // | To update them edit the d.ts file and run "yarn proptypes" | + // ---------------------------------------------------------------------- + + /** + * You can wrap a node. + */ + children: PropTypes.node +} : void 0; +export default CssBaseline; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010824_requestinfo.js b/pool/shard001/JavaScript/0010824_requestinfo.js new file mode 100644 index 0000000000000000000000000000000000000000..8aae41c4521fe30d3cdb7e57b3c16e71b4449099 --- /dev/null +++ b/pool/shard001/JavaScript/0010824_requestinfo.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var RequestInfo = /** @class */ (function () { + function RequestInfo(url, method, + /** + * Returns the value with which to resolve the request's promise. Only called + * if the request is successful. Throw from this function to reject the + * returned Request's promise with the thrown error. + * Note: The XhrIo passed to this function may be reused after this callback + * returns. Do not keep a reference to it in any way. + */ + handler, timeout) { + this.url = url; + this.method = method; + this.handler = handler; + this.timeout = timeout; + this.urlParams = {}; + this.headers = {}; + this.body = null; + this.errorHandler = null; + /** + * Called with the current number of bytes uploaded and total size (-1 if not + * computable) of the request body (i.e. used to report upload progress). + */ + this.progressCallback = null; + this.successCodes = [200]; + this.additionalRetryCodes = []; + } + return RequestInfo; +}()); +exports.RequestInfo = RequestInfo; + +//# sourceMappingURL=requestinfo.js.map diff --git a/pool/shard001/JavaScript/0010828_nodeindx.js b/pool/shard001/JavaScript/0010828_nodeindx.js new file mode 100644 index 0000000000000000000000000000000000000000..8c5c9afec1b0804875076530ec1bf79baa478baf --- /dev/null +++ b/pool/shard001/JavaScript/0010828_nodeindx.js @@ -0,0 +1,62 @@ + +// nodejs shims for indxjs +// you can 'require' me like : require('nodeindx')) +// + +var angular = require('angular'), + Backbone = require('backbone'), + _ = require('underscore'), + jQuery = require('jquery'), + fs = require('fs'), + WebSocket = require('ws'), + argv = require('optimist').argv, + path = require('path'); + +// compatibility shims start here >>>>>>> +console.debug = console.error; +var window = {}, document = {location:{}}; +var savage_require = function(p) { + // read from the base of the INDX codebase + var resolved = path.resolve(__dirname,'..','..','..',p); + var read = fs.readFileSync(resolved).toString(); + eval(read); +}; + +// now we are going to start the load +var _NODE_AJAX = require('./node_ajax.js'), + indx_ = savage_require('html/js/indx.js'), + indx_ws_ = savage_require('html/js/indx-ws.js'), + utils_ = savage_require('html/js/indx-utils.js'); + entities_ = savage_require('html/js/indx-entities.js'); + +var injector = angular.injector(['ng','indx']); +var u = injector.get('utils'), + indx = injector.get('client'); + +// please set these parameters to what you want htem to be. +// var username=argv.username || 'nobody', +// password=argv.password || 'nobody', +// hostname=argv.host || argv.hostname || 'https://localhost:8211'; + +// console.debug('user: ', username, ' passwordlen: ', password.length, ' - ', hostname); + +module.exports = { + utils:u, + indx:indx, + login: function(hostname,username,password) { + console.debug('attempting login >> // indx:', hostname, ' // u:', username, ' // p:', password); + var s = new indx.Store({server_host:hostname}), d = u.deferred(); + s.login(username,password) + .then(function(x) { d.resolve(s); }) + .fail(function(err) { d.reject('error logging in -- ', err); }); + return d.promise(); + }, + injector:injector, + require:savage_require +}; + +// if (require.main === module) { +// module.exports.login() +// .then(function() { console.debug('ok!'); }) +// .fail(function() { console.error('fail :('); }); +// } \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010830_app.js b/pool/shard001/JavaScript/0010830_app.js new file mode 100644 index 0000000000000000000000000000000000000000..310f57e9f57d50649141823598c0d53dfe022f16 --- /dev/null +++ b/pool/shard001/JavaScript/0010830_app.js @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2014-2015 Neil Munro . + */ + +"use strict"; + +var fs = require('fs'); +var path = require('path'); +var express = require('express'); +var app = express(); +var server = require('http').createServer(app); +var io = require('socket.io').listen(server); +var API = require('./api'); + +var name = process.argv[2]; +var presentation = path.join(__dirname, "presentations", name); +var sections = path.join(presentation, "presentation.json"); +var sectionList = JSON.parse(fs.readFileSync(sections, "utf8")); +var sectionCounter = 0; +var msg = "No messages."; + +console.log("Starting: ", name); + +app.use(express.static(presentation)); +app.use(express.static('public')); +app.use(express.static('bower_components')); + +app.get('/admin', function(request, response) { + var admin = path.join(__dirname, "public", "html", "admin.html"); + response.sendfile(admin); +}); + +app.get('/staff', function(request, response) { + "use strict"; + var staff = path.join(__dirname, "public", "html", "staff.html"); + response.sendfile(staff); +}); + +app.get('/test/:id', function(request, response) { + var testName = path.join(__dirname, 'public', 'test', request.params.id + '.html'); + response.sendfile(testName); +}); + +function counterNext() { + sectionCounter = (sectionCounter >= sectionList.length -1) ? 0 : sectionCounter +1; +} + +function counterPrev() { + sectionCounter = (sectionCounter === 0) ? sectionList.length -1 : sectionCounter -1; +} + +function getSectionCounter() { + return sectionCounter; +} + +function getSection() { + return sectionList[sectionCounter]; +} + +function counterReset() { + sectionCounter = 0; +} + +function counterSet(number) { + if(number < 0 || number > sectionList.length -1) { + number = 0; + } + + sectionCounter = number; +} + +function getAll() { + return sectionList; +} + +io.sockets.on('connection', function(socket) { + // Emit needed information upfront. + socket.emit(API.section.recv.current, { + "section": getSection(), + "counter": getSectionCounter() + }); + + socket.emit(API.section.recv.all, { + "sections": getAll(), + "counter": getSectionCounter() + }); + + io.sockets.emit(API.message.recv, { + "msg": msg + }); + + socket.on(API.section.send.next, function(data) { + counterNext(); + io.sockets.emit(API.section.recv.current, { + "section": getSection(), + "counter": getSectionCounter() + }); + }); + + socket.on(API.section.send.previous, function(data) { + counterPrev(); + io.sockets.emit(API.section.recv.current, { + "section": getSection(), + "counter": getSectionCounter() + }); + }); + + socket.on(API.section.send.get, function(data) { + counterSet(parseInt(data.id, 10)); + io.sockets.emit(API.section.recv.current, { + "section": getSection(), + "counter": getSectionCounter() + }); + }); + + socket.on(API.section.send.all, function() { + io.sockets.emit(API.section.recv.all, { + "sections": getAll(), + "counter": getSectionCounter() + }); + }); + + socket.on(API.section.send.reset, function(data) { + counterReset(); + io.sockets.emit(API.section.recv.reset, { + "section": getSection(), + "counter": getSectionCounter() + }); + }); + + socket.on(API.message.send, function(data) { + msg = data.msg; + io.sockets.emit(API.message.recv, { + "msg": data.msg + }); + }); + + // Send the play signal. + socket.on(API.media.send.play, function(data) { + io.sockets.emit(API.media.recv.play, { + "state": data.state, + "id": data.id + }); + }); + + socket.on(API.media.send.pause, function(data) { + io.sockets.emit(API.media.recv.pause, { + "state": data.state, + "id": data.id + }); + }); + + socket.on(API.media.send.stop, function(data) { + io.sockets.emit(API.media.recv.stop, { + "state": data.state, + "id": data.id + }); + }); +}); + +// This keeps the server alive. +server.listen(1337, function() { "use strict"; }); diff --git a/pool/shard001/JavaScript/0010837_sunos.js b/pool/shard001/JavaScript/0010837_sunos.js new file mode 100644 index 0000000000000000000000000000000000000000..86f7ca109ab0b39066c515b9757c84a91db20ef0 --- /dev/null +++ b/pool/shard001/JavaScript/0010837_sunos.js @@ -0,0 +1,16 @@ +module.exports = function() { + var sysinfo = require('../../sysinfo.js')(); + return { + lookup: lookup + }; + + function lookup(pid, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + options = options || {}; + + sysinfo.getUsage(pid, callback); + }; +}; diff --git a/pool/shard001/JavaScript/0010842_Editors__Replace_Selection_with_Date.js b/pool/shard001/JavaScript/0010842_Editors__Replace_Selection_with_Date.js new file mode 100644 index 0000000000000000000000000000000000000000..a4370787644fcd86c8adb7c06c6a1f94b7356113 --- /dev/null +++ b/pool/shard001/JavaScript/0010842_Editors__Replace_Selection_with_Date.js @@ -0,0 +1,36 @@ +/* + * Menu: Examples > Editors > JS > Replace Selecton with Date + * Kudos: Paul Colton (Aptana, Inc.) + * Description: You can use this script to replace the current seleciton of the active text editorwith the current date + * License: EPL 1.0 + * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript + */ + +function main() { + + var sourceEditor = editors.activeEditor; + + var valid = true; + + // make sure we have an editor + if (sourceEditor === undefined) { + valid = false; + showError("No active editor"); + } + + // inject + if (valid) { + + var range = sourceEditor.selectionRange; + var offset = range.startingOffset; + var deleteLength = range.endingOffset - range.startingOffset; + var source = sourceEditor.source; + + var text = new Date(); + + // apply edit and reveal in editor + sourceEditor.applyEdit(offset, deleteLength, text); + sourceEditor.selectAndReveal(offset, text.length); + + } +} diff --git a/pool/shard001/JavaScript/0010844_recording-streams.js b/pool/shard001/JavaScript/0010844_recording-streams.js new file mode 100644 index 0000000000000000000000000000000000000000..9837318dbcc025c39327243d51ff74fed884de9e --- /dev/null +++ b/pool/shard001/JavaScript/0010844_recording-streams.js @@ -0,0 +1,90 @@ +'use strict'; + +self.recordingReadableStream = (extras = {}, strategy) => { + let controllerToCopyOver; + const stream = new ReadableStream({ + start(controller) { + controllerToCopyOver = controller; + + if (extras.start) { + return extras.start(controller); + } + + return undefined; + }, + pull(controller) { + stream.events.push('pull'); + + if (extras.pull) { + return extras.pull(controller); + } + + return undefined; + }, + cancel(reason) { + stream.events.push('cancel', reason); + stream.eventsWithoutPulls.push('cancel', reason); + + if (extras.cancel) { + return extras.cancel(reason); + } + + return undefined; + } + }, strategy); + + stream.controller = controllerToCopyOver; + stream.events = []; + stream.eventsWithoutPulls = []; + + return stream; +}; + +self.recordingWritableStream = (extras = {}, strategy) => { + let controllerToCopyOver; + const stream = new WritableStream({ + start(controller) { + controllerToCopyOver = controller; + + if (extras.start) { + return extras.start(controller); + } + + return undefined; + }, + write(chunk) { + stream.events.push('write', chunk); + + if (extras.write) { + return extras.write(chunk); + } + + return undefined; + }, + close(...args) { + assert_array_equals(args, [controllerToCopyOver], 'close must always be called with the controller'); + + stream.events.push('close'); + + if (extras.close) { + return extras.close(); + } + + return undefined; + }, + abort(e) { + stream.events.push('abort', e); + + if (extras.abort) { + return extras.abort(e); + } + + return undefined; + } + }, strategy); + + stream.controller = controllerToCopyOver; + stream.events = []; + + return stream; +}; diff --git a/pool/shard001/JavaScript/0010845_Gruntfile.js b/pool/shard001/JavaScript/0010845_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..f40cd1779be7016918839a81c4bfe595d76bc40f --- /dev/null +++ b/pool/shard001/JavaScript/0010845_Gruntfile.js @@ -0,0 +1,40 @@ +/*jshint node:true */ +module.exports = function(grunt) { + 'use strict'; + + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + + jshint: { + options: grunt.file.readJSON('.jshintrc'), + src: [ + 'Gruntfile.js', + 'src/compiler.js', + 'src/razor.js', + 'test/TestAftershave.js' + ] + }, + + simplemocha: { + options: { + globals: ['assert'], + timeout: 3000, + ignoreLeaks: false, + ui: 'bdd', + reporter: 'Nyan' + }, + + all: { + src: ['test/Test*.js'] + } + } + }); + + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-simple-mocha'); + + var testTasks = ['jshint', 'simplemocha']; + grunt.registerTask('test', testTasks); + + grunt.registerTask('default', ['test']); +}; diff --git a/pool/shard001/JavaScript/0010848_asset-viewer.js b/pool/shard001/JavaScript/0010848_asset-viewer.js new file mode 100644 index 0000000000000000000000000000000000000000..ecdef01c24c29d45da4f92b7ea3182237f478a90 --- /dev/null +++ b/pool/shard001/JavaScript/0010848_asset-viewer.js @@ -0,0 +1,104 @@ +/******************************************************************************* + + uBlock Origin - a browser extension to block requests. + Copyright (C) 2014-present Raymond Hill + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see {http://www.gnu.org/licenses/}. + + Home: https://github.com/gorhill/uBlock +*/ + +/* global CodeMirror, uBlockDashboard */ + +'use strict'; + +/******************************************************************************/ + +(async ( ) => { + const subscribeURL = new URL(document.location); + const subscribeParams = subscribeURL.searchParams; + const assetKey = subscribeParams.get('url'); + if ( assetKey === null ) { return; } + + const subscribeElem = subscribeParams.get('subscribe') !== null + ? document.getElementById('subscribe') + : null; + if ( subscribeElem !== null && subscribeURL.hash !== '#subscribed' ) { + const title = subscribeParams.get('title'); + const promptElem = document.getElementById('subscribePrompt'); + promptElem.children[0].textContent = title; + const a = promptElem.children[1]; + a.textContent = assetKey; + a.setAttribute('href', assetKey); + subscribeElem.classList.remove('hide'); + } + + const cmEditor = new CodeMirror(document.getElementById('content'), { + autofocus: true, + foldGutter: true, + gutters: [ 'CodeMirror-linenumbers', 'CodeMirror-foldgutter' ], + lineNumbers: true, + lineWrapping: true, + matchBrackets: true, + maxScanLines: 1, + readOnly: true, + styleActiveLine: { + nonEmpty: true, + }, + }); + + uBlockDashboard.patchCodeMirrorEditor(cmEditor); + + const hints = await vAPI.messaging.send('dashboard', { + what: 'getAutoCompleteDetails' + }); + if ( hints instanceof Object ) { + const mode = cmEditor.getMode(); + if ( mode.setHints instanceof Function ) { + mode.setHints(hints); + } + } + + const details = await vAPI.messaging.send('default', { + what : 'getAssetContent', + url: assetKey, + }); + cmEditor.setValue(details && details.content || ''); + + if ( subscribeElem !== null ) { + document.getElementById('subscribeButton').addEventListener( + 'click', + ( ) => { + subscribeElem.classList.add('hide'); + vAPI.messaging.send('scriptlets', { + what: 'applyFilterListSelection', + toImport: assetKey, + }).then(( ) => { + vAPI.messaging.send('scriptlets', { + what: 'reloadAllFilters' + }); + }); + }, + { once: true } + ); + } + + if ( details.sourceURL ) { + const a = document.querySelector('.cm-search-widget .sourceURL'); + a.setAttribute('href', details.sourceURL); + a.setAttribute('title', details.sourceURL); + } + + document.body.classList.remove('loading'); +})(); diff --git a/pool/shard001/JavaScript/0010849_login.js b/pool/shard001/JavaScript/0010849_login.js new file mode 100644 index 0000000000000000000000000000000000000000..fba4d5b5aa25deabef8ca24e4e2e3e56779fc359 --- /dev/null +++ b/pool/shard001/JavaScript/0010849_login.js @@ -0,0 +1,43 @@ +'use strict'; + +const user = require('../models/user'); +const bcrypt = require('bcryptjs'); + +exports.loginUser = (email, password) => + + new Promise((resolve,reject) => { + + user.find({email: email}) + + .then(users => { + + if (users.length == 0) { + + reject({ status: 404, message: 'User Not Found !' }); + + } else { + + return users[0]; + + } + }) + + .then(user => { + + const hashed_password = user.hashed_password; + + if (bcrypt.compareSync(password, hashed_password)) { + + resolve({ status: 200, message: email }); + + } else { + + reject({ status: 401, message: 'Invalid Credentials !' }); + } + }) + + .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); + + }); + + diff --git a/pool/shard001/JavaScript/0010851_AndGate.js b/pool/shard001/JavaScript/0010851_AndGate.js new file mode 100644 index 0000000000000000000000000000000000000000..031950a34f511c25afa3a575f47f4a85a903acf5 --- /dev/null +++ b/pool/shard001/JavaScript/0010851_AndGate.js @@ -0,0 +1,157 @@ +/* + + Copyright (c) 2017 Jirtdan Team and other collaborators + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + */ + +'use strict'; +/* jshint esversion: 6*/ +import { + BaseControl, + DEFAULT_STROKE_COLOR, + DEFAULT_STROKE_WIDTH, + DEFAULT_FILL_COLOR, + DEBUG, +} from '../BaseControl.js'; +import {ConnectionPin} from '../ConnectionPin.js'; + +const LOGTAG = 'AndGate'; + +/** + * Control for AND gate. + * + * Truth table: + * |In1|In2|Out| + * |0 |0 |0 | + * |0 |1 |0 | + * |1 |0 |0 | + * |1 |1 |1 | + */ +export class AndGate extends BaseControl { + /** + * Constructor for AndGate + * @param paper raphael paper object. + */ + constructor(paper) { + super(paper); + this.inputPin1Value = 0; + this.inputPin2Value = 0; + } + + /** + * Draw the component surface. + */ + draw() { + super.draw(); + + this.componentBodyShape = this.paper.path('m 58.611201,1.1397665 c 9.55485,0.18892 20.16562,5.82395 ' + + '24.0335,17.2506995 4.9232,15.87108 -9.03622,29.35593 -20.8054,30.21669 -3.85823,0.45079 ' + + '-7.74776,0.13486 -11.62055,0.22897 -6.74559,0 -13.49119,0 -20.23678,0 0,-15.89882 0,-31.79764 ' + + '0,-47.6964595 9.54305,6e-5 19.08632,-1.4e-4 28.62923,10e-5 z'); + this.componentBodyShape.attr('stroke', DEFAULT_STROKE_COLOR); + this.componentBodyShape.attr('stroke-width', DEFAULT_STROKE_WIDTH); + this.componentBodyShape.attr('stroke-linejoin', 'round'); + this.componentBodyShape.attr('stroke-miterlimit', 4); + + this.componentBodyFill = this.paper.path('m 31.061892,2.5815355 c 9.19315,5e-5 18.38665,-2.3e-4 ' + + '27.579611,0 9.22798,0.18246 19.421691,5.6541 23.087521,16.4532025 2.30565,7.451782 ' + + '0.22309,14.191732 -3.92241,19.402882 -4.14843,5.21484 -10.395901,8.69029 ' + + '-15.982541,9.09888 a 1.0330703,1.2574718 0 0 0 -0.0365,0.004 c -3.7468,0.43777 ' + + '-7.609851,0.12826 -11.542571,0.22383 l 0.0204,-4.7e-4 -19.2035,0 0,-45.1816745 z'); + this.componentBodyFill.attr('stroke-width', 1); + this.componentBodyFill.attr('stroke', DEFAULT_FILL_COLOR); + this.componentBodyFill.attr('fill', DEFAULT_FILL_COLOR); + + this.componentBodyGradient = this.paper.path('m 31.082459,2.252571 0,24.159714 c 3.12863,-2.275521 ' + + '6.62158,-4.297522 10.765451,-5.053942 3.297449,-0.41071 6.757419,0.66406 8.796369,2.799571 ' + + '2.05993,1.709771 3.767,3.940621 6.649721,4.805901 2.48868,0.43561 5.09369,0.24618 7.60804,0.0319 ' + + '6.20929,-0.84447 12.166581,-2.59522 17.790441,-4.852561 -0.0646,-1.759691 -0.3663,-3.575801 ' + + '-0.94218,-5.437041 C 78.084471,7.907001 67.88986,2.435011 58.66187,2.252551 c -9.192961,-2.2e-4 ' + + '-18.386261,5e-5 -27.579411,0 z'); + this.componentBodyGradient.attr('stroke-width', 0); + this.componentBodyGradient.attr('fill', '90-#0066ff-#fff'); + + this.componentInputWire1 = this.paper.path('m 10.000001,11.233446 19.55419,0'); + this.componentInputWire1.attr('stroke', DEFAULT_STROKE_COLOR); + this.componentInputWire1.attr('stroke-width', DEFAULT_STROKE_WIDTH); + + this.componentInputWire2 = this.paper.path('m 10.000001,38.765746 19.55419,0'); + this.componentInputWire2.attr('stroke', DEFAULT_STROKE_COLOR); + this.componentInputWire2.attr('stroke-width', DEFAULT_STROKE_WIDTH); + + this.componentOutputWire = this.paper.path('m 83.523741,24.999596 19.554189,0'); + this.componentOutputWire.attr('stroke', DEFAULT_STROKE_COLOR); + this.componentOutputWire.attr('stroke-width', DEFAULT_STROKE_WIDTH); + + this.inputPin1 = new ConnectionPin(this, 5, 11, 'in'); + this.inputPin2 = new ConnectionPin(this, 5, 39, 'in'); + this.outputPin = new ConnectionPin(this, 109, 25, 'out'); + } + + /** + * Initialize the component. + */ + initControl() { + super.initControl(); + const _this = this; + + this.inputPin1.addStateChangeListener( + function(newState) { + _this.inputPin1Value = newState; + _this.outputPin.notifyStateChange(_this.getValue()); + }); + + this.inputPin2.addStateChangeListener( + function(newState) { + _this.inputPin2Value = newState; + _this.outputPin.notifyStateChange(_this.getValue()); + }); + + this.setShapes([ + this.componentBodyShape, + this.componentBodyFill, + this.componentBodyGradient, + this.componentInputWire1, + this.componentInputWire2, + this.componentOutputWire]); + + this.addInputPins(this.inputPin1, this.inputPin2); + this.addOutputPins(this.outputPin); + } + + /** + * An event fired when element is selected. + * @param event + */ + onSelect(event) { + super.onSelect(event); + this.glow = this.componentBodyShape.glow(); + this.glow.toBack(); + } + + /** + * Get the value. + * @returns {*|number} + */ + getValue() { + return this.inputPin1Value && this.inputPin2Value; + } +} diff --git a/pool/shard001/JavaScript/0010853_MeBank.js b/pool/shard001/JavaScript/0010853_MeBank.js new file mode 100644 index 0000000000000000000000000000000000000000..672e31d0a7c4b7d16641526b76e1512d8548524e --- /dev/null +++ b/pool/shard001/JavaScript/0010853_MeBank.js @@ -0,0 +1,135 @@ +var _ = require('underscore'); +var FormView = require('./common/__FormView'); +var $ = require('jquery'); +var Backbone = require('backbone'); +var config = require('../conf'); + +Backbone.$ = $; + +//** 模型 +var Bank = Backbone.Model.extend({ + idAttribute: '_id', + urlRoot: config.api.host + '/private/finance/banks', + validation: { + 'bankName': { + required: true, + msg: '请输入开户银行名称' + }, + 'accountNo': { + required: true, + msg: '请输入银行卡号', + }, + 'accountName': { + required: true, + msg: '请输入账户姓名', + }, + 'cardId': { + required: true, + msg: '请输入身份证号码', + }, + } +}); + +//** 主页面 +exports = module.exports = FormView.extend({ + + el: '#bankForm', + template: _.template($('#tpl-me-bank').html()), + + modelFilled: false, + + initialize: function(options) { + this.router = options.router; + this.model = new Bank({_id: 'me'}); + FormView.prototype.initialize.apply(this, options); + }, + + events: { + 'keyup input[type=text]': 'inputText', + 'submit form': 'submit', + 'click .back': 'cancel', + }, + + load: function(){ + if(this.model.isNew()){ + this.modelFilled = true; + return; + } + this.model.fetch({ + xhrFields: { + withCredentials: true + }, + }); + }, + + inputText: function(evt){ + var that = this; + //clear error + this.$(evt.currentTarget).parent().removeClass('has-error'); + this.$(evt.currentTarget).parent().find('span.help-block').empty(); + var arr = this.$(evt.currentTarget).serializeArray(); + _.each(arr,function(obj){ + var error = that.model.preValidate(obj.name,obj.value); + if(error){ + //set error + this.$(evt.currentTarget).parent().addClass('has-error'); + this.$(evt.currentTarget).parent().find('span.help-block').text(error); + } + }) + return false; + }, + + submit: function() { + var that = this; + if(window.confirm('您确信要修改银行卡信息吗?')){ + //clear errors + this.$('.form-group').removeClass('has-error'); + this.$('.form-group').find('span.help-block').empty(); + var arr = this.$('form').serializeArray(); + var errors = []; + _.each(arr,function(obj){ + var error = that.model.preValidate(obj.name,obj.value); + if(error){ + errors.push(error); + that.$('[name="' + obj.name + '"]').parent().addClass('has-error'); + that.$('[name="' + obj.name + '"]').parent().find('span.help-block').text(error); + } + }); + if(!_.isEmpty(errors)) return false; + //validate finished. + + var object = this.$('form').serializeJSON(); + this.model.set(object); + // console.log(this.model.attributes); + this.model.save(null, { + xhrFields: { + withCredentials: true + }, + }); + } + return false; + }, + + + cancel: function(){ + this.router.navigate('me/index',{trigger: true, replace: true}); + return false; + }, + + //fetch event: done + done: function(response){ + if(!this.modelFilled){ + //first fetch: get model + this.modelFilled = true; + this.render(); + }else{ + //second fetch: submit + this.router.navigate('me/index',{trigger: true, replace: true}); + } + }, + + render: function(){ + this.$el.html(this.template({model: this.model.toJSON()})); + return this; + }, +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010854_gulpfile.js b/pool/shard001/JavaScript/0010854_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..334a97259e30ac0066fe37c82846dd7c500ab650 --- /dev/null +++ b/pool/shard001/JavaScript/0010854_gulpfile.js @@ -0,0 +1,253 @@ +/** + * gulpfile.js + * + * Available tasks: + * `gulp` + * `gulp watch` + * + * Modules: + * gulp : The streaming build system. + * gulp-util : Utility functions for gulp plugins. + * fs : File System. + * del : Delete files and folders. + * path : Node.JS path module. + * merge-stream : Create a stream that emits events from + * multiple other streams. + * gulp-gulp-clip-empty-files : Clip empty files from stream. + * gulp-changed : Only pass through changed files. + * gulp-imagemin : Minify PNG, JPEG, GIF and SVG images. + * gulp-svg-sprite : Reads in a bunch of SVG files, optimizes + * them and creates SVG sprites and CSS + * resources in various flavours. + * gulp-jshint : JSHint plugin for Gulp. + * gulp-uglify : Minify files with UglifyJS. + * gulp-sass : Gulp plugin for sass. + * gulp-sourcemaps : Source map support for Gulp.js. + * gulp-autoprefixer : Prefix CSS. + * gulp-combine-mq : Gulp plugin for node-combine-mq. + * gulp-cssnano : Minify CSS with cssnano. + */ +var gulp = require('gulp'); +var $ = { + util : require('gulp-util'), + fs : require('fs'), + del : require('del'), + path : require('path'), + mergeStream : require('merge-stream'), + clipEmptyFiles: require('gulp-clip-empty-files'), + changed : require('gulp-changed'), + imageMin : require('gulp-imagemin'), + svgSprite : require('gulp-svg-sprite'), + jsHint : require('gulp-jshint'), + uglify : require('gulp-uglify'), + sass : require('gulp-sass'), + sourcemaps : require('gulp-sourcemaps'), + autoPrefixer : require('gulp-autoprefixer'), + combineMq : require('gulp-combine-mq'), + cssNano : require('gulp-cssnano') +}; + +/** + * Config +*/ +var root = { + src: './src', + dest: './build' +}; + +var tasks = { + clean: { + }, + vendor: { + src: 'vendor', + dest: 'vendor' + }, + + images: { + src: 'img', + dest: 'img', + exclude: 'img/vectors', + extensions: [ + 'jpg', + 'png', + 'svg', + 'gif' + ], + plugins: { + imageMin: { + optimizationLevel: 3, + progressive: true, + interlaced: true + } + } + }, + + svgSprite: { + src: 'img/vectors', + dest: 'img/vectors', + extensions: [ + 'svg' + ], + plugins: { + svgSprite: { + shape: { + dest: 'svg' + }, + mode: { + view: false, + symbol: { + sprite: 'sprite-symbol.svg' + } + } + } + } + }, + + js: { + src: 'js', + dest: 'js', + extensions: [ + 'js' + ] + }, + + css: { + src: 'scss', + dest: 'css', + extensions: [ + 'scss' + ], + plugins: { + autoPrefixer: [ + 'last 2 versions' + ], + cssNano: { + zindex: false, + reduceIdents: false, + mergeIdents: false, + discardUnused: false + } + } + } +}; + +/** + * Returns list of sub folders within a directory + * @param {string} str - path to directory + * @return {array} array +*/ +function getFolders(dir) { + return $.fs.readdirSync(dir) + .filter(function(file) { + return $.fs.statSync($.path.join(dir, file)).isDirectory(); + }); +} + +/** + * Deletes dist directory +*/ +function clean() { + return $.del([ + root.dest + ]); +} + +/** + * Moves vendor files to the dist directory +*/ +function vendor() { + return gulp.src(root.src + '/' + tasks.vendor.src + '/**/*') + .pipe($.changed(root.dest + '/' + tasks.vendor.dest)) + .pipe(gulp.dest(root.dest + '/' + tasks.vendor.dest + '/')); +} + +/** + * Minifies images and moves processed files to the dist directory. +*/ +function images() { + return gulp.src([ + root.src + '/' + tasks.images.src + '/**/*', + '!' + root.src + '/' + tasks.images.exclude + '/**/*' + ]) + .pipe($.changed(root.dest + '/' + tasks.images.dest)) + .pipe($.util.env.production ? $.imageMin(tasks.images.plugins.imageMin) : $.util.noop()) + .pipe(gulp.dest(root.dest + '/' + tasks.images.dest + '/')); +} + +/** + * Merges SVGs into sprite and moves processed files to the dist directory +*/ +function svgSprite() { + + var folders = getFolders(root.src + '/' + tasks.svgSprite.src); + + var streams = folders.map(function(folder) { + return gulp.src($.path.join(root.src + '/' + tasks.svgSprite.src + '/', folder, '/**/*.' + tasks.svgSprite.extensions)) + .pipe($.svgSprite(tasks.svgSprite.plugins.svgSprite)) + .pipe(gulp.dest(root.dest + '/' + tasks.svgSprite.dest + '/' + folder + '/')); + }); + + return $.mergeStream(streams); +} + +/** + * JSHint and minify javascript files and moves processed files to the dist + directory +*/ +function js() { + return gulp.src(root.src + '/' + tasks.js.src + '/**/*.' + tasks.js.extensions) + .pipe($.jsHint()) + .pipe($.jsHint.reporter('default')) + .pipe($.util.env.production ? $.uglify() : $.util.noop()) + .pipe(gulp.dest(root.dest + '/' + tasks.js.dest + '/')); +} + +/** + * Clips empty files, Sourcemaps (if not production), AutoPrefixes css, combines + * media queries, minifes css and moves processed files to the dist directory +*/ +function css() { + return gulp.src(root.src + '/' + tasks.css.src + '/**/*.' + tasks.css.extensions) + .pipe($.clipEmptyFiles()) + .pipe(!$.util.env.production ? $.sourcemaps.init() : $.util.noop()) + .pipe(!$.util.env.production ? $.sass.sync().on('error', $.sass.logError) : $.util.noop()) + .pipe($.util.env.production ? $.sass.sync() : $.util.noop()) + .pipe($.autoPrefixer(tasks.css.plugins.autoPrefixer)) + .pipe(!$.util.env.production ? $.sourcemaps.write() : $.util.noop()) + .pipe($.util.env.production ? $.combineMq() : $.util.noop()) + .pipe($.util.env.production ? $.cssNano(tasks.css.plugins.cssNano) : $.util.noop()) + .pipe(gulp.dest(root.dest + '/' + tasks.css.dest + '/')); +} + +/** + * Watches files for changes +*/ +function watch() { + gulp.watch(root.src + '/' + tasks.vendor.src + '/**/*', vendor); + gulp.watch(root.src + '/' + tasks.images.src + '/**/*', images); + gulp.watch(root.src + '/' + tasks.svgSprite.src + '/**/*', svgSprite); + gulp.watch(root.src + '/' + tasks.js.src + '/**/*', js); + gulp.watch(root.src + '/' + tasks.css.src + '/**/*', css); +} + +/** + * Combines clean, vendor, images, svgSprite, js and css tasks. +*/ +var build = gulp.series( + clean, + gulp.parallel( + vendor, + gulp.series( + images, + svgSprite + ), + js, + css + ) +); + +/** + * Gulp tasks +*/ +exports.default = build; +exports.watch = watch; diff --git a/pool/shard001/JavaScript/0010865_imageSize.js b/pool/shard001/JavaScript/0010865_imageSize.js new file mode 100644 index 0000000000000000000000000000000000000000..a75ef452f02b2f1cfd60977f956af6732b120664 --- /dev/null +++ b/pool/shard001/JavaScript/0010865_imageSize.js @@ -0,0 +1,117 @@ + +'use strict'; +var fs = require('fs'); +var pathFn = require('path'); +var url = require('url'); +var http = require('follow-redirects').http; +var https = require('follow-redirects').https; +var imgSize = require('image-size'); +var lg = require('./log.js'); +var externalPathReg = /^(?:\/\/|[a-zA-Z0-9]*?\:\/\/)/; +var config; + + +module.exports.getSizeInfo = function(inImgsrc , data , callback){ + + var imgWidth; + var imgHeight; + var imgDevPath = ""; + var imgsrc = inImgsrc; + + if(!externalPathReg.test(imgsrc)){ + // Local image + if(imgsrc.indexOf(data.path) != -1){ + // console.log("画像パス判定(1): "+ "_posts/**/記事.mdと同階層化に画像がある"); + imgDevPath = pathFn.join(data.asset_dir , pathFn.basename(imgsrc) ); + }else{ + // console.log("画像パス判定(2): "+ "source/**/に画像がある"); + // Disable post_asset_folder option (see: https://hexo.io/docs/asset-folders.html) + if(!config.post_asset_folder){ + imgDevPath = pathFn.join(process.env.PWD || process.cwd() , "source/" , imgsrc); + }else{ + // Enable post_asset_folder option (see: https://hexo.io/docs/asset-folders.html) + imgDevPath = pathFn.join(process.env.PWD || process.cwd() , "source/" , pathFn.join(pathFn.dirname(data.source) , pathFn.basename(data.source).replace( pathFn.extname(data.source) , "")) , imgsrc); + imgsrc = pathFn.join( "/" , data.path , imgsrc ); + } + } + // console.log(" ファイルパス ->"+ imgDevPath ); + // console.log(" 入力値: " + imgsrc); + // console.log(" 入力値data.path: " + data.path); + // console.log(" 入力値data.asset_dir: " + data.asset_dir); + }else{ + // External image + imgDevPath = imgsrc; + if(/^\/\//.test(imgDevPath)){ + imgDevPath = 'http:' + imgDevPath; + } + } + + + if(!externalPathReg.test(imgsrc)){ + // Local image + if(fs.existsSync(imgDevPath)){ + var ims = imgSize( imgDevPath ); + imgWidth = ims.width; + imgHeight = ims.height; + callback( {"w":imgWidth, "h":imgHeight , "src": imgsrc} ); + }else{ + lg.log("error", "no such file or directory. img path: "+imgDevPath , data.source); + callback( null ); + } + }else{ + // external image + var options = url.parse(imgDevPath); + if(imgDevPath.match(/^https\:/)){ + var req_https = https.get(options, function (response) { + var chunks = []; + response.on('data', function (chunk) { + chunks.push(chunk); + }).on('end', function() { + getExternalImageSize( chunks, callback , lg , imgDevPath , imgsrc , data ); + // chunks = null; + }); + }); + + req_https.on('error', function(e) { + lg.log("error", e + "\nThis plugin checks whether the image URL exists. \nimg path: "+imgDevPath , data.source); + callback( null ); + }); + }else if(imgDevPath.match(/^http\:/)){ + var req_http = http.get(options, function (response) { + var chunks = []; + response.on('data', function (chunk) { + chunks.push(chunk); + }).on('end', function() { + getExternalImageSize( chunks, callback , lg , imgDevPath , imgsrc , data ); + // chunks = null; + }); + }); + + req_http.on('error', function(e) { + lg.log("error", e + "\nThis plugin checks whether the image URL exists. \nimg path: "+imgDevPath , data.source); + callback( null ); + }); + }else{ + lg.log("error", "This plugin can not acquire the width and height of such url images. Please change the URL to HTTP or HTTPS, or add height and width. \nimg path: "+imgDevPath , data.source); + callback( null ); + } + } +}; + +module.exports.setConfig = function(inConfig){ + config = inConfig; + lg.setConfig(config); +}; + +function getExternalImageSize( chunks, callback , inLg , imgDevPath , imgsrc , post ){ + var buffer = Buffer.concat(chunks); + var ims; + try{ + ims = imgSize(buffer); + callback( {"w":ims.width, "h":ims.height , "src":imgsrc } ); + }catch(e){ + inLg.log("error", e + "\n This plugin gets width and height by accessing the external image. However, the plugin could not access the external image. Please confirm that the image URL is correct. Or, add the width and height to the post. : "+imgDevPath , post.source); + callback( null ); + } + // buffer = null; +} diff --git a/pool/shard001/JavaScript/0010870_client_test_integration.js b/pool/shard001/JavaScript/0010870_client_test_integration.js new file mode 100644 index 0000000000000000000000000000000000000000..c15cba09cfe1a25c4b3183971677fdeeb82d63c0 --- /dev/null +++ b/pool/shard001/JavaScript/0010870_client_test_integration.js @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +'use strict'; + +var Registry = require('azure-iothub').Registry; +var Http = require('../lib/http.js'); +var clientTests = require('azure-iot-device/test/_client_common_testrun.js'); + +describe('Over real HTTPS', function () { + this.timeout(60000); + var registry = Registry.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING); + clientTests.sendEventTests(Http, registry); + clientTests.sendEventBatchTests(Http, registry); +}); diff --git a/pool/shard001/JavaScript/0010871_Email.js b/pool/shard001/JavaScript/0010871_Email.js new file mode 100644 index 0000000000000000000000000000000000000000..8eec3eeb2186ada263d5efce395a77c221697c96 --- /dev/null +++ b/pool/shard001/JavaScript/0010871_Email.js @@ -0,0 +1,44 @@ +var nunjucks = require('nunjucks'); +/** + * @module + */ + + +/** + * Email provides an abstraction for sending emails. + * @alias Email + * + * @constructor + * + */ +module.exports = function Email (template, emailFolder) { + + return { + templateExt: 'html', + templateEngine: { + compile: function(html, paths) { + return function(locals) { + + return nunjucks.configure( + emailFolder, { + autoescape: true + }). + renderString(html, locals); + }; + } + }, + + templateName: template, + templatePath: emailFolder, + mandrill: { + track_opens: true, + track_clicks: true, + preserve_recipients: false, + inline_css: true + } + + })) } + + +}; + diff --git a/pool/shard001/JavaScript/0010874_households.js b/pool/shard001/JavaScript/0010874_households.js new file mode 100644 index 0000000000000000000000000000000000000000..18ea8f048085daaf9c3fb3264c922bc0a0861ce3 --- /dev/null +++ b/pool/shard001/JavaScript/0010874_households.js @@ -0,0 +1,59 @@ +//= require_self +// +$(function(){ + + function cleanJsonPerson(jsonPerson) { + jsonPerson.first_name = ( jsonPerson.first_name == null ? "" : jsonPerson.first_name ) + jsonPerson.last_name = ( jsonPerson.last_name == null ? "" : jsonPerson.last_name ) + jsonPerson.email = ( jsonPerson.email == null ? "" : jsonPerson.email ) + jsonPerson.company_name = ( jsonPerson.company_name == null ? "" : jsonPerson.company_name ) + return jsonPerson + } + $(document).on('keyup.autocomplete', '.fields.individual-fields .individual-name-input', function(){ + var autocompleteField = this; + $(this).autocomplete({ + html: true, + minLength: 3, + focus: function(event, person) { + event.preventDefault() + }, + source: function(request, response) { + $.getJSON("/people?utf8=%E2%9C%93&type=Individual&commit=Search", { search: request.term }, function(people) { + responsePeople = new Array(); + + $.each(people, function (i, person) { + person = cleanJsonPerson(person) + responsePeople[i] = "
    "+ person.first_name +" "+ person.last_name +"
    " + responsePeople[i] += "
    "+ person.email +"
    " + responsePeople[i] += "
    " + responsePeople[i] += "
    "+ person.company_name +"
    " + responsePeople[i] += "
    "+person.id+"
    " + }); + response(responsePeople) + }); + }, + + select: function(event, item) { + event.preventDefault() + var personId = $(item.item.value).filter("#search-result-id").html() + var personFirstName = $("#search-result-first-name", item.item.value).html() + var personLastName = $("#search-result-last-name", item.item.value).html() + + var personLabel = personFirstName + " " + personLastName + $(this).val(personLabel) + $(this).siblings('.individual-id').val(personId) + }, + open: function() { + $(this).removeClass("ui-corner-all").addClass("ui-corner-top") + }, + close: function() { + $(this).removeClass("ui-corner-top").addClass("ui-corner-all") + } + + }); + + // Ensure the autocomplete drop-down shows up in the modal and on this row + $(this).autocomplete("widget").insertAfter($(this)) + }); +}); + diff --git a/pool/shard001/JavaScript/0010887_Eradication.js b/pool/shard001/JavaScript/0010887_Eradication.js new file mode 100644 index 0000000000000000000000000000000000000000..92824f1a82c3b2cb615700a85aba37b7bc9cec36 --- /dev/null +++ b/pool/shard001/JavaScript/0010887_Eradication.js @@ -0,0 +1,161 @@ +import React from 'react'; + +import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; +import Enemies from 'parser/shared/modules/Enemies'; +import Events from 'parser/core/Events'; +import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; + +import SPELLS from 'common/SPELLS'; +import { SpellLink } from 'interface'; +import { formatPercentage, formatThousands, formatNumber } from 'common/format'; +import { TooltipElement } from 'interface'; + +import Statistic from 'parser/ui/Statistic'; +import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; +import UptimeIcon from 'interface/icons/Uptime'; +import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; + +import { t } from '@lingui/macro'; + +const MAX_TRAVEL_TIME = 3000; // Chaos Bolt being the slowest, takes around 2 seconds to land from max range, added a second to account for maybe target movement? +const ERADICATION_DAMAGE_BONUS = 0.1; +const debug = false; + +/* + Eradication - Chaos Bolt increases the damage you deal to the target by 10% for 7 sec + */ +class Eradication extends Analyzer { + get uptime() { + return this.enemies.getBuffUptime(SPELLS.ERADICATION_DEBUFF.id) / this.owner.fightDuration; + } + + get CBpercentage() { + return (this._buffedCB / this._totalCB) || 0; + } + + get suggestionThresholds() { + return { + actual: this.uptime, + isLessThan: { + minor: 0.7, + average: 0.65, + major: 0.55, + }, + style: 'percentage', + }; + } + + get dps() { + return this.bonusDmg / this.owner.fightDuration * 1000; + } + + static dependencies = { + enemies: Enemies, + }; + _buffedCB = 0; + _totalCB = 0; + bonusDmg = 0; + // queues spells CAST with target having Eradication (except DoTs) + queue = [ + /* + { + timestamp + spellId + targetID + targetInstance + } + */ + ]; + + constructor(...args) { + super(...args); + this.active = this.selectedCombatant.hasTalent(SPELLS.ERADICATION_TALENT.id); + this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.INCINERATE, SPELLS.CHAOS_BOLT]), this.onTravelSpellCast); + this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage); + } + + onTravelSpellCast(event) { + const spellId = event.ability.guid; + const enemy = this.enemies.getEntity(event); + if (!enemy || !enemy.hasBuff(SPELLS.ERADICATION_DEBUFF.id, event.timestamp)) { + return; + } + this.queue.push({ + timestamp: event.timestamp, + spellId: spellId, + targetID: event.targetID, + targetInstance: event.targetInstance, + }); + debug && console.log('Pushed a buffed cast into queue', JSON.parse(JSON.stringify(this.queue))); + } + + onDamage(event) { + const spellId = event.ability.guid; + if (spellId === SPELLS.INCINERATE.id || spellId === SPELLS.CHAOS_BOLT.id) { + this._handleTravelSpellDamage(event); + return; + } + + const enemy = this.enemies.getEntity(event); + if (!enemy || !enemy.hasBuff(SPELLS.ERADICATION_DEBUFF.id, event.timestamp)) { + return; + } + + this.bonusDmg += calculateEffectiveDamage(event, ERADICATION_DAMAGE_BONUS); + } + + _handleTravelSpellDamage(event) { + if (event.ability.guid === SPELLS.CHAOS_BOLT.id) { + this._totalCB += 1; + } + // first filter out old casts (could happen if player would cast something on a target and BEFORE it hits, it would die - then it couldn't be paired) + this.queue = this.queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME)); + // try pairing damage event with casts in this.queue + const castIndex = this.queue.findIndex(queuedCast => queuedCast.targetID === event.targetID + && queuedCast.targetInstance === event.targetInstance + && queuedCast.spellId === event.ability.guid); + if (castIndex === -1) { + debug && console.log(`(${this.owner.formatTimestamp(event.timestamp, 3)}) Encountered damage event with no buffed cast associated, queue:`, JSON.parse(JSON.stringify(this.queue)), 'event', event); + return; + } + + debug && console.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this.queue[castIndex]))); + if (event.ability.guid === SPELLS.CHAOS_BOLT.id) { + this._buffedCB += 1; + } + this.bonusDmg += calculateEffectiveDamage(event, ERADICATION_DAMAGE_BONUS); + this.queue.splice(castIndex, 1); + } + + suggestions(when) { + when(this.suggestionThresholds) + .addSuggestion((suggest, actual, recommended) => suggest(<>Your uptime on the debuff could be improved. You should try to spread out your casts more for higher uptime.
    NOTE: Uptime may vary based on the encounter.) + .icon(SPELLS.ERADICATION_TALENT.icon) + .actual(t({ + id: "warlock.destruction.suggestions.eradication.uptime", + message: `${formatPercentage(actual)}% Eradication uptime` + })) + .recommended(`>${formatPercentage(recommended)}% is recommended`)); + } + + statistic() { + return ( + + + {formatNumber(this.dps)} DPS {formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDmg))} % of total
    + {formatPercentage(this.uptime, 0)} % uptime
    + {formatPercentage(this.CBpercentage, 0)} % + + buffed Chaos Bolts * + +
    +
    + ); + } +} + +export default Eradication; diff --git a/pool/shard001/JavaScript/0010891_gulpfile.js b/pool/shard001/JavaScript/0010891_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..c54a01a10fd40cb0bdef398ab6b138ba552df806 --- /dev/null +++ b/pool/shard001/JavaScript/0010891_gulpfile.js @@ -0,0 +1,66 @@ +var gulp = require('gulp') +var nodemon = require('gulp-nodemon') +var sourcemaps = require('gulp-sourcemaps') +var concat = require('gulp-concat') +var uglify = require('gulp-uglify') +var cssmin = require('gulp-cssmin') +var del = require('del') +var path = require('path') + +var client = { + js: { + src: 'client/js', + dest: 'public/js' + }, + css: { + src: 'client/css', + dest: 'public/css' + } +} + +gulp.task('default', ['jsmin', 'cssmin', 'start']) + +gulp.task('start', function () { + nodemon({ + script: 'bin/www', + ext: 'js css ejs', + ignore: ['public', 'logs'], + tasks: function (files) { + var tasks = [] + files.forEach(function (file) { + if (path.relative(client.js.src, file).substr(0, 2) !== '..' + && !~tasks.indexOf('jsmin')) { + tasks.push('jsmin') + } + if (path.relative(client.css.src, file).substr(0, 2) !== '..' + && !~tasks.indexOf('cssmin')) { + tasks.push('cssmin') + } + }) + return tasks + } + }) +}) + +gulp.task('cleanjs', function () { + return del([client.js.dest]) +}) + +gulp.task('cleancss', function () { + return del([client.css.dest]) +}) + +gulp.task('jsmin', ['cleanjs'], function () { + return gulp.src(client.js.src + '/**/*.js') + .pipe(sourcemaps.init()) + .pipe(concat('graph.js')) + .pipe(uglify()) + .pipe(gulp.dest(client.js.dest)) +}) + +gulp.task('cssmin', ['cleancss'], function () { + return gulp.src(client.css.src + '/**/*.css') + .pipe(concat('style.css')) + .pipe(cssmin()) + .pipe(gulp.dest(client.css.dest)) +}) diff --git a/pool/shard001/JavaScript/0010892_published_display_templates.js b/pool/shard001/JavaScript/0010892_published_display_templates.js new file mode 100644 index 0000000000000000000000000000000000000000..607cda9ae68f7cd0a46ab271d58ba915b6329ebd --- /dev/null +++ b/pool/shard001/JavaScript/0010892_published_display_templates.js @@ -0,0 +1,35 @@ +import { Mongo } from 'meteor/mongo'; + +export const PublishedDisplayTemplates = new Mongo.Collection('published_display_templates'); + +// These are server side only +PublishedDisplayTemplates.deny({ + remove () { + return true; + }, + insert () { + return true; + }, + update () { + return true; + } +}); + +/** + * Helpers + */ +PublishedDisplayTemplates.helpers({ + /** + * Compile the template + */ + compile () { + let displayTemplate = this; + Template[ displayTemplate.templateName ] = new Template(displayTemplate.templateName, eval(SpacebarsCompiler.compile(displayTemplate.templateLayout, { isTemplate: true }))); + Template[ displayTemplate.templateName ].helpers(eval('new Object(' + displayTemplate.templateHelpers + ')')); + Template[ displayTemplate.templateName ].events(eval('new Object(' + displayTemplate.templateEvents + ')')); + Template[ displayTemplate.templateName ].onCreated(new Function(displayTemplate.templateCreated)); + Template[ displayTemplate.templateName ].onRendered(new Function(displayTemplate.templateRendered)); + Template[ displayTemplate.templateName ].onDestroyed(new Function(displayTemplate.templateDestroyed)); + return Template[ displayTemplate.templateName ] + } +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010897_index.js b/pool/shard001/JavaScript/0010897_index.js new file mode 100644 index 0000000000000000000000000000000000000000..6d363656536f0e842376a61f287aaff891070c2b --- /dev/null +++ b/pool/shard001/JavaScript/0010897_index.js @@ -0,0 +1,64 @@ +'use strict'; + +const _ = require('lodash'); +const nodem = require('nodem'); +const RPCRunner = require('../../../VDM/prototypes/rpcRunner').RPCRunner; +const vdmUtils = require('../../../VDM/prototypes/vdmUtils'); +const vdmNonClinicalModel = require('../../vdmNonClinicalModel').vdmModel; + +// ******************************** Named list of Out-Of-Scope RPCs ******************************** +const OUT_OF_SCOPE_RPCS = [ + 'ORWCIRN FACLIST', + 'ORWMHV MHV', + 'ORWPCE I10IMPDT', + 'ORWPT LEGACY', + 'ORWRP GET DEFAULT PRINTER', + 'XWB DEFERRED CLEARALL', +]; +// ************************************************************************************************* + + +// *************************************** Utility Functions *************************************** +const rpcRunner = (function createRPCRunner() { + // Set up the path for all mumps GT.M routines (compiled .m files) + process.env.gtmroutines = `${process.env.gtmroutines} ${vdmUtils.getVdmPath()}`; + + // Set up the Nodem instance and connection once for this module + const db = new nodem.Gtm(); + db.open(); + + // Set up the exit handler to close the database on exit + process.on('exit', () => { + db.close(); + }); + + process.on('SIGINT', () => { + db.close(); + }); + + return new RPCRunner(db); +}()); + +function invokeRPC(rpcName, rpcArgs) { + return rpcRunner.run(rpcName, rpcArgs).result; +} + +function toReturnValue(res) { + return res; +} + +// ***************************** Generated Out-Of-Scope Emulator Models ****************************** +module.exports = { + rpcEmulatorModel: OUT_OF_SCOPE_RPCS.map((name) => { + const id = name.split(' ').join('_'); + const processRPCInvocation = _.partial(invokeRPC, name); + + return { + id, + name, + processRPCInvocation, + toReturnValue, + }; + }), + vdmModel: vdmNonClinicalModel, +}; diff --git a/pool/shard001/JavaScript/0010899_pagination.js b/pool/shard001/JavaScript/0010899_pagination.js new file mode 100644 index 0000000000000000000000000000000000000000..7453fee40a849612fae45130b5d9df16abfd7636 --- /dev/null +++ b/pool/shard001/JavaScript/0010899_pagination.js @@ -0,0 +1,210 @@ +/*global define*/ +define(['jquery', 'underscore', 'backbone' + ], function ($, _, Backbone) { + 'use strict'; + + /** + * Datagrid pagination widget + * + * @export orodatagrid/js/datagrid/pagination + * @class orodatagrid.datagrid.Pagination + * @extends Backbone.View + */ + return Backbone.View.extend({ + /** @property */ + windowSize: 10, + + /** @property */ + enabled: true, + + /** @property */ + hidden: false, + + /** @property */ + template: '#template-datagrid-toolbar-pagination', + + /** @property */ + events: { + "click a": "onChangePage" + }, + + /** @property */ + fastForwardHandleConfig: { + prev: { + label: 'Prev', + wrapClass: 'icon-chevron-left hide-text' + }, + next: { + label: 'Next', + wrapClass: 'icon-chevron-right hide-text' + } + }, + + /** + * Initializer. + * + * @param {Object} options + * @param {Backbone.Collection} options.collection + * @param {Object} options.fastForwardHandleConfig + * @param {Number} options.windowSize + */ + initialize: function (options) { + options = options || {}; + + if (!options.collection) { + throw new TypeError("'collection' is required"); + } + + this.collection = options.collection; + this.listenTo(this.collection, "add", this.render); + this.listenTo(this.collection, "remove", this.render); + this.listenTo(this.collection, "reset", this.render); + + this.hidden = options.hide == true; + + this.template = _.template($(options.template || this.template).html()); + + Backbone.View.prototype.initialize.call(this, options); + }, + + /** + * Disable pagination + * + * @return {*} + */ + disable: function () { + this.enabled = false; + this.render(); + return this; + }, + + /** + * Enable pagination + * + * @return {*} + */ + enable: function () { + this.enabled = true; + this.render(); + return this; + }, + + /** + * jQuery event handler for the page handlers. Goes to the right page upon clicking. + * + * @param {Event} e + * @protected + */ + onChangePage: function (e) { + e.preventDefault(); + + if (!this.enabled) { + return; + } + + var label = $.trim($(e.target).text()); + var ffConfig = this.fastForwardHandleConfig; + + var collection = this.collection; + var state = collection.state; + + if (ffConfig) { + var prevLabel = _.has(ffConfig.prev, 'label') ? ffConfig.prev.label : undefined; + var nextLabel = _.has(ffConfig.next, 'label') ? ffConfig.next.label : undefined; + switch (label) { + case prevLabel: + if (collection.hasPrevious()) { + collection.getPreviousPage(); + } + return; + case nextLabel: + if (collection.hasNext()) { + collection.getNextPage(); + } + return; + } + } + + var pageIndex = $(e.target).text() * 1 - state.firstPage; + collection.getPage(state.firstPage === 0 ? pageIndex : pageIndex + 1); + }, + + /** + * Internal method to create a list of page handle objects for the template + * to render them. + * + * @return {Array.} an array of page handle objects hashes + */ + makeHandles: function (handles) { + handles = handles || []; + + var collection = this.collection; + var state = collection.state; + + // convert all indices to 0-based here + var lastPage = state.lastPage ? state.lastPage : state.firstPage; + lastPage = state.firstPage === 0 ? lastPage : lastPage - 1; + var currentPage = state.firstPage === 0 ? state.currentPage : state.currentPage - 1; + var windowStart = Math.floor(currentPage / this.windowSize) * this.windowSize; + var windowEnd = windowStart + this.windowSize; + windowEnd = windowEnd <= lastPage ? windowEnd : lastPage + 1; + + if (collection.mode !== "infinite") { + for (var i = windowStart; i < windowEnd; i++) { + handles.push({ + label: i + 1, + title: "No. " + (i + 1), + className: currentPage === i ? "active" : undefined + }); + } + } + + var ffConfig = this.fastForwardHandleConfig; + + if (ffConfig.prev) { + handles.unshift({ + label: _.has(ffConfig.prev, 'label') ? ffConfig.prev.label : undefined, + wrapClass: _.has(ffConfig.prev, 'wrapClass') ? ffConfig.prev.wrapClass : undefined, + className: collection.hasPrevious() ? undefined : "disabled" + }); + } + + if (ffConfig.next) { + handles.push({ + label: _.has(ffConfig.next, 'label') ? ffConfig.next.label : undefined, + wrapClass: _.has(ffConfig.next, 'wrapClass') ? ffConfig.next.wrapClass : undefined, + className: collection.hasNext() ? void 0 : "disabled" + }); + } + + return handles; + }, + + /** + * Render pagination + * + * @return {*} + */ + render: function () { + var state = this.collection.state; + + // prevent render if data is not loaded yet + if (state.totalRecords == null) { + return this; + } + + this.$el.empty(); + this.$el.append($(this.template({ + disabled: !this.enabled || !state.totalRecords, + handles: this.makeHandles(), + state: state + }))); + + if (this.hidden) { + this.$el.hide(); + } + + return this; + } + }); +}); diff --git a/pool/shard001/JavaScript/0010902_helpers.js b/pool/shard001/JavaScript/0010902_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..81619803e9f714e191991b22a56378e98e5bf3b5 --- /dev/null +++ b/pool/shard001/JavaScript/0010902_helpers.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var stretch_mapping_1 = require("./stretch-mapping"); +var proxy_base_controller_listener_1 = require("./proxy-base-controller-listener"); +var types = require("tns-core-modules/utils/types"); +var utils = require("tns-core-modules/utils/utils"); +var fs = require("tns-core-modules/file-system"); +var Helpers = (function () { + function Helpers() { + } + Helpers.setNativeStretch = function (draweeHierarchy, stretch) { + var frescoStretch = stretch_mapping_1.StretchMapping.get(stretch) || com.facebook.drawee.drawable.ScalingUtils.ScaleType.CENTER; + draweeHierarchy.setActualImageScaleType(frescoStretch); + }; + Helpers.setRounded = function (draweeHierarchy, rounded) { + var roundingParams = new com.facebook.drawee.generic.RoundingParams.fromCornersRadius(0); + if (rounded) + roundingParams.setRoundAsCircle(true); + else + roundingParams.setRoundAsCircle(false); + draweeHierarchy.setRoundingParams(roundingParams); + }; + Helpers.setPlaceholder = function (draweeHierarchy, src, placeholderStretch) { + var drawable = this.getPlaceholderImageDrawable(src), nativePlaceholderStretch = stretch_mapping_1.StretchMapping.get(placeholderStretch) || com.facebook.drawee.drawable.ScalingUtils.ScaleType.CENTER; + if (null == drawable) { + return; + } + draweeHierarchy.setPlaceholderImage(drawable, nativePlaceholderStretch); + }; + Helpers.getPlaceholderImageDrawable = function (value) { + var fileName = "", drawable = null; + if (types.isString(value)) { + value = value.trim(); + if (utils.isFileOrResourcePath(value)) { + if (0 === value.indexOf("~/")) { + fileName = fs.path.join(fs.knownFolders.currentApp().path, value.replace("~/", "")); + drawable = android.graphics.drawable.Drawable.createFromPath(fileName); + } + else if (0 === value.indexOf("res")) { + fileName = value; + var res = utils.ad.getApplicationContext().getResources(); + var resName = fileName.substr(utils.RESOURCE_PREFIX.length); + var identifier = res.getIdentifier(resName, 'drawable', utils.ad.getApplication().getPackageName()); + drawable = res.getDrawable(identifier); + } + } + } + return drawable; + }; + Helpers.setSource = function (image, value) { + image.nativeView.setImageURI(null, null); + if (types.isString(value)) { + value = value.trim(); + if (utils.isFileOrResourcePath(value) || 0 === value.indexOf("http")) { + image.isLoading = true; + var fileName = ""; + if (0 === value.indexOf("~/")) { + fileName = fs.path.join(fs.knownFolders.currentApp().path, value.replace("~/", "")); + fileName = "file:" + fileName; + } + else if (0 === value.indexOf("res")) { + fileName = value; + var res = utils.ad.getApplicationContext().getResources(); + var resName = fileName.substr(utils.RESOURCE_PREFIX.length); + var identifier = res.getIdentifier(resName, 'drawable', utils.ad.getApplication().getPackageName()); + fileName = "res:/" + identifier; + } + else if (0 === value.indexOf("http")) { + image.isLoading = true; + fileName = value; + } + image.nativeView.setImageURI(android.net.Uri.parse(fileName), null); + var controllerListener = new proxy_base_controller_listener_1.ProxyBaseControllerListener(); + controllerListener.setNSCachedImage(image); + var controller = com.facebook.drawee.backends.pipeline.Fresco.newDraweeControllerBuilder() + .setControllerListener(controllerListener) + .setUri(android.net.Uri.parse(fileName)) + .build(); + image.nativeView.setController(controller); + image.requestLayout(); + } + else { + throw new Error("Path \"" + "\" is not a valid file or resource."); + } + } + }; + Helpers.onRoundedPropertyChanged = function (nativeObject, value) { + if (!nativeObject) { + return; + } + var draweeHierarchy = nativeObject.getHierarchy(); + this.setRounded(draweeHierarchy, value); + }; + Helpers.onPlaceholderPropertyChanged = function (nativeObject, src, placeholderStretch) { + if (!nativeObject) { + return; + } + var draweeHierarchy = nativeObject.getHierarchy(); + this.setPlaceholder(draweeHierarchy, src, placeholderStretch); + }; + Helpers.onSrcPropertySet = function (viewWrapper, src) { + var image = viewWrapper, value = src; + if (!image.nativeView) { + return; + } + this.setSource(image, value); + }; + Helpers.onStretchPropertyChanged = function (nativeObject, value) { + if (!nativeObject) { + return; + } + var draweeHierarchy = nativeObject.getHierarchy(); + this.setNativeStretch(draweeHierarchy, value); + }; + return Helpers; +}()); +exports.Helpers = Helpers; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010903_platform.js b/pool/shard001/JavaScript/0010903_platform.js new file mode 100644 index 0000000000000000000000000000000000000000..9da0cc9f17e3c1b82df0799b27ba432818b42b48 --- /dev/null +++ b/pool/shard001/JavaScript/0010903_platform.js @@ -0,0 +1,102 @@ +/*! + * Module dependencies. + */ + +/** + * Get Platform Names for each Environment. + * + * Options: + * + * - `platforms` {Array} of {String} platform keywords. + * + * Returns: + * + * - {Array} of {Object} that contain keywords for each environment. + */ + +module.exports.names = function(platforms) { + platforms = platforms || []; + + // filter out unsupported platforms + platforms = platforms.filter(function(platform) { + return module.exports.map[platform]; + }); + + // map platform names + return platforms.map(function(platform) { + return module.exports.map[platform]; + }); +}; + +/** + * Platform Environment Names. + * + * Mapping: + * 'local' => cordova-cli + * 'remote' => PhoneGap/Build + * 'human' => Human readable name + */ + +module.exports.map = { + android: { + local: 'android', + remote: 'android', + human: 'Android' + }, + blackberry: { + local: 'blackberry10', + remote: 'blackberry', + human: 'BlackBerry' + }, + ios: { + local: 'ios', + remote: 'ios', + human: 'iOS' + }, + wp7: { + local: 'wp7', + remote: null, + human: 'Windows Phone 7' + }, + wp8: { + local: 'wp8', + remote: 'winphone', + human: 'Windows Phone 8' + }, + firefoxos: { + local: 'firefoxos', + remote: null, + human: 'Firefox OS' + } +}; + +/** + * check to see if a given set of platform labels are supported + * + * @param platforms to check, can be a platform label string or an array of platform label strings + * @return array of valid platforms + */ +module.exports.supports = function (platforms) { + var results = []; + var supported = module.exports.map; + var check = function(value) { + for (var i in supported) { + var plat = supported[i]; + if (plat.local === value) { + return true; + } + } + return false + }; + + if (!platforms.length) { + if (check(platforms)) { + results.push(platforms); + }; + } else { + results = platforms.filter(function(value) { + return check(value); + }); + } + return results; +}; diff --git a/pool/shard001/JavaScript/0010904_misc.test.js b/pool/shard001/JavaScript/0010904_misc.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2938979b2b36276f1ab23e251958a8f70d17c864 --- /dev/null +++ b/pool/shard001/JavaScript/0010904_misc.test.js @@ -0,0 +1,30 @@ +const test = require('tape') +const nlp = require('../_lib') + +test('verbs.json', function(t) { + let json = nlp('She has called twice, not the tv') + .verbs() + .json() + t.equal(json.length, 1, 'one verb') + t.equal(json[0].isNegative, false, 'not negative') + t.equal(json[0].parts.verb, 'called', 'got main verb') + t.equal(json[0].parts.auxiliary, 'has', 'got aux verb') + t.end() +}) + +test('verbs.adverbs', function(t) { + let doc = nlp('spencer is really great! Spencer really really was superb.') + doc + .verbs() + .adverbs() + .delete() + t.equal(doc.out(), 'spencer is great! Spencer was superb.', 'no-adverbs') + + doc = nlp('spencer truly would really run quickly') + .verbs() + .adverbs() + t.equal(doc.length, 3, 'found all three adverbs') + t.equal(doc.text('reduced'), 'truly really quickly', 'found adverbs in order') + + t.end() +}) diff --git a/pool/shard001/JavaScript/0010906_SoftLocalStorage.js b/pool/shard001/JavaScript/0010906_SoftLocalStorage.js new file mode 100644 index 0000000000000000000000000000000000000000..623f8f46084a3f5e0337f8792020621fb03b04c9 --- /dev/null +++ b/pool/shard001/JavaScript/0010906_SoftLocalStorage.js @@ -0,0 +1,13 @@ +/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/ +Ext.define('Jarvus.patch.SoftLocalStorage', { + override: 'Ext.state.LocalStorageProvider' + + // stop LocalStorageProvider from generating a hard error in IE6 + // see http://www.sencha.com/forum/showthread.php?220574-4.1.x-Instantiating-local-storage-provider-in-old-IE-causes-hard-error + ,constructor: function() { + var me = this; + Ext.state.Provider.prototype.constructor.apply(me, arguments); + me.store = me.getStorageObject(); + me.state = me.store ? me.readLocalStorage() : false; + } +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010912_AvatarForm.js b/pool/shard001/JavaScript/0010912_AvatarForm.js new file mode 100644 index 0000000000000000000000000000000000000000..ebca6ee2b08ae730b1ab2439c8ed2ef85bcce292 --- /dev/null +++ b/pool/shard001/JavaScript/0010912_AvatarForm.js @@ -0,0 +1,256 @@ +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { Field, reduxForm } from 'redux-form'; +import Button from 'react-bootstrap/lib/Button'; +import Image from 'react-bootstrap/lib/Image'; +import FormNames from '../../../constants/FormNames'; +import configs from '../../../../../configs/project/client'; +import firebaseAPI from '../../../api/firebase'; +import userAPI from '../../../api/user'; +import { pushErrors } from '../../../actions/errorActions'; +import { setCookies } from '../../../actions/cookieActions'; +import { + BsInput as Input, + BsRadio as Radio, +} from '../../fields/adapters'; +import { + BsForm as Form, + BsFormFooter as FormFooter, + BsField as FormField, +} from '../../fields/widgets'; +import Head from '../../widgets/Head'; +import toRefreshURL from '../../../utils/toRefreshURL'; + +const initialValues = { + storage: 'local', +}; + +/** + * Test server side validation with Postman: + * 1. Setup the method and url `POST http://localhost:3000/api/users/me/avatar` + * 2. Select `Body` tab + * 3. Select `form-data` type + * 4. Add new key `avatar` and select some invalid file on purpose + * 5. Send + */ +export let validate = (values) => { + const errors = {}; + + if (!values.avatar || values.avatar.length !== 1) { + errors.avatar = 'Required'; + } else { + let { size, type, mimetype } = values.avatar[0]; + let { maxSize, validMIMETypes } = configs.fileUpload.avatar; + + if (size > maxSize) { + errors.avatar = ( + `Your file(${Math.floor(size / 1024)} Kb) ` + + `exceeds the limit size(${Math.floor(maxSize / 1024)} Kb).` + ); + } + // we check the key `type` for client side and `mimetype` for server side + if (validMIMETypes.indexOf(type || mimetype) < 0) { + errors.avatar = 'Invalid type. Please upload .jpg, .png or .gif file.'; + } + } + + return errors; +}; + +class AvatarForm extends Component { + constructor() { + super(); + this.uploadToLocal = this._uploadToLocal.bind(this); + this.uploadToFirebase = this._uploadToFirebase.bind(this); + this.signInFirebase = this._signInFirebase.bind(this); + this.clearFileField = this._clearFileField.bind(this); + this.handleSubmit = this._handleSubmit.bind(this); + this.state = { + isFirebaseInitialized: false, + avatarURL: null, + }; + } + + _uploadToLocal(formData) { + let { apiEngine } = this.props; + + return userAPI(apiEngine) + .uploadAvatar(formData.avatar[0]) + .catch((err) => { + return Promise.reject(err); + }) + .then((json) => { + return Promise.resolve(json.downloadURL); + }); + } + + _signInFirebase() { + let { dispatch, apiEngine } = this.props; + + return firebaseAPI(apiEngine) + .readToken() + .catch((err) => { + dispatch(pushErrors([{ + title: 'Fail To Read Token', + detail: 'Read firebase token fail.', + }])); + throw err; + }) + .then((json) => { + // Initialize firebase + if (!this.state.isFirebaseInitialized) { + firebase.initializeApp(configs.firebase); + this.setState({ + isFirebaseInitialized: true, + }); + } + + // SignIn firebase + return firebase.auth() + .signInWithCustomToken(json.token) + .catch(function(err) { + dispatch(pushErrors([{ + title: 'Fail To Signin Firebase', + detail: 'Signin firebase fail.', + }])); + throw err; + }); + }); + } + + _uploadToFirebase(formData) { + let _this = this; + let { user } = this.props; + + return new Promise((resolve, reject) => { + _this.signInFirebase().then(() => { + // ref: + let storageRef = firebase.storage().ref(); + let avatarRef = storageRef.child( + `${process.env.NODE_ENV}/${user._id}/avatar.jpg`); + let uploadTask = avatarRef.put(formData.avatar[0]); + + uploadTask.on('state_changed', function(snapshot) { + // Observe state change events such as progress, pause, and resume + // See below for more detail + }, function(err) { + // Handle unsuccessful uploads + return reject(err); + }, function complete() { + // Handle successful uploads on complete + // For instance, get the download URL: https://firebasestorage.googleapis.com/... + let downloadURL = uploadTask.snapshot.downloadURL; + return resolve(downloadURL); + }); + }); + }); + } + + _clearFileField() { + let { change, untouch } = this.props; + change('avatar', ''); + untouch('avatar'); + } + + _handleSubmit(formData) { + let { dispatch, apiEngine } = this.props; + let uploadProcedure; + if (formData.storage === 'firebase') { + uploadProcedure = this.uploadToFirebase(formData); + } else if (formData.storage === 'local') { + uploadProcedure = this.uploadToLocal(formData); + } + + return uploadProcedure + .catch((err) => { + dispatch(pushErrors([{ + title: 'Fail To Upload Avatar', + detail: 'Upload avatar fail.', + meta: err, + }])); + throw err; + }) + .then((downloadURL) => { + return userAPI(apiEngine) + .updateAvatarURL({ + avatarURL: downloadURL, + }) + .catch((err) => { + dispatch(pushErrors([{ + title: 'Fail To Update Avatar URL', + detail: 'Update user avatar URL fail.', + meta: err, + }])); + throw err; + }) + .then((json) => { + let newAvatarURL = toRefreshURL(downloadURL); + json.user.avatarURL = newAvatarURL; + dispatch(setCookies({ + user: json.user, + })); + this.clearFileField(); + }); + }); + } + + render() { + const { + user: { avatarURL }, + handleSubmit, + pristine, + submitting, + invalid, + } = this.props; + + return ( +
    + + {avatarURL && } + + + + + + + ); + } +}; + +export default reduxForm({ + form: FormNames.USER_AVATAR, + initialValues, + validate, +})(connect(({ apiEngine, cookies: { user } }) => ({ + apiEngine: apiEngine, + user: user || {}, +}))(AvatarForm)); diff --git a/pool/shard001/JavaScript/0010914_error.js b/pool/shard001/JavaScript/0010914_error.js new file mode 100644 index 0000000000000000000000000000000000000000..f04276ab25e7eca51e455a1ec0f2a37c6b6d90d4 --- /dev/null +++ b/pool/shard001/JavaScript/0010914_error.js @@ -0,0 +1,17 @@ +const assert = require('assert') + +exports.assert_error_msg = (fn, msgOrErr) => { + let msg = msgOrErr instanceof Error ? msgOrErr.message : msgOrErr + let errored = false + + try { + fn.apply(null) + } catch (error) { + errored = !!error; + assert.strictEqual(error.message, msg) + } + + assert.isTrue(errored) + + return errored; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010915_sl-date-time-test.js b/pool/shard001/JavaScript/0010915_sl-date-time-test.js new file mode 100644 index 0000000000000000000000000000000000000000..b9e1f3245bbc66572184e55b931910b4b03f9bcc --- /dev/null +++ b/pool/shard001/JavaScript/0010915_sl-date-time-test.js @@ -0,0 +1,149 @@ +import Ember from 'ember'; +import { moduleForComponent, test } from 'ember-qunit'; + +moduleForComponent( 'sl-date-time', 'Unit | Component | sl date time', { + unit: true +}); + +test( 'Default class names are present', function( assert ) { + this.subject({ timezone: 'America/Chicago' }); + + assert.ok( + this.$().hasClass( 'sl-datetime' ), + 'Default rendered component has class "sl-datetime"' + ); +}); + +test( 'Attribute "datetime" is properly set', function( assert ) { + this.subject({ + timezone: 'America/Chicago', + value: new Date( 2015, 0, 1 ) + }); + + assert.equal( + this.$().attr( 'datetime' ), + '2015-01-01 00:00 CST', + '"datetime" attribute is expected value' + ); +}); + +test( 'Format "date" results in correctly formatted value', function( assert ) { + const component = this.subject({ + format: 'date', + timezone: 'America/Chicago', + value: new Date( 2015, 0, 1 ) + }); + + const formattedValue = '2015-01-01'; + + assert.equal( + component.get( 'formattedValue' ), + formattedValue, + '"date" formatted date is expected value' + ); + + assert.equal( + Ember.$.trim( this.$().text() ), + formattedValue, + 'Rendered component text is expected formatted value' + ); +}); + +test( 'Format "relative" results in correctly formatted value', function( assert ) { + const component = this.subject({ + format: 'relative', + timezone: 'America/Chicago', + value: window.moment().subtract( 1, 'year' ) + }); + + const formattedValue = 'a year ago'; + + assert.equal( + component.get( 'formattedValue' ), + formattedValue, + '"relative" formatted date is expected value' + ); + + assert.equal( + Ember.$.trim( this.$().text() ), + formattedValue, + 'Rendered component text is expected formatted value' + ); +}); + +test( 'Format "datetime" results in correctly formatted value', function( assert ) { + const component = this.subject({ + format: 'datetime', + timezone: 'America/Chicago', + value: new Date( 2015, 0, 1 ) + }); + + const formattedValue = 'Thursday, January 1st 2015, 12:00 AM CST'; + + assert.equal( + component.get( 'formattedValue' ), + formattedValue, + '"datetime" formatted date is expected value' + ); + + assert.equal( + Ember.$.trim( this.$().text() ), + formattedValue, + 'Rendered component text is expected formatted value' + ); +}); + +test( 'Computed momentValue is set and updated correctly', function( assert ) { + const component = this.subject({ + timezone: 'America/Chicago', + value: new Date( 2015, 0, 1 ) + }); + + assert.equal( + component.get( 'momentValue' ).calendar(), + '01/01/2015', + 'Initial momentValue is expected value' + ); + + Ember.run( () => { + component.set( 'value', new Date( 2015, 1, 15 ) ); + }); + assert.equal( + component.get( 'momentValue' ).calendar(), + '02/15/2015', + 'Updated momentValue is expected value' + ); +}); + +test( 'Computed timezoneString is set and updated correctly', function( assert ) { + const component = this.subject({ + timezone: 'America/Chicago', + value: new Date( 2015, 0, 1 ) + }); + + assert.equal( + component.get( 'timezoneString' ), + 'CST', + 'Initial timezoneString is expected value' + ); + + Ember.run( () => { + component.set( 'timezone', 'America/Los_Angeles' ); + }); + + assert.equal( + component.get( 'timezoneString' ), + 'PST', + 'Updated timezoneString is expected value' + ); +}); + +test( '"title" property is an alias to "datetime" value', function( assert ) { + const component = this.subject({ timezone: 'America/Chicago' }); + + assert.equal( + component.get( 'title' ), + component.get( 'datetime' ), + '"title" property is aliased to "datetime" property' + ); +}); diff --git a/pool/shard001/JavaScript/0010919_commonUtil.js b/pool/shard001/JavaScript/0010919_commonUtil.js new file mode 100644 index 0000000000000000000000000000000000000000..a8b93454bf80440421cf5164bf502173c8d13431 --- /dev/null +++ b/pool/shard001/JavaScript/0010919_commonUtil.js @@ -0,0 +1,67 @@ +/* + * 存放常用工具类 + */ + +/* + * 格式化日期 + * @param date Date or timestamp + * @param formatter yyyyMMddHHmmss + */ +export function formatDate(date, formatter) { + if (typeof date !== 'object') { + date = new Date(date); + } + const transform = function(value) { + return value < 10 ? '0' + value : value; + }; + return formatter.replace(/^YYYY|MM|DD|hh|mm|ss/g, function(match) { + switch (match) { + case 'YYYY': + return transform(date.getFullYear()); + case 'MM': + return transform(date.getMonth() + 1); + case 'mm': + return transform(date.getMinutes()); + case 'DD': + return transform(date.getDate()); + case 'hh': + return transform(date.getHours()); + case 'ss': + return transform(date.getSeconds()); + } + }); +} + +export function selectText(element) { + let range, selection; + + if (window.getSelection) { + selection = window.getSelection(); + range = document.createRange(); + range.selectNodeContents(element); + selection.removeAllRanges(); + selection.addRange(range); + } else if (document.body.createTextRange) { + range = document.body.createTextRange(); + range.moveToElementText(element); + range.select(); + } +} + +export function getQueryParameter (name) { + var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (results == null) { + return ''; + } else { + return results[1] || ''; + } +} + +const CommonUtil = { + formatDate, + selectText, + getQueryParameter +}; + +export default CommonUtil; + diff --git a/pool/shard001/JavaScript/0010926_usage.js b/pool/shard001/JavaScript/0010926_usage.js new file mode 100644 index 0000000000000000000000000000000000000000..9bd5a0a818fdc4f9f6882995b9369db941df6007 --- /dev/null +++ b/pool/shard001/JavaScript/0010926_usage.js @@ -0,0 +1,14 @@ +var key = 'your api key'; +var path = require('path'); +var modulePath = path.resolve(__dirname, '..', 'lib', 'yandex-dictionary.js'); +var yandexDictionary = require(modulePath)(key); + + +yandexDictionary.getLangs(function(err, res) { + err ? console.log(err) : console.log(res); +}); + +yandexDictionary.lookup('dick', 'en-ru', {ui: 'ru', flags: 1 }, function(err, res) { + var util = require('util'); + err ? console.log(err) : console.log(util.inspect(res, {depth: null})); +}); diff --git a/pool/shard001/JavaScript/0010937_IoTEventConverter.js b/pool/shard001/JavaScript/0010937_IoTEventConverter.js new file mode 100644 index 0000000000000000000000000000000000000000..1a198f2ad5bef6da9835d83805c3b90e35aeaa15 --- /dev/null +++ b/pool/shard001/JavaScript/0010937_IoTEventConverter.js @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Stefano Buliani (@sapessi) + * + * 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 strct' + +const utils = require('../utils'); + +class IoTEventConverter { + constructor(serverless) { + this.serverless = serverless; + } + + getEventType() { + return "IoTRule"; + } + + convertEvent(event, targetResourceName) { + if (!event.sql) { + throw new Error("Not sql property in IoT event"); + } + + let baseEvent = { + Sql: event.sql + } + + if (event.sqlVersion) { + baseEvent["AwsIotSqlVersion"] = event.sqlVersion; + } + + return { + event: baseEvent, + resources: {} + } + } +} + +module.exports = IoTEventConverter; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010938_ready.js b/pool/shard001/JavaScript/0010938_ready.js new file mode 100644 index 0000000000000000000000000000000000000000..c29c90520177d0e220ddf69dee3d8193a15945d7 --- /dev/null +++ b/pool/shard001/JavaScript/0010938_ready.js @@ -0,0 +1,41 @@ +/** + * @license ready 0.0.1 Copyright jQuery Foundation and other contributors. + * Released under MIT license, http://github.com/requirejs/domReady/LICENSE + */ +/*jslint */ +/*global require: false, define: false, requirejs: false, + window: false, clearInterval: false, document: false, + self: false, setInterval: false */ + +define(function () { + 'use strict'; + + /** START OF PUBLIC API **/ + + /** + * Registers a callback for DOM ready. If DOM is already ready, the + * callback is called immediately. + * @param {Function} callback + */ + function ready(callback) { + callback(''); + return ready; + } + + ready.version = '0.0.1'; + + /** + * Loader Plugin API method + */ + ready.load = function (name, req, onLoad, config) { + if (config.isBuild) { + onLoad(null); + } else { + ready(onLoad); + } + }; + + /** END OF PUBLIC API **/ + + return ready; +}); diff --git a/pool/shard001/JavaScript/0010939_enumerable.js b/pool/shard001/JavaScript/0010939_enumerable.js new file mode 100644 index 0000000000000000000000000000000000000000..f2e5394d5b641cd5937465d53240941bf2b5e04f --- /dev/null +++ b/pool/shard001/JavaScript/0010939_enumerable.js @@ -0,0 +1,324 @@ +import { Suite } from 'ember-runtime/tests/suites/suite'; +import EmberObject from "ember-runtime/system/object"; +import {guidFor, generateGuid} from "ember-metal/utils"; +import {computed} from "ember-metal/computed"; +import {get} from "ember-metal/property_get"; +import { addBeforeObserver } from 'ember-metal/observer'; + +var ObserverClass = EmberObject.extend({ + + _keysBefore: null, + _keys: null, + _values: null, + _before : null, + _after: null, + + isEnabled: true, + + init() { + this._super.apply(this, arguments); + this.reset(); + }, + + + propertyWillChange(target, key) { + if (this._keysBefore[key] === undefined) { this._keysBefore[key] = 0; } + this._keysBefore[key]++; + }, + + /* + Invoked when the property changes. Just records the parameters for + later analysis. + */ + propertyDidChange(target, key, value) { + if (this._keys[key] === undefined) { this._keys[key] = 0; } + this._keys[key]++; + this._values[key] = value; + }, + + /* + Resets the recorded results for another run. + + @returns {Object} receiver + */ + reset() { + this._keysBefore = {}; + this._keys = {}; + this._values = {}; + this._before = null; + this._after = null; + return this; + }, + + + observeBefore(obj) { + var keys = Array.prototype.slice.call(arguments, 1); + var loc = keys.length; + while (--loc>=0) { + addBeforeObserver(obj, keys[loc], this, 'propertyWillChange'); + } + + return this; + }, + + /* + Begins observing the passed key names on the passed object. Any changes + on the named properties will be recorded. + + @param {Ember.Enumerable} obj + The enumerable to observe. + + @returns {Object} receiver + */ + observe(obj) { + if (obj.addObserver) { + var keys = Array.prototype.slice.call(arguments, 1); + var loc = keys.length; + + while (--loc >= 0) { + obj.addObserver(keys[loc], this, 'propertyDidChange'); + } + } else { + this.isEnabled = false; + } + return this; + }, + + /* + Returns true if the passed key was invoked. If you pass a value as + well then validates that the values match. + + @param {String} key + Key to validate + + @param {Object} value + (Optional) value + + @returns {Boolean} + */ + validate(key, value) { + if (!this.isEnabled) { + return true; + } + + if (!this._keys[key]) { + return false; + } + + if (arguments.length>1) { + return this._values[key] === value; + } else { + return true; + } + }, + + /* + Returns times the before observer as invoked. + + @param {String} key + Key to check + */ + timesCalledBefore(key) { + return this._keysBefore[key] || 0; + }, + + /* + Returns times the observer as invoked. + + @param {String} key + Key to check + */ + timesCalled(key) { + return this._keys[key] || 0; + }, + + /* + begins acting as an enumerable observer. + */ + observeEnumerable(obj) { + obj.addEnumerableObserver(this); + return this; + }, + + stopObserveEnumerable(obj) { + obj.removeEnumerableObserver(this); + return this; + }, + + enumerableWillChange() { + equal(this._before, null, 'should only call once'); + this._before = Array.prototype.slice.call(arguments); + }, + + enumerableDidChange() { + equal(this._after, null, 'should only call once'); + this._after = Array.prototype.slice.call(arguments); + } + +}); + + +var EnumerableTests = Suite.extend({ + /* + __Required.__ You must implement this method to apply this mixin. + + Implement to return a new enumerable object for testing. Should accept + either no parameters, a single number (indicating the desired length of + the collection) or an array of objects. + + @param {Array} content + An array of items to include in the enumerable optionally. + + @returns {Ember.Enumerable} a new enumerable + */ + newObject: null, + + /* + Implement to return a set of new fixture strings that can be applied to + the enumerable. This may be passed into the newObject method. + + @param {Number} count + The number of items required. + + @returns {Array} array of strings + */ + newFixture(cnt) { + var ret = []; + while (--cnt >= 0) { + ret.push(generateGuid()); + } + + return ret; + }, + + /* + Implement to return a set of new fixture objects that can be applied to + the enumerable. This may be passed into the newObject method. + + @param {Number} cnt + The number of items required. + + @returns {Array} array of objects + */ + newObjectsFixture(cnt) { + var ret = []; + var item; + while (--cnt >= 0) { + item = {}; + guidFor(item); + ret.push(item); + } + return ret; + }, + + /* + __Required.__ You must implement this method to apply this mixin. + + Implement accept an instance of the enumerable and return an array + containing the objects in the enumerable. This is used only for testing + so performance is not important. + + @param {Ember.Enumerable} enumerable + The enumerable to convert. + + @returns {Array} array of items + */ + toArray: null, + + /* + Implement this method if your object can mutate internally (even if it + does not support the MutableEnumerable API). The method should accept + an object of your desired type and modify it somehow. Suite tests will + use this to ensure that all appropriate caches, etc. clear when the + mutation occurs. + + If you do not define this optional method, then mutation-related tests + will be skipped. + + @param {Ember.Enumerable} enumerable + The enumerable to mutate + + @returns {void} + */ + mutate() {}, + + /* + Becomes true when you define a new mutate() method, indicating that + mutation tests should run. This is calculated automatically. + + @type Boolean + */ + canTestMutation: computed(function() { + return this.mutate !== EnumerableTests.prototype.mutate; + }), + + /* + Invoked to actually run the test - overridden by mixins + */ + run() {}, + + + /* + Creates a new observer object for testing. You can add this object as an + observer on an array and it will record results anytime it is invoked. + After running the test, call the validate() method on the observer to + validate the results. + */ + newObserver(obj) { + var ret = get(this, 'observerClass').create(); + if (arguments.length>0) { + ret.observeBefore.apply(ret, arguments); + } + + if (arguments.length>0) { + ret.observe.apply(ret, arguments); + } + + return ret; + }, + + observerClass: ObserverClass +}); + +import anyTests from 'ember-runtime/tests/suites/enumerable/any'; +import isAnyTests from 'ember-runtime/tests/suites/enumerable/is_any'; +import compactTests from 'ember-runtime/tests/suites/enumerable/compact'; +import containsTests from 'ember-runtime/tests/suites/enumerable/contains'; +import everyTests from 'ember-runtime/tests/suites/enumerable/every'; +import filterTests from 'ember-runtime/tests/suites/enumerable/filter'; +import findTests from 'ember-runtime/tests/suites/enumerable/find'; +import firstObjectTests from 'ember-runtime/tests/suites/enumerable/firstObject'; +import forEachTests from 'ember-runtime/tests/suites/enumerable/forEach'; +import mapByTests from 'ember-runtime/tests/suites/enumerable/mapBy'; +import invokeTests from 'ember-runtime/tests/suites/enumerable/invoke'; +import lastObjectTests from 'ember-runtime/tests/suites/enumerable/lastObject'; +import mapTests from 'ember-runtime/tests/suites/enumerable/map'; +import reduceTests from 'ember-runtime/tests/suites/enumerable/reduce'; +import rejectTests from 'ember-runtime/tests/suites/enumerable/reject'; +import sortByTests from 'ember-runtime/tests/suites/enumerable/sortBy'; +import toArrayTests from 'ember-runtime/tests/suites/enumerable/toArray'; +import uniqTests from 'ember-runtime/tests/suites/enumerable/uniq'; +import withoutTests from 'ember-runtime/tests/suites/enumerable/without'; + +EnumerableTests.importModuleTests(anyTests); +EnumerableTests.importModuleTests(isAnyTests); +EnumerableTests.importModuleTests(compactTests); +EnumerableTests.importModuleTests(containsTests); +EnumerableTests.importModuleTests(everyTests); +EnumerableTests.importModuleTests(filterTests); +EnumerableTests.importModuleTests(findTests); +EnumerableTests.importModuleTests(firstObjectTests); +EnumerableTests.importModuleTests(forEachTests); +EnumerableTests.importModuleTests(mapByTests); +EnumerableTests.importModuleTests(invokeTests); +EnumerableTests.importModuleTests(lastObjectTests); +EnumerableTests.importModuleTests(mapTests); +EnumerableTests.importModuleTests(reduceTests); +EnumerableTests.importModuleTests(rejectTests); +EnumerableTests.importModuleTests(sortByTests); +EnumerableTests.importModuleTests(toArrayTests); +EnumerableTests.importModuleTests(uniqTests); +EnumerableTests.importModuleTests(withoutTests); + +export default EnumerableTests; +export {EnumerableTests, ObserverClass}; diff --git a/pool/shard001/JavaScript/0010947_UnaryExpression.js b/pool/shard001/JavaScript/0010947_UnaryExpression.js new file mode 100644 index 0000000000000000000000000000000000000000..913391459f1a677e788d10ff6a3668b3a1798ab6 --- /dev/null +++ b/pool/shard001/JavaScript/0010947_UnaryExpression.js @@ -0,0 +1,82 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); + +var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); + +var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = require('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require('babel-runtime/helpers/inherits'); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _Expression2 = require('../Expression'); + +var _Expression3 = _interopRequireDefault(_Expression2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var unaryOperators = { + '-': true, + '+': true, + '!': true, + '~': true, + 'typeof': true, + 'void': true, + 'delete': true +}; + +var UnaryExpression = function (_Expression) { + (0, _inherits3.default)(UnaryExpression, _Expression); + + + // TODO: Should respect operator precedence: putting "-a" after "b" without parens should raise an error. + + function UnaryExpression(childNodes) { + (0, _classCallCheck3.default)(this, UnaryExpression); + + var _this = (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(UnaryExpression).call(this, 'UnaryExpression', childNodes)); + + _this.prefix = true; + return _this; + } + + (0, _createClass3.default)(UnaryExpression, [{ + key: '_acceptChildren', + value: function _acceptChildren(children) { + if (children.currentElement.type === 'Punctuator' || children.currentElement.type === 'Keyword') { + children.assertToken(children.currentElement.type, unaryOperators); + } else { + children.assertToken('Punctuator'); + } + + var operator = children.passToken().value; + children.skipNonCode(); + + var argument = children.passExpression(); + + children.assertEnd(); + + this.argument = argument; + this.operator = operator; + } + }]); + return UnaryExpression; +}(_Expression3.default); + +exports.default = UnaryExpression; +//# sourceMappingURL=UnaryExpression.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010950_stage.js b/pool/shard001/JavaScript/0010950_stage.js new file mode 100644 index 0000000000000000000000000000000000000000..5f127bb7f5003fcb2525961d6336646cf312219f --- /dev/null +++ b/pool/shard001/JavaScript/0010950_stage.js @@ -0,0 +1,119 @@ +// This file is part of Ambience Stage +// Copyright 2012 Jakob Kallin +// License: GNU GPL (http://www.gnu.org/licenses/gpl-3.0.txt) + +describe('Ambience stage', function() { + var stage; + var stageNode; + + beforeEach(function() { + stageNode = document.createElement('div'); + document.body.appendChild(stageNode); + stage = new Ambience.DebugStage(stageNode); + }); + + afterEach(function() { + document.body.removeChild(stageNode); + }); + + it('stops current scene when starting new scene', function() { + var scene = new Ambience.Scene(['Image']); + scene.image.url = 'test-image.jpg'; + stage.play(scene); + + var newScene = new Ambience.Scene(['Image']); + scene.image.url = 'test-image.jpg'; + stage.play(scene); + + expect(stage.imageCount).toBe(1); + }); + + it("fades the entire stage's opacity", function() { + runs(function() { + var scene = new Ambience.Scene(); + scene.fade.in = 1000; + stage.play(scene); + }); + + waits(500); + + runs(function() { + // If CSS transitions are used, this has to be changed to getComputedStyle. + // We're using a fairly generous interval for the opacity. + expect(stage.opacity).toBeGreaterThan(0.25); + expect(stage.opacity).toBeLessThan(0.75); + }); + + waits(1000); + + runs(function() { + expect(stage.opacity).toBeGreaterThan(0.9); + }); + }); + + it('stops all media after fading out', function() { + runs(function() { + var scene = new Ambience.Scene(['Background', 'Image', 'Sound', 'Text']); + scene.fade.in = scene.fade.out = 1000; + scene.background.color = 'red'; + scene.image.url = 'test-image.jpg'; + scene.sound.tracks = ['test-audio.ogg']; + scene.text.string = 'Test'; + + stage.play(scene); + + expect(stage.background).toBe('red'); + expect(stage.imageCount).toBe(1); + expect(stage.soundCount).toBe(1); + expect(stage.textCount).toBe(1); + }); + + waits(1500); + + runs(function() { + stage.fadeOut(); + }); + + waits(1500); + + runs(function() { + expect(stage.background).toBe('black'); + expect(stage.imageCount).toBe(0); + expect(stage.soundCount).toBe(0); + expect(stage.textCount).toBe(0); + }); + }); + + it('interrupts scene that is fading out', function() { + runs(function() { + var scene = new Ambience.Scene(['Image']); + scene.image.url = 'test-image.jpg'; + scene.fade.out = 1000; + stage.play(scene); + stage.fadeOut(); + }); + + waits(500); + + runs(function() { + stage.stop(); + expect(stage.opacity).toBe(0); + expect(stageNode.style.visibility).toBe('hidden'); + expect(stage.sceneIsPlaying).toBe(false); + }); + }); + + // This test guards against possible leftover state. + // In particular, a previous bug made a stopped stage appear to be fading out even though it was not. + it('plays scene again after immediate fade-out', function() { + var scene = new Ambience.Scene(['Image']); + scene.image.url = 'test-image.jpg'; + + stage.play(scene); + stage.fadeOut(); + stage.play(scene); + + expect(stage.opacity).toNotBe(0); + expect(stage.sceneIsPlaying).toBe(true); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010953_ArticleEditView.js b/pool/shard001/JavaScript/0010953_ArticleEditView.js new file mode 100644 index 0000000000000000000000000000000000000000..eecc42d010eab096710ad72df23a2a862a4ba456 --- /dev/null +++ b/pool/shard001/JavaScript/0010953_ArticleEditView.js @@ -0,0 +1,82 @@ +define([ + 'backbone', + 'marionette', + 'jquery', + + 'hbs!templates/articleedit', + 'editor', + 'views/ViewTools' +],function( + Backbone, + Marionette, + $, + + template, + editor, + tools +){ + + return Backbone.Marionette.Layout.extend( { + template: template, + className: 'article', + + events: { + "mousedown .editable" : "startEdit", + "change .upload" : "onUploadChange", + "click .cancel" : "exitEditMode", + "click .save" : "onSave" + }, + + startEdit: editor.editableInit, + + initialize: function() { + _.extend(editor.config.buttonClasses, { + 'default': [], + 'all': ['bold', 'italic', 'unordered-list', 'ordered-list', 'link', 'clear-formatting'] + }); + }, + + onShow: function(){ + tools.setPageTitle( 'Editing: ' + this.model.get('title') ); + }, + + onUploadChange: function(event){ + var file = event.currentTarget.files[0]; + + this.model.readFile(file); + }, + + exitEditMode: function(){ + Backbone.history.navigate('/news', {trigger: true}); + }, + + onSave: function(){ + this.storeEditable(); + + var self = this; + + this.$(':input').attr('disabled', 'disabled'); + + this.model.save({}, { + success: function(model, response){ + self.exitEditMode(); + }, + error: function(){ + alert("Error Saving!"); + self.$(':input').prop('disabled', false); + } + }); + }, + + storeEditable: function(){ + var self = this; + this.$('.editable').each(function(){ + var element = $(this); + self.model.set(element.data('attribute'), element.html()); + }); + } + + }); + + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010954_IndividualsSearchService.js b/pool/shard001/JavaScript/0010954_IndividualsSearchService.js new file mode 100644 index 0000000000000000000000000000000000000000..330503f09637509fc665175b8c7716aad8e7c4a4 --- /dev/null +++ b/pool/shard001/JavaScript/0010954_IndividualsSearchService.js @@ -0,0 +1,156 @@ +'use strict'; + +/** + * Created by caio on 28/12/15. + */ + +angular.module('birdaApp') + .service('IndividualsSearchService', ['$q', '$timeout', '$resource', 'ConfigService', 'UIService', + function($q, $timeout, $resource, ConfigService, UIService) { + + var self = this; + var config = ConfigService.getConf(); + + var params = null; + var results = []; + + var IndividualsSearch = $resource( + config.buildApiUri('/individuals-search'), + { + form_uri:'@form_uri', + lang:'@lang' + }, + { + search: {method:'POST'} + } + ); + + function init() { + self.clean(); + } + + /* ========================================= */ + + self.clean = function() { + params = { + 'properties': [], + 'filters': [], + 'order_by': [] + }; + clearObject(results); + }; + + /* ----------------------------------------- */ + + self.addProperty = function(property) { + if (results) { + console.log('IndividualsSearchService: Warning: altering params in a not cleaned status'); + } + if ( (typeof property !== 'object') || (property === null) ) { + throw Error('IndividualsSearchService: "property" should be a not null object'); + } + if ( ! ('uri' in property) ) { + throw Error('IndividualsSearchService: "property" should have a "uri" property'); + } + + params.properties.push(property); + }; + + self.addFilter = function(filter) { + if (results) { + console.log('IndividualsSearchService: Warning: altering params in a not cleaned status'); + } + if ( (typeof filter !== 'object') || (filter === null) ) { + throw Error('IndividualsSearchService: "filter" should be a not null object'); + } + if ( ! ('property' in filter) ) { + throw Error('IndividualsSearchService: "filter" should have a "property" property'); + } + if ( ! ('value' in filter) ) { + throw Error('IndividualsSearchService: "filter" should have a "value" property'); + } + if ( ! ('match' in filter) ) { + throw Error('IndividualsSearchService: "filter" should have a "match" property'); + } + + params.filters.push(filter); + }; + + self.addOrderBy = function(orderBy) { + if (results) { + console.log('IndividualsSearchService: Warning: altering params in a not cleaned status'); + } + if ( (typeof orderBy !== 'object') || (orderBy === null) ) { + throw Error('IndividualsSearchService: "orderBy" should be a not null object'); + } + if ( ! ('property' in orderBy) ) { + throw Error('IndividualsSearchService: "orderBy" should have a "property" property'); + } + if ( ! ('order' in orderBy) ) { + throw Error('IndividualsSearchService: "orderBy" should have a "order" property'); + } + + params.order_by.push(orderBy); + }; + + /* ----------------------------------------- */ + + self.search = function(form_uri) { + + if (config.dummyData) { + clearObject(results); + var defer = $q.defer(); + + // simulated async function + $timeout(function() { + angular.extend(results, getDummyResults()); + defer.resolve(results); + console.log('Results: ', results); + }, config.dummyWaitTime); + + return defer.promise; + + } else { + + results = IndividualsSearch.search({ + lang: config.lang, + form_uri: form_uri + }, params); + + console.log("Results: ",results); + + results.$promise.then( + function(response) { + console.log('Results: ', response); + }, + UIService.notifyError); + + return results.$promise; + } + + }; + + /* ----------------------------------------- */ + + self.getResults = function() { + console.log(results); + return results; + }; + + /* ----------------------------------------- */ + + function getDummyResults() { + assert( + ((params.properties.length === 0) && + (params.filters[0].property === RDF_TYPE))); + + //console.log(dummy_jsons.test_individuals_search_results, 'value', params.filters[0].value); + return dummy_jsons.test_individuals_search_results[params.filters[0].value]; + + } + + /* ========================================= */ + + init(); + + }]); diff --git a/pool/shard001/JavaScript/0010956_index.js b/pool/shard001/JavaScript/0010956_index.js new file mode 100644 index 0000000000000000000000000000000000000000..9433972f5675486e863051aa2da3b1799c26c1ab --- /dev/null +++ b/pool/shard001/JavaScript/0010956_index.js @@ -0,0 +1,120 @@ +/* eslint no-console: [ 'error', { allow: [ 'error' ] } ] */ + +/** + * External dependencies. + */ +import { createHigherOrderComponent, compose } from '@wordpress/compose'; +import { withDispatch, withSelect } from '@wordpress/data'; +import { withEffects } from 'refract-callbag'; +import { __, sprintf } from '@wordpress/i18n'; +import { + has, + find, + some, + every, + isEmpty +} from 'lodash'; + +/** + * Internal dependencies. + */ +import compare from './compare'; + +/** + * Creates a high-order components which adds ability to evalute + * the conditional logic of fields. + * + * @param {Function} input + * @param {Function} output + * @return {Function} + */ +export default function withConditionalLogic( input, output ) { + /** + * The function that controls the stream of side-effects. + * + * @param {Object} component + * @param {Object} props + * @return {Object} + */ + function aperture( component, props ) { + if ( isEmpty( props.field.conditional_logic ) ) { + return; + } + + return input( props, component ); + } + + /** + * The function that causes the side effects. + * + * @param {Object} props + * @return {Function} + */ + function handler( props ) { + return function( effect ) { + const fieldExists = has( effect, props.name ) || find( effect, [ 'id', props.id ] ); + + if ( ! fieldExists ) { + return; + } + + const { relation, rules } = props.field.conditional_logic; + const data = output( props, effect ); + + const results = rules.reduce( ( accumulator, rule ) => { + if ( ! has( data, rule.field ) ) { + // eslint-disable-next-line + console.error( + sprintf( + __( 'An unknown field is used in condition - "%s"', 'carbon-fields-ui' ), + rule.field + ) + ); + + return accumulator.concat( false ); + } + + // TODO: Handle the conditional logic for chained fields. Probably we'll need the id of each sibling. + // See https://github.com/htmlburger/carbon-fields/commit/3628a86c8840c8323f45c829a96c512a9985ad10#diff-b1aea524a4b1ab510e28e01a54c25fcd + const result = compare( data[ rule.field ], rule.compare, rule.value ); + + return accumulator.concat( result ); + }, [] ); + + let isVisible = false; + + switch ( relation ) { + case 'AND': + isVisible = every( results ); + break; + + case 'OR': + isVisible = some( results ); + break; + } + + if ( isVisible ) { + props.showField( props.id ); + } else { + props.hideField( props.id ); + } + }; + } + + return createHigherOrderComponent( ( OriginalComponent ) => { + return compose( + withDispatch( ( dispatch ) => { + const { showField, hideField } = dispatch( 'carbon-fields/core' ); + + return { + showField, + hideField + }; + } ), + withSelect( ( select, props ) => ( { + visible: select( 'carbon-fields/core' ).isFieldVisible( props.id ) + } ) ), + withEffects( aperture, { handler } ) + )( OriginalComponent ); + }, 'withConditionalLogic' ); +} diff --git a/pool/shard001/JavaScript/0010959_problemHistory.js b/pool/shard001/JavaScript/0010959_problemHistory.js new file mode 100644 index 0000000000000000000000000000000000000000..94b4bfc98a0dc3ab4a525eaeaca071e4851a09ef --- /dev/null +++ b/pool/shard001/JavaScript/0010959_problemHistory.js @@ -0,0 +1,14 @@ +function historyGraphLineChart(cell, response) { + cell.style.display = 'block'; + cell.parentNode.style.display = 'block'; + cell.innerHTML = response; + + var data = $('#errorTrendMeta', cell).text(); + graphLineChart($('#errorTrend', cell)[0], eval('(' + data + ')')); + + data = $('#distributionChartMeta', cell).text(); + + if (data != null && data.length > 0) { + graphPieChart($('#distributionChart', cell)[0], eval('(' + data + ')')); + } +} diff --git a/pool/shard001/JavaScript/0010963_init-scales.js b/pool/shard001/JavaScript/0010963_init-scales.js new file mode 100644 index 0000000000000000000000000000000000000000..36134d8887b692cd046247a099a3ae03e4c1ea49 --- /dev/null +++ b/pool/shard001/JavaScript/0010963_init-scales.js @@ -0,0 +1,191 @@ +/* Copyright 2022 Google LLC. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + + +window.initScales = function(){ + var sel = d3.select('#image-container').html('') + + var diverging = 'BrBG PRGn PiYG PuOr RdBu RdGy RdYlBu RdYlGn Spectral'.split(' ') + var sequential = 'Turbo Viridis Custom Inferno Magma Plasma Cividis Warm Cool CubehelixDefault Rainbow Sinebow'.split(' ') + var boring = 'Blues Greens Greys Oranges Purples'.split(' ') + + var allScales = sequential.concat(diverging).concat(boring) + + var scales = window.scales || allScales//.slice(0, 4) + .map((d, i) => ({interpolate: d3['interpolate' + d], name: d, i})) + + // var scales = 'Turbo'.split(' ') + // .map(d => ({interpolate: d3['interpolate' + d], name: d})) + + var {width, height} = image + var {nSamples} = config + + var scaleSel = sel + .append('div').st({width: width*2 + 50}) + .appendMany('div', scales).each(drawScale).st({display: 'inline-block'}) + + function drawScale(scale){ + + scale.offScreen = false + scale.dirty = false + + var observer = new IntersectionObserver((entries, observer) => { + var prevOffScreen = scale.offScreen + scale.offScreen = !entries[0].isIntersecting + + if (prevOffScreen && !scale.offScreen) scale.update() + }) + observer.observe(this) + + var sel = d3.select(this).html('') + .st({position: 'relative'}) + .on('click', function(){ + scale.setAsActive() + }) + + scale.setAsActive = () => { + scales.active = scale + exportCode.update(scale) + scaleSel.selectAll('.code-button').classed('active', d => d == scale) + } + + var selectSel = sel.append('select') + .st({position: 'absolute', top: 3, left: 4, zIndex: 100, fontSize: 14}) + .on('change', () => { + var name = selectSel.parent().node().value + var {i, invert} = scale + var newScale = {interpolate: d3['interpolate' + name], name, i, invert} + scales[scale.i] = newScale + + drawScale.call(this, newScale) + newScale.update() + }) + .appendMany('option', allScales) + .text(d => d) + .at({value: d => d}) + .property('selected', d => d == scale.name) + + var invertSel = sel.append('div.button.invert') + .st({position: 'absolute', top: 0, left: 140, zIndex: 100}) + .text('invert') + .classed('inverted', scale.invert) + .on('click', () => { + scale.invert = !scale.invert + drawScale.call(this, scale) + scale.update() + }) + + var ctx = sel.append('canvas') + .at({width: width, height: height}) + .st({width, height, marginRight: 5, position: 'relative', paddingTop: 22*0, paddingBottom: 5*0}) + .node().getContext('2d') + + ctx.fillRect(0, 0, width, height) + var imageDataRaw = ctx.getImageData(0, 0, width, height) + + if (!scale.interpolate){ + scale.samples = custom.samples.slice() + } else { + scale.samples = d3.range(nSamples) + .map(d => scale.interpolate(d/(nSamples - 1))) + .map(d3.color) + .map(d => [d.r, d.g, d.b]) + } + + if (scale.invert) scale.samples.reverse() + + scale.samples[nSamples] = [255, 255, 255] + scale.samples[nSamples + 1] = [255, 255, 255] + + scale.update = () => { + if (scale.offScreen) return scale.dirty = true + + var [e0, e1] = brush.domain + imageData = imageDataRaw.data + + var samples = scale.samples + + for (var i = 0; i < imageData.length/4 && i < transform.data.length; i++){ + var colorIndex = Math.round((transform.data[i] - e0)/(e1 - e0)*nSamples) + + if (colorIndex == Infinity){ + colorIndex = nSamples + } else if (colorIndex == -Infinity) { + colorIndex = nSamples + 1 + } else if (colorIndex < 0){ + colorIndex = 0 + } else if (colorIndex >= nSamples){ + colorIndex = nSamples - 1 + } + + imageData[i*4 + 0] = samples[colorIndex][0] + imageData[i*4 + 1] = samples[colorIndex][1] + imageData[i*4 + 2] = samples[colorIndex][2] + } + + ctx.putImageData(imageDataRaw, 0, 0) + } + + var svg = sel.append('svg') + .at({width, height}) + .st({position: 'absolute', top: 0, left: 0}) + + svg.append('rect').at({width, height, opacity: 0}) + + var rectSel = svg.append('rect') + .at({stroke: '#f0f', fill: 'none'}) + + var start = {} + var drag = d3.drag() + .filter(() => d3.event.shiftKey) // only shift + .on('start', () => { + start = d3.event; rectSel.at({opacity: 1, width: 0, height: 0}) + }) + .on('drag', () => { + var x = Math.min(d3.event.x, start.x) + var y = Math.min(d3.event.y, start.y) + var width = Math.abs(d3.event.x - start.x) + 1 + var height = Math.abs(d3.event.y - start.y) + 1 + rectSel.at({x, y, width, height}) + + var extent = d3.extent(transform.data.filter((d, i) => { + var px = i % image.width + var py = Math.floor(i / image.width) + + return x <= px && px <= (width + x )&& y <= py && py <= (height + y) + })) + + brush.setDomain(extent) + + }) + .on('end', () => rectSel.at({opacity: 0})) + + svg.call(drag) + } + + window.scales = scales + scales[0].setAsActive() + + scales.update = _.throttle(() => scales.forEach(d => d.update()), 0) + scales.update = () => { + scales.forEach(d => d.update()) + + exportCode.update() + } + return scales +} + + +if (window.init) init() diff --git a/pool/shard001/JavaScript/0010964_debug.enabled.spec.js b/pool/shard001/JavaScript/0010964_debug.enabled.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..ad92d461694885ea5f23504306332a569c049aa3 --- /dev/null +++ b/pool/shard001/JavaScript/0010964_debug.enabled.spec.js @@ -0,0 +1,25 @@ +import noop from "utils/noop"; +import { debuggingSupported, logDispatch, logDispatchSubscriptions } from "utils/debug"; + +let logStack = []; + +global.console = { + log: (...args) => logStack.push(args), + debug: (...args) => logStack.push(args), + group: (...args) => logStack.push(args), + groupEnd: () => logStack.push(">>EOF"), + groupCollapsed: (...args) => logStack.push(args) +}; + +beforeEach(() => { + logStack = []; +}); + +describe("utils", () => { + describe("debug (enabled)", () => { + it.skip("should detect internal debugging support", () => { + expect(debuggingSupported).toEqual(true); + expect(global.console).toBeTruthy(); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0010967_index.js b/pool/shard001/JavaScript/0010967_index.js new file mode 100644 index 0000000000000000000000000000000000000000..912002ae1710396cc2cf1e34f93d06dcdf19cf8a --- /dev/null +++ b/pool/shard001/JavaScript/0010967_index.js @@ -0,0 +1,45 @@ +//if 'steps' is not specified, we'll just approximate it +module.exports = function arc(x, y, radius, start, end, clockwise, steps, path) { + if (!path) + path = [] + + x = x||0 + y = y||0 + radius = radius||0 + start = start||0 + end = end||0 + + //determine distance between the two angles + //...probably a nicer way of writing this + var dist = Math.abs(start-end) + if (!clockwise && start > end) + dist = 2*Math.PI - dist + else if (clockwise && end > start) + dist = 2*Math.PI - dist + + //approximate the # of steps using the cube root of the radius + if (typeof steps !== 'number') + steps = Math.max(6, Math.floor(6 * Math.pow(radius, 1/3) * (dist / (Math.PI)))) + + //ensure we have at least 3 steps.. + steps = Math.max(steps, 3) + + var f = dist / (steps), + t = start + + //modify direction + f *= clockwise ? -1 : 1 + + for (var i=0; i 0 && moveInDate > moveOutDate) return false + /* + In all other cases, i.e + 1) if the moveOut date is not specified or + 2) it is a date greater than move in date, it returns true */ + return true +} + +export const ResidenciesCollection = Residencies diff --git a/pool/shard001/JavaScript/0010974_Form.js b/pool/shard001/JavaScript/0010974_Form.js new file mode 100644 index 0000000000000000000000000000000000000000..3f313399cc1960847fdd3c1bc26a9e1759338f5c --- /dev/null +++ b/pool/shard001/JavaScript/0010974_Form.js @@ -0,0 +1,86 @@ +import React, { Component, PropTypes } from 'react'; +import InjectAutocomplete from '../autocomplete/Autocomplete.js'; +import InjectButton from '../button/Button.js'; +import InjectCheckbox from '../checkbox/Checkbox.js'; +import InjectDatePicker from '../date_picker/DatePicker.js'; +import InjectDropdown from '../dropdown/Dropdown.js'; +import InjectInput from '../input/Input.js'; +import InjectRadioGroup from '../radio/RadioGroup.js'; +import InjectSlider from '../slider/Slider.js'; +import InjectSwitch from '../switch/Switch.js'; +import InjectTimePicker from '../time_picker/TimePicker.js'; + +const factory = ( + Autocomplete, Button, Checkbox, DatePicker, Dropdown, + Input, RadioGroup, Slider, Switch, TimePicker + ) => { + + const COMPONENTS = { + 'autocomplete': Autocomplete, + 'button': Button, + 'checkbox': Checkbox, + 'datepicker': DatePicker, + 'dropdown': Dropdown, + 'input': Input, + 'radioGroup': RadioGroup, + 'slider': Slider, + 'switch': Switch, + 'timepicker': TimePicker + }; + + class Form extends Component { + static propTypes = { + attributes: PropTypes.array, + children: PropTypes.node, + className: PropTypes.string, + model: PropTypes.object, + onChange: PropTypes.func, + onError: PropTypes.func, + onSubmit: PropTypes.func, + onValid: PropTypes.func, + storage: PropTypes.string + }; + + static defaultProps = { + attributes: [], + className: '' + }; + + onSubmit = (event) => { + event.preventDefault(); + if (this.props.onSubmit) this.props.onSubmit(event); + }; + + onChange = (field, value, event) => { + if (this.props.onChange) this.props.onChange(field, value, event); + }; + + renderFields () { + return Object.keys(this.props.model).map((field, index) => { + const properties = this.props.model[field]; + const Field = COMPONENTS[properties.kind.toLowerCase()]; + return ; + }); + } + + render () { + return ( +
    + {this.renderFields()} + {this.props.children} +
    + ); + } + } + + return Form; +}; + +const Form = factory( + InjectAutocomplete, InjectButton, InjectCheckbox, InjectDatePicker, InjectDropdown, + InjectInput, InjectRadioGroup, InjectSlider, InjectSwitch, InjectTimePicker +); + +export default Form; +export { factory as formFactory }; +export { Form }; diff --git a/pool/shard001/JavaScript/0010976_test.js b/pool/shard001/JavaScript/0010976_test.js new file mode 100644 index 0000000000000000000000000000000000000000..b38a21d0eb45af12e429b1ff111ceb73e8cac0f5 --- /dev/null +++ b/pool/shard001/JavaScript/0010976_test.js @@ -0,0 +1,116 @@ +/*! + * make-callback + * + * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk) + * Released under the MIT license. + */ + +/* jshint asi:true */ + +'use strict' + +var fs = require('fs') +var test = require('assertit') +var makeCallback = require('./index') + +test('make-callback:', function () { + test('should throw TypeError "is-async-function expect a function"', function (done) { + function fixture () { + makeCallback(12345) + } + + test.throws(fixture, TypeError) + test.throws(fixture, /is-async-function expect a function/) + done() + }) + test('should throw TypeError "make-callback expect sync function', function (done) { + function fixture () { + makeCallback(fs.readFile) + } + + test.throws(fixture, TypeError) + test.throws(fixture, /make-callback expect sync function/) + done() + }) + test('should throw TypeError "async `fn` expect a callback"', function (done) { + function fixture () { + var JSONParseAsync = makeCallback(JSON.parse) + JSONParseAsync('{"foo":"bar"}') + } + + test.throws(fixture, TypeError) + test.throws(fixture, /async `fn` expect a callback/) + done() + }) + test('should pass result to callback', function (done) { + var JSONParseAsync = makeCallback(JSON.parse) + + JSONParseAsync('{"foo":"bar"}', function (err, res) { + test.ifError(err) + test.deepEqual(res, {foo: 'bar'}) + done() + }) + }) + test('should pass error to callback', function (done) { + var JSONParseAsync = makeCallback(JSON.parse) + + JSONParseAsync('foo bar baz', function (err) { + test.ok(err) + test.ifError(!err) + test.equal(err.message, 'Unexpected token o') + done() + }) + }) + test('should pass contents of file to callback (when readFileSync)', function (done) { + var readFile = makeCallback(fs.readFileSync) + + readFile('./package.json', 'utf8', function (err, res) { + test.ifError(err) + test.ok(res.indexOf('tunnckoCore/make-callback') !== -1) + done() + }) + }) + test('should pass errors to callback (when readFileSync)', function (done) { + var readFile = makeCallback(fs.readFileSync) + + readFile('./packdsgfdfgdfgage.json', 'utf8', function (err, res) { + test.ifError(!err) + test.equal(err.code, 'ENOENT') + test.ok(err.message.indexOf('no such file') !== -1) + done() + }) + }) + test('should support generators (transform generator to callback)', function (done) { + function * gen (val) { + var a = yield 'a' + var b = yield {b: 'b'} + var c = yield ['c', 'f'] + var d = yield 123 + return [a, b, c, d, val || 'foobar'] + } + + var genCallback = makeCallback(gen) + genCallback(function (err, res) { + test.ifError(err) + test.equal(res.length, 5) + test.deepEqual(res, ['a', {b: 'b'}, ['c', 'f'], 123, 'foobar']) + done() + }) + }) + test('should handle error in callback if generator throws', function (done) { + function * gen (val) { + yield 'a' + yield val + + throw new Error('yeah') + } + + var genCallback = makeCallback(gen) + genCallback(123, function (err, res) { + test.ifError(!err) + test.equal(err.message, 'yeah') + test.equal(res, undefined) + done() + }) + }) +}) diff --git a/pool/shard001/JavaScript/0010977_invoke.js b/pool/shard001/JavaScript/0010977_invoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c65c6af816b4dde83c4548557b5f74d750611145 --- /dev/null +++ b/pool/shard001/JavaScript/0010977_invoke.js @@ -0,0 +1,95 @@ +// 'invoke' - Promise extension +// +// promise.invoke(name[, arg0[, arg1[, ...]]]) +// +// On resolved object calls method that returns immediately. +// 'name' can be method name or method itself. + +'use strict'; + +var isCallable = require('es5-ext/object/is-callable') + , deferred = require('../../deferred') + , isPromise = require('../../is-promise') + , processArguments = require('../_process-arguments') + + , slice = Array.prototype.slice, apply = Function.prototype.apply + , reject = deferred.reject + , applyFn; + +applyFn = function (fn, args, resolve, reject) { + var value; + try { + value = apply.call(fn, this, args); + } catch (e) { + return reject(e); + } + return resolve(value); +}; + +deferred.extend('invoke', function (method/*, …args*/) { + var def; + if (!this.pending) this.pending = []; + def = deferred(); + this.pending.push('invoke', [arguments, def.resolve, def.reject]); + return def.promise; +}, function (args, resolve, reject) { + var fn; + if (this.failed) { + reject(this.value); + return; + } + + if (this.value == null) { + reject(new TypeError("Cannot use null or undefined")); + return; + } + + fn = args[0]; + if (!isCallable(fn)) { + fn = String(fn); + if (!isCallable(this.value[fn])) { + reject(new TypeError(fn + " is not a function")); + return; + } + fn = this.value[fn]; + } + + args = processArguments(slice.call(args, 1)); + if (isPromise(args)) { + if (args.failed) { + reject(args.value); + return; + } + args.done(function (args) { + applyFn.call(this, fn, args, resolve, reject); + }.bind(this.value), reject); + } else { + applyFn.call(this.value, fn, args, resolve, reject); + } +}, function (method/*, …args*/) { + var args, def; + if (this.failed) return this; + + if (this.value == null) { + return reject(new TypeError("Cannot use null or undefined")); + } + + if (!isCallable(method)) { + method = String(method); + if (!isCallable(this.value[method])) { + return reject(new TypeError(method + " is not a function")); + } + method = this.value[method]; + } + + args = processArguments(slice.call(arguments, 1)); + if (isPromise(args)) { + if (args.failed) return args; + def = deferred(); + args.done(function (args) { + applyFn.call(this, method, args, def.resolve, def.reject); + }.bind(this.value), def.reject); + return def.promise; + } + return applyFn.call(this.value, method, args, deferred, reject); +}); diff --git a/pool/shard001/JavaScript/0010981_ext.translate.pagemode.js b/pool/shard001/JavaScript/0010981_ext.translate.pagemode.js new file mode 100644 index 0000000000000000000000000000000000000000..8f665a3314a997aaacbb039ba1f9017b6a6d6280 --- /dev/null +++ b/pool/shard001/JavaScript/0010981_ext.translate.pagemode.js @@ -0,0 +1,130 @@ +( function ( $, mw ) { + 'use strict'; + /** + * Page mode plugin + * + * Prepare the page mode UI with all the required actions + * for a translation unit (message). + * This is mainly used with the messagetable plugin in page mode, + * but it is independent of messagetable. + * Example usage: + * + * $( 'div.pagemode' ).pagemode( { + * message: messageObject, // Mandatory message object + * sourcelangcode: 'en', // Mandatory source language code + * targetlangcode: 'hi' // Mandatory target language code + * } ); + */ + function PageMode( element, options ) { + this.$message = $( element ); + this.options = options; + this.message = this.options.message; + this.init(); + this.listen(); + } + + PageMode.prototype = { + + /** + * Initialize the plugin + */ + init: function () { + var pagemode = this; + + this.render(); + + pagemode.$message.translateeditor( { + message: pagemode.message, + beforeSave: function ( translation ) { + pagemode.$message.find( '.tux-pagemode-translation' ) + .html( mw.translate.formatMessageGently( translation || '', pagemode.message.key ) ) + .addClass( 'highlight' ); + }, + onSave: function ( translation ) { + pagemode.$message.find( '.tux-pagemode-translation' ) + .removeClass( 'highlight' ); + pagemode.message.translation = translation; + + pagemode.$message.find( '.tux-pagemode-status' ) + .removeClass( 'translated fuzzy proofread untranslated' ) + .addClass( pagemode.message.properties.status ); + } + } ); + + }, + + render: function () { + var targetLangAttrib, targetLangDir, + sourceLangDir = $.uls.data.getDir( this.options.sourcelangcode ); + + if ( this.options.targetlangcode === + mw.config.get( 'wgTranslateDocumentationLanguageCode' ) + ) { + targetLangAttrib = mw.config.get( 'wgContentLanguage' ); + } else { + targetLangAttrib = this.options.targetlangcode; + } + + targetLangDir = $.uls.data.getDir( targetLangAttrib ); + + this.$message.append( + $( '
    ' ) + .addClass( 'row tux-message-item-compact message ' + this.message.properties.status ) + .append( + $( '
    ' ) + .addClass( 'one column tux-pagemode-status ' + this.message.properties.status ), + $( '
    ' ) + .addClass( 'five columns tux-pagemode-source' ) + .attr( { + lang: this.options.sourcelangcode, + dir: sourceLangDir + } ) + .html( mw.translate.formatMessageGently( this.message.definition, this.message.key ) ), + $( '
    ' ) + .addClass( 'five columns tux-pagemode-translation' ) + .attr( { + lang: targetLangAttrib, + dir: targetLangDir + } ) + .html( mw.translate.formatMessageGently( this.message.translation || '', this.message.key ) ), + $( '
    ' ) + .attr( 'title', mw.msg( 'translate-edit-title', this.message.key ) ) + .addClass( 'tux-pagemode-edit' ) + ) + ) + + .addClass( this.message.properties.status ); + }, + + /** + * Attach event listeners + */ + listen: function () { + var pagemode = this; + + this.$message.children( '.message' ).on( 'click', function ( e ) { + pagemode.$message.data( 'translateeditor' ).show(); + e.preventDefault(); + } ); + } + }; + + /* + * pagemode PLUGIN DEFINITION + */ + $.fn.pagemode = function ( options ) { + return this.each( function () { + var $this = $( this ), + data = $this.data( 'pagemode' ); + + if ( !data ) { + $this.data( 'pagemode', + ( data = new PageMode( this, options ) ) + ); + } + + } ); + }; + + $.fn.pagemode.Constructor = PageMode; +}( jQuery, mediaWiki ) ); diff --git a/pool/shard001/JavaScript/0010983_viewmodel.js b/pool/shard001/JavaScript/0010983_viewmodel.js new file mode 100644 index 0000000000000000000000000000000000000000..e62141f4a70c0fe7864472cd9f30936c273e9209 --- /dev/null +++ b/pool/shard001/JavaScript/0010983_viewmodel.js @@ -0,0 +1,142 @@ +var Viewmodel = function () { + var self = this; + + var dummyEpisode = { + slides: [ + new Slide("", "", "", [ + new Item("") + ]) + ] + }; + + this.episodeIndex = 0; + + this.mode = ko.observable(GameModes["title"]); + + this.mode.subscribe(function (v) { + if ([GameModes.game, GameModes.title].indexOf(v) > -1) { + self.isLoading(true); + setTimeout(function () { + self.isLoading(false); + }, 5000); + } + }); + + this.isLoading = ko.observable(false); + + this.characters = ko.observableArray([ + { + name: "Vim user", + description: "Works with the world's most popular text-editor and dares to remember weird shortcuts.

    Gets annoyed when in proximity of Emacs users." + }, + { + name: "Sublime Text user", + description: "Habitual of a tabbed interface with a mini-map towards the right of the editor.

    Customizes shortcuts, chains them to perform complex operations from quickly.

    Works within a graphical interface." + }, + { + name: "Notepad++ user", + description: "Had been using Notepad on Microsoft Windows until came across Notepad++ that is free, efficient editor that also maintains an undo history.

    Does not care about the editor he/she works with as far as it retains the comfort level of Notepad." + } + ]); + + this.episode = ko.observable(dummyEpisode); + + this.currentSlide = ko.observable(this.episode().slides[0]); + + this.nextQuest = ko.computed(function () { + var currentSlideIndex = self.episode().slides.indexOf(self.currentSlide()), + nextSlide = self.episode().slides[currentSlideIndex + 1]; + + return nextSlide ? + nextSlide.objective : + ""; + }); + + // Stats + + this.stats = { + character: ko.observable(self.characters()[0]), + health: ko.observable(100), + mana: ko.observable(100) + }; + + this.experience = { + level: ko.observable(self.episodeIndex), + progress: ko.computed(function () { + var watchedSlides = self.episode().slides.filter(function (s) { + return s.items.filter(function (t) { + return t.state(); + }).length === s.items.length; + }).length; + + return watchedSlides * 100 / self.episode().slides.length; + }) + }; + + this.experience.progress.subscribe(function (v) { + if (v >= 100) { + self.experience.level(self.episodeIndex + 1); + } else { + self.experience.level(self.episodeIndex); + } + }); + + // Messages + + this.isLevelComplete = ko.computed(function () { + return self.episode().slides.filter(function (s) { + return !s.isComplete(); + }).length === 0; + }); + + this.isLevelUp = ko.computed(function () { + return self.experience.level() > self.episodeIndex; + }); + + this.shouldShowObjectiveCompleteMessage = ko.computed(function () { + return self.currentSlide().isComplete(); + }); + + // Methods + + this.reset = function () { + self.mode(GameModes["title"]); + + self.episode().slides.forEach(function (s) { + s.items.forEach(function (t) { + t.state(false); + }); + }); + + self.episode(dummyEpisode); + self.currentSlide(self.episode().slides[0]); + }; + + this.startEpisode = function (index) { + self.episodeIndex = index; + self.experience.level(index); + self.episode(episodes[index]); + self.currentSlide(self.episode().slides[0]); + self.mode(GameModes["game"]); + }; + + this.moveToNext = function () { + var isCurrentSlideOver = self.currentSlide().items.filter(function (t) { + return t.state(); + }).length === self.currentSlide().items.length; + + if (isCurrentSlideOver) { + // Move to next slide + var currentItemIndex = self.episode().slides.indexOf(self.currentSlide()); + + self.currentSlide(self.episode().slides[currentItemIndex + 1]); + } else { + // Move to the next item in current slide + var nextItem = self.currentSlide().items.filter(function (t) { + return !t.state(); + })[0]; + + nextItem.state(true); + } + }; +}; diff --git a/pool/shard001/JavaScript/0010984_Plot.js b/pool/shard001/JavaScript/0010984_Plot.js new file mode 100644 index 0000000000000000000000000000000000000000..2f5ae40a244fbf2f26fec3505bacb00ee3a9bedf --- /dev/null +++ b/pool/shard001/JavaScript/0010984_Plot.js @@ -0,0 +1,114 @@ +function drawPlot(div_name, get_path, xlabel, ylabel, yscale_0_1) { + + var color = 'black'; + + var plot = $('#' + div_name)[0]; + while (plot.firstChild) { + plot.removeChild(plot.firstChild); + } + + var margin = {top: 20, right: 20, bottom: 30, left: 40}; + var width = 300 - margin.left - margin.right; + var height = 300 - margin.top - margin.bottom; + + var svg = d3.select('#' + div_name).append('svg') + .attr('width', width + margin.left + margin.right) + .attr('height', height + margin.top + margin.bottom) + .append('g') + .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); + + d3.csv(get_path(), function(error, data) { + + // change string (from CSV) into number format + data.forEach(function(d) { + d.x = +d.x; + d.y = +d.y; + }); + + var xValue = function(d) { return d.x;}; + var xScale = d3.scale.linear().range([0, width]); + var xMap = function(d) { return xScale(xValue(d));}; + var xAxis = d3.svg.axis().scale(xScale).orient('bottom'); + xScale.domain(d3.extent(data, function(d) {return d.x} )); + + var yValue = function(d) { return d.y;}; + var yScale = d3.scale.linear().range([height, 0]); + var yMap = function(d) { return yScale(yValue(d));}; + var yAxis = d3.svg.axis().scale(yScale).orient('left'); + if (yscale_0_1()) { + yScale.domain([0,1]); + } else { + yScale.domain(d3.extent(data, function(d) {return d.y} )); + } + + // x-axis + svg.append('g') + .attr('class', 'x axis') + .attr('transform', 'translate(0,' + height + ')') + .call(xAxis) + .append('text') + .attr('class', 'label') + .attr('x', width) + .attr('y', -6) + .style('text-anchor', 'end') + .text(xlabel); + + // y-axis + svg.append('g') + .attr('class', 'y axis') + .call(yAxis) + .append('text') + .attr('class', 'label') + .attr('transform', 'rotate(-90)') + .attr('y', 6) + .attr('dy', '.71em') + .style('text-anchor', 'end') + .text(ylabel); + + // draw dots + svg.selectAll('.dot') + .data(data) + .enter().append('circle') + .attr('class', 'dot') + .attr('r', 2) + .attr('cx', xMap) + .attr('cy', yMap) + .style('fill', color) + .style('stroke', color) + .on('mouseover', function(d) { + tooltip.transition() + .duration(200) + .style('opacity', .9); + tooltip.html(d.y + '
    ') + .style('left', (d3.event.pageX + 5) + 'px') + .style('top', (d3.event.pageY - 28) + 'px') + .style('color', 'red'); + }) + .on('mouseout', function(d) { + tooltip.transition() + .duration(500) + .style('opacity', 0); + }); + + // draw lines between dots + var valueline = d3.svg.line() + .x(xMap) + .y(yMap) + .interpolate('linear'); + svg.append('path') + .attr('d', valueline(data)) + .attr('stroke', color) + .attr('stroke-width', 2) + .attr('fill', 'none'); + + }); +} + +function addCallBackOnPlotSelectList(div_name, get_path, + select_list_name, xlabel, ylabel, get_yscale_0_1) { + var select_list = $('#' + select_list_name)[0]; + select_list.addEventListener('change', function() { + drawPlot(div_name, get_path, xlabel, ylabel, get_yscale_0_1); + }); + drawPlot(div_name, get_path, xlabel, ylabel, get_yscale_0_1); +} diff --git a/pool/shard001/JavaScript/0010985_SelectTemplate.js b/pool/shard001/JavaScript/0010985_SelectTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..6a2cf3d1e912bfc3b90bad6317e447921e38ab7e --- /dev/null +++ b/pool/shard001/JavaScript/0010985_SelectTemplate.js @@ -0,0 +1,52 @@ +/** + * Copyright Intermesh + * + * This file is part of Group-Office. You should have received a copy of the + * Group-Office license along with Group-Office. See the file /LICENSE.TXT + * + * If you have questions write an e-mail to info@intermesh.nl + * + * @version $Id: SelectTemplate.js + * @copyright Copyright Intermesh + * @author Wilmar van Beusekom + */ + +GO.projects2.SelectTemplate = Ext.extend(GO.form.ComboBox, { + initComponent : function(){ + + if(!this.hiddenName) + this.hiddenName='template_id'; + + Ext.apply(this, { + fieldLabel: GO.projects2.lang.template, + store:GO.projects2.templatesStore, + valueField:'id', + displayField:'name', + mode: 'local', + triggerAction: 'all', + editable: false, + selectOnFocus:true, + forceSelection: true, + disabled: !GO.settings.modules.projects2.write_permission + }); + }, + setValue : function(v){ + GO.form.ComboBox.superclass.setValue.call(this, v); + if(this.rendered) + { + //this.triggers[0].setDisplayed(v!=''); + } + }, + afterRender:function(){ + GO.form.ComboBox.superclass.afterRender.call(this); + if(Ext.isIE8)this.el.setTop(1); + + if(!GO.projects2.templatesStore.loaded) + GO.projects2.templatesStore.load(); + + //this.on('resize', function(combo, adjWidth, adjHeight, rawWidth, rawHeight ){console.log(adjWidth);}, this); + } + }); + + +Ext.reg('pmselecttemplate', GO.projects2.SelectTemplate); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0010986_core.js b/pool/shard001/JavaScript/0010986_core.js new file mode 100644 index 0000000000000000000000000000000000000000..03f9abf56c13cad1d361788746dfaf1377aac0ec --- /dev/null +++ b/pool/shard001/JavaScript/0010986_core.js @@ -0,0 +1,59 @@ +function getMatchesSelector() { + choices = [ + Element.prototype.matches, + Element.prototype.mozMatchesSelector, + Element.prototype.webkitMatchesSelector, + Element.prototype.msMatchesSelector, + Element.prototype.oMatchesSelector, + ]; + for (var i = 0; i <= choices.length - 1; ++i) { + if (choices[i] !== undefined) { + return function(elem, selector) { + return choices[i].bind(elem, selector)(); + }; + }; + }; +} + +var matchesSelector = getMatchesSelector(); + +var $ = document.querySelector.bind(document); +var $$ = document.querySelectorAll.bind(document); + +function last(collection, i) { + if (i === undefined) + i = 1; + return collection[collection.length - i]; +} + +// Search upward from `elem` for an element matched by `selector`. +function $up(elem, selector) { + var target; + while (elem = elem.parentElement) { + if (matchesSelector(elem, selector)) { + return elem; + }; + }; + // Didn't find it: return undefined. +} + +function forEach(collection, f) { + for (var i = 0; i < collection.length; ++i) + f(collection[i]); +} + +function handle(selector, type, f) { + handler = function(elem) { + elem.addEventListener(type, f.bind(elem)); + } + + forEach($$(selector), handler); + + return handler; +} + +function parse(s) { + t = document.createElement('template'); + t.innerHTML = s; + return document.importNode(t.content.firstChild, true); +} diff --git a/pool/shard001/JavaScript/0010989_video_delete_all.js b/pool/shard001/JavaScript/0010989_video_delete_all.js new file mode 100644 index 0000000000000000000000000000000000000000..e6b87d76b4f2e5efebd4d7df648e9f0216047d89 --- /dev/null +++ b/pool/shard001/JavaScript/0010989_video_delete_all.js @@ -0,0 +1,49 @@ +var app_token = process.argv[2]; +var private_key = process.argv[3]; + +var Ziggeo = require("../index.js"); +var ZiggeoSdk = new Ziggeo(app_token, private_key); + +var video_to_delete = []; +var video_to_skip = 0; +console.log('Start fetching video tokens '); +indexRemoveVideo(0); +function indexRemoveVideo (skip) { + ZiggeoSdk.Videos.index({limit:100, skip: skip}, { + success: function (index) { + var video_counter = 0; + // console.log(data); + if (index.length > 0) { + for (var i = 0; i < index.length; ++i) { + video_to_delete.push(index[i].token); + } + video_to_skip += index.length; + indexRemoveVideo(video_to_skip); + }else{ + console.log("Video tokens fetched : "+video_to_delete.length); + deleteVideo(video_to_delete); + } + }, + failure: function (args, error) { + console.log("failed: " + error); + return false; + } + }); +} + +function deleteVideo (token_list) { + console.log('Start deleting '+token_list.length+' videos'); + var video_counter = 0; + for (var i = 0; i < token_list.length; i++) { + ZiggeoSdk.Videos.destroy(token_list[i],{ + success: function (result) { + // to show progress on the console until it's done. + video_counter += 1; + console.log('Deleted video '+video_counter+' of '+token_list.length+' videos'); + if (video_counter == token_list.length) { + console.log ('Deletion of all videos is completed.'); + } + } + }); + } +} diff --git a/pool/shard001/JavaScript/0010993_vkontakte.js b/pool/shard001/JavaScript/0010993_vkontakte.js new file mode 100644 index 0000000000000000000000000000000000000000..30fcdd3a0273419f7f4cd788aa6c43a7e4489edf --- /dev/null +++ b/pool/shard001/JavaScript/0010993_vkontakte.js @@ -0,0 +1,47 @@ +import Vkontakte from 'passport-vkontakte'; +import fetch from 'isomorphic-fetch'; + +export default (ctx, { Strategy }) => class VkontakteStrategy extends Strategy { + Strategy = Vkontakte.Strategy + type = 'vkontakte' + + async getProfile(passport) { //eslint-disable-line + console.log('getProfile', passport); + + const fields = [ + 'sex', + 'bdate', + 'city', + 'country', + 'photo_50', + 'photo_100', + 'photo_200', + 'photo_max_orig', + 'photo_max', + 'domain', + 'id', + 'about', + ]; + const res = await fetch(`https://api.vk.com/method/users.get?fields=${fields.join(',')}&access_token=${passport.token}&v=5`); + const json = await res.json(); + const data = json.response[0]; + return { + firstName: data.first_name, + lastName: data.last_name, + gender: data.sex === 1 ? 'female' : 'male', + photos: [ + data.photo_50, + data.photo_100, + data.photo_200, + data.photo_max, + data.photo_max_orig, + ], + domain: data.domain, + about: data.about, + bdate: data.bdate, + avatar: data.photo_200, + city: data.city, + country: data.country, + }; + } +}; diff --git a/pool/shard001/JavaScript/0010997_tests-stress.js b/pool/shard001/JavaScript/0010997_tests-stress.js new file mode 100644 index 0000000000000000000000000000000000000000..9cb5ec3bd3c53578df1f434b7239e5de1cd2581c --- /dev/null +++ b/pool/shard001/JavaScript/0010997_tests-stress.js @@ -0,0 +1,19 @@ +var loadtest = require('loadtest'); +var expect = require('chai').expect; + +suite('Stress tests', function(){ + + test('Homepage should handle 50 requests in under a second', function(done){ + var options = { + url: 'http://localhost:3000', + concurrency: 4, + maxRequests: 50, + }; + loadtest.loadTest(options, function(err,result){ + expect(!err); + expect(result.totalTimeSeconds < 1); + done(); + }); + }); + +}); diff --git a/pool/shard001/JavaScript/0011001_botSimulate.js b/pool/shard001/JavaScript/0011001_botSimulate.js new file mode 100644 index 0000000000000000000000000000000000000000..c07f65b17538d1f8bce0c4574b8e339090385fac --- /dev/null +++ b/pool/shard001/JavaScript/0011001_botSimulate.js @@ -0,0 +1,51 @@ +/// +/// +/// +function simulateDriveBot() { + + if ((botNavigate.stop) || (botNavigate.dead) || (deadman == 1)) { + document.getElementById('d1').src = 'i/i0.png'; + document.getElementById('d2').src = 'i/i0.png'; + document.getElementById('d3').src = 'i/i0.png'; + document.getElementById('d4').src = 'i/i0.png'; + document.getElementById('d6').src = 'i/i0.png'; + document.getElementById('d7').src = 'i/i0.png'; + document.getElementById('d8').src = 'i/i0.png'; + document.getElementById('d9').src = 'i/i0.png'; + if ((botNavigate.stop) || (deadman == 1)) { + document.getElementById('d1').src = 'i/iD.png'; + document.getElementById('d9').src = 'i/iU.png'; + document.getElementById('d3').src = 'i/iR.png'; + document.getElementById('d7').src = 'i/iL.png'; + } + } else { + if (botNavigate.forward) { + document.getElementById('d1').src = 'i/iU.png'; + document.getElementById('d2').src = 'i/iU.png'; + } else { + document.getElementById('d1').src = 'i/i0.png'; + document.getElementById('d2').src = 'i/i0.png'; + } + if (botNavigate.backward) { + document.getElementById('d8').src = 'i/iD.png'; + document.getElementById('d9').src = 'i/iD.png'; + } else { + document.getElementById('d8').src = 'i/i0.png'; + document.getElementById('d9').src = 'i/i0.png'; + } + if (botNavigate.left) { + document.getElementById('d3').src = 'i/iL.png'; + document.getElementById('d4').src = 'i/iL.png'; + } else { + document.getElementById('d3').src = 'i/i0.png'; + document.getElementById('d4').src = 'i/i0.png'; + } + if (botNavigate.right) { + document.getElementById('d6').src = 'i/iR.png'; + document.getElementById('d7').src = 'i/iR.png'; + } else { + document.getElementById('d6').src = 'i/i0.png'; + document.getElementById('d7').src = 'i/i0.png'; + } + } +} diff --git a/pool/shard001/JavaScript/0011002_input.js b/pool/shard001/JavaScript/0011002_input.js new file mode 100644 index 0000000000000000000000000000000000000000..67ad2eeeb569708fa48b1f7fdf7af0d37b27c263 --- /dev/null +++ b/pool/shard001/JavaScript/0011002_input.js @@ -0,0 +1,29 @@ +var keymap = { + tetrisUp: Phaser.Keyboard.E, + tetrisDown: Phaser.Keyboard.D, + tetrisLeft: Phaser.Keyboard.S, + tetrisRight: Phaser.Keyboard.F, + tetrisRotLeft: Phaser.Keyboard.W, + tetrisRotRight: Phaser.Keyboard.R, + tetrisSlam: Phaser.Keyboard.SPACEBAR, + + snakeUp: Phaser.Keyboard.I, + snakeDown: Phaser.Keyboard.K, + snakeLeft: Phaser.Keyboard.J, + snakeRight: Phaser.Keyboard.L, + snakeRotLeft: Phaser.Keyboard.U, + snakeRotRight: Phaser.Keyboard.O +}; + +var controls = []; + +input = { + create: function() { + for (var key in keymap) + keymap[key] = game.input.keyboard.addKey(keymap[key]); + }, + update: function() { + for (var i = 0; i < controls.length; ++i) + controls[i].update(); + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011005_index.js b/pool/shard001/JavaScript/0011005_index.js new file mode 100644 index 0000000000000000000000000000000000000000..96854478b4f12b277091420ce7b2aabd88f16d01 --- /dev/null +++ b/pool/shard001/JavaScript/0011005_index.js @@ -0,0 +1,130 @@ +/** + * External Dependencies + */ +var React = require( 'react/addons' ); + +/** + * Internal Dependencies + */ +var warn = require( 'lib/warn' ), + tokenize = require( './tokenize.js' ); + +var currentTranslation; + +function getCloseIndex( openIndex, tokens ) { + var openToken = tokens[ openIndex ], + nestLevel = 0, + token, i; + for ( i = openIndex + 1; i < tokens.length; i++ ) { + token = tokens[ i ]; + if ( token.value === openToken.value ) { + if ( token.type === 'componentOpen' ) { + nestLevel++; + continue; + } + if ( token.type === 'componentClose' ) { + if ( nestLevel === 0 ) { + return i; + } + nestLevel--; + } + } + } + // if we get this far, there was no matching close token + throw new Error( 'Missing closing component token `' + openToken.value + '`' ); +} + +function buildChildren( tokens, components ) { + var children = [], + childrenObject = {}, + openComponent, clonedOpenComponent, openIndex, closeIndex, token, i, grandChildTokens, grandChildren, siblingTokens, siblings; + + for ( i = 0; i < tokens.length; i++ ) { + token = tokens[ i ]; + if ( token.type === 'string' ) { + children.push( token.value ); + continue; + } + // component node should at least be set + if ( ! components.hasOwnProperty( token.value ) || typeof components[ token.value ] === 'undefined' ) { + throw new Error( 'Invalid translation, missing component node: `' + token.value + '`' ); + } + // should be either ReactElement or null (both type "object"), all other types deprecated + if ( typeof components[ token.value ] !== 'object' ) { + warn( 'Invalid translation, component node must be a ReactElement or null: `' + token.value + '`', '\n> ' + currentTranslation ); + } + // we should never see a componentClose token in this loop + if ( token.type === 'componentClose' ) { + throw new Error( 'Missing opening component token: `' + token.value + '`' ); + } + if ( token.type === 'componentOpen' ) { + openComponent = components[ token.value ]; + openIndex = i; + break; + } + // componentSelfClosing token + children.push( components[ token.value ] ); + continue; + } + + if ( openComponent ) { + closeIndex = getCloseIndex( openIndex, tokens ); + grandChildTokens = tokens.slice( ( openIndex + 1 ), closeIndex ); + grandChildren = buildChildren( grandChildTokens, components ); + clonedOpenComponent = React.cloneElement( openComponent, {}, grandChildren ); + children.push( clonedOpenComponent ); + + if ( closeIndex < tokens.length - 1 ) { + siblingTokens = tokens.slice( closeIndex + 1 ); + siblings = buildChildren( siblingTokens, components ); + children = children.concat( siblings ); + } + } + + if ( children.length === 1 ) { + return children[ 0 ]; + } + + children.forEach( function( child, index ) { + if ( child ) { + childrenObject[ 'translation-child-' + index ] = child; + } + } ); + + return React.addons.createFragment( childrenObject ); +} + +module.exports = function interpolate( options ) { + var translation = options.translation, + components = options.components, + throwErrors = options.throwErrors, + tokens; + + currentTranslation = translation; + + if ( ! components ) { + return translation; + } + + if ( typeof components !== 'object' ) { + warn( 'Translation Error: components argument must be an object', translation, components ); + return translation; + } + + tokens = tokenize( translation ); + + try { + return buildChildren( tokens, components ); + } catch( error ) { + // don't mess around in production, just return what we can + if ( ! throwErrors ) { + return translation; + } + // in pre-production environments we should make errors very visible + if ( window && window.console && window.console.error ) { + window.console.error( '\nTranslation Error: ', interpolate.caller.caller, '\n> ' + translation ); + } + + throw error; + } +}; diff --git a/pool/shard001/JavaScript/0011010_repeatDur.js b/pool/shard001/JavaScript/0011010_repeatDur.js new file mode 100644 index 0000000000000000000000000000000000000000..f4752100e8ad533bb2d7993b06cb8a6407c2c6a2 --- /dev/null +++ b/pool/shard001/JavaScript/0011010_repeatDur.js @@ -0,0 +1,41 @@ +var error = require("../../../../error"); +var util = require("./util"); + + + +function parse(instance) +{ + var dur = instance.$currentElement.data("dur"); + var repeatCount = instance.$currentElement.data("repeatCount"); + var repeatDur = instance.$currentElement.attr("repeatDur"); + + // Avoid indefinite repeatCounts (0) + repeatCount = Math.max(1, repeatCount); + + if (repeatDur && repeatDur!="indefinite") + { + /*if (repeatDur == "indefinite") + { + repeatDur = 0; + } + else + {*/ + repeatDur = util.strings.timing.clock(repeatDur, instance); + + if (repeatDur != dur*repeatCount) + { + error.incompatible("Interrupted animation", "https://github.com/stevenvachon/smil2css/wiki/Interrupted-animations", instance); + } + //} + } + else + { + repeatDur = dur*repeatCount; + } + + instance.$currentElement.data("repeatDur", repeatDur); +} + + + +module.exports = parse; diff --git a/pool/shard001/JavaScript/0011012_time-module.js b/pool/shard001/JavaScript/0011012_time-module.js new file mode 100644 index 0000000000000000000000000000000000000000..ed25939f1916d6ee61ebf14115a540a88e768983 --- /dev/null +++ b/pool/shard001/JavaScript/0011012_time-module.js @@ -0,0 +1,98 @@ +var $time = require("royal/clock"); + +var timeModule = angular.module("Time", [], function( $provide, $controllerProvider, $compileProvider, $filterProvider) +{ + // TODO: [prince] This is a hack way to update activity service + $compileProvider.directive( "eeRefresh", function($frameProvider, gameClock, activityService) + { + var directiveDefinition = + { + link: function( scope, element, attrs ) + { + // TODO: [prince] Implements config + var framesPerSecond = attrs["eeRefresh"]; + var millisPerFrame = 1000 / framesPerSecond; + + // TODO: [prince] Don't DI frameProvidor, just build a new one + $frameProvider.frame( function( startTime, endTime ) + { + // TODO: [prince] Still need to fix stuff here, not very neat + //scope.time = gameClock.getTime(); + gameClock.DeltaClock.lap(); + var time = gameClock.getTime(); + + // TODO: [prince] restore activity service, have some way to register with clock? + activityService.setTime( time ); + scope.$apply(); + }); + } + }; + + return directiveDefinition; + }); + + $filterProvider.register( "time", function() + { + return $time.formatTime; + }); + + $provide.factory( "$frameProvider" , function() + { + // TODO: [prince] Factor out this clock + var clock = new time.buildSystemClock(); + + var frameProvider = + { + intervalHandle: null, + frameHandlers: [], + + lastTime: 0, + thisTime: 0, + + frame: function( func ) + { + this.frameHandlers.push( func ); + }, + + start: function() + { + var frameProvider = this; + + // TODO: [prince] Wait for $interval to be supported in stable version + this.intervalHandle = setInterval( function() + { + frameProvider.lastTime = frameProvider.thisTime; + frameProvider.thisTime = clock.getTime(); + + frameProvider.dispatchFrame( frameProvider.lastTime, frameProvider.thisTime ); + + }, 16); // Increment triggers 60 times per second ( 1000 / 16ms ) + + // TODO: [prince] Make "framesPerSecond" configurable + }, + + stop: function() + { + if( this.intervalHandle != null ) + { + clearInterval( this.intervalHandle ); + } + }, + + dispatchFrame: function( startTime, endTime ) + { + for( var i in this.frameHandlers ) + { + var frameHandler = this.frameHandlers[i]; + frameHandler.call( this, startTime, endTime ); + } + }, + }; + + frameProvider.start(); + + return frameProvider; + }); +}); + +module.exports = timeModule; diff --git a/pool/shard001/JavaScript/0011017_Alert.js b/pool/shard001/JavaScript/0011017_Alert.js new file mode 100644 index 0000000000000000000000000000000000000000..a777bd06a478a7b123db9bff96bc362b79a7a919 --- /dev/null +++ b/pool/shard001/JavaScript/0011017_Alert.js @@ -0,0 +1,268 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default; + +var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); + +var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); + +var _jsxRuntime = require("../../lib/jsxRuntime"); + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); + +var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); + +var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper")); + +var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); + +var React = _interopRequireWildcard(require("react")); + +var _Tappable = _interopRequireDefault(require("../Tappable/Tappable")); + +var _PopoutWrapper = require("../PopoutWrapper/PopoutWrapper"); + +var _getClassName = require("../../helpers/getClassName"); + +var _classNames = require("../../lib/classNames"); + +var _supportEvents = require("../../lib/supportEvents"); + +var _platform = require("../../lib/platform"); + +var _withPlatform = require("../../hoc/withPlatform"); + +var _withAdaptivity = require("../../hoc/withAdaptivity"); + +var _Button = _interopRequireDefault(require("../Button/Button")); + +var _utils = require("../../lib/utils"); + +var _Headline = _interopRequireDefault(require("../Typography/Headline/Headline")); + +var _Title = _interopRequireDefault(require("../Typography/Title/Title")); + +var _Caption = _interopRequireDefault(require("../Typography/Caption/Caption")); + +var _ModalDismissButton = _interopRequireDefault(require("../ModalDismissButton/ModalDismissButton")); + +var _excluded = ["actions", "actionsLayout", "children", "className", "style", "platform", "viewWidth", "text", "header"]; + +var Alert = /*#__PURE__*/function (_React$Component) { + (0, _inherits2.default)(Alert, _React$Component); + + var _super = (0, _createSuper2.default)(Alert); + + function Alert(props) { + var _this; + + (0, _classCallCheck2.default)(this, Alert); + _this = _super.call(this, props); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "element", void 0); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "transitionFinishTimeout", void 0); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onItemClick", function (item) { + return function () { + var action = item.action, + autoclose = item.autoclose; + + if (autoclose) { + _this.setState({ + closing: true + }); + + _this.waitTransitionFinish(function (e) { + if (!e || e.propertyName === 'opacity') { + autoclose && _this.props.onClose(); + action && action(); + } + }); + } else { + action && action(); + } + }; + }); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onClose", function () { + _this.setState({ + closing: true + }); + + _this.waitTransitionFinish(function (e) { + if (!e || e.propertyName === 'opacity') { + _this.props.onClose(); + } + }); + }); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "stopPropagation", function (e) { + e.stopPropagation(); + }); + (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "renderAction", function (action, i) { + var platform = _this.props.platform; + + if (platform === _platform.IOS) { + var _action$Component = action.Component, + Component = _action$Component === void 0 ? 'button' : _action$Component; + return (0, _jsxRuntime.createScopedElement)(_Tappable.default, { + Component: action.href ? 'a' : Component, + vkuiClass: (0, _classNames.classNames)('Alert__action', "Alert__action--".concat(action.mode)), + onClick: _this.onItemClick(action), + href: action.href, + key: "alert-action-".concat(i), + target: action.target + }, action.title); + } + + var mode = action.mode === 'cancel' ? 'secondary' : 'primary'; + + if (platform === _platform.ANDROID) { + mode = 'tertiary'; + + if (_this.props.viewWidth === _withAdaptivity.ViewWidth.DESKTOP && action.mode === 'destructive') { + mode = 'destructive'; + } + } + + return (0, _jsxRuntime.createScopedElement)(_Button.default, { + vkuiClass: (0, _classNames.classNames)('Alert__button', "Alert__button--".concat(action.mode)), + mode: mode, + size: "m", + onClick: _this.onItemClick(action), + Component: action.Component, + href: action.href, + key: "alert-action-".concat(i), + target: action.target + }, action.title); + }); + _this.element = /*#__PURE__*/React.createRef(); + _this.state = { + closing: false + }; + return _this; + } + + (0, _createClass2.default)(Alert, [{ + key: "waitTransitionFinish", + value: function waitTransitionFinish(eventHandler) { + if (_supportEvents.transitionEvent.supported) { + this.element.current.removeEventListener(_supportEvents.transitionEvent.name, eventHandler); + this.element.current.addEventListener(_supportEvents.transitionEvent.name, eventHandler); + } else { + clearTimeout(this.transitionFinishTimeout); + this.transitionFinishTimeout = setTimeout(eventHandler.bind(this), this.props.platform === _platform.ANDROID || this.props.platform === _platform.VKCOM ? 200 : 300); + } + } + }, { + key: "renderHeader", + value: function renderHeader(header) { + switch (this.props.platform) { + case _platform.VKCOM: + return (0, _jsxRuntime.createScopedElement)(_Headline.default, { + vkuiClass: "Alert__header", + weight: "medium" + }, header); + + case _platform.IOS: + return (0, _jsxRuntime.createScopedElement)(_Title.default, { + vkuiClass: "Alert__header", + weight: "semibold", + level: "3" + }, header); + + case _platform.ANDROID: + return (0, _jsxRuntime.createScopedElement)(_Title.default, { + vkuiClass: "Alert__header", + weight: "medium", + level: "2" + }, header); + } + } + }, { + key: "renderText", + value: function renderText(text) { + switch (this.props.platform) { + case _platform.VKCOM: + return (0, _jsxRuntime.createScopedElement)(_Caption.default, { + vkuiClass: "Alert__text", + level: "1", + weight: "regular" + }, text); + + case _platform.IOS: + return (0, _jsxRuntime.createScopedElement)(_Caption.default, { + vkuiClass: "Alert__text", + level: "2", + weight: "regular" + }, text); + + case _platform.ANDROID: + return (0, _jsxRuntime.createScopedElement)(_Headline.default, { + vkuiClass: "Alert__text", + weight: "regular" + }, text); + } + } + }, { + key: "render", + value: function render() { + var _this$props = this.props, + actions = _this$props.actions, + actionsLayout = _this$props.actionsLayout, + children = _this$props.children, + className = _this$props.className, + style = _this$props.style, + platform = _this$props.platform, + viewWidth = _this$props.viewWidth, + text = _this$props.text, + header = _this$props.header, + restProps = (0, _objectWithoutProperties2.default)(_this$props, _excluded); + var closing = this.state.closing; + var resolvedActionsLayout = platform === _platform.VKCOM ? 'horizontal' : actionsLayout; + var canShowCloseButton = platform === _platform.VKCOM || platform === _platform.ANDROID && viewWidth >= _withAdaptivity.ViewWidth.SMALL_TABLET; + var isDesktop = viewWidth >= _withAdaptivity.ViewWidth.SMALL_TABLET; + return (0, _jsxRuntime.createScopedElement)(_PopoutWrapper.PopoutWrapper, { + className: className, + closing: closing, + style: style, + onClick: this.onClose + }, (0, _jsxRuntime.createScopedElement)("div", (0, _extends2.default)({}, restProps, { + ref: this.element, + onClick: this.stopPropagation, + vkuiClass: (0, _classNames.classNames)((0, _getClassName.getClassName)('Alert', platform), { + 'Alert--v': resolvedActionsLayout === 'vertical', + 'Alert--h': resolvedActionsLayout === 'horizontal', + 'Alert--closing': closing, + 'Alert--desktop': isDesktop + }) + }), canShowCloseButton && (0, _jsxRuntime.createScopedElement)(_ModalDismissButton.default, { + onClick: this.onClose + }), (0, _jsxRuntime.createScopedElement)("div", { + vkuiClass: "Alert__content" + }, (0, _utils.hasReactNode)(header) && this.renderHeader(header), (0, _utils.hasReactNode)(text) && this.renderText(text), children), (0, _jsxRuntime.createScopedElement)("footer", { + vkuiClass: "Alert__actions" + }, actions.map(this.renderAction)))); + } + }]); + return Alert; +}(React.Component); + +(0, _defineProperty2.default)(Alert, "defaultProps", { + actionsLayout: 'horizontal', + actions: [] +}); + +var _default = (0, _withPlatform.withPlatform)((0, _withAdaptivity.withAdaptivity)(Alert, { + viewWidth: true +})); + +exports.default = _default; +//# sourceMappingURL=Alert.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011019_local.js b/pool/shard001/JavaScript/0011019_local.js new file mode 100644 index 0000000000000000000000000000000000000000..c72838569c47d8d478a56e1f0343751f2ad58cbc --- /dev/null +++ b/pool/shard001/JavaScript/0011019_local.js @@ -0,0 +1,25 @@ +const passport = require('passport'); +const LocalStrategy = require('passport-local').Strategy; + +const init = require('./passport'); +const knex = require('../db/connection'); +const authHelpers = require('./_helpers'); + +const options = {}; + +init(); + +passport.use(new LocalStrategy(options, (username, password, done) => { + knex('users').where({ username }).first() + .then((user) => { + if (!user) return done(null, false); + if (!authHelpers.comparePass(password, user.password)) { + return done(null, false); + } else { + return done(null, user); + } + }) + .catch((err) => { return done(err); }); +})); + +module.exports = passport; diff --git a/pool/shard001/JavaScript/0011021_dstr-gen-meth-static-ary-ptrn-elem-ary-elem-init.js b/pool/shard001/JavaScript/0011021_dstr-gen-meth-static-ary-ptrn-elem-ary-elem-init.js new file mode 100644 index 0000000000000000000000000000000000000000..e2b27ccf7a372f2060d572be9c8f758a5b63bcc0 --- /dev/null +++ b/pool/shard001/JavaScript/0011021_dstr-gen-meth-static-ary-ptrn-elem-ary-elem-init.js @@ -0,0 +1,88 @@ +// This file was procedurally generated from the following sources: +// - src/dstr-binding/ary-ptrn-elem-ary-elem-init.case +// - src/dstr-binding/default/cls-expr-gen-meth-static.template +/*--- +description: BindingElement with array binding pattern and initializer is used (static class expression generator method) +esid: sec-class-definitions-runtime-semantics-evaluation +es6id: 14.5.16 +features: [generators, destructuring-binding] +flags: [generated] +info: | + ClassExpression : class BindingIdentifieropt ClassTail + + 1. If BindingIdentifieropt is not present, let className be undefined. + 2. Else, let className be StringValue of BindingIdentifier. + 3. Let value be the result of ClassDefinitionEvaluation of ClassTail + with argument className. + [...] + + 14.5.14 Runtime Semantics: ClassDefinitionEvaluation + + 21. For each ClassElement m in order from methods + a. If IsStatic of m is false, then + b. Else, + Let status be the result of performing PropertyDefinitionEvaluation + for m with arguments F and false. + [...] + + 14.4.13 Runtime Semantics: PropertyDefinitionEvaluation + + GeneratorMethod : + * PropertyName ( StrictFormalParameters ) { GeneratorBody } + + 1. Let propKey be the result of evaluating PropertyName. + 2. ReturnIfAbrupt(propKey). + 3. If the function code for this GeneratorMethod is strict mode code, + let strict be true. Otherwise let strict be false. + 4. Let scope be the running execution context's LexicalEnvironment. + 5. Let closure be GeneratorFunctionCreate(Method, + StrictFormalParameters, GeneratorBody, scope, strict). + + 9.2.1 [[Call]] ( thisArgument, argumentsList) + + [...] + 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). + [...] + + 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) + + 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). + [...] + + 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) + + [...] + 23. Let iteratorRecord be Record {[[iterator]]: + CreateListIterator(argumentsList), [[done]]: false}. + 24. If hasDuplicates is true, then + [...] + 25. Else, + b. Let formalStatus be IteratorBindingInitialization for formals with + iteratorRecord and env as arguments. + [...] + + 13.3.3.6 Runtime Semantics: IteratorBindingInitialization + + BindingElement : BindingPatternInitializer opt + + [...] + 2. If iteratorRecord.[[done]] is true, let v be undefined. + 3. If Initializer is present and v is undefined, then + a. Let defaultValue be the result of evaluating Initializer. + b. Let v be ? GetValue(defaultValue). + 4. Return the result of performing BindingInitialization of BindingPattern + with v and environment as the arguments. +---*/ + +var callCount = 0; +var C = class { + static *method([[x, y, z] = [4, 5, 6]]) { + assert.sameValue(x, 4); + assert.sameValue(y, 5); + assert.sameValue(z, 6); + callCount = callCount + 1; + } +}; + +C.method([]).next(); +assert.sameValue(callCount, 1, 'method invoked exactly once'); diff --git a/pool/shard001/JavaScript/0011023_model-cloudsql.js b/pool/shard001/JavaScript/0011023_model-cloudsql.js new file mode 100644 index 0000000000000000000000000000000000000000..8855aa58f3d44fce683d90a6db070abe212bca69 --- /dev/null +++ b/pool/shard001/JavaScript/0011023_model-cloudsql.js @@ -0,0 +1,161 @@ +// Copyright 2015-2016, Google, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +const extend = require('lodash').assign; +const mysql = require('mysql'); +const config = require('../config'); + +function getConnection () { + const options = { + user: config.get('MYSQL_USER'), + password: config.get('MYSQL_PASSWORD'), + database: 'bookshelf' + }; + + if (config.get('INSTANCE_CONNECTION_NAME') && config.get('NODE_ENV') === 'production') { + options.socketPath = `/cloudsql/${config.get('INSTANCE_CONNECTION_NAME')}`; + } + + return mysql.createConnection(options); +} + +// [START list] +function list (limit, token, cb) { + token = token ? parseInt(token, 10) : 0; + const connection = getConnection(); + connection.query( + 'SELECT * FROM `books` LIMIT ? OFFSET ?', [limit, token], + (err, results) => { + if (err) { + cb(err); + return; + } + const hasMore = results.length === limit ? token + results.length : false; + cb(null, results, hasMore); + } + ); + connection.end(); +} +// [END list] + +// [START create] +function create (data, cb) { + const connection = getConnection(); + connection.query('INSERT INTO `books` SET ?', data, (err, res) => { + if (err) { + cb(err); + return; + } + read(res.insertId, cb); + }); + connection.end(); +} +// [END create] + +function read (id, cb) { + const connection = getConnection(); + connection.query( + 'SELECT * FROM `books` WHERE `id` = ?', id, (err, results) => { + if (err) { + cb(err); + return; + } + if (!results.length) { + cb({ + code: 404, + message: 'Not found' + }); + return; + } + cb(null, results[0]); + }); + connection.end(); +} + +// [START update] +function update (id, data, cb) { + const connection = getConnection(); + connection.query( + 'UPDATE `books` SET ? WHERE `id` = ?', [data, id], (err) => { + if (err) { + cb(err); + return; + } + read(id, cb); + }); + connection.end(); +} +// [END update] + +function _delete (id, cb) { + const connection = getConnection(); + connection.query('DELETE FROM `books` WHERE `id` = ?', id, cb); + connection.end(); +} + +module.exports = { + createSchema: createSchema, + list: list, + create: create, + read: read, + update: update, + delete: _delete +}; + +if (module === require.main) { + const prompt = require('prompt'); + prompt.start(); + + console.log( + `Running this script directly will allow you to initialize your mysql database. + This script will not modify any existing tables.`); + + prompt.get(['user', 'password'], (err, result) => { + if (err) { + return; + } + createSchema(result); + }); +} + +function createSchema (config) { + const connection = mysql.createConnection(extend({ + multipleStatements: true + }, config)); + + connection.query( + `CREATE DATABASE IF NOT EXISTS \`bookshelf\` + DEFAULT CHARACTER SET = 'utf8' + DEFAULT COLLATE 'utf8_general_ci'; + USE \`bookshelf\`; + CREATE TABLE IF NOT EXISTS \`bookshelf\`.\`books\` ( + \`id\` INT UNSIGNED NOT NULL AUTO_INCREMENT, + \`title\` VARCHAR(255) NULL, + \`author\` VARCHAR(255) NULL, + \`publishedDate\` VARCHAR(255) NULL, + \`imageUrl\` VARCHAR(255) NULL, + \`description\` TEXT NULL, + \`createdBy\` VARCHAR(255) NULL, + \`createdById\` VARCHAR(255) NULL, + PRIMARY KEY (\`id\`));`, + (err) => { + if (err) { + throw err; + } + console.log('Successfully created schema'); + connection.end(); + } + ); +} diff --git a/pool/shard001/JavaScript/0011026_text.js b/pool/shard001/JavaScript/0011026_text.js new file mode 100644 index 0000000000000000000000000000000000000000..2cbc86b3a73b496a02341a180b5a7ae4180512f0 --- /dev/null +++ b/pool/shard001/JavaScript/0011026_text.js @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2014 Tomas Machalek + * + * 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. + */ + +/** + * General text processing related functionality + */ + +(function (module) { + 'use strict'; + + var lib = {}; + + module.exports = lib; + + /** + * + * @param {string} text + * @param {bool} [caseSensitive] if false then all letters are converted into lowercase + * @constructor + */ + function Sentence(text, caseSensitive) { + var self = this, + words = text.trim().split(/[\s\.,:;!\?'\-\(\)\|]+/); + + if (caseSensitive) { + this._words = words; + + } else { + self._words = words.map(function (w) { return w.toLowerCase(); }); + } + } + + /** + * + * @returns {Array} + */ + Sentence.prototype.words = function () { + return this._words; + }; + + /** + * + * @returns {string} + */ + Sentence.prototype.toString = function () { + return '[object Sentence]'; + }; + + /** + * + * @returns {string} + */ + Sentence.prototype.asText = function () { + return this._words.join(' '); + }; + + /** + * Finds a word matching passed pattern. If a string is + * passed then only exact match (i.e. no substring) is + * accepted. + * + * @param {RegExp|string} pattern + * @returns {Array} + */ + Sentence.prototype.find = function (pattern) { + var ans = []; + + if (typeof pattern === 'string') { + pattern = new RegExp('^' + pattern + '$'); + } + + this._words.forEach(function (w, i) { + if (pattern.exec(w)) { + ans.push([w, i]); + } + }); + return ans; + }; + + /** + * Returns selected context of a word + * + * @param {number} pos where to start (KWIC) + * @param {number} rangeLeft + * @param {number} [rangeRight] if omitted then rangeLeft value is used + * @returns {Array} + */ + Sentence.prototype.context = function (pos, rangeLeft, rangeRight) { + var ans = [], + i; + + if (rangeRight === undefined) { + rangeRight = rangeLeft; + } + + for (i = Math.max(0, pos - rangeLeft); i < Math.min(this._words.length, pos + rangeRight + 1); i += 1) { + ans.push(this._words[i]); + } + return ans; + }; + + /** + * Tests whether the passed argument is of Sentence type. + * + * @param {*} obj + * @returns {boolean} + */ + lib.isSentence = function (obj) { + return obj !== null && obj.toString() === '[object Sentence]'; + }; + + lib.Sentence = Sentence; + + /** + * Parses bunch of sentences (~ paragraph) into a list of Sentence + * instances. + * + * @param {string} p + * @returns {Array} + */ + lib.parseText = function (p) { + var sentences = []; + + p = p.replace(/["']/g, ' '); + p.trim().split(/[\.\!\?]\s*(?=[A-ZÁČĎÉĚÍŇÓŠŤÚŽ])/).forEach(function (s) { + var sent = s.trim(); + + if (sent) { + sentences.push(new Sentence(s)); + } + }); + return sentences; + }; + +}(this.module)); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011028_app.js b/pool/shard001/JavaScript/0011028_app.js new file mode 100644 index 0000000000000000000000000000000000000000..434e3f27011b62b0b7bcffdca93943510467cf74 --- /dev/null +++ b/pool/shard001/JavaScript/0011028_app.js @@ -0,0 +1,212 @@ +$(document).ready(function() { + + // Navigation menu + + $('ul#navigation').superfish({ + delay: 1000, + animation: {opacity:'show',height:'show'}, + speed: 'fast', + autoArrows: true, + dropShadows: false + }); + + $('ul#navigation li').hover(function(){ + $(this).addClass('sfHover2'); + }, + function(){ + $(this).removeClass('sfHover2'); + }); + + // Accordion + $("#accordion, #accordion2").accordion({ header: "h3" }); + + // Tabs + $('#tabs, #tabs2, #tabs5').tabs(); + + // Dialog + $('#dialog').dialog({ + autoOpen: false, + width: 600, + bgiframe: false, + modal: false, + buttons: { + "Ok": function() { + $(this).dialog("close"); + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); + + // Login Dialog Link + $('#login_dialog').click(function(){ + $('#login').dialog('open'); + return false; + }); + + // Login Dialog + $('#login').dialog({ + autoOpen: false, + width: 300, + height: 230, + bgiframe: true, + modal: true, + buttons: { + "Login": function() { + $(this).dialog("close"); + }, + "Close": function() { + $(this).dialog("close"); + } + } + }); + + // Dialog Link + $('#dialog_link').click(function(){ + $('#dialog').dialog('open'); + return false; + }); + + // Dialog auto open + $('#welcome_login').dialog({ + autoOpen: true, + width: 370, + height: 430, + bgiframe: true, + modal: true, + buttons: { + "Proceed to demo !": function() { + window.location = "index.php"; + } + } + }); + + // Datepicker + $('#datepicker').datepicker({ + inline: true + }); + + //Hover states on the static widgets + $('#dialog_link, ul#icons li').hover( + function() { $(this).addClass('ui-state-hover'); }, + function() { $(this).removeClass('ui-state-hover'); } + ); + + //Sortable + + $(".column").sortable({ + connectWith: '.column' + }); + + //Sidebar only sortable boxes + $(".side-col").sortable({ + axis: 'y', + connectWith: '.side-col' + }); + + $(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all") + .find(".portlet-header") + .addClass("ui-widget-header") + .prepend('') + .end() + .find(".portlet-content"); + + $(".portlet-header .ui-icon").click(function() { + $(this).toggleClass("ui-icon-circle-arrow-n"); + $(this).parents(".portlet:first").find(".portlet-content").slideToggle(); + }); + + $(".column").disableSelection(); + + + /* Table Sorter */ + $("#sort-table") + .tablesorter({ + widgets: ['zebra'], + headers: { + // assign the secound column (we start counting zero) + 0: { + // disable it by setting the property sorter to false + sorter: false + }, + // assign the third column (we start counting zero) + 6: { + // disable it by setting the property sorter to false + sorter: false + } + } + }) + + .tablesorterPager({container: $("#pager")}); + + $(".header").append(''); + + /** + * Make iframes full height of browser window + * + * @author Cosmo Mathieu + * @source http://stackoverflow.com/questions/20125340/can-i-use-jquery-to-resize-an-iframe-to-fill-the-remaining-window-space + */ + $(window).on('load resize', function(){ + $window = $(window); + $('iframe.fullheight').height(function(){ + return $window.height()-$(this).offset().top; + }); + }); + +}); + +/* Tooltip */ + +$(function() { + $('.tooltip').tooltip({ + track: true, + delay: 0, + showURL: false, + showBody: " - ", + fade: 250 + }); +}); + + + +/* Check all table rows */ + +var checkflag = "false"; +function check(field) { + if (checkflag == "false") + { + for (i = 0; i < field.length; i++) { + field[i].checked = true; + } + checkflag = "true"; + return "check_all"; + } + else + { + for (i = 0; i < field.length; i++) { + field[i].checked = false; + } + checkflag = "false"; + return "check_none"; + } +} + +/* + * This script checks and unchecks boxes on a form + * Checks and unchecks unlimited number in the group... + * Pass the Checkbox group name... + */ +function selectToggle(toggle, form) { + var myForm = document.forms[form]; + for( var i=0; i < myForm.length; i++ ) { + if(toggle) { + myForm.elements[i].checked = "checked"; + } + else { + myForm.elements[i].checked = ""; + } + } +} +// End --> \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011034_external.js b/pool/shard001/JavaScript/0011034_external.js new file mode 100644 index 0000000000000000000000000000000000000000..e1d522ba1d5d773c8148a640a0299325512f3552 --- /dev/null +++ b/pool/shard001/JavaScript/0011034_external.js @@ -0,0 +1,106 @@ +/* jshint qunit: true */ +/* global JSZip,JSZipTestUtils,Promise */ +'use strict'; + +QUnit.module("external"); + +/** + * Creates a wrapper around an existing Promise implementation to count + * calls and detect custom implementations. + * @param {Promise} OriginalPromise the promise to wrap + * @return {Promise} the wrapped promise + */ +function createPromiseProxy(OriginalPromise) { + function MyShinyPromise (input) { + if (input.then) { // thenable, we wrap it + this._promise = input; + } else { // executor + this._promise = new OriginalPromise(input); + } + MyShinyPromise.calls++; + } + MyShinyPromise.calls = 0; + MyShinyPromise.prototype = { + then: function (onFulfilled, onRejected) { + return new MyShinyPromise(this._promise.then(onFulfilled, onRejected)); + }, + "catch": function (onRejected) { + return new MyShinyPromise(this._promise['catch'](onRejected)); + }, + isACustomImplementation: true + }; + + MyShinyPromise.resolve = function (value) { + return new MyShinyPromise(OriginalPromise.resolve(value)); + }; + MyShinyPromise.reject = function (value) { + return new MyShinyPromise(OriginalPromise.reject(value)); + }; + MyShinyPromise.all = function (value) { + return new MyShinyPromise(OriginalPromise.all(value)); + }; + return MyShinyPromise; +} + +test("JSZip.external.Promise", function (assert) { + assert.ok(JSZip.external.Promise, "JSZip.external.Promise is defined"); + assert.ok(JSZip.external.Promise.resolve, "JSZip.external.Promise looks like a Promise"); + assert.ok(JSZip.external.Promise.reject, "JSZip.external.Promise looks like a Promise"); +}); + +test("load JSZip doesn't override the global Promise", function (assert) { + if (typeof Promise !== "undefined"){ + assert.equal(Promise, JSZipTestUtils.oldPromise, "the previous Promise didn't change"); + assert.equal(Promise, JSZip.external.Promise, "JSZip.external.Promise reused the global Promise"); + } else { + assert.ok(JSZip.external.Promise, "JSZip.external.Promise is defined even if the global Promise doesn't exist"); + } +}); + +test("external.Promise can be replaced in .async()", function (assert) { + var done = assert.async(); + var OriginalPromise = JSZip.external.Promise; + var MyShinyPromise = createPromiseProxy(OriginalPromise); + + JSZip.external.Promise = MyShinyPromise; + + var promise = JSZipTestUtils.createZipAll().file("Hello.txt").async("string").then(function (result) { + ok(MyShinyPromise.calls > 0, "at least 1 call of the new Promise"); + JSZip.external.Promise = OriginalPromise; + done(); + })['catch'](JSZipTestUtils.assertNoError); + + assert.ok(promise.isACustomImplementation, "the custom implementation is used"); +}); + +test("external.Promise can be replaced in .generateAsync()", function (assert) { + var done = assert.async(); + var OriginalPromise = JSZip.external.Promise; + var MyShinyPromise = createPromiseProxy(OriginalPromise); + + JSZip.external.Promise = MyShinyPromise; + + var promise = JSZipTestUtils.createZipAll().generateAsync({type:"string"}).then(function (result) { + ok(MyShinyPromise.calls > 0, "at least 1 call of the new Promise"); + JSZip.external.Promise = OriginalPromise; + done(); + })['catch'](JSZipTestUtils.assertNoError); + + assert.ok(promise.isACustomImplementation, "the custom implementation is used"); +}); + +JSZipTestUtils.testZipFile("external.Promise can be replaced in .loadAsync()", "ref/all.zip", function (all) { + stop(); + var OriginalPromise = JSZip.external.Promise; + var MyShinyPromise = createPromiseProxy(OriginalPromise); + + JSZip.external.Promise = MyShinyPromise; + + var promise = JSZip.loadAsync(all).then(function (result) { + ok(MyShinyPromise.calls > 0, "at least 1 call of the new Promise"); + JSZip.external.Promise = OriginalPromise; + start(); + })['catch'](JSZipTestUtils.assertNoError); + + ok(promise.isACustomImplementation, "the custom implementation is used"); +}); diff --git a/pool/shard001/JavaScript/0011037_results-create.controller.js b/pool/shard001/JavaScript/0011037_results-create.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..fea1d4ffdc82555ffb84032eeaa3f95ad764b1b5 --- /dev/null +++ b/pool/shard001/JavaScript/0011037_results-create.controller.js @@ -0,0 +1,46 @@ +angular.module('coloring') + .controller('ResultsCreateController', function (ResultService, $state, AlertService) { + var self = this; + self.start = 0; + self.end = 100; + self.increment = 1; + + self.createResult = function() { + + if(self.start < 0 || self.start > 100) { + AlertService.Warning("The starting edge percentage must be between 0 and 100."); + return; + } + + if(self.end < 0 || self.end > 100) { + AlertService.Warning("The ending edge percentage must be between 0 and 100."); + return; + } + + if(self.start >= self.end) { + AlertService.Warning("The starting percentage must be less than the ending percentage."); + return; + } + + if(self.increment < 1 || self.increment > 10) { + AlertService.Warning("The edge percentage increment must be between 1 and 10."); + return; + } + + var data = { + name: self.name, + vertices: self.vertices, + runs: self.runs, + start: self.start, + end: self.end, + increment: self.increment + }; + + ResultService.save(data, function (response) { + $state.go('results-view', {'id': response.id}); + }, function (error) { + AlertService.Warning(error.data.message); + }); + }; + + }); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011038_dbCustomMessage.js b/pool/shard001/JavaScript/0011038_dbCustomMessage.js new file mode 100644 index 0000000000000000000000000000000000000000..e8e2b8c0dd60ff4bd8f548906e43d242137439ef --- /dev/null +++ b/pool/shard001/JavaScript/0011038_dbCustomMessage.js @@ -0,0 +1,52 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * Copyright (c) 2015 ChiYoung Choi, Yoav Gurevich, Kieran Sedgwick, + * Alina Shtramwasser, Seneca College */ + +var db = require("../server/lib/db"); +var models = require("../server/models")(db.connection); + +function _generateMessageData() { + var m1 = new models.Message({ + messageText: 'Please enter your text' + }); + + models.Message.find({}, function(err, messages) { + if (err) { + console.error(err); + return process.exit(1); + } + if (messages.length === 0) + { + m1.save(function(err, m1) { + if (err) { + console.error(err); + return process.exit(1); + } + + models.Message.find({}, function(err, message) { + if (err) { + return process.exit(1); + } + + console.log(message); + console.log("The initial message has been successfully generated.") + process.exit(); + }); + }); + }else{ + console.log("The initial message already exists.") + return process.exit(); + } + }); +} + +if (db.health.connected) { + _generateMessageData(); +} else { + db.health.once("connected", function() { + _generateMessageData(); + }); +} diff --git a/pool/shard001/JavaScript/0011041_login.js b/pool/shard001/JavaScript/0011041_login.js new file mode 100644 index 0000000000000000000000000000000000000000..491bfad6d75455f01b5399d962880f5c8be601a4 --- /dev/null +++ b/pool/shard001/JavaScript/0011041_login.js @@ -0,0 +1,20 @@ +/* This file is part of Syj, Copyright (c) 2010-2011 Arnaud Renevier, + and is published under the AGPL license. */ + +"use strict"; + +document.observe("dom:loaded", function() { + var form = $("loginform"); + form.setfocus(); + + form.observe("submit", function(evt) { + var loginput = $("login_user"); + $$('.error').invoke('remove'); + + if (!loginput.check(function() { return !this.value.strip().empty(); }, SyjStrings.userEmptyWarn)) { + loginput.highlight('#F08080').activate(); + evt.stop(); + return; + } + }); +}); diff --git a/pool/shard001/JavaScript/0011046_default-config.integration.js b/pool/shard001/JavaScript/0011046_default-config.integration.js new file mode 100644 index 0000000000000000000000000000000000000000..23f9c598ebcb5e3b1147ebcb5d96c5d6190cb044 --- /dev/null +++ b/pool/shard001/JavaScript/0011046_default-config.integration.js @@ -0,0 +1,35 @@ +'use strict'; + +var should = require('chai').should(); +var defaultConfig = require('../../lib/scaffold/default-config'); + +describe('#defaultConfig', function() { + + it('will return expected configuration', function() { + var cwd = process.cwd(); + delete process.env.BITCORENODE_DIR; + delete process.env.BITCORENODE_NETWORK; + delete process.env.BITCORENODE_PORT; + var home = process.env.HOME; + var info = defaultConfig(); + info.path.should.equal(cwd); + info.config.datadir.should.equal(home + '/.bitcoin'); + info.config.network.should.equal('livenet'); + info.config.port.should.equal(3001); + info.config.services.should.deep.equal(['bitcoind', 'db', 'address', 'web']); + }); + + it('will return expected configuration from environment variables', function() { + var cwd = process.cwd(); + process.env.BITCORENODE_DIR = '/home/bitcore-node/.bitcoin'; + process.env.BITCORENODE_NETWORK = 'testnet'; + process.env.BITCORENODE_PORT = 3002; + var info = defaultConfig(); + info.path.should.equal(cwd); + info.config.datadir.should.equal('/home/bitcore-node/.bitcoin'); + info.config.network.should.equal('testnet'); + info.config.port.should.equal(3002); + info.config.services.should.deep.equal(['bitcoind', 'db', 'address', 'web']); + }); + +}); diff --git a/pool/shard001/JavaScript/0011050_classMemberInitializerScoping.js b/pool/shard001/JavaScript/0011050_classMemberInitializerScoping.js new file mode 100644 index 0000000000000000000000000000000000000000..dd4319f612b30f056fcb9e36e662f2553ca1deb5 --- /dev/null +++ b/pool/shard001/JavaScript/0011050_classMemberInitializerScoping.js @@ -0,0 +1,20 @@ +//// [classMemberInitializerScoping.js] +var aaa = 1; +var CCC = (function () { + function CCC(aaa) { + this.y = aaa; + this.y = ''; // was: error, cannot assign string to number + } + CCC.staticY = aaa; + return CCC; +})(); + +// above is equivalent to this: +var aaaa = 1; +var CCCC = (function () { + function CCCC(aaaa) { + this.y = aaaa; + this.y = ''; + } + return CCCC; +})(); diff --git a/pool/shard001/JavaScript/0011054_buildfromxml.js b/pool/shard001/JavaScript/0011054_buildfromxml.js new file mode 100644 index 0000000000000000000000000000000000000000..803ba97c9734d3648ad59e4366b238a7efb5684b --- /dev/null +++ b/pool/shard001/JavaScript/0011054_buildfromxml.js @@ -0,0 +1,77 @@ +var outback = function (s) { + while (s.length < 70) s += ' '; + var l = s.length; + for (var i = 0; i < l; i++) s += String.fromCharCode(8); + process.stdout.write(s); +} +var movefile=function(sourcefn,targetfolder) { + var fs = require("fs"); + var source = fs.createReadStream(sourcefn); + var path=require("path"); + var targetfn=path.resolve(process.cwd(),"..")+path.sep+path.basename(sourcefn); + var destination = fs.createWriteStream(targetfn); + console.log(targetfn); + source.pipe(destination, { end: false }); + source.on("end", function(){ + fs.unlinkSync(sourcefn); + }); + return targetfn; +} +var mkdbjs="mkdb.js"; +var starttime=0; +var startindexer=function(mkdbconfig) { + var indexer=require("ksana-document").indexer; + var session=indexer.start(mkdbconfig); + if (!session) { + console.log("No file to index"); + return; + } + var getstatus=function() { + var status=indexer.status(); + + if (status.done) { + var endtime=new Date(); + console.log("END",endtime, "elapse",(endtime-starttime) /1000,"seconds") ; + //status.outputfn=movefile(status.outputfn,".."); + clearInterval(timer); + } else { + if (mkdbconfig.callbacks && mkdbconfig.callbacks.onStatus) { + mkdbconfig.callbacks.onStatus(status); + } + } + } + var timer=setInterval( getstatus, 1000); +} + +var build=function(path,mkdbjs){ + var fs=require("fs"); + mkdbjs=mkdbjs||"mkdb.js"; + + if (!fs.existsSync(mkdbjs)) { + throw "no "+mkdbjs ; + } + starttime=new Date(); + console.log("START",starttime); + if (!path) path="."; + + var glob = require("glob"); + + var fn=require("path").resolve(path,mkdbjs); + var mkdbconfig=require(fn); + + if (typeof mkdbconfig.glob=="string") { + glob(mkdbconfig.glob, function (err, files) { + if (err) throw err; + mkdbconfig.files=files.sort(); + startindexer(mkdbconfig); + }); + } else { + mkdbconfig.files=mkdbconfig.glob; + startindexer(mkdbconfig); + } + + + +} + +module.exports=build; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011058_index.js b/pool/shard001/JavaScript/0011058_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3838339ce6b200108b8ca322df169409f2414571 --- /dev/null +++ b/pool/shard001/JavaScript/0011058_index.js @@ -0,0 +1,54 @@ +'use strict' + +var JSONIC = require('jsonic') +var S = require('string') +var delimitLen = process.env.DELIMIT_LEN || 25 +var colors = require('colors') + +function delimit(str, len) { + len = len || delimitLen + str = str || '' + if (str.length > len) str = str.substr(0, len) + return str + S('.').repeat(len - str.length).s + ':' +} + +function enval(name, defaultValue, log) { + function logVal(val) { + if (val !== undefined && val !== null && log) { + if (typeof log == 'number' && log > 0 && typeof val == 'string' && val.length > 0) { + console.log(colors.gray(delimit(name)), colors.gray(val.substr(0, log) + '...')) + } else if (typeof log == 'function') { + if (typeof val == 'object') { + val = JSON.parse(JSON.stringify(val)) // create new object preclude assignements in logging function + } + console.log(colors.gray(delimit(name)), colors.gray(JSON.stringify(log(val)))) + } else { + console.log(colors.gray(delimit(name)), colors.gray(JSON.stringify(val))) + } + } + } + + if (typeof name == 'string') { + try { + var value = JSON.parse(process.env[name]) + logVal(value) + return value + } catch(e) { + try { + var value = JSONIC(process.env[name]) + logVal(value) + return value + } catch(e) { + var value = process.env[name] + logVal(value) + return value + } + } + } + + var value = (typeof process.env[name] == 'undefined' || typeof process.env[name] == 'null') ? defaultValue : process.env[name] + logVal(value) + return value +} + +module.exports = enval; diff --git a/pool/shard001/JavaScript/0011059_SurveyTemplatesList.js b/pool/shard001/JavaScript/0011059_SurveyTemplatesList.js new file mode 100644 index 0000000000000000000000000000000000000000..8d1aa2b9cd56b30bbfb6629fe5e5a1b4fd3f18c7 --- /dev/null +++ b/pool/shard001/JavaScript/0011059_SurveyTemplatesList.js @@ -0,0 +1,69 @@ +import React from 'react' +import Pagination from 'components/navigation/Pagination' +import { debounce } from 'lodash' + +class SurveyTemplatesList extends React.Component { + componentWillMount () { + this.setSearch = debounce(this.setSearch, 250) + } + + setSearch (value) { + this.setState({search: value}) + this.props.update(this.props.page, value) + } + + render () { + let { update, page, pages, surveys, onDelete, total } = this.props + + return ( +
    +
    + this.setSearch(e.target.value)} + /> +
    + Total templates: {total} +
    +
    + + + + + + + + + + + + + {surveys && surveys.map((survey, index) => + + + + + + + + + )} + +
    #NameChangedPagesQuestionsActions
    {index + 1}{survey.name}{survey.changed}{survey.pages}{survey.questions} +
    + + +
    +
    + update(page, this.state.search)} page={page} pages={pages} /> +
    + ) + } +} + +export default SurveyTemplatesList diff --git a/pool/shard001/JavaScript/0011061_server.js b/pool/shard001/JavaScript/0011061_server.js new file mode 100644 index 0000000000000000000000000000000000000000..69dc8a8ffae0d94ddb753874d13b061140c6d550 --- /dev/null +++ b/pool/shard001/JavaScript/0011061_server.js @@ -0,0 +1,36 @@ +const express = require('express'); +const app = express(); +const mongoose = require('mongoose'); + +const config = require(__dirname + '/.env'); +process.env.APP_SECRET = config.APP_SECRET; +process.env.GOOGLE_MAPS_API_KEY = config.GOOGLE_MAPS_API_KEY; + +const businessRouter = require(__dirname + '/routes/business_router'); +const reviewRouter = require(__dirname + '/routes/review_router'); +const userRouter = require(__dirname + '/routes/user_router'); +const externalRouter = require(__dirname + '/routes/external_api_router'); +const jsonParser = require('body-parser').json(); +const cloudTokenizer = require(__dirname + '/lib/cloud_tokenizer'); + +mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/grok_dev'); + +app.use(express.static(__dirname + '/build')); + +app.use('/api', businessRouter); +app.use('/api', reviewRouter); +app.use('/api', userRouter); +app.use('/api', externalRouter); + +app.get('/cloudData', jsonParser, (req, res)=>{ + // data needs validation + var obj = req.body; + console.log(req.body); + var tokenCloud = cloudTokenizer(obj); + console.log(tokenCloud); + res.json(tokenCloud); + res.end(); +}); + +var PORT = process.env.PORT || 3000; +app.listen(PORT, () => console.log('Server started on port: ' + PORT)); diff --git a/pool/shard001/JavaScript/0011062_index.js b/pool/shard001/JavaScript/0011062_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d9fb4e97a0f55be198151ab6c77fd2b3bb9c9a2f --- /dev/null +++ b/pool/shard001/JavaScript/0011062_index.js @@ -0,0 +1,16 @@ +const modern = require('../../src/modern'); +const compress = require('compression'); + +module.exports = { + name: 'compress', + options: { + __root: 'compress', + compress: { + default: {}, + type: Object + } + }, + + // The whole plugin won't be loaded if the option is false + before: ctx => modern(compress(ctx.options.compress))(ctx) +}; diff --git a/pool/shard001/JavaScript/0011065_regress-crbug-1069530.js b/pool/shard001/JavaScript/0011065_regress-crbug-1069530.js new file mode 100644 index 0000000000000000000000000000000000000000..1fca911f3bba361773b5d402afc7a4a810ec270f --- /dev/null +++ b/pool/shard001/JavaScript/0011065_regress-crbug-1069530.js @@ -0,0 +1,29 @@ +// Copyright 2020 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --no-lazy-feedback-allocation + +function store(ar, index) { + ar[index] = "a"; +} + +let growable_array = []; + +// Train IC on growable array +store(growable_array, 0); +store(growable_array, 1); +store(growable_array, 2); +store(growable_array, 3); + +// Now make IC polymorphic +var array = []; +Object.defineProperty(array, "length", { value: 3, writable: false }); + +store(array, 0); +store(array, 1); + +// ... and try to grow it. +store(array, 3); +assertEquals(undefined, array[3]); +assertEquals(3, array.length); diff --git a/pool/shard001/JavaScript/0011068_plugin.js b/pool/shard001/JavaScript/0011068_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..85d82cc1274a67d161d9e654b3a99216f218e084 --- /dev/null +++ b/pool/shard001/JavaScript/0011068_plugin.js @@ -0,0 +1,85 @@ +(function () { +var nonbreaking = (function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var stringRepeat = function (string, repeats) { + var str = ''; + for (var index = 0; index < repeats; index++) { + str += string; + } + return str; + }; + var isVisualCharsEnabled = function (editor) { + return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false; + }; + var insertNbsp = function (editor, times) { + var nbsp = isVisualCharsEnabled(editor) ? ' ' : ' '; + editor.insertContent(stringRepeat(nbsp, times)); + editor.dom.setAttrib(editor.dom.select('span.mce-nbsp'), 'data-mce-bogus', '1'); + }; + var $_eqfkn3htjjgwecrh = { insertNbsp: insertNbsp }; + + var register = function (editor) { + editor.addCommand('mceNonBreaking', function () { + $_eqfkn3htjjgwecrh.insertNbsp(editor, 1); + }); + }; + var $_duyz3ehsjjgwecrg = { register: register }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK'); + + var getKeyboardSpaces = function (editor) { + var spaces = editor.getParam('nonbreaking_force_tab', 0); + if (typeof spaces === 'boolean') { + return spaces === true ? 3 : 0; + } else { + return spaces; + } + }; + var $_7krohxhwjjgwecrk = { getKeyboardSpaces: getKeyboardSpaces }; + + var setup = function (editor) { + var spaces = $_7krohxhwjjgwecrk.getKeyboardSpaces(editor); + if (spaces > 0) { + editor.on('keydown', function (e) { + if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) { + if (e.shiftKey) { + return; + } + e.preventDefault(); + e.stopImmediatePropagation(); + $_eqfkn3htjjgwecrh.insertNbsp(editor, spaces); + } + }); + } + }; + var $_cy5vbshujjgwecri = { setup: setup }; + + var register$1 = function (editor) { + editor.addButton('nonbreaking', { + title: 'Nonbreaking space', + cmd: 'mceNonBreaking' + }); + editor.addMenuItem('nonbreaking', { + icon: 'nonbreaking', + text: 'Nonbreaking space', + cmd: 'mceNonBreaking', + context: 'insert' + }); + }; + var $_6surrthxjjgwecrl = { register: register$1 }; + + global.add('nonbreaking', function (editor) { + $_duyz3ehsjjgwecrg.register(editor); + $_6surrthxjjgwecrl.register(editor); + $_cy5vbshujjgwecri.setup(editor); + }); + function Plugin () { + } + + return Plugin; + +}()); +})(); diff --git a/pool/shard001/JavaScript/0011069_item.js b/pool/shard001/JavaScript/0011069_item.js new file mode 100644 index 0000000000000000000000000000000000000000..a91a3f0196359d09056b2e17d716449981e4bebf --- /dev/null +++ b/pool/shard001/JavaScript/0011069_item.js @@ -0,0 +1,55 @@ +import { connect } from 'react-redux'; +import { getItem } from '../managers/item'; +import actions from '../actions/item' +import ItemComponent from '../components/item.jsx'; + +const mapStateToProps = (state, ownProps) => { + const item = getItem(ownProps.id); + + return { + draggedOver: state.drag.draggedOverItem === ownProps.id, + isOverItself: state.drag.draggedOverItem === state.drag.draggedItem === ownProps.id, + canBePicked: item.canPick, + label: item.label + } +} + +const mapDispatchToProps = (dispatch, ownProps) => { + const item = getItem(ownProps.id); + + return { + handleDragStart: (e) => { + dispatch(actions.startDragging(ownProps.id)); + }, + handleDragEnd: (e) => { + dispatch(actions.stopDragging()); + }, + handleDragEnter: (e) => { + dispatch(actions.startDragOver(ownProps.id)); + e.stopPropagation(); + }, + handleDragLeave: (e) => { + dispatch(actions.stopDragOver()); + e.stopPropagation(); + }, + handleDrop: (e) => { + dispatch(actions.dropItem()); + }, + handleMouseEnter: (e) => { + dispatch(actions.startHover(ownProps.id)); + }, + handleMouseLeave: (e) => { + dispatch(actions.stopHover()); + }, + handleClick: (e) => { + dispatch(actions.examine(item.label, item.description)) + } + } +} + +const Item = connect( + mapStateToProps, + mapDispatchToProps +)(ItemComponent) + +export default Item diff --git a/pool/shard001/JavaScript/0011071_timeline.js b/pool/shard001/JavaScript/0011071_timeline.js new file mode 100644 index 0000000000000000000000000000000000000000..2071a91712fe85fcfa63329bce341042eb3936d9 --- /dev/null +++ b/pool/shard001/JavaScript/0011071_timeline.js @@ -0,0 +1,55 @@ +//------------- timeline.js -------------// +$(document).ready(function() { + + + +}); + +//sparkline in sidebar area +var positive = [1,5,3,7,8,6,10]; +var negative = [10,6,8,7,3,5,1] +var negative1 = [7,6,8,7,6,5,4] + +$('#stat1').sparkline(positive,{ + height:15, + spotRadius: 0, + barColor: '#9FC569', + type: 'bar' +}); +$('#stat2').sparkline(negative,{ + height:15, + spotRadius: 0, + barColor: '#ED7A53', + type: 'bar' +}); +$('#stat3').sparkline(negative1,{ + height:15, + spotRadius: 0, + barColor: '#ED7A53', + type: 'bar' +}); +$('#stat4').sparkline(positive,{ + height:15, + spotRadius: 0, + barColor: '#9FC569', + type: 'bar' +}); +//sparkline in widget +$('#stat5').sparkline(positive,{ + height:15, + spotRadius: 0, + barColor: '#9FC569', + type: 'bar' +}); + +$('#stat6').sparkline(positive, { + width: 70,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth) + height: 20,//Height of the chart - Defaults to 'auto' (line height of the containing tag) + lineColor: '#88bbc8',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string + fillColor: '#f2f7f9',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill + spotColor: '#e72828',//The CSS colour of the final value marker. Set to false or an empty string to hide it + maxSpotColor: '#005e20',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it + minSpotColor: '#f7941d',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it + spotRadius: 3,//Radius of all spot markers, In pixels (default: 1.5) - Integer + lineWidth: 2//In pixels (default: 1) - Integer +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011072_home.controller.js b/pool/shard001/JavaScript/0011072_home.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..ee248009e3db5b7b38960d37c8eaff2e3b63cd9d --- /dev/null +++ b/pool/shard001/JavaScript/0011072_home.controller.js @@ -0,0 +1,41 @@ +(function() { + 'use strict'; + + angular + .module('supermodular.home') + .controller('HomeController', HomeController); + + HomeController.$inject = ['menuItems', 'homeDataService', 'externalAppsService', '$cordovaEmailComposer']; + + /* @ngInject */ + function HomeController(menuItems, homeDataService, externalAppsService, $cordovaEmailComposer) { + var vm = angular.extend(this, { + entries: menuItems, + phoneNumber: homeDataService.phoneNumber, + getDirections: getDirections, + sendEmail: sendEmail, + openFacebookPage: openFacebookPage + }); + + function getDirections() { + externalAppsService.openMapsApp(homeDataService.officeLocation); + } + + function sendEmail() { + $cordovaEmailComposer.isAvailable().then(function() { + var email = { + to: homeDataService.email, + subject: 'Cordova Icons', + body: 'How are you? Nice greetings from Leipzig' + }; + + $cordovaEmailComposer.open(email); + }); + } + + function openFacebookPage() { + externalAppsService.openExternalUrl(homeDataService.facebookPage); + } + + } +})(); diff --git a/pool/shard001/JavaScript/0011076_serialization.js b/pool/shard001/JavaScript/0011076_serialization.js new file mode 100644 index 0000000000000000000000000000000000000000..4fc1e9b519bbd836dbdefaf5772ea1a0bb0c553a --- /dev/null +++ b/pool/shard001/JavaScript/0011076_serialization.js @@ -0,0 +1,166 @@ +//---------------------------------------------------------------------- +// +// This source file is part of the Folktale project. +// +// Licensed under MIT. See LICENCE for full licence information. +// See CONTRIBUTORS for the list of contributors to the project. +// +//---------------------------------------------------------------------- + +// --[ Dependencies ]--------------------------------------------------- +const { tagSymbol, typeSymbol } = require('../union'); +const mapValues = require('folktale/core/object/map-values'); +const values = require('folktale/core/object/values'); +const extend = require('folktale/helpers/extend'); + + +// --[ Constants ]------------------------------------------------------ +const typeJsonKey = '@@type'; +const tagJsonKey = '@@tag'; +const valueJsonKey = '@@value'; + + +// --[ Helpers ]-------------------------------------------------------- + +/*~ + * type: ((Object 'a) => 'b) => ([Object 'a]) => Object 'b + */ +const arrayToObject = (extractKey) => (array) => + array.reduce((object, element) => { + object[extractKey(element)] = element; + return object; + }, {}); + + +/*~ + * type: (String) => (Object 'a) => 'a | None + */ +const property = (propertyName) => (object) => object[propertyName]; + + +/*~ + * type: ([Object 'a]) => Object 'a + */ +const indexByType = arrayToObject(property(typeSymbol)); + + +/*~ + * type: (String, String) => Bool + */ +const assertType = (given, expected) => { + if (expected !== given) { + throw new TypeError(` + The JSON structure was generated from ${expected}. + You are trying to parse it as ${given}. + `); + } +}; + + +/*~ + * type: | + * type JSONSerialisation = { + * "@@type": String, + * "@@tag": String, + * "@@value": Object Any + * } + * type JSONParser = { + * fromJSON: (JSONSerialisation, Array JSONParser) => Variant + * } + * + * (Object JSONParser) => (JSONSerialisation) => Any + */ +const parseValue = (parsers) => (value) => { + if (value !== null && typeof value[typeJsonKey] === 'string') { + const type = value[typeJsonKey]; + if (parsers[type]) { + return parsers[type].fromJSON(value, parsers, true); + } else { + return value; + } + } else { + return value; + } +}; + + +/*~ + * type: ('a) => JSON + */ +const serializeValue = (value) => + value === undefined ? null +: value !== null && typeof value.toJSON === 'function' ? value.toJSON() +: /* otherwise */ value; + + +// --[ Implementation ]------------------------------------------------- + +/*~ + * stability: experimental + * authors: + * - "@boris-marinov" + * + * type: | + * (Variant, ADT) => Void + */ +const serialization = (variant, adt) => { + const typeName = adt[typeSymbol]; + const tagName = variant.prototype[tagSymbol]; + + /*~ + * stability: experimental + * module: null + * authors: + * - "@boris-marinov" + * + * type: | + * type JSONSerialisation = { + * "@@type": String, + * "@@tag": String, + * "@@value": Object Any + * } + * + * Variant . () => JSONSerialisation + */ + variant.prototype.toJSON = function() { + return { + [typeJsonKey]: typeName, + [tagJsonKey]: tagName, + [valueJsonKey]: mapValues(this, serializeValue) + }; + }; + + /*~ + * stability: experimental + * module: null + * authors: + * - "@boris-marinov" + * + * type: | + * type JSONSerialisation = { + * "@@type": String, + * "@@tag": String, + * "@@value": Object Any + * } + * type JSONParser = { + * fromJSON: (JSONSerialisation, Array JSONParser) => Variant + * } + * + * (JSONSerialisation, Array JSONParser) => Variant + */ + adt.fromJSON = function(value, parsers = { [typeName]: adt }, keysIndicateType = false) { + const valueTypeName = value[typeJsonKey]; + const valueTagName = value[tagJsonKey]; + const valueContents = value[valueJsonKey]; + assertType(typeName, valueTypeName); + const parsersByType = keysIndicateType ? parsers + : /*otherwise*/ indexByType(values(parsers)); + + const parsedValue = mapValues(valueContents, parseValue(parsersByType)); + return extend(Object.create(adt[valueTagName].prototype), parsedValue); + }; +}; + + +// --[ Exports ]-------------------------------------------------------- +module.exports = serialization; diff --git a/pool/shard001/JavaScript/0011077_lengthValidator.js b/pool/shard001/JavaScript/0011077_lengthValidator.js new file mode 100644 index 0000000000000000000000000000000000000000..caab6a2640fe5538fa09ec4eb3adb144ea09c46d --- /dev/null +++ b/pool/shard001/JavaScript/0011077_lengthValidator.js @@ -0,0 +1,44 @@ +/** + * Developer: Stepan Burguchev + * Date: 1/26/2015 + * Copyright: 2009-2016 Comindware® + * All Rights Reserved + * Published under the MIT license + */ + +"use strict"; + +import '../../libApi'; +import LocalizationService from '../../services/LocalizationService'; + +Backbone.Form.validators.length = function(options) { + options = _.extend({ + type: 'length', + message: LocalizationService.get('CORE.FORM.VALIDATION.LENGTH') + }, options); + + return function length(value) { + + var val = _.isObject(value) ? value.value : value; + options.value = val; + var err = { + type: options.type, + message: _.isFunction(options.message) ? options.message(options) : options.message + }; + //Don't check empty values (add a 'required' validator for this) + if (val === null || val === undefined || val === '') return; + + if (options.min) { + if (val.length < options.min) { + return err; + } + } + if (options.max) { + if (val.length > options.max) { + return err; + } + } + }; +}; + +export default Backbone.Form.validators.length; diff --git a/pool/shard001/JavaScript/0011078_hole-carousel.js b/pool/shard001/JavaScript/0011078_hole-carousel.js new file mode 100644 index 0000000000000000000000000000000000000000..705b0fde2c49c0ad2b21977070a33e21023e4df1 --- /dev/null +++ b/pool/shard001/JavaScript/0011078_hole-carousel.js @@ -0,0 +1,68 @@ +define('views/hole-carousel',['require','jquery','backbone','utils/browser','utils/pubsub','utils/carousel','collections/holes','views/base-carousel','views/hole-card','utils/metrics','unveil'],function(require) { + var $ = require('jquery'), + Backbone = require('backbone'), + Browser = require('utils/browser'), + PubSub = require('utils/pubsub'), + Carousel = require('utils/carousel'), + Holes = require('collections/holes'), + BaseCarousel = require('views/base-carousel'), + HoleCard = require('views/hole-card'), + Metrics = require('utils/metrics') + ; + + require('unveil'); + + var HoleCarouselView = BaseCarousel.extend({ + + initialize: function(opts) { + this.logger = new eventsCore.util.Logger('HoleCarouselView'); + BaseCarousel.prototype.initialize.apply(this, arguments); + }, + + // overrides base carousel loadContentCarousel() here + loadContentCarousel : function() { + + var $hole_data; + + var that = this; + + Holes.fetch({ + success: function(holes){ + that.collection = holes; + that.process(); + } + }); + }, + + process: function() { + var holes_list = []; + + _.each(this.options.article_holes, function(hole){ + + this.logger.info('loadHoleCarousel - article_holes hole:%o', hole); + + var html = ""; + var obj; + var hole_num = this.collection.get(hole); + + obj = new HoleCard({model: hole_num, story: true, flyover: true, metrics_suffix: 'course_article'}).render(); + this.cards.push(obj); + + html = obj.$el; + holes_list.push(html); + }.bind(this)); + + // write new html + this.$('.carousel').append(holes_list); + + this.clearUnveil(); + this.unveil(this.$('.carousel').find('.image img, .photo img'), { horizontal: true }); + + this.hole_carousel = new Carousel(); + h_opts = this.getCarouselOptions(); + this.hole_carousel.init(this.$('.carousel'),h_opts); + } + }); + + return HoleCarouselView; +}); diff --git a/pool/shard001/JavaScript/0011079_index.js b/pool/shard001/JavaScript/0011079_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4d0ef2a25d52b4de4682802eb7976b2cd7c385ea --- /dev/null +++ b/pool/shard001/JavaScript/0011079_index.js @@ -0,0 +1,188 @@ +import React, { Component } from 'react' +import * as PropTypes from "prop-types" +import { Segment, Container, Grid, Image } from 'semantic-ui-react' + +import BigTitle from '../components/Text/BigTitle' +import MediumTitle from '../components/Text/MediumTitle' +import IndexCover from '../components/IndexCover' +import PreviewCard from '../components/PreviewCard' +import Noticia from '../components/Noticia' + +const propTypes = { + data: PropTypes.object.isRequired, +} + +class IndexPage extends Component { + componentDidMount() { + //this.props.updateTitle('') + } + render() { + //const randomCover = this.props.data.allContentfulCover.edges[Math.floor(Math.random() * cover.length)] + const randomCover = this.props.data.allContentfulCover.edges["2"] + const lastNews = this.props.data.allContentfulNews.edges + const lastArtists = this.props.data.allContentfulArtist.edges + const lastAlbum = this.props.data.allContentfulAlbum.edges["0"].node + + return ( +
    + + + + + + + + + Álbums + + + {lastAlbum.title} + +

    + {lastAlbum.description.description} +

    +
    + + + +
    +
    +
    +
    + + + + + + + + { + lastArtists.map(({ node }) => + + + + ) + } + + + + + Artistas + +

    + Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. +

    +
    +
    +
    +
    +
    + + + + { + lastNews.map(({ node }) => + + ) + } + + + +
    + ) + } +} + +export default IndexPage + +export const pageQuery = graphql` + query CoverQuery { + allContentfulCover { + edges { + node { + id + photo { + responsiveResolution(width: 1800) { + base64 + aspectRatio + width + height + src + srcSet + } + } + } + } + } + allContentfulAlbum( + limit:1 + sort: { fields: [date], order: DESC}) { + edges { + node { + id + title + description { + description + } + artist { + artistName + } + cover { + responsiveResolution(width: 1200, height: 1200) { + src + srcSet + } + } + } + } + } + allContentfulArtist( + limit:2 + ) { + edges { + node { + id + artistName + soundCloudUsername + profilePicture { + responsiveResolution { + src + srcSet + } + } + bio { + bio + } + } + } + } + allContentfulNews( + limit: 1 + sort: { fields: [date], order: DESC } + ) { + edges { + node { + id + date + title + content { + content + } + media { + responsiveResolution { + src + srcSet + } + } + } + } + } + } +` diff --git a/pool/shard001/JavaScript/0011080_setAccessForUser.js b/pool/shard001/JavaScript/0011080_setAccessForUser.js new file mode 100644 index 0000000000000000000000000000000000000000..85517435b582b61307228ab50fca19dc6335e25c --- /dev/null +++ b/pool/shard001/JavaScript/0011080_setAccessForUser.js @@ -0,0 +1,69 @@ +'use strict'; + +var method = require('./../method'); +var assign = require('lodash.assign'); + +/** + * @memberof machines + * @method setAccessForUser + * @description Show machine information for the machine with the given id. + * + * The state property can take on the follow values: + * - off + * - starting - machine is in the process of changing to the ready or serviceready state + * - stopping - machine is in the process of changing to the off state + * - restarting - combines stopping follow immediately by starting + * - serviceready - services are running on the machine but the Paperspace agent is not yet available + * - ready - services are running on machine and the Paperspace agent is ready to stream or accept logins + * - upgrading - the machine specification are being upgraded, which involves a shutdown and startup sequence + * - provisioning - the machine is in the process of being created for the first time + * + * The updatesPending property is either true or false and reflects whether the operating system has scheduled updates + * for the next machine state transition, e.g, stopping, starting, restarting or upgrading. + * + * Note: in some cases the operating system can force installation of critical updates immediately upon a state + * transition, or automatically restart a machine to install updates. In such cases the updatesPending property + * may not always be set accurately by the underlying os. + * @param {object} params - Machine show parameters + * @param {string} params.machineId - Id of the machine to show + * @param {string} params.userId - Id of the user to enable machine access for + * @param {boolean} params.enabeAccess- releases any assigned public ip address for the machine; defaults to false + * @param {function} cb - Node-style error-first callback function + * @returns {object} machine - The machine JSON object + * @example + * paperspace.machines.setAccessForUser({ + * machineId: 'ps123abc', + * userId: 'u123abc, + * }, function(err, res) { + * // handle error or result + * }); + * @example + * $ paperspace machines setAccessForUser \ + * --machineId "ps123abc" --userId "u12abc" + * @example + * # HTTP request: + * https://api.paperspace.io + * GET /machines/:machineId/setMachineAccessPublic?userId=u123abc + * x-api-key: 1ba4f98e7c0... + * # Returns 200 on success + */ + +function setAccessForUser(params, cb) { + return method(setAccessForUser, params, cb); +} + +assign(setAccessForUser, { + auth: true, + group: 'machines', + name: 'setAccessForUser', + method: 'post', + route: '/machines/:machineId/setMachineAccess', + requires: { + machineId: 'string', + userId: "string", + enableAccess: 'boolean', + }, + returns: {}, +}); + +module.exports = setAccessForUser; diff --git a/pool/shard001/JavaScript/0011081_touch.js b/pool/shard001/JavaScript/0011081_touch.js new file mode 100644 index 0000000000000000000000000000000000000000..db3ecd2b9597a1db9af02331f38963f8ec700dbb --- /dev/null +++ b/pool/shard001/JavaScript/0011081_touch.js @@ -0,0 +1,309 @@ +/* + * This file is part of the Fxp package. + * + * (c) François Pluchino + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import {isOverMinWidth, getTargetPosition, changeTransition, changeTranslate, changeTransform} from "./css"; +import {triggerEvent} from "./events"; +import {lockBodyScroll, unlockBodyScroll} from "./scrollbar"; +import {cleanCloseDelay} from "./actions"; +import {FORCE_TOGGLE, FORCE_TOGGLE_ALWAYS, POSITION_LEFT, POSITION_RIGHT} from "./const"; +import {addClassToggles, removeClassToggles} from "./toggle"; + +/** + * Trigger the opened or closed event when the transition is finished. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + */ +export function onEndTransition(event) { + let self = event.data, + action = event.data.isOpen() ? 'opened' : 'closed'; + + if (event.target !== self.$element.get(0)) { + return; + } + + if (event.data.isOpen()) { + addClassToggles(self, self.options.classOpen + '-toggle'); + + if ($.fn.scroller && self.options.useScroller) { + self.$element.scroller('resizeScrollbar'); + } + + $('a:visible:first', self.$toggles.get(0).parent()).focus(); + } else { + removeClassToggles(self, self.options.classOpen + '-toggle'); + + if ($.fn.scroller && self.options.useScroller) { + self.$element.scroller('resizeScrollbar'); + } + } + + if (self.isLocked()) { + if (!isOverMinWidth(self) && self.isOpen()) { + lockBodyScroll(self); + } else { + unlockBodyScroll(self); + } + } + + triggerEvent(action, self); +} + +/** + * Action of "on drag" hammer event. + * + * @param {Sidebar} self The sidebar instance + * @param {object} event The hammer event + * + * @typedef {Number} event.deltaX The hammer delta X + * @typedef {Number} event.deltaY The hammer delta Y + */ +export function onDrag(self, event) { + let delta; + + if (null !== self.resetScrolling || event.target === self.$obfuscator.get(0)) { + return; + } + + // drag start + if (null === self.dragDirection) { + if (Math.abs(event.deltaX) <= Math.abs(event.deltaY)) { + return; + } + + self.mouseDragEnd = null; + self.dragDirection = event.direction; + self.$element.css('user-select', 'none'); + cleanCloseDelay(self); + } + + // drag + if (-1 === $.inArray(self.dragDirection, [Hammer.DIRECTION_LEFT, Hammer.DIRECTION_RIGHT]) || + (self.options.locked && isOverMinWidth(self) && self.isOpen())) { + return; + } + + event.preventDefault(); + + if (null === self.dragStartPosition) { + self.dragStartPosition = getTargetPosition(self.$element); + } + + delta = Math.round(self.dragStartPosition + event.deltaX); + + if ((POSITION_LEFT === self.getPosition() && delta > 0) || + (POSITION_RIGHT === self.getPosition() && delta < 0)) { + delta = 0; + } + + self.$element.addClass(self.options.classOnDragging); + changeTransition(self.$element, 'none'); + changeTranslate(self.$element, delta); +} + +/** + * Action of "on drag end" hammer event. + * + * @param {Sidebar} self The sidebar instance + * @param {object} event The hammer event + * + * + * @typedef {Number} event.deltaX The hammer delta X + * @typedef {Number} event.direction The hammer direction const + */ +export function onDragEnd(self, event) { + let closeGesture = Hammer.DIRECTION_LEFT, + openGesture = Hammer.DIRECTION_RIGHT; + + if (null !== self.resetScrolling || event.target === self.$obfuscator.get(0)) { + return; + } + + self.dragStartPosition = null; + event.preventDefault(); + + if (self.fixDragClick && -1 !== $.inArray(event.srcEvent.type, ['pointerup', 'mouseup'])) { + self.mouseDragEnd = true; + } + + self.$element.removeClass(self.options.classOnDragging); + self.$element.css('user-select', ''); + changeTransition(self.$element, ''); + changeTransform(self.$element, ''); + + if (Math.abs(event.deltaX) <= (self.$element.innerWidth() / 4)) { + self.dragDirection = null; + self.$toggles.focus(); + + return; + } + + if (POSITION_RIGHT === self.getPosition()) { + closeGesture = Hammer.DIRECTION_RIGHT; + openGesture = Hammer.DIRECTION_LEFT; + } + + if (self.isOpen() && closeGesture === self.dragDirection) { + self.forceClose(); + + } else if (openGesture === self.dragDirection) { + self.mouseDragEnd = null; + + if (self.isOpen() && isOverMinWidth(self) && + $.inArray(self.options.forceToggle, [FORCE_TOGGLE, FORCE_TOGGLE_ALWAYS]) >= 0) { + self.forceOpen(); + + } else if (isOverMinWidth(self) && FORCE_TOGGLE_ALWAYS === self.options.forceToggle) { + self.forceOpen(); + + } else { + self.open(); + } + } + + self.dragDirection = null; +} + +/** + * Init the hammer instance. + * + * @param {Sidebar} self The sidebar instance + */ +export function initHammer(self) { + if (!self.options.draggable || typeof Hammer !== 'function') { + return; + } + + self.$swipe = $(''); + self.$element.after(self.$swipe); + + self.hammer = new Hammer(self.$wrapper.get(0), $.extend(true, {}, self.options.hammer)); + + self.hammer.get('swipe').set({ enable: false }); + self.hammer.get('tap').set({ enable: false }); + + self.hammer.on('panstart', function (event) { + onDrag(self, event); + }); + self.hammer.on('pan', function (event) { + onDrag(self, event); + }); + self.hammer.on('panend', function (event) { + onDragEnd(self, event); + }); + + self.$wrapper.on('mousedown.fxp.sidebar', null, self, onItemMouseDown); + self.$wrapper.on('click.fxp.sidebar', null, self, onItemClick); + + if (self.options.clickableSwipe) { + self.$swipe + .on('click.fxp.sidebar' + self.guid, null, self, swipeClick) + .on('mouseenter.fxp.sidebar' + self.guid, null, self, swipeMouseEnter) + .on('mouseleave.fxp.sidebar' + self.guid, null, self, swipeMouseLeave) + ; + } +} + +/** + * Destroy the hammer configuration. + * + * @param {Sidebar} self The sidebar instance + */ +export function destroyHammer(self) { + if (!self.options.draggable || typeof Hammer !== 'function') { + return; + } + + if (self.options.clickableSwipe) { + self.$swipe + .off('click.fxp.sidebar' + self.guid, swipeClick) + .off('mouseenter.fxp.sidebar' + self.guid, swipeMouseEnter) + .off('mouseleave.fxp.sidebar' + self.guid, swipeMouseLeave) + ; + } + + self.$wrapper.off('mousedown.fxp.sidebar', onItemMouseDown); + self.$wrapper.off('click.fxp.sidebar', onItemClick); + self.$swipe.remove(); + self.hammer.destroy(); + + delete self.$swipe; + delete self.hammer; +} + + + +/** + * Action on swipe is clicked. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + * + * @private + */ +function swipeClick(event) { + swipeMouseLeave(event); + event.data.toggle(event); +} + +/** + * Action when mouse enter on sur swipe. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + * + * @private + */ +function swipeMouseEnter(event) { + event.data.$swipe.addClass('mouse-hover'); +} + +/** + * Action when mouse leave on sur swipe. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + * + * @private + */ +function swipeMouseLeave(event) { + event.data.$swipe.removeClass('mouse-hover'); +} + +/** + * Action on item mouse down. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + */ +function onItemMouseDown(event) { + event.preventDefault(); +} + +/** + * Action on item click. + * + * @param {Event} event The event + * + * @typedef {Sidebar} Event.data The sidebar instance + */ +function onItemClick(event) { + let self = event.data; + + if (true === self.mouseDragEnd) { + event.preventDefault(); + cleanCloseDelay(self); + self.mouseDragEnd = null; + } +} diff --git a/pool/shard001/JavaScript/0011084_adminEmailLog.js b/pool/shard001/JavaScript/0011084_adminEmailLog.js new file mode 100644 index 0000000000000000000000000000000000000000..9ac161bbf52a82cea460052629ac6b3493f17fa3 --- /dev/null +++ b/pool/shard001/JavaScript/0011084_adminEmailLog.js @@ -0,0 +1,91 @@ +'use strict'; + +var retryTimes = 0; +var numOfEntriesPerPage = 50; + +$(document).ready(function() { + bindClickAction(); + clickOlderButtonIfNeeded(); + $('#filterReference').toggle(); +}); + +function toggleReference() { + $('#filterReference').toggle('slow'); + + var button = $('#detailButton').attr('class'); + + if (button === 'glyphicon glyphicon-chevron-down') { + $('#detailButton').attr('class', 'glyphicon glyphicon-chevron-up'); + $('#referenceText').text('Hide Reference'); + } else { + $('#detailButton').attr('class', 'glyphicon glyphicon-chevron-down'); + $('#referenceText').text('Show Reference'); + } +} + +function bindClickAction() { + $('body').unbind('click', handler).on('click', '.log', handler); +} + +var handler = function() { + $(this).next('#small').toggle(); + $(this).next('#small').next('#big').toggle(); +}; + +function clickOlderButtonIfNeeded() { + if (retryTimes >= 20) { + return; + } + + var curNumOfEntries = $('#emailLogsTable tbody tr').length; + + if (curNumOfEntries < numOfEntriesPerPage) { + if ($('#button_older').length) { + $('#button_older').click(); + retryTimes++; + } + } +} + +function submitFormAjax(offset) { + $('input[name=offset]').val(offset); + var formObject = $('#ajaxLoaderDataForm'); + var formData = formObject.serialize(); + var button = $('#button_older'); + var lastLogRow = $('#emailLogsTable tr:last'); + + $.ajax({ + type: 'POST', + url: '/admin/adminEmailLogPage?' + formData, + beforeSend: function() { + button.html(""); + }, + error: function() { + setFormErrorMessage(button, 'Failed to load older logs. Please try again.'); + button.html('Retry'); + }, + success: function(data) { + setTimeout(function() { + if (data.isError) { + setFormErrorMessage(button, data.errorMessage); + } else { + // Inject new log row + var logs = data.logs; + $.each(logs, function(i, value) { + lastLogRow.after(value.logInfoAsHtml); + lastLogRow = $('#emailLogsTable tr:last'); + bindClickAction(); + clickOlderButtonIfNeeded(); + }); + } + + setStatusMessage(data.statusForAjax, StatusType.INFO); + + }, 500); + } + }); +} + +function setFormErrorMessage(button, msg) { + button.after('   ' + msg); +} diff --git a/pool/shard001/JavaScript/0011086_responsive_menus_mean_menu.js b/pool/shard001/JavaScript/0011086_responsive_menus_mean_menu.js new file mode 100644 index 0000000000000000000000000000000000000000..815b9e1fb5a8b0aa6a5bcae68829c89a5d9ae4ac --- /dev/null +++ b/pool/shard001/JavaScript/0011086_responsive_menus_mean_menu.js @@ -0,0 +1,35 @@ +/** + * @file + * Integrate Mean Menu library with Responsive Menus module. + */ +(function ($) { + Drupal.behaviors.responsive_menus_mean_menu = { + attach: function (context, settings) { + settings.responsive_menus = settings.responsive_menus || {}; + $.each(settings.responsive_menus, function(ind, iteration){ + if (iteration.responsive_menus_style != 'mean_menu') { + return true; + } + if (!iteration.selectors.length) { + return; + } + // Call meanmenu() with our custom settings. + $(iteration.selectors).once('responsive-menus-mean-menu', function() { + $(this).meanmenu({ + meanMenuClose: iteration.close_txt || "X", + meanMenuCloseSize: iteration.close_size || "18px", + meanMenuOpen: iteration.trigger_txt || "", + meanRevealPosition: iteration.position || "right", + meanScreenWidth: iteration.media_size || "480", + meanShowChildren: iteration.show_children || true, + meanExpandableChildren: iteration.expand_children || true, + meanExpand: iteration.expand_txt || "+", + meanContract: iteration.contract_txt || "-", + meanRemoveAttrs: iteration.remove_attrs || true + }); + }); + }); + + } + }; +}(jQuery)); diff --git a/pool/shard001/JavaScript/0011088_Config.js b/pool/shard001/JavaScript/0011088_Config.js new file mode 100644 index 0000000000000000000000000000000000000000..36c1e101d940f0921049095a37efebfb39867690 --- /dev/null +++ b/pool/shard001/JavaScript/0011088_Config.js @@ -0,0 +1,26 @@ +const fs = require("fs"); + +const AUTH_TOKEN_COOKIE_NAME = "ark_asm_authToken"; +let config; + +function loadConfig() { + const defaultConfig = { + authTokenCookieName: AUTH_TOKEN_COOKIE_NAME, + port: 8083, + users: [] + }; + try { + let config = JSON.parse(fs.readFileSync("./config.json", "utf8")); + config.authTokenCookieName = AUTH_TOKEN_COOKIE_NAME; + return config; + } catch (e) { + console.log("Error reading the config file, using default config: ", e); + return defaultConfig; + } +} + +if (!config) { + config = loadConfig(); +} + +module.exports = config; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011089_SimpleDashboard.js b/pool/shard001/JavaScript/0011089_SimpleDashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..35b86a08142edb272372fadef1abb5f1b2a11c39 --- /dev/null +++ b/pool/shard001/JavaScript/0011089_SimpleDashboard.js @@ -0,0 +1,209 @@ +/* + * Copyright 2007-2017 Charles du Jeu - Abstrium SAS + * This file is part of Pydio. + * + * Pydio is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Pydio 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 Pydio. If not, see . + * + * The latest code can be found at . + */ +const React = require('react') +const {muiThemeable} = require('material-ui/styles') +const {Paper, Card, CardTitle, CardMedia, CardActions, CardHeader, CardText, + FlatButton, List, ListItem, Divider, IconButton, FontIcon} = require('material-ui') +import {MessagesConsumerMixin} from '../util/Mixins' +const shuffle = require('lodash.shuffle') + +let Dashboard = React.createClass({ + + mixins: [MessagesConsumerMixin], + + getInitialState: function(){ + return {kb: []}; + }, + + componentDidMount: function(){ + PydioApi.getClient().loadFile('plugins/access.ajxp_conf/res/i18n/kb.json', (transport) => { + const data = transport.responseJSON; + this.setState({kb: data}); + }); + }, + + getOpenIcon: function(link){ + return ( + {window.open(link)}} + /> + ); + }, + + getDocButton: function(icon, message, link){ + return ( +
    +
    {message}
    } + fullWidth={true} + onTouchTap={()=>{window.open(link)}} + /> +
    + ); + }, + + welcomeClick: function(e){ + if(e.target.getAttribute('data-path')){ + const p = e.target.getAttribute('data-path'); + this.props.pydio.goTo(p); + } + }, + + render: function(){ + + const horizontalFlex = {display:'flex', width:'100%'}; + const verticalFlex = {display:'flex', flexDirection:'column', height: '100%'}; + const flexFill = {flex:1}; + const flexFillNo = {width:120}; + + const paperStyle = {width:500, marginLeft:12, marginTop: 12}; + const flexContainerStyle = {...verticalFlex}; + const {primary1Color, accent1Color, accent2Color} = this.props.muiTheme.palette; + const textLinkStyle = {cursor: 'pointer', color: accent1Color}; + + const MEDIA_TEST_CARD = ( + + } + >
    +
    +
    +
    +
    +
    + + + + +
    + ); + + const {pydio} = this.props; + const message = (id) => {return pydio.MessageHash['admin_dashboard.' + id]}; + const OPEN_IN_NEW_ICON = ; + + // ADMIN GUIDE BUTTONS + const guidesButtons = [ + {icon:'clock-start', id:'start', link:'https://pydio.com/en/docs/v8/getting-started'}, + {icon:'network', id:'ws', link:'https://pydio.com/en/docs/v8/setup-workspaces-and-users'}, + {icon:'account-multiple', id:'users', link:'https://pydio.com/en/docs/v8/groups-admin-and-delegation'}, + {icon:'settings', id:'parameters', link:'https://pydio.com/en/docs/v8/pydio-advanced-configuration'}, + {icon:'professional-hexagon', id:'advanced', link:'https://pydio.com/en/docs/v8/pydio-advanced-configuration'} + ]; + + // DOCS LIST + let kbItems = []; + shuffle(this.state.kb).forEach((object) => { + kbItems.push(); + kbItems.push(); + }); + // Remove last divider + if(kbItems.length) kbItems.pop(); + + return ( +
    +
    + + + + "; + c = d.insertBefore(c.lastChild, d.firstChild); + b.hasCSS = !!c + } + g || t(a, b); + return a + } + + var k = l.html5 + || {}, s = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, r = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, j, o = "_html5shiv", h = 0, n = {}, g; + (function () { + try { + var a = f.createElement("a"); + a.innerHTML = ""; + j = "hidden"in a; + var b; + if (!(b = 1 == a.childNodes.length)) { + f.createElement("a"); + var c = f.createDocumentFragment(); + b = "undefined" == typeof c.cloneNode || "undefined" == typeof c.createDocumentFragment || "undefined" == typeof c.createElement + } + g = b + } catch (d) { + g = j = !0 + } + })(); + var e = {elements: k.elements + || "abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video", version: "3.6.2", shivCSS: !1 + !== k.shivCSS, supportsUnknownElements: g, shivMethods: !1 + !== k.shivMethods, type: "default", shivDocument: q, createElement: p, createDocumentFragment: function (a, b) { + a || (a = f); + if (g) { + return a.createDocumentFragment(); + } + for (var b = b || i(a), c = b.frag.cloneNode(), d = 0, e = m(), h = e.length; d < h; d++) { + c.createElement(e[d]); + } + return c + }}; + l.html5 = e; + q(f) +})(this, document); diff --git a/pool/shard001/JavaScript/0011766_querycontext.js b/pool/shard001/JavaScript/0011766_querycontext.js new file mode 100644 index 0000000000000000000000000000000000000000..69b148f5c0bbbc2a3c75089415d4967db6cf66ca --- /dev/null +++ b/pool/shard001/JavaScript/0011766_querycontext.js @@ -0,0 +1,169 @@ +//======================================================================== +// QueryContext definition +//======================================================================== + +function QueryContext(props) { + this.nextIndex = (props && props.nextIndex) ? props.nextIndex : null; + this.pageSize = (props && props.pageSize) ? props.pageSize : 100; + this.maxSize = (props && props.maxSize) ? props.maxSize : 5000; + this.timeout = (props && props.timeout) ? props.timeout : 3000; + this.continuous = (props && props.continuous) ? props.continuous : false; + this.format = (props && props.format) ? props.format : "DEFAULT"; + this.exhausted = false; + this.cummulative = 0; + this.elapsed = -1; + this.expired = false; +} + +QueryContext.newContext = function(props) { + return new QueryContext(props); +} + +QueryContext.readContext = function(props) { + return new QueryContext(props); +} + +QueryContext.prototype.shouldContinue = function() { + console.info("Max: c:[%s], m:[%s]", this.cummulative , this.maxSize) + return this.continuous && this.nextIndex != null && !this.isExpired() && !this.isExhausted() && (this.cummulative < this.maxSize); +} + +QueryContext.prototype.clone = function() { + try { + return JSON.parse(JSON.stringify(this)); + } catch (e) { + throw new Error("Unable to copy this! Its type isn't supported."); + } +} + +QueryContext.prototype.export = function() { + return { + extIndex : this.nextIndex, + pageSize : this.pageSize, + maxSize : this.maxSize, + timeout : this.timeout, + continuous : this.continuous, + format : this.format, + exhausted : this.exhausted, + cummulative : this.cummulative, + elapsed : this.elapsed, + expired : this.expired + } +} + + +QueryContext.prototype.getFormat = function() { + return this.format; +}; + +QueryContext.prototype.format = function(format) { + var f = format.replace(/ /g, "").toUpperCase(); + this.format = f; + return this; +}; + + +QueryContext.prototype.getElapsed = function() { + return this.elapsed; +}; + +QueryContext.prototype.getNextIndex = function() { + return this.nextIndex; +}; + +QueryContext.prototype.isContinuous = function() { + return this.continuous; +}; + + +QueryContext.prototype.nextIndex = function(index) { + this.nextIndex = index; + return this; +}; + + +QueryContext.prototype.getCummulative = function() { + return this.cummulative; +}; + +QueryContext.prototype.getPageSize = function() { + return this.pageSize; +}; + +QueryContext.prototype.pageSize = function(size) { + this.pageSize = size; + return this; +}; + + +QueryContext.prototype.getMaxSize = function() { + return this.maxSize; +}; + +QueryContext.prototype.maxSize = function(size) { + this.maxSize = size; + return this; +}; + +QueryContext.prototype.continuous = function(enabled) { + return this.continuous = enabled; + return this; +}; + + +QueryContext.prototype.isExhausted = function() { + return this.exhausted; +}; + +QueryContext.prototype.isExpired = function() { + return this.expired; +}; + +QueryContext.prototype.getTimeout = function() { + return this.timeout; +}; + +QueryContext.prototype.timeout = function(time) { + this.timeout = time; + return this; +}; + +QueryContext.getCtx = function(ctx) { + var sortable = []; + for (var item in ctx) { + sortable.push([item, ctx[item]]) + } + sortable.sort(function(a, b) {return a[1] - b[1]}); + console.group("====================== CTX ======================"); + var prior = -1, elapsed = 0, total = 0; + for(var i = 0, x = sortable.length; i < x; i++) { + if(prior != -1) { + elapsed = sortable[i][1] - prior; + } + prior = sortable[i][1]; + total += elapsed; + console.info("Step: [%s] -- [%s] -- [%s] ----- Total: [%s]", sortable[i][0], prior, elapsed, total); + } + console.groupEnd(); + return sortable; +} + + + +QueryContext.prototype.refresh = function(props) { + if(props!=null) { + this.nextIndex = props.nextIndex!=null ? props.nextIndex : null; + this.exhausted = props.exhausted!=null ? props.exhausted : false; + this.cummulative = props.cummulative!=null ? props.cummulative : 0; + this.elapsed = props.elapsed!=null ? props.elapsed : -1; + console.info("ReadContext Elapsed: [%s]", this.elapsed); + this.expired = props.expired!=null ? props.expired : false; + this.format = props.format!=null ? props.formar : "DEFAULT"; + if(props.timeout!=null) this.timeout = props.timeout; + } +} + +QueryContext.prototype.toString = function() { + return "{timeout:" + this.timeout + ", nextIndex:" + this.nextIndex + ", pageSize:" + this.pageSize + ", maxSize:" + this.maxSize + ", exhausted:" + this.exhausted + ", cummulative:" + this.cummulative + ", expired:" + this.expired + ", elapsed:" + this.elapsed + "}"; +}; + diff --git a/pool/shard001/JavaScript/0011767_index.js b/pool/shard001/JavaScript/0011767_index.js new file mode 100644 index 0000000000000000000000000000000000000000..c74ce24e5e08155da4a22d158ac0c1add00162f8 --- /dev/null +++ b/pool/shard001/JavaScript/0011767_index.js @@ -0,0 +1,62 @@ +require.config({ + "baseUrl": "vendors/", + "paths": { + "cachelru": "cachelru/release/cachelru.min", + "image-manager": "image-manager/release/image-manager.min" + }, + "waitSeconds": 0 +}); +require(["image-manager"], function (ImageManager) { + var imageList = [ + 'http://fc01.deviantart.net/fs50/f/2009/308/f/c/Sacred_Forest_1_4_Hi_Res_by__zagadka_.png', + 'http://fc00.deviantart.net/fs71/f/2015/046/5/5/extrasolar_comet___4k_high_res_remake_by_nirklars-d8i4foj.png', + 'http://fc08.deviantart.net/fs71/f/2012/009/6/7/67618400181402536a68ed4d982d9aff-d4lvaow.jpg', + 'http://fc02.deviantart.net/fs71/f/2012/111/d/0/winter_holiday_by_deoce-d4wmh06.png', + 'http://fc00.deviantart.net/fs71/f/2013/291/d/1/old_library_render_high_res_by_misterjl-d6qwnmi.png', + 'http://fc02.deviantart.net/fs70/i/2012/342/6/6/mordor__super_final_high_res_variant__by_entar0178-d5nfjcu.jpg' + ]; + var imageManager = new ImageManager(false); + console.info('%cCurrent image loading configuration', 'color: magenta;'); + console.dir(imageManager.configGet()); + imageManager.debug = true; + imageManager.activeDerived = 1; + imageManager.listSize = 9; + imageManager.configSet('maxDownloads', 999); + imageManager.onFinish = function () { + console.info('%c[Loading of images completed]', 'color: blue;'); + }; + imageManager.configSet('onError', function OnError(image) { + console.info('%c[OnError]', 'color: red;'); + console.dir(image); + }); + imageManager.configSet('onSuccess', function OnSuccess(image) { + console.info('%c[OnSuccess]', 'color: green;'); + console.dir(image); + var img = new Image(); + img.src = image.src; + document.body.appendChild(img); + }); + imageManager.configSet('onResolve', function OnResolve(image) { + console.info('%c[OnResolve]', 'color: blue;'); + console.dir(image); + }); + imageManager.loadImage(imageList[0], {isPaused: true}); + imageManager.loadImage(imageList[1], {isPaused: true}); + imageManager.loadImage(imageList[2], {isPaused: true}); + imageManager.loadImage(imageList[3], {isPaused: true}); + imageManager.loadImage(imageList[4], {isPaused: true}); + imageManager.loadImage(imageList[5], { + isPaused: true, + onSuccess: function (image) { + console.info('%c[OnSuccess-CustomFunction]', 'color: magenta;'); + console.dir(image); + var img = new Image(); + img.src = image.src; + img.style.border = '3px double lime'; + document.body.appendChild(img); + } + }); + console.info('%cList of SRC:', 'color: magenta;'); + console.dir(imageManager.srcList); + imageManager.startAll(); +}); diff --git a/pool/shard001/JavaScript/0011772_paging.js b/pool/shard001/JavaScript/0011772_paging.js new file mode 100644 index 0000000000000000000000000000000000000000..414c3a95a5b24b5939a2009b89497b71bfc5116f --- /dev/null +++ b/pool/shard001/JavaScript/0011772_paging.js @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +'use strict'; + +var should = require('should'); +var http = require('http'); +var util = require('util'); +var assert = require('assert'); +var msRest = require('ms-rest'); +var msRestAzure = require('ms-rest-azure'); + +var pagingClient = require('../Expected/AcceptanceTests/Paging/autoRestPagingTestService'); + +var dummySubscriptionId = 'a878ae02-6106-429z-9397-58091ee45g98'; +var dummyToken = 'dummy12321343423'; +var credentials = new msRestAzure.TokenCredentials(dummyToken); + +var clientOptions = {}; +var baseUri = 'http://localhost:3000'; + +describe('nodejs', function () { + + describe('Swagger Pageable BAT', function () { + + describe('Pageable Operations', function () { + clientOptions.requestOptions = { jar: true }; + clientOptions.filters = [new msRest.ExponentialRetryPolicyFilter(3, 0, 0, 0)]; + clientOptions.noRetryPolicy = true; + var testClient = new pagingClient(credentials, baseUri, clientOptions); + + it('should get single pages', function (done) { + testClient.paging.getSinglePages(function (error, result) { + should.not.exist(error); + should.not.exist(result.nextLink); + done(); + }); + }); + + it('should get multiple pages', function (done) { + testClient.paging.getMultiplePages({'clientRequestId': 'client-id', 'pagingGetMultiplePagesOptions': null}, function (error, result) { + var loop = function (nextLink, count) { + if (nextLink !== null && nextLink !== undefined) { + testClient.paging.getMultiplePagesNext(nextLink, {'clientRequestId': 'client-id', 'pagingGetMultiplePagesOptions': null}, function (err, res) { + should.not.exist(err); + loop(res.nextLink, count + 1); + }); + } else { + count.should.be.exactly(10); + done(); + } + }; + + should.not.exist(error); + should.exist(result.nextLink); + loop(result.nextLink, 1); + }); + }); + + it('should get multiple pages with offset', function (done) { + testClient.paging.getMultiplePagesWithOffset({'offset': 100}, {'clientRequestId': 'client-id'}, function (error, result) { + var loop = function (nextLink, count) { + if (nextLink !== null && nextLink !== undefined) { + testClient.paging.getMultiplePagesWithOffsetNext(nextLink, {'clientRequestId': 'client-id'}, function (err, res) { + should.not.exist(err); + result = res; + loop(res.nextLink, count + 1); + }); + } else { + count.should.be.exactly(10); + result[0].properties.id.should.be.exactly(110); + done(); + } + }; + + should.not.exist(error); + should.exist(result.nextLink); + loop(result.nextLink, 1); + }); + }); + + it('should get multiple pages with retry on first call', function (done) { + testClient.paging.getMultiplePagesRetryFirst(function (error, result) { + var loop = function (nextLink, count) { + if (nextLink !== null && nextLink !== undefined) { + testClient.paging.getMultiplePagesRetryFirstNext(nextLink, function (err, res) { + should.not.exist(err); + loop(res.nextLink, count + 1); + }); + } else { + count.should.be.exactly(10); + done(); + } + }; + + should.not.exist(error); + should.exist(result.nextLink); + loop(result.nextLink, 1); + }); + }); + + it('should get multiple pages with retry on second call', function (done) { + testClient.paging.getMultiplePagesRetrySecond(function (error, result) { + var loop = function (nextLink, count) { + if (nextLink !== null && nextLink !== undefined) { + testClient.paging.getMultiplePagesRetrySecondNext(nextLink, function (err, res) { + should.not.exist(err); + loop(res.nextLink, count + 1); + }); + } else { + count.should.be.exactly(10); + done(); + } + }; + + should.not.exist(error); + should.exist(result.nextLink); + loop(result.nextLink, 1); + }); + }); + + it('should fail on 400 single page', function (done) { + testClient.paging.getSinglePagesFailure(function (error, result) { + should.exist(error); + error.message.should.containEql('Expected'); + done(); + }); + }); + + it('should fail on 400 multiple pages', function (done) { + testClient.paging.getMultiplePagesFailure(function (error, result) { + should.not.exist(error); + testClient.paging.getMultiplePagesFailureNext(result.nextLink, function (error, result) { + should.exist(error); + error.message.should.containEql('Expected'); + done(); + }); + }); + }); + + it('should fail on invalid next link URL in multiple pages', function (done) { + testClient.paging.getMultiplePagesFailureUri(function (error, result) { + should.not.exist(error); + testClient.paging.getMultiplePagesFailureUriNext(result.nextLink, function (error, result) { + should.exist(error); + error.message.should.containEql('Invalid URI'); + done(); + }); + }); + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0011774_get_info.js b/pool/shard001/JavaScript/0011774_get_info.js new file mode 100644 index 0000000000000000000000000000000000000000..d79d3f297b9c0e7d00b577eac5b777b83fb650f6 --- /dev/null +++ b/pool/shard001/JavaScript/0011774_get_info.js @@ -0,0 +1,55 @@ +/* + quinner - 140502 + get_info - gum.js + - base probe + gum.script('http://' + gum.domain + '/static/brows/get_info.js', function(){ + //gum.post('http://' + gum.domain + '/ing', gum.backinfo); + //gum.backinfo = {}; + }); + and + get_info.py +*/ +gum_getinfo = function(){ + var info_cookie = document.cookie; + var info_localStorage = gum.e("JSON.stringify(window['localStorage'])"); + var info_sessionStorage = gum.e("JSON.stringify(window['sessionStorage'])"); + var info_page_html = document.documentElement.outerHTML; + var info_browser = (!!self.ActiveXObject)&&('ie') + ||(!!self.chrome)&&('chrome') + ||(self.mozPaintCount>-1)&&('firefox') + ||(!!self.opera)&&('opera') + ||(!self.chrome&&!!self.WebKitPoint)&&('safari') + ||('unknow'); + var info_user_agent = navigator.userAgent; + var info_screen = 'screen='+screen.height+'*'+screen.width+' window='+screen.availHeight+'*'+ screen.availWidth; + var info_istouch = (document.ontouchstart)?('yes'):('no'); + var info_isgps = (navigator.geolocation)?('yes'):('no'); + var info_os = navigator.platform; + var info_date = Date(); + var info_referrer = document.referrer; + var info_plugins = '|'; + for (i=0; i { + let converted = camelCase(key); + if (key !== converted) { + obj[converted] = obj[key]; + delete obj[key]; + } + this.camelize(obj[converted]); + }); + } + acceptable(obj: any) { + if (obj === undefined || obj === null) { + return false; + } + let clas = Object.prototype.toString.call(obj).slice(8, -1); + return clas === 'Object' || clas === 'Array'; + } +} diff --git a/pool/shard001/JavaScript/0011783_test_executions.js b/pool/shard001/JavaScript/0011783_test_executions.js new file mode 100644 index 0000000000000000000000000000000000000000..9314553a0b2502aa499ddc541a25fab28acfa68d --- /dev/null +++ b/pool/shard001/JavaScript/0011783_test_executions.js @@ -0,0 +1,144 @@ +$(".test_executions").ready(function () { + console.log("Test Execution JS Ready"); + + // poll test execution status on test_executions show + if (jQuery(".test_executions.show").length) { + console.log("Test Execution polling status"); + var timeOutId = 0; + var ajaxFn = function () { + $.ajax({ + url: document.URL + '/poll', + success: function (response) { + if (response.status == 40) { + console.log("Test Execution finished - no need to poll anymore.", response); + clearTimeout(timeOutId); + testExecutionFinished(); + } else { + timeOutId = setTimeout(ajaxFn, 2000); + if (response.status < 40) { + testExecutionUpdate(response); + } + console.log("Test Execution running: ", response); + } + } + }); + }; + // wait 0.5 secs before first call + // window hash shouldn't contain #finished + if(!window.location.hash) { + timeOutId = setTimeout(ajaxFn, 2000); + }; + } + + // checkbox hide/show all actions + //set initial state. + $('#checkbox_stdin').val($(this).is(':checked')); + $('#checkbox_stdin').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .stdin').fadeIn('fast') + else + $('.test_plan .items .stdin').hide(); + }); + $('#checkbox_stdout').val($(this).is(':checked')); + $('#checkbox_stdout').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .stdout').fadeIn('fast') + else + $('.test_plan .items .stdout').hide(); + }); + $('#checkbox_stderr').val($(this).is(':checked')); + $('#checkbox_stderr').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .stderr').fadeIn('fast') + else + $('.test_plan .items .stderr').hide(); + }); + $('#checkbox_markup').val($(this).is(':checked')); + $('#checkbox_markup').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .markup').fadeIn('fast') + else + $('.test_plan .items .markup').hide(); + }); + $('#checkbox_markup_raw').val($(this).is(':checked')); + $('#checkbox_markup_raw').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .markup_raw').fadeIn('fast') + else + $('.test_plan .items .markup_raw').hide(); + }); + $('#checkbox_quality').val($(this).is(':checked')); + $('#checkbox_quality').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .quality').fadeIn('fast') + else + $('.test_plan .items .quality').hide(); + }); + $('#checkbox_quality_criteria').val($(this).is(':checked')); + $('#checkbox_quality_criteria').change(function() { + if ( $(this).is(':checked') ) + $('.test_plan .items .quality_criteria').fadeIn('fast') + else + $('.test_plan .items .quality_criteria').hide(); + }); + + $('#checkbox_showall').val($(this).is(':checked')); + $('#checkbox_showall').change(function() { + if ( $(this).is(':checked') ) { + $('.test_plan ul.items li').fadeIn('fast'); + $('#checkbox_quality, #checkbox_quality_criteria, #checkbox_markup_raw, #checkbox_markup, #checkbox_stderr, #checkbox_stdout, #checkbox_stdin').attr('checked', true); + } else { + $('.test_plan ul.items li').hide(); + $('#checkbox_quality, #checkbox_quality_criteria, #checkbox_markup_raw, #checkbox_markup, #checkbox_stderr, #checkbox_stdout, #checkbox_stdin').attr('checked', false); + + } + }); + + // specific status_toggle (input, output, error) + $('.toggle_status i').on('click', function(e) { + var toggle = $(this).data('toggle'); + var element = $(this).closest('li').children('ul.items').children('li.'+toggle); + if ( $(element).is(':visible') ) { + $(element).hide(); + } else { + $(element).fadeIn('fast'); + } + + }); + + + + // popover for test execution display settings + $('.display_options').popover({ + trigger: 'click', + html: true, + // overwrite template to adapt popover width, see http://getbootstrap.com/javascript/#popovers + template: '

    ', + content: function () { + return $("#display_options_popover"); + } + }).on('hidden.bs.popover', function () { + $("#popover_content_container").append($("#display_options_popover")); + }); + +}); + +// TODO update processing status based on response +function testExecutionUpdate(response) { + //window.location.reload(); + //console.log(response); +} +function testExecutionFinished() { + if(!window.location.hash) { + window.location = window.location + '#finshed'; + window.location.reload(); + } +} + + + +//// poll status from sse stream +//var stream = new EventSource(document.URL+'/poll'); +//stream.onmessage = function(event) { +// console.log(event.data); +//}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011788_cache-update-display.js b/pool/shard001/JavaScript/0011788_cache-update-display.js new file mode 100644 index 0000000000000000000000000000000000000000..fd87f63a18b2825083999bd37688f1d40bf9cd3c --- /dev/null +++ b/pool/shard001/JavaScript/0011788_cache-update-display.js @@ -0,0 +1,243 @@ +/** + * @fileoverview Display sugarcrm cache update process. + */ + + +goog.provide('ydn.crm.ui.CacheUpdateDisplay'); +goog.require('ydn.crm.shared'); +goog.require('ydn.crm.su'); +goog.require('ydn.crm.su.ui.UpdateOptionDialog'); +goog.require('ydn.msg'); + + + +/** + * Display sugarcrm cache update process. + * @constructor + * @struct + */ +ydn.crm.ui.CacheUpdateDisplay = function() { + /** + * @type {Element} + * @private + */ + this.head_ = document.createElement('div'); + /** + * @type {Element} + * @private + */ + this.body_ = document.createElement('DIV'); + + /** + * @protected + * @type {goog.events.EventHandler} + */ + this.handler = new goog.events.EventHandler(this); + +}; + + +/** + * Render UI. + * @param {Element} footer_el + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.render = function(footer_el) { + var button = footer_el.querySelector('.center-item'); + this.body_.style.display = 'none'; + button.appendChild(this.head_); + this.head_.classList.add('cache-update-display'); + this.head_.setAttribute('title', 'Cache update process not observed.'); + this.head_.innerHTML = '- ' + + '
    ' + + '
    '; + + footer_el.appendChild(this.body_); + this.body_.classList.add('cache-update-display-body'); + this.body_.innerHTML = '

    Cache statistics in this browser

    ' + + '
      ' + + ''; + + this.handler.listen(ydn.msg.getMain(), ydn.crm.ch.BReq.SUGARCRM_CACHE_UPDATE, + this.onMessage_); + this.handler.listen(this.head_, 'click', this.onBtnClick_); + this.handler.listen(this.body_, 'click', this.onBodyClick_); + var ua_btn = this.body_.querySelector('button[name="update-all"]'); + var op_btn = this.body_.querySelector('button[name="option"]'); + var cl_btn = this.body_.querySelector('button[name="close"]'); + this.handler.listen(ua_btn, 'click', this.onUpdateAll_); + this.handler.listen(cl_btn, 'click', this.onClose_); +}; + + +/** + * @param {goog.events.BrowserEvent} ev + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.onClose_ = function(ev) { + goog.style.setElementShown(this.body_, false); +}; + + +/** + * @param {goog.events.BrowserEvent} ev + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.onUpdateAll_ = function(ev) { + var btn = ev.currentTarget; + btn.setAttribute('disabled', 'disabled'); + var me = this; + var ch = ydn.msg.getMain().findChannel(ydn.msg.Group.SUGAR); + ch.send(ydn.crm.ch.SReq.UPDATE_NOW) + .addBoth(function(e) { + me.showDetails_().addBoth(function() { + btn.removeAttribute('disabled'); + }); + if (e && e.message) { + alert(e.message); + } + }, this); +}; + + +/** + * @param {goog.events.BrowserEvent} e + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.onBodyClick_ = function(e) { + if (e.target.tagName == 'A') { + var a = e.target; + var li = goog.dom.getAncestorByTagNameAndClass(a, 'LI'); + var hash = a.getAttribute('href'); + var mn = /** @type {ydn.crm.su.ModuleName} */(li.getAttribute('data-module')); + if (hash == '#update-now') { + e.preventDefault(); + var val = 0; + if (mn) { + var ch = ydn.msg.getMain().findChannel(ydn.msg.Group.SUGAR); + if (ch) { + val = 1; + a.textContent = 'updating...'; + a.href = ''; + var data = {'module': mn}; + ch.send(ydn.crm.ch.SReq.UPDATE_NOW, data).addCallbacks(function(x) { + a.textContent = 'updated'; + this.showDetails_(); + }, function(e) { + a.textContent = 'failed'; + }, this); + } + } + } else if (hash == '#option') { + e.preventDefault(); + ydn.crm.su.ui.UpdateOptionDialog.showModel(mn); + ydn.crm.shared.logAnalyticValue('ui.cache-update', + 'option.click.' + hash, mn, 0); + } + ydn.crm.shared.logAnalyticValue('ui.cache-update', + 'updateNow.click.' + hash, mn, val); + } +}; + + +/** + * @param {goog.events.BrowserEvent} e + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.onBtnClick_ = function(e) { + var showing = goog.style.isElementShown(this.body_); + goog.style.setElementShown(this.body_, !showing); + if (!showing) { + this.showDetails_(); + ydn.crm.shared.logAnalyticValue('ui.cache-update', + 'click', 'open', 0); + } +}; + + +ydn.crm.ui.CacheUpdateDisplay.prototype.showDetails_ = function() { + var ch = ydn.msg.getMain().findChannel(ydn.msg.Group.SUGAR); + if (!ch) { + goog.style.setElementShown(this.body_, false); + this.head_.querySelector('.label').textContent = ''; + this.head_.setAttribute('title', 'No SugarCRM instance.'); + return; + } + return ch.send(ydn.crm.ch.SReq.STATS).addCallback(function(arr) { + this.renderDetail_(arr); + }, this); +}; + + +/** + * @param {ydn.msg.Event} ev + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.onMessage_ = function(ev) { + var data = ev.mesage ? ev.mesage['data'] : null; + if (data) { + this.refreshHead_(data); + var showing = goog.style.isElementShown(this.body_); + if (showing) { + this.updateItem_(data); + } + } +}; + + +/** + * @param {Object} data + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.refreshHead_ = function(data) { + if (!data['end']) { + return; + } + var label = ydn.crm.su.toModuleSymbol(data['module']); + this.head_.querySelector('.label').textContent = label; + this.head_.querySelector('.sub').textContent = data['total']; + this.head_.querySelector('.sup').textContent = data['count']; + var title = data['module'] + ' module'; + if (data['ok']) { + title += ' updated on ' + new Date(data['end']).toLocaleTimeString(); + } else { + title += ' updating fail on ' + new Date(data['end']).toLocaleTimeString(); + } + this.head_.setAttribute('title', title); +}; + + +/** + * @param {Array} arr + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.renderDetail_ = function(arr) { + var ul = this.body_.querySelector('UL'); + ul.innerHTML = ''; + for (var i = 0; i < arr.length; i++) { + var li = document.createElement('LI'); + ydn.crm.su.renderCacheStats(li, arr[i], true); + ul.appendChild(li); + } +}; + + +/** + * @param {Object} data + * @private + */ +ydn.crm.ui.CacheUpdateDisplay.prototype.updateItem_ = function(data) { + if (!data['end']) { + return; + } + var mn = data['module']; + var li = this.body_.querySelector('LI[data-module="' + mn + '"]'); + li.innerHTML = ''; + var ch = ydn.msg.getMain().findChannel(ydn.msg.Group.SUGAR); + return ch.send(ydn.crm.ch.SReq.STATS, mn).addCallback(function(obj) { + ydn.crm.su.renderCacheStats(li, obj, true); + }, this); +}; + + diff --git a/pool/shard001/JavaScript/0011792_admiunUsers.spec.js b/pool/shard001/JavaScript/0011792_admiunUsers.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b95f5d658737ec60b0ae74f051c883ec83e22b68 --- /dev/null +++ b/pool/shard001/JavaScript/0011792_admiunUsers.spec.js @@ -0,0 +1,127 @@ +describe('Component: AdminUsers', function() { + var scope, + q, + adminUser, + oc; + beforeEach(module(function($provide) { + $provide.value('Parameters', {search:null, page: null, pageSize: null, searchOn: null, sortBy: null, userID: null, userGroupID: null, level: null, buyerID: null}) + })); + beforeEach(module('orderCloud')); + beforeEach(module('orderCloud.sdk')); + beforeEach(inject(function($q, $rootScope, OrderCloud) { + q = $q; + scope = $rootScope.$new(); + adminUser = { + "Username": "TestAdminUser", + "ID": "TestAdminUser123456789", + "Email": "testadmin@four51.com", + "Password": "Fails345", + "FirstName": "Test", + "LastName": "Test" + }; + oc = OrderCloud; + })); + + describe('State: adminUsers', function() { + var state; + beforeEach(inject(function($state, OrderCloudParameters) { + state = $state.get('adminUsers'); + var defer = q.defer(); + defer.resolve(); + spyOn(OrderCloudParameters, 'Get').and.returnValue(null); + spyOn(oc.AdminUsers, 'List').and.returnValue(defer.promise); + })); + it('should resolve Parameters', inject(function($injector, OrderCloudParameters){ + $injector.invoke(state.resolve.Parameters); + expect(OrderCloudParameters.Get).toHaveBeenCalled(); + })); + it('should resolve AdminUserList', inject(function($injector) { + $injector.invoke(state.resolve.AdminUsersList); + expect(oc.AdminUsers.List).toHaveBeenCalled(); + })); + }); + + describe('State: adminUsers.edit', function() { + var state; + beforeEach(inject(function($state) { + state = $state.get('adminUsers.edit'); + spyOn(oc.AdminUsers, 'Get').and.returnValue(null); + })); + it('should resolve AdminUserList', inject(function($injector) { + $injector.invoke(state.resolve.SelectedAdminUser); + expect(oc.AdminUsers.Get).toHaveBeenCalled(); + })); + }); + + describe('Controller: AdminUserCreateCtrl', function() { + var adminUserCreateCtrl; + beforeEach(inject(function($state, $controller) { + adminUserCreateCtrl = $controller('AdminUserCreateCtrl', { + $scope: scope + }); + spyOn($state, 'go').and.returnValue(true); + })); + + describe('Submit', function() { + beforeEach(function() { + adminUserCreateCtrl.adminUser = adminUser; + var defer = q.defer(); + defer.resolve(adminUser); + spyOn(oc.AdminUsers, 'Create').and.returnValue(defer.promise); + adminUserCreateCtrl.Submit(); + scope.$digest(); + }); + it ('should call the AdminUsers Create method', function() { + expect(oc.AdminUsers.Create).toHaveBeenCalledWith(adminUser); + }); + it ('should enter the adminUsers state', inject(function($state) { + expect($state.go).toHaveBeenCalledWith('adminUsers', {}, {reload: true}); + })); + }); + }); + + describe('Controller: AdminUserEditCtrl', function() { + var adminUserEditCtrl; + beforeEach(inject(function($state, $controller) { + adminUserEditCtrl = $controller('AdminUserEditCtrl', { + $scope: scope, + SelectedAdminUser: adminUser + }); + spyOn($state, 'go').and.returnValue(true); + })); + + describe('Submit', function() { + beforeEach(function() { + adminUserEditCtrl.adminUser = adminUser; + adminUserEditCtrl.adminUserID = "TestAdminUser123456789"; + var defer = q.defer(); + defer.resolve(adminUser); + spyOn(oc.AdminUsers, 'Update').and.returnValue(defer.promise); + adminUserEditCtrl.Submit(); + scope.$digest(); + }); + it ('should call the AdminUsers Update method', function() { + expect(oc.AdminUsers.Update).toHaveBeenCalledWith(adminUserEditCtrl.adminUserID, adminUser); + }); + it ('should enter the adminUsers state', inject(function($state) { + expect($state.go).toHaveBeenCalledWith('adminUsers', {}, {reload: true}); + })); + }); + + describe('Delete', function() { + beforeEach(function() { + var defer = q.defer(); + defer.resolve(adminUser); + spyOn(oc.AdminUsers, 'Delete').and.returnValue(defer.promise); + adminUserEditCtrl.Delete(); + scope.$digest(); + }); + it ('should call the AdminUsers Delete method', function() { + expect(oc.AdminUsers.Delete).toHaveBeenCalledWith(adminUser.ID); + }); + it ('should enter the adminUsers state', inject(function($state) { + expect($state.go).toHaveBeenCalledWith('adminUsers', {}, {reload: true}); + })); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011794_CircularArray.js b/pool/shard001/JavaScript/0011794_CircularArray.js new file mode 100644 index 0000000000000000000000000000000000000000..41962eeda9900ef99faa2a5b167ec0d70a15b051 --- /dev/null +++ b/pool/shard001/JavaScript/0011794_CircularArray.js @@ -0,0 +1,40 @@ + +/** + * An array with an add method which ensures the array length doesn't exceed a + * given capacity. If the array is full the oldest value [0] is copied over. + * + * @param number capacity + * The maximum number of values allowed in this CircularArray. + */ +function CircularArray(capacity) +{ + this.capacity = capacity; +} + +/** + * CircularArray should inherit Array. + */ +CircularArray.prototype = new Array(); + +/** + * Adds a new item to the end of this array possibly removing elements form the + * beginning of the array to keep it's size within capacity. + * + * @param any item + * The item to add to the array. + */ +CircularArray.prototype.add = function(item) +{ + if (this.capacity > 0) + { + while (this.length >= this.capacity) + { + this.shift(); + } + + this.push(item); + } +}; + +// Export the CircularArray class. +module.exports = CircularArray; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011796_groupedCategoryChart.js b/pool/shard001/JavaScript/0011796_groupedCategoryChart.js new file mode 100644 index 0000000000000000000000000000000000000000..1d6885b3bad44dc222edd5f0e05523fdea6d7b25 --- /dev/null +++ b/pool/shard001/JavaScript/0011796_groupedCategoryChart.js @@ -0,0 +1,54 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +import { CartesianChart } from "./cartesianChart"; +import { numericExtent } from "../util/array"; +import { ChartAxisDirection } from "./chartAxis"; +var GroupedCategoryChart = /** @class */ (function (_super) { + __extends(GroupedCategoryChart, _super); + function GroupedCategoryChart() { + return _super !== null && _super.apply(this, arguments) || this; + } + GroupedCategoryChart.prototype.updateAxes = function () { + this.axes.forEach(function (axis) { + var _a; + var direction = axis.direction, boundSeries = axis.boundSeries; + var domains = []; + var isNumericX = undefined; + boundSeries.filter(function (s) { return s.visible; }).forEach(function (series) { + if (direction === ChartAxisDirection.X) { + if (isNumericX === undefined) { + // always add first X domain + var domain_1 = series.getDomain(direction); + domains.push(domain_1); + isNumericX = typeof domain_1[0] === 'number'; + } + else if (isNumericX) { + // only add further X domains if the axis is numeric + domains.push(series.getDomain(direction)); + } + } + else { + domains.push(series.getDomain(direction)); + } + }); + var domain = (_a = new Array()).concat.apply(_a, domains); + axis.domain = numericExtent(domain) || domain; + axis.update(); + }); + }; + GroupedCategoryChart.className = 'GroupedCategoryChart'; + GroupedCategoryChart.type = 'groupedCategory'; + return GroupedCategoryChart; +}(CartesianChart)); +export { GroupedCategoryChart }; diff --git a/pool/shard001/JavaScript/0011800_feature_manager.test.js b/pool/shard001/JavaScript/0011800_feature_manager.test.js new file mode 100644 index 0000000000000000000000000000000000000000..61552894b5b8cf94362ae0cb1e2a31d8b48ad66e --- /dev/null +++ b/pool/shard001/JavaScript/0011800_feature_manager.test.js @@ -0,0 +1,79 @@ +// Copyright 2015 Las Venturas Playground. All rights reserved. +// Use of this source code is governed by the MIT license, a copy of which can +// be found in the LICENSE file. + +const Feature = require('components/feature_manager/feature.js'); +const FeatureManager = require('components/feature_manager/feature_manager.js'); +const MockServer = require('test/mock_server.js'); + +describe('FeatureManager', (it, beforeEach, afterEach) => { + MockServer.bindTo(beforeEach, afterEach); + + it('initializes the features', assert => { + let counter = 0; + + class MySimpleFeature extends Feature { + constructor() { super(); counter += 1; } + }; + + class MySecondFeature extends Feature { + constructor() { super(); counter += 10; } + }; + + server.featureManager.load({ + simple: MySimpleFeature, + second: MySecondFeature + }); + + assert.equal(counter, 11); + }); + + it('should allow declaring dependencies', assert => { + let value = 0; + + class MySimpleFeature extends Feature { + constructor() { super(); value = this.defineDependency('second').value; } + }; + + class MySecondFeature extends Feature { + constructor() { super(); this.value = 42; } + }; + + server.featureManager.load({ + simple: MySimpleFeature, + second: MySecondFeature + }); + + assert.equal(value, 42); + }); + + it('should throw on invalid dependencies', assert => { + class MySimpleFeature extends Feature { + constructor() { + super(); + + this.defineDependency('fakeFeature'); + } + }; + + assert.throws(() => + server.featureManager.load({ simple: MySimpleFeature })); + }); + + it('should throw on circular dependencies', assert => { + class MySimpleFeature extends Feature { + constructor() { super(); this.defineDependency('second'); } + }; + + class MySecondFeature extends Feature { + constructor() { super(); this.defineDependency('simple'); } + }; + + assert.throws(() => { + server.featureManager.load({ + simple: MySimpleFeature, + second: MySecondFeature + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0011802_pageCache.js b/pool/shard001/JavaScript/0011802_pageCache.js new file mode 100644 index 0000000000000000000000000000000000000000..8c520d75e1ef6443ab229d6b2c9fc8ad3b2c375d --- /dev/null +++ b/pool/shard001/JavaScript/0011802_pageCache.js @@ -0,0 +1,50 @@ +// pluggable caching for proxy +/*jslint node: true */ + +'use strict'; + +var fs = require('fs'); +var url = require('url'); + +exports.cache = function(uri, referer, isHTML, content, contentType, headers, browser_request) { + var fileName = cacheLoc(browser_request.url); + + if (!contentType) { GLOBAL.debug('missing contentType', browser_request.url); contentType = "text/text"; } + + if (fileName.length < 220) { +// GLOBAL.debug('caching', uri, browser_request.encoding); + fs.writeFile(cacheLoc(browser_request.url), content, browser_request.encoding, function(err) { + if (err) { + GLOBAL.debug(err); + } + }); + + fs.writeFile(fileName + ".headers.json", JSON.stringify(headers), function(err) { + if (err) { + GLOBAL.debug('\nError writing header', err); + } + }); + } +}; + +exports.isCached = function(url) { + return fs.existsSync(cacheLoc(url) + '.headers.json'); +}; + +exports.get = function(url, callback) { + try { + var received = require(cacheLoc(url) + ".headers.json"); + } catch (e) { + GLOBAL.error('pageCache', e); + callback(e); + } + GLOBAL.debug("got cached " + url); + + var pageBuffer = fs.readFile(cacheLoc(url), function(err, pageBuffer) { + callback(null, received, pageBuffer.toString()); + }); +}; + +function cacheLoc(page) { + return GLOBAL.config.CACHE_DIR + encodeURIComponent(page); +} diff --git a/pool/shard001/JavaScript/0011805_bands.js b/pool/shard001/JavaScript/0011805_bands.js new file mode 100644 index 0000000000000000000000000000000000000000..5403b2387b423ee7d39965d9d50053851dcf2caf --- /dev/null +++ b/pool/shard001/JavaScript/0011805_bands.js @@ -0,0 +1,205 @@ +import {getDataSetBands} from './sources' +import {getIndexes} from './indexes' +import {msg} from 'translate' +import {selectFrom} from 'stateUtils' + +export const getAvailableBands = (recipe, select = ['dataSetBands', 'indexes', 'metadata']) => { + const compose = selectFrom(recipe, 'model.compositeOptions.compose') + const bandsByType = { + dataSetBands: getDataSetBands(recipe), + indexes: getIndexes(recipe), + metadata: compose === 'MEDIAN' + ? [] + : metadataBands + } + const bands = {} + const allBands = getBands() + select.map(bandType => bandsByType[bandType]) + .flat() + .forEach(band => bands[band] = allBands[band]) + return bands +} + +export const getGroupedBandOptions = (recipe, select = ['dataSetBands', 'indexes', 'metadata']) => { + const availableBands = getAvailableBands(recipe, select) + return bandGroups + .map(bands => bands.filter(band => availableBands[band])) + .filter(bands => bands.length) + .map(bands => bands.map(band => ({value: band, label: band, ...availableBands[band]}))) +} + +const int10000 = {precision: 'int', min: -10000, max: 10000} +const intFullRange = {precision: 'int', min: -32768, max: 32767} + +const getBands = () => ({ + blue: { + dataType: intFullRange, + tooltip: msg('bands.blue'), + }, + green: { + dataType: intFullRange, + tooltip: msg('bands.green'), + }, + red: { + dataType: intFullRange, + tooltip: msg('bands.red'), + }, + nir: { + dataType: intFullRange, + tooltip: msg('bands.nir'), + }, + swir1: { + dataType: intFullRange, + tooltip: msg('bands.swir1'), + }, + thermal: { + dataType: intFullRange, + tooltip: msg('bands.thermal'), + }, + swir2: { + dataType: intFullRange, + tooltip: msg('bands.swir2'), + }, + qa: { + dataType: intFullRange, + }, + thermal2: { + dataType: intFullRange, + tooltip: msg('bands.thermal2'), + }, + pan: { + dataType: intFullRange, + tooltip: msg('bands.pan'), + }, + aerosol: { + dataType: intFullRange, + tooltip: msg('bands.aerosol'), + }, + cirrus: { + dataType: intFullRange, + tooltip: msg('bands.cirrus'), + }, + redEdge1: { + dataType: intFullRange, + tooltip: msg('bands.redEdge1'), + }, + redEdge2: { + dataType: intFullRange, + tooltip: msg('bands.redEdge2'), + }, + redEdge3: { + dataType: intFullRange, + tooltip: msg('bands.redEdge3'), + }, + redEdge4: { + dataType: intFullRange, + tooltip: msg('bands.redEdge4'), + }, + waterVapor: { + dataType: intFullRange, + tooltip: msg('bands.waterVapor'), + }, + brightness: { + dataType: intFullRange, + tooltip: msg('bands.brightness'), + }, + greenness: { + dataType: intFullRange, + tooltip: msg('bands.greenness'), + }, + wetness: { + dataType: intFullRange, + tooltip: msg('bands.wetness'), + }, + fourth: { + dataType: intFullRange, + tooltip: msg('bands.fourth'), + }, + fifth: { + dataType: intFullRange, + tooltip: msg('bands.fifth'), + }, + sixth: { + dataType: intFullRange, + tooltip: msg('bands.sixth'), + }, + ndvi: { + dataType: int10000, + tooltip: '(nir - red) / (nir + red)' + }, + ndmi: { + dataType: int10000, + tooltip: '(nir - swir1) / (nir + swir1)', + }, + ndwi: { + dataType: int10000, + tooltip: '(green - nir) / (green + nir)', + }, + mndwi: { + dataType: int10000, + tooltip: '(green - swir1) / (green + swir1)', + }, + ndfi: { + dataType: intFullRange, + tooltip: 'Normalized Difference Fraction Index', + }, + evi: { + dataType: intFullRange, + tooltip: '2.5 * (nir - red) / (nir + 6 * red - 7.5 * blue + 1)', + }, + evi2: { + dataType: intFullRange, + tooltip: '2.5 * (nir - red) / (nir + 2.4 * red + 1)', + }, + savi: { + dataType: intFullRange, + tooltip: '(1.5 * (nir - red) / (nir + red + 0.5)', + }, + nbr: { + dataType: int10000, + tooltip: '(nir - swir2) / (nir + swir2)', + }, + ui: { + dataType: int10000, + tooltip: '(swir2 - nir) / (swir2 + nir)', + }, + ndbi: { + dataType: int10000, + tooltip: '(swir1 - nir) / (swir1 + nir)', + }, + ibi: { + dataType: intFullRange, + tooltip: '(ndbi - (savi + mndwi) / 2) / (ndbi + (savi + mndwi) / 2)', + }, + nbi: { + dataType: intFullRange, + tooltip: 'red * swir1 / nir', + }, + ebbi: { + dataType: intFullRange, + tooltip: '(swir1 - nir) / (10 * sqrt(swir1 + thermal))', + }, + bui: { + dataType: intFullRange, + tooltip: '(red - swir1) / (red + swir1) + (swir2 - swir1) / (swir2 + swir1)', + }, + dayOfYear: { + dataType: {precision: 'int', min: 0, max: 366}, + tooltip: msg('bands.dayOfYear'), + }, + daysFromTarget: { + dataType: {precision: 'int', min: 0, max: 183}, + tooltip: msg('bands.daysFromTarget'), + }, +}) + +const bandGroups = [ + ['blue', 'green', 'red', 'nir', 'swir1', 'swir2'], + ['redEdge1', 'redEdge2', 'redEdge3', 'redEdge4'], + ['aerosol', 'waterVapor', 'pan', 'cirrus', 'thermal', 'thermal2'], + ['brightness', 'greenness', 'wetness', 'fourth', 'fifth', 'sixth'], + ['ndvi', 'ndmi', 'ndwi', 'mndwi', 'ndfi', 'evi', 'evi2', 'savi', 'nbr', 'ui', 'ndbi', 'ibi', 'nbi', 'ebbi', 'bui'], + ['dayOfYear', 'daysFromTarget'] +] + +const metadataBands = ['dayOfYear', 'daysFromTarget'] diff --git a/pool/shard001/JavaScript/0011807_JavaObjectToShort-002-n.js b/pool/shard001/JavaScript/0011807_JavaObjectToShort-002-n.js new file mode 100644 index 0000000000000000000000000000000000000000..297fe96fbe1bd4a06ff4b905818555974a7d696d --- /dev/null +++ b/pool/shard001/JavaScript/0011807_JavaObjectToShort-002-n.js @@ -0,0 +1,103 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * + * Copyright (C) 1998 Netscape Communications Corporation. + * Copyright (C) 2010 Apple Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + * ***** END LICENSE BLOCK ***** */ + +gTestfile = 'JavaObjectToShort-002-n.js'; + +/* -*- Mode: java; tab-width: 8 -*- + * Copyright (C) 1997, 1998 Netscape Communications Corporation, + * All Rights Reserved. + */ +/** + * JavaScript to Java type conversion. + * + * This test passes JavaScript number values to several Java methods + * that expect arguments of various types, and verifies that the value is + * converted to the correct value and type. + * + * This tests instance methods, and not static methods. + * + * Running these tests successfully requires you to have + * com.netscape.javascript.qa.liveconnect.DataTypeClass on your classpath. + * + * Specification: Method Overloading Proposal for Liveconnect 3.0 + * + * @author: christine@netscape.com + * + */ +var SECTION = "JavaObject to short"; +var VERSION = "1_4"; +var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " + + SECTION; +startTest(); + +var dt = applet.createQAObject("com.netscape.javascript.qa.liveconnect.DataTypeClass"); + +var a = new Array(); +var i = 0; + +// 1. If the object does not have a doubleValue() method, a runtime error +// occurs. +// 2. Call the object's doubleValue() method +// 3. If result(2) is NaN, a runtime error occurs +// 3. Convert Result(2) to Java numeric type. Round JS number to integral +// value using round-to-negative-infinity mode. +// Numbers with a magnitude too large to be represented in the target +// integral type should result in a runtime error. + +DESCRIPTION = "dt.PUB_DOUBLE_REPRESENTATION = NaN;"+ + "dt.setShort( dt )"; +EXPECTED = "error"; + +a[i++] = new TestObject ( + "dt.PUB_DOUBLE_REPRESENTATION = NaN;"+ + "dt.setShort( dt )", + "dt.PUB_SHORT", + "dt.getShort()", + "typeof dt.getShort()", + "'error'", + "'number'" ); + +for ( i = 0; i < a.length; i++ ) { + shouldBeWithErrorCheck( + a[i].description +"; "+ a[i].javaFieldName, + a[i].jsValue); + + shouldBeWithErrorCheck( + a[i].description +"; " + a[i].javaMethodName, + a[i].jsValue); + + shouldBeWithErrorCheck( + a[i].javaTypeName, + a[i].jsType); +} + +function TestObject( description, javaField, javaMethod, javaType, + jsValue, jsType ) +{ + this.description = description; + this.javaFieldName = javaField; + this.javaMethodName = javaMethod; + this.javaTypeName = javaType, + + this.jsValue = jsValue; + this.jsType = jsType; +} diff --git a/pool/shard001/JavaScript/0011812_productGridItemsContainer.js b/pool/shard001/JavaScript/0011812_productGridItemsContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..2cb83595f1fab33f1dc39a6236b92da884deadce --- /dev/null +++ b/pool/shard001/JavaScript/0011812_productGridItemsContainer.js @@ -0,0 +1,238 @@ +import React, { Component } from "react"; +import PropTypes from "prop-types"; +import _ from "lodash"; +import { compose } from "recompose"; +import { registerComponent } from "@reactioncommerce/reaction-components"; +import { Session } from "meteor/session"; +import { Reaction } from "/client/api"; +import { ReactionProduct } from "/lib/api"; +import { SortableItem } from "/imports/plugins/core/ui/client/containers"; +import ProductGridItems from "../components/productGridItems"; + +const wrapComponent = (Comp) => ( + class ProductGridItemsContainer extends Component { + static propTypes = { + connectDragSource: PropTypes.func, + connectDropTarget: PropTypes.func, + isSearch: PropTypes.bool, + itemSelectHandler: PropTypes.func, + product: PropTypes.object, + unmountMe: PropTypes.func + } + + componentDidMount() { + document.querySelector(".page > main").addEventListener("click", this.onPageClick); + } + + componentWillUnmount() { + document.querySelector(".page > main").removeEventListener("click", this.onPageClick); + } + + onPageClick = (event) => { + // Do nothing if we are in preview mode + if (Reaction.isPreview() === false) { + // Don't trigger the clear selection if we're clicking on a grid item. + if (event.target.closest(".product-grid-item") === null) { + const selectedProducts = Session.get("productGrid/selectedProducts"); + + // Do we have any selected products? + // If we do then lets reset the Grid Settings ActionView + if (Array.isArray(selectedProducts) && selectedProducts.length) { + // Reset sessions ver of selected products + Session.set("productGrid/selectedProducts", []); + + // Reset the action view of selected products + Reaction.setActionView({ + label: "Grid Settings", + i18nKeyLabel: "gridSettingsPanel.title", + template: "productSettings", + type: "product", + data: {} + }); + } + } + } + } + + productPath = () => { + if (this.props.product) { + let { handle } = this.props.product; + + if (this.props.product.__published) { + ({ handle } = this.props.product.__published); + } + + return Reaction.Router.pathFor("product", { + hash: { + handle + } + }); + } + + return "/"; + } + + positions = () => { + const tag = ReactionProduct.getTag(); + return (this.props.product.positions && this.props.product.positions[tag]) || {}; + } + + weightClass = () => { + const positions = this.positions(); + const weight = positions.weight || 0; + switch (weight) { + case 1: + return "product-medium"; + case 2: + return "product-large"; + default: + return "product-small"; + } + } + + isSelected = () => { + if (Reaction.isPreview() === false) { + return _.includes(Session.get("productGrid/selectedProducts"), this.props.product._id) ? "active" : ""; + } + return false; + } + + isMediumWeight = () => { + const positions = this.positions(); + const weight = positions.weight || 0; + + return weight === 1; + } + + displayPrice = () => { + if (this.props.product.price && this.props.product.price.range) { + return this.props.product.price.range; + } + } + + handleCheckboxSelect = (list, product) => { + let checkbox = list.querySelector(`input[type=checkbox][value="${product._id}"]`); + const items = document.querySelectorAll("li.product-grid-item"); + const activeItems = document.querySelectorAll("li.product-grid-item.active"); + const selected = activeItems.length; + + if (event.shiftKey && selected > 0) { + const indexes = [ + Array.prototype.indexOf.call(items, document.querySelector(`li.product-grid-item[id="${product._id}"]`)), + Array.prototype.indexOf.call(items, activeItems[0]), + Array.prototype.indexOf.call(items, activeItems[selected - 1]) + ]; + for (let i = _.min(indexes); i <= _.max(indexes); i += 1) { + checkbox = items[i].querySelector("input[type=checkbox]"); + if (checkbox.checked === false) { + checkbox.checked = true; + this.props.itemSelectHandler(checkbox.checked, product._id); + } + } + } else if (checkbox) { + checkbox.checked = !checkbox.checked; + this.props.itemSelectHandler(checkbox.checked, product._id); + } + } + + onDoubleClick = () => { + const { product } = this.props; + const handle = (product.__published && product.__published.handle) || product.handle; + + Reaction.Router.go("product", { + handle + }); + + // Open actionView to productDetails panel + Reaction.state.set("edit/focus", "productDetails"); + + Reaction.setActionView({ + i18nKeyLabel: "productDetailEdit.productSettings", + label: "Product Settings", + template: "ProductAdmin" + }); + + if (this.props.isSearch) { + this.props.unmountMe(); + } + } + + onClick = (event) => { + event.preventDefault(); + const { product } = this.props; + + if (Reaction.hasPermission("createProduct") && Reaction.isPreview() === false) { + if (this.props.isSearch) { + let { handle } = product; + if (product.__published) { + ({ handle } = product.__published); + } + + Reaction.Router.go("product", { + handle + }); + + this.props.unmountMe(); + } + + const isSelected = event.target.closest("li.product-grid-item.active"); + const list = document.getElementById("product-grid-list"); + + if (isSelected) { + // If a product is already selected, and you are single clicking on another product(s) + // WITH command key, the product(s) are added to the selected products Session array + this.handleCheckboxSelect(list, product); + if (event.metaKey || event.ctrlKey || event.shiftKey) { + this.handleCheckboxSelect(list, product); + } + } else if (event.metaKey || event.ctrlKey || event.shiftKey) { + this.handleCheckboxSelect(list, product); + } else { + const checkbox = list.querySelector(`input[type=checkbox][value="${product._id}"]`); + Session.set("productGrid/selectedProducts", []); + if (checkbox) { + checkbox.checked = true; + this.props.itemSelectHandler(checkbox.checked, product._id); + } + } + } else { + const handle = (product.__published && product.__published.handle) || product.handle; + + Reaction.Router.go("product", { + handle + }); + + if (this.props.isSearch) { + this.props.unmountMe(); + } + } + } + + render() { + return ( + + ); + } + } +); + +registerComponent("ProductGridItems", ProductGridItems, [ + SortableItem("productGridItem"), + wrapComponent +]); + +export default compose( + SortableItem("productGridItem"), + wrapComponent +)(ProductGridItems); diff --git a/pool/shard001/JavaScript/0011815_CoreLayout.js b/pool/shard001/JavaScript/0011815_CoreLayout.js new file mode 100644 index 0000000000000000000000000000000000000000..98f4793de010d0ec48879773364e72785104330d --- /dev/null +++ b/pool/shard001/JavaScript/0011815_CoreLayout.js @@ -0,0 +1,21 @@ +import React, { PropTypes } from 'react'; +import HeaderContainer from 'containers/header/headerContainer.jsx'; + +export const CoreLayout = ({ children, location }) => ( +
      + +
      + {children} +
      +
      +); + +CoreLayout.propTypes = { + children: React.PropTypes.oneOfType([ + PropTypes.array, + PropTypes.element + ]), + location: React.PropTypes.object.isRequired +}; + +export default CoreLayout; diff --git a/pool/shard001/JavaScript/0011817_argument_parser.js b/pool/shard001/JavaScript/0011817_argument_parser.js new file mode 100644 index 0000000000000000000000000000000000000000..9f9c17ee0289eebb2c37d8b49cd976d2b5ab89eb --- /dev/null +++ b/pool/shard001/JavaScript/0011817_argument_parser.js @@ -0,0 +1,128 @@ +var ArgumentParser = function(argv) { + var Cucumber = require('../../cucumber'); + + var nopt = require('nopt'); + var path = require('path'); + var options; + + var self = { + parse: function parse() { + var knownOptionDefinitions = self.getKnownOptionDefinitions(); + var shortenedOptionDefinitions = self.getShortenedOptionDefinitions(); + var options = nopt(knownOptionDefinitions, + shortenedOptionDefinitions, + argv, + ArgumentParser.NUMBER_OF_LEADING_ARGS_TO_SLICE); + self.storeOptions(options); + }, + + getFeatureFilePaths: function getFeatureFilePaths() { + var unexpandedFeaturePaths = self.getUnexpandedFeaturePaths(); + var expandedFeaturePaths = ArgumentParser.FeaturePathExpander.expandPaths(unexpandedFeaturePaths); + return expandedFeaturePaths; + }, + + getFeatureDirectoryPaths: function getFeatureDirectoryPaths() { + var featureDirectoryPaths = []; + var featureFilePaths = self.getFeatureFilePaths(); + featureFilePaths.forEach(function(featureFilePath) { + var featureDirectoryPath = featureFilePath.replace(ArgumentParser.FEATURE_FILENAME_REGEXP, ''); + featureDirectoryPaths.push(featureDirectoryPath); + }); + return featureDirectoryPaths; + }, + + getUnexpandedFeaturePaths: function unexpandedFeaturePaths() { + var options = self.getOptions(); + var remaining = options['argv']['remain']; + var paths = (remaining.length > 0 ? remaining : [ArgumentParser.DEFAULT_FEATURES_DIRECTORY]); + return paths; + }, + + getSupportCodeFilePaths: function getSupportCodeFilePaths() { + var unexpandedSupportCodeFilePaths = self.getUnexpandedSupportCodeFilePaths(); + var expandedSupportCodePaths = ArgumentParser.SupportCodePathExpander.expandPaths(unexpandedSupportCodeFilePaths); + return expandedSupportCodePaths; + }, + + getUnexpandedSupportCodeFilePaths: function getUnexpandedSupportCodeFilePaths() { + var unexpandedFeatureDirectoryPaths = self.getFeatureDirectoryPaths(); + var unexpandedSupportCodeFilePaths = self.getOptionOrDefault(ArgumentParser.REQUIRE_OPTION_NAME, unexpandedFeatureDirectoryPaths); + return unexpandedSupportCodeFilePaths; + }, + + getTagGroups: function getTagGroups() { + var tagOptionValues = self.getOptionOrDefault(ArgumentParser.TAGS_OPTION_NAME, []); + var tagGroups = Cucumber.TagGroupParser.getTagGroupsFromStrings(tagOptionValues); + return tagGroups; + }, + + getFormat: function getFormat() { + var format = self.getOptionOrDefault(ArgumentParser.FORMAT_OPTION_NAME, ArgumentParser.DEFAULT_FORMAT_VALUE); + return format; + }, + + getKnownOptionDefinitions: function getKnownOptionDefinitions() { + var definitions = {}; + definitions[ArgumentParser.REQUIRE_OPTION_NAME] = [path, Array]; + definitions[ArgumentParser.TAGS_OPTION_NAME] = [String, Array]; + definitions[ArgumentParser.FORMAT_OPTION_NAME] = String; + definitions[ArgumentParser.HELP_FLAG_NAME] = Boolean; + definitions[ArgumentParser.VERSION_FLAG_NAME] = Boolean; + return definitions; + }, + + getShortenedOptionDefinitions: function getShortenedOptionDefinitions() { + var definitions = {}; + definitions[ArgumentParser.REQUIRE_OPTION_SHORT_NAME] = [ArgumentParser.LONG_OPTION_PREFIX + ArgumentParser.REQUIRE_OPTION_NAME]; + definitions[ArgumentParser.FORMAT_OPTION_SHORT_NAME] = [ArgumentParser.LONG_OPTION_PREFIX + ArgumentParser.FORMAT_OPTION_NAME]; + definitions[ArgumentParser.HELP_FLAG_SHORT_NAME] = [ArgumentParser.LONG_OPTION_PREFIX + ArgumentParser.HELP_FLAG_NAME]; + return definitions; + }, + + isHelpRequested: function isHelpRequested() { + var isHelpRequested = self.getOptionOrDefault(ArgumentParser.HELP_FLAG_NAME, ArgumentParser.DEFAULT_HELP_FLAG_VALUE); + return isHelpRequested; + }, + + isVersionRequested: function isVersionRequested() { + var isVersionRequested = self.getOptionOrDefault(ArgumentParser.VERSION_FLAG_NAME, ArgumentParser.DEFAULT_VERSION_FLAG_VALUE); + return isVersionRequested; + }, + + storeOptions: function storeOptions(newOptions) { + options = newOptions; + }, + + getOptions: function getOptions() { + return options; + }, + + getOptionOrDefault: function getOptionOrDefault(optionName, defaultValue) { + var options = self.getOptions(); + var optionValue = options[optionName]; + return (typeof(optionValue) != 'undefined' ? optionValue : defaultValue); + } + }; + return self; +}; +ArgumentParser.NUMBER_OF_LEADING_ARGS_TO_SLICE = 2; +ArgumentParser.DEFAULT_FEATURES_DIRECTORY = "features"; +ArgumentParser.FEATURE_FILENAME_REGEXP = /[\/\\][^\/\\]+\.feature$/i; +ArgumentParser.LONG_OPTION_PREFIX = "--"; +ArgumentParser.REQUIRE_OPTION_NAME = "require"; +ArgumentParser.REQUIRE_OPTION_SHORT_NAME = "r"; +ArgumentParser.TAGS_OPTION_NAME = "tags"; +ArgumentParser.TAGS_OPTION_SHORT_NAME = "t"; +ArgumentParser.FORMAT_OPTION_NAME = "format"; +ArgumentParser.FORMAT_OPTION_SHORT_NAME = "f"; +ArgumentParser.DEFAULT_FORMAT_VALUE = "progress"; +ArgumentParser.HELP_FLAG_NAME = "help"; +ArgumentParser.HELP_FLAG_SHORT_NAME = "h"; +ArgumentParser.DEFAULT_HELP_FLAG_VALUE = false; +ArgumentParser.VERSION_FLAG_NAME = "version"; +ArgumentParser.DEFAULT_VERSION_FLAG_VALUE = false; +ArgumentParser.FeaturePathExpander = require('./argument_parser/feature_path_expander'); +ArgumentParser.PathExpander = require('./argument_parser/path_expander'); +ArgumentParser.SupportCodePathExpander = require('./argument_parser/support_code_path_expander'); +module.exports = ArgumentParser; diff --git a/pool/shard001/JavaScript/0011824_slider.js b/pool/shard001/JavaScript/0011824_slider.js new file mode 100644 index 0000000000000000000000000000000000000000..9e57fc70ec86e872c22de676b6cae86f1f0efdd0 --- /dev/null +++ b/pool/shard001/JavaScript/0011824_slider.js @@ -0,0 +1,189 @@ +(function(){ + 'use strict'; + + angular + .module('ion-gallery') + .directive('ionSlider',ionSlider); + + ionSlider.$inject = ['$ionicModal','ionGalleryData','$ionicPlatform','$timeout','$ionicScrollDelegate']; + + function ionSlider($ionicModal,ionGalleryData,$ionicPlatform,$timeout,$ionicScrollDelegate){ + + return { + restrict: 'A', + controller: controller, + link : link + }; + + function controller($scope){ + var lastSlideIndex; + var currentImage; + + var rowSize = ionGalleryData.getRowSize(); + var zoomStart = false; + + $scope.selectedSlide = 1; + $scope.hideAll = false; + + $scope.showImage = function(index) { + $scope.slides = []; + + currentImage = index; + + var galleryLength = ionGalleryData.getGalleryLength(); + var previndex = index - 1 < 0 ? galleryLength - 1 : index - 1; + var nextindex = index + 1 >= galleryLength ? 0 : index + 1; + + $scope.slides[0] = $scope.ionGalleryItems[previndex]; + $scope.slides[1] = $scope.ionGalleryItems[index]; + $scope.slides[2] = $scope.ionGalleryItems[nextindex]; + + console.log( 'loadSingles: ' + previndex + ' ' + index + ' ' + nextindex); + + lastSlideIndex = 1; + $scope.loadModal(); + }; + + $scope.slideChanged = function(currentSlideIndex) { + + if(currentSlideIndex === lastSlideIndex){ + return; + } + + var slideToLoad = $scope.slides.length - lastSlideIndex - currentSlideIndex; + var galleryLength = ionGalleryData.getGalleryLength(); + var imageToLoad; + var slidePosition = lastSlideIndex + '>' + currentSlideIndex; + + console.log( 'loadSingles: ' + slidePosition); + + if(slidePosition === '0>1' || slidePosition === '1>2' || slidePosition === '2>0'){ + currentImage++; + imageToLoad = currentImage + 1; + } + else if(slidePosition === '0>2' || slidePosition === '1>0' || slidePosition === '2>1'){ + currentImage--; + imageToLoad = currentImage - 1; + } + + if( currentImage < 0 ){ + currentImage = galleryLength - 1; + } + + if( currentImage >= galleryLength ){ + currentImage = 0; + } + + if( imageToLoad < 0 ){ + imageToLoad = galleryLength + imageToLoad; + } + + if( imageToLoad >= galleryLength ){ + imageToLoad = imageToLoad - galleryLength; + } + + //Clear zoom + $ionicScrollDelegate.$getByHandle('slide-' + slideToLoad).zoomTo(1); + + $scope.slides[slideToLoad] = $scope.ionGalleryItems[imageToLoad]; + + lastSlideIndex = currentSlideIndex; + }; + + $scope.$on('ZoomStarted', function(e){ + $timeout(function () { + zoomStart = true; + $scope.hideAll = true; + }); + + }); + + $scope.$on('ZoomOriginal', function(e){ + $timeout(function () { + _isOriginalSize(); + },300); + + }); + + $scope.$on('TapEvent', function(e){ + $timeout(function () { + _onTap(); + }); + + }); + + $scope.$on('DoubleTapEvent', function(event,position){ + $timeout(function () { + _onDoubleTap(position); + }); + + }); + + var _onTap = function _onTap(){ + + if(zoomStart === true){ + $ionicScrollDelegate.$getByHandle('slide-'+lastSlideIndex).zoomTo(1,true); + + $timeout(function () { + _isOriginalSize(); + },300); + + return; + } + + if(($scope.hasOwnProperty('ionSliderToggle') && $scope.ionSliderToggle === false && $scope.hideAll === false) || zoomStart === true){ + return; + } + + $scope.hideAll = !$scope.hideAll; + }; + + var _onDoubleTap = function _onDoubleTap(position){ + if(zoomStart === false){ + $ionicScrollDelegate.$getByHandle('slide-'+lastSlideIndex).zoomTo(3,true,position.x,position.y); + zoomStart = true; + $scope.hideAll = true; + } + else{ + _onTap(); + } + }; + + function _isOriginalSize(){ + zoomStart = false; + _onTap(); + } + + } + + function link(scope, element, attrs) { + var _modal; + + scope.loadModal = function(){ + $ionicModal.fromTemplateUrl('slider.html', { + scope: scope, + animation: 'fade-in' + }).then(function(modal) { + _modal = modal; + scope.openModal(); + }); + }; + + scope.openModal = function() { + _modal.show(); + }; + + scope.closeModal = function() { + _modal.hide(); + }; + + scope.$on('$destroy', function() { + try{ + _modal.remove(); + } catch(err) { + console.log(err.message); + } + }); + } + } +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011831_categories-controller.js b/pool/shard001/JavaScript/0011831_categories-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..0f549357ad3f864267a05f03793d0bf84b020062 --- /dev/null +++ b/pool/shard001/JavaScript/0011831_categories-controller.js @@ -0,0 +1,182 @@ +(function(){ + angular + .module('categories') + .controller('CategoriesListController', [ + '$mdDialog', '$log', '$q', '$scope', '$timeout', 'Category', '$filter', '$rootScope', 'categoryService', + CategoriesListController + ]).controller('CategoriesEditController', [ + 'elt', '$mdDialog', '$scope', 'Category', '$filter', 'languageService', + CategoriesEditController + ]); + + function CategoriesListController($mdDialog, $log, $q, $scope, $timeout, Category, $filter, $rootScope, categoryService) { + var self = this; + $scope.listCategories = categoryService.getCategories(); + + // For the height of the list + var decreaseForMaxHeight = 250; + $("#listCategories").height(window.innerHeight - decreaseForMaxHeight); + + $(window).on("resize.doResize", function () { + $scope.$apply(function () { + $("#listCategories").height(window.innerHeight - decreaseForMaxHeight); + }); + }); + + $scope.$on("$destroy", function () { + $(window).off("resize.doResize"); //remove the handler added earlier + }); + // End of the height thingy + + $scope.gridData = { + onRegisterApi: function(gridApi){ + $scope.gridApi = gridApi; + $timeout(function() { + $scope.gridApi.core.handleWindowResize(); + }); + }, + enableSorting: true, + rowHeight: 100, + expandableRowHeight: 700, + columnDefs: [ + { name: 'ID', field: '_id', width: '10%' }, + { name: 'Titre', width: '40%', cellTemplate: 'categories/grid-title.html' }, + { name: 'Dernière modif', width: '10%', cellTemplate: 'categories/grid-last-update.html' }, + { name: 'Informations', width: '20%', cellTemplate : 'categories/grid-info.html' }, + { name: 'Action', width: '20%', cellTemplate: 'categories/grid-actions.html' } + ], + data : $scope.listCategories + }; + + $scope.refreshData = function () { + $scope.gridData.data = $filter('filter')($scope.listCategories, $scope.searchText, undefined); + }; + + $scope.newCategory = function(ev) { + var category = new Category(); + + $mdDialog.show({ + controller: CategoriesEditController, + templateUrl: 'partials/categories-form.html', + targetEvent: ev, + locals: {elt: category}, + bindToController: true + + }) + .then(function(answer) { + category.save(function (data) { + if(data.OK == 1) { + categoryService.resetCategories(); + $scope.listCategories = categoryService.getCategories(); + + $rootScope.$broadcast('addNotification', 'La catégorie a bien été sauvegardée'); + } else { + $rootScope.$broadcast('errorApi', data); + } + }); + console.log("OK"); + }, function() { /* CANCEL */ }); + }; + + $scope.editCategory= function(ev, cat) { + var category = angular.copy(cat); + $log.info("Edit category : " + category._id); + $mdDialog.show({ + controller: CategoriesEditController, + templateUrl: 'partials/categories-form.html', + targetEvent: ev, + locals: {elt: category}, + bindToController: true + + }) + .then(function(answer) { + category.save(function (data) { + if(data.OK == 1) { + categoryService.resetCategories(); + $scope.listCategories = categoryService.getCategories(); + + $rootScope.$broadcast('addNotification', 'La catégorie a bien été mise à jour'); + } else { + $rootScope.$broadcast('errorApi', data); + } + }); + console.log("OK"); + }, function() { /* CANCEL */ }); + }; + + $scope.showConfirmDeleteCategory = function(ev, category) { + var confirm = $mdDialog.confirm() + .title('Êtes vous sur de vouloir supprimer la catégorie "' + category.name + '" ?') + .content('Attention, si vous supprimer la catégorie, il n\'y a pas de retour arrière possible.') + .ok('OUI') + .cancel('Annuler') + .targetEvent(ev); + $mdDialog.show(confirm).then(function() { + category.delete(function (data) { + if(data.OK == 1) { + categoryService.resetCategories(); + $scope.listCategories = categoryService.getCategories(); + + $rootScope.$broadcast('addNotification', 'La catégorie a bien été supprimée'); + } else { + $rootScope.$broadcast('errorApi', data); + } + }); + + }, function() {}); + }; + } + + function CategoriesEditController(elt, $mdDialog, $scope, Category, $filter, languageService) { + $scope.availableLanguages = languageService.getLanguages(); + $scope.lang = "fr"; + + var categoryProductSwap = function(key, newKey) { + var tmp = $scope.category.products[key]; + $scope.category.products[key] = $scope.category.products[newKey]; + $scope.category.products[key].position = key; + $scope.category.products[newKey] = tmp; + $scope.category.products[newKey].position = newKey; + }; + + $scope.categoryIngredientAdd = function(cat) { + if(cat.ingredients == undefined) { + cat.ingredients = new Array(); + } + cat.ingredients.push({position: cat.ingredients.length}); + + return cat; + }; + + $scope.title = "Edition de la catégorie : "+ elt.name; + var cat = $scope.categoryIngredientAdd(elt); + + $scope.category = cat; + + $scope.categoryProductUp = function(e, key) { + var newKey = key - 1; + categoryProductSwap(key, newKey); + }; + + $scope.categoryProductDown = function(e, key) { + var newKey = key + 1; + categoryProductSwap(key, newKey); + }; + + $scope.hide = function() { + $mdDialog.hide(); + }; + $scope.cancel = function() { + $mdDialog.cancel(); + }; + $scope.confirm = function() { + for (var key in $scope.category.infos) { + if($scope.category.infos[key].lang == undefined) { + $scope.category.infos[key].lang = key; + } + } + $mdDialog.hide(); + }; + } + +})(); diff --git a/pool/shard001/JavaScript/0011835_reward_page.js b/pool/shard001/JavaScript/0011835_reward_page.js new file mode 100644 index 0000000000000000000000000000000000000000..3fdc2007671b05d7041ceda5fe545d75f3abf3c3 --- /dev/null +++ b/pool/shard001/JavaScript/0011835_reward_page.js @@ -0,0 +1,51 @@ +function RewardPage(world) { + this.browser = world.browser; +} + +RewardPage.prototype.amount = function () { + return this.browser.findElement({ + className: "payoutTotalAmount" + }).getText() + .then(function (amount) { + //get rid of the currency symbol & whitespace + amount = amount.substring(1).trim(); + + return amount; + }); +}; + +//NOTE: need to find elements every time something changes +//because whenever you change a bound value the page will get re-rendered +RewardPage.prototype.checkContributor = function (index) { + return this.browser.findElement({ + xpath: "(//input[@type='checkbox' and @class='shouldPay'])[" + (index + 1) + "]" + }).click(); +}; + +RewardPage.prototype.setContributorAmount = function (index, amount) { + var contributorInput = this.browser.findElement({ + xpath: "(//input[@type='number' and @class='rewardInput'])[" + (index + 1) + "]" + }); + contributorInput.clear(); + contributorInput.sendKeys(amount); + + //lose focus by clicking on a span + contributorInput.findElement({xpath: "//span"}).click(); + + //allow the page to re-render + return this.browser.sleep(500); +}; + +RewardPage.prototype.contributorRows = function () { + return this.browser.findElements({ + className: "contributorRow" + }); +}; + +RewardPage.prototype.switchTo = function () { + this.browser.switchTo().frame(this.browser.findElement({id: "overlayIframe"})); +}; + +module.exports = { + RewardPage: RewardPage +}; diff --git a/pool/shard001/JavaScript/0011839_getStatus.js b/pool/shard001/JavaScript/0011839_getStatus.js new file mode 100644 index 0000000000000000000000000000000000000000..1f8d589dc0a9b3ef92b40745fa8759867177f002 --- /dev/null +++ b/pool/shard001/JavaScript/0011839_getStatus.js @@ -0,0 +1,24 @@ +// Includes +var http = require('../util/http.js').func; +var parser = require('cheerio'); + +// Args +exports.required = ['userId']; + +// Define +exports.func = function (args) { + return http({ + url: '//www.roblox.com/users/' + args.userId + '/profile', + options: { + resolveWithFullResponse: true, + followRedirect: false + } + }) + .then(function (res) { + if (res.statusCode === 200) { + return parser.load(res.body)('div[data-statustext]').attr('data-statustext'); + } else { + throw new Error('User does not exist'); + } + }); +}; diff --git a/pool/shard001/JavaScript/0011840_dashboard.js b/pool/shard001/JavaScript/0011840_dashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..b553371f685ba7ae11ef983c39e483deeb007364 --- /dev/null +++ b/pool/shard001/JavaScript/0011840_dashboard.js @@ -0,0 +1,82 @@ +/* + Define useful variable for flavor display + * FLAVORS: list of flavors w/ there parameters + * FLAVOR_SORT_PARAMS: Which parameter will be use to sort flavors + * FLAVOR_MIN: Minimum value of free flavor available to be displayed + * FLAVOR_DIV_NAME: The
      section that will host view +*/ +var FLAVORS = {}; +var FLAVOR_SORT_PARAMS = 'free'; +var FLAVOR_MIN = 0; +var FLAVOR_DIV_NAME = '#flavors-list'; +var FLAVOR_ORDER = 1; +var FLAVOR_PARAMS_DESC = { + 'free': 'Free', + 'name': 'Name', + 'cpu': 'CPU', + 'ram': 'RAM', + 'disk': 'Disk', + 'max': 'Max' +}; + +/* Activate flavor menu */ +function activeFlavorMenu() { + var sort_css=''; + if (!FLAVOR_ORDER) { + sort_css = 'bottom-up'; + } + /* build refreshFlavorDiv call for active li */ + var onClick = 'refreshFlavorDiv(\'' + FLAVOR_SORT_PARAMS + '\', FLAVOR_MIN, ' + !(FLAVOR_ORDER) + ')'; + + $('#'+FLAVOR_SORT_PARAMS).attr('onClick',onClick); + return 'sort'; +} + +/* + Function to refresh the div name based on user input +*/ +function refreshFlavorDiv(sort_params, min_value, sort_order) { + /* Cleanup current selection */ + $("#"+FLAVOR_SORT_PARAMS).removeClass("active"); + $('#'+FLAVOR_SORT_PARAMS+'_desc').html(FLAVOR_PARAMS_DESC[FLAVOR_SORT_PARAMS]); + + /* Change global variable */ + FLAVOR_SORT_PARAMS = sort_params; + FLAVOR_ORDER = sort_order; + + /* Active modification */ + $("#"+FLAVOR_SORT_PARAMS).addClass("active"); + $('#'+FLAVOR_SORT_PARAMS+'_desc').html(FLAVOR_PARAMS_DESC[FLAVOR_SORT_PARAMS] + activeFlavorMenu()); + FLAVOR_MIN = min_value; + var sorted_data = sortOnParams(FLAVOR_SORT_PARAMS, FLAVORS, FLAVOR_ORDER); + + buildFlavorsView(sorted_data, FLAVOR_MIN, FLAVOR_DIV_NAME); +} + +/* Change slide-out menu or disable menu button */ +function menuSelector(tab_name, enable) { + if (enable) { + // We remove the disable class (if was present) + $('#menu').removeClass('disabled'); + // We put the slide-out version for the current tab + $('#menu').attr('data-activates', 'slide-out-'+tab_name); + // We reload the slide button effect + $(".btn-slide").sideNav(); + } else { + // We disable the menu and don't care about menu action + $('#menu').addClass('disabled'); + } +} + +/* Swap admin tables */ +function swapAdminTables(type) { + var to_hide = 'database'; + // If we want to display database, so we hide instances + if (type == 'database') { + to_hide = 'instances'; + } + $('#table-admin-' + type + '_wrapper').show(); + $('#menu-admin-' + type).addClass('active'); + $('#table-admin-' + to_hide + '_wrapper').hide(); + $('#menu-admin-' + to_hide).removeClass('active'); +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011845_GadgetEditor.js b/pool/shard001/JavaScript/0011845_GadgetEditor.js new file mode 100644 index 0000000000000000000000000000000000000000..abc4f528ff720bfc5f647c4b6168921b038c19ac --- /dev/null +++ b/pool/shard001/JavaScript/0011845_GadgetEditor.js @@ -0,0 +1,213 @@ +// Copyright 2014 The Oppia Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Controller for a state's gadgets editor. + */ + +// Controls adding, deleting and updating gadgets. +oppia.controller('GadgetEditor', [ + '$scope', '$modal', '$log', 'editorContextService', + 'explorationGadgetsService', 'GADGET_SPECS', + function( + $scope, $modal, $log, editorContextService, + explorationGadgetsService, GADGET_SPECS) { + $scope.GADGET_SPECS = GADGET_SPECS; + + $scope.$on('gadgetsChangedOrInitialized', function() { + $scope.refreshGadgetsInfo(); + }); + + $scope.$watch(function() { + return editorContextService.getActiveStateName(); + }, function(currentStateName) { + $scope.activeStateName = currentStateName; + }); + + $scope.refreshGadgetsInfo = function() { + $scope.gadgets = explorationGadgetsService.getGadgets(); + $scope.panels = explorationGadgetsService.getPanels(); + }; + + $scope.deleteGadget = function(gadgetName) { + explorationGadgetsService.deleteGadget(gadgetName, true); + }; + + $scope.addNewGadget = function() { + // Initializing gadgetData with required keys. + var gadgetData = { + gadget_type: '', + gadget_name: '', + panel: '', + customization_args: {}, + visible_in_states: [editorContextService.getActiveStateName()] + }; + _openCustomizeGadgetModal(gadgetData, function(gadgetData) { + explorationGadgetsService.addGadget(gadgetData); + }); + }; + + $scope.editGadget = function(gadgetName) { + var gadgetData = angular.copy($scope.gadgets[gadgetName]); + + _openCustomizeGadgetModal(gadgetData, function(newGadgetData) { + var gadgetName = newGadgetData.gadget_name; + var newCustomizationArgs = newGadgetData.customization_args; + var newVisibleInStates = newGadgetData.visible_in_states; + + explorationGadgetsService.updateGadget( + gadgetName, newCustomizationArgs, newVisibleInStates); + }); + }; + + /** + * @param {Object} gadgetDict - A dict representing the gadget + * being edited. It has the following keys: gadget_type, gadget_name, + * panel, customization_args, and visible_in_states. + * If the gadget's type is an empty string (''), it means no gadget is + * selected, and the gadget selector should be shown. + * @param {Function} successCallback - Success callback when modal is + * dismissed. + */ + var _openCustomizeGadgetModal = function(gadgetDict, successCallback) { + $modal.open({ + templateUrl: 'modals/customizeGadget', + // Clicking outside this modal should not dismiss it. + backdrop: 'static', + resolve: { + gadgetDict: function() { + return gadgetDict; + } + }, + controller: [ + '$scope', '$modalInstance', 'explorationStatesService', + 'explorationGadgetsService', 'gadgetDict', 'GADGET_SPECS', + function( + $scope, $modalInstance, explorationStatesService, + explorationGadgetsService, gadgetDict, GADGET_SPECS) { + $scope.ALLOWED_GADGETS = GLOBALS.ALLOWED_GADGETS; + $scope.GADGET_SPECS = GADGET_SPECS; + $scope.SHOW_GADGET_NAME_EDITOR = false; + + var _initializeCustomizationArgs = function(gadgetType) { + var gadgetSpec = GADGET_SPECS[gadgetType]; + $scope.customizationArgSpecs = gadgetSpec.customization_arg_specs; + for (var i = 0; i < $scope.customizationArgSpecs.length; i++) { + var argName = $scope.customizationArgSpecs[i].name; + $scope.gadgetDict.customization_args[argName] = { + value: ( + $scope.gadgetDict.customization_args.hasOwnProperty( + argName) ? + angular.copy( + $scope.gadgetDict.customization_args[argName].value) : + angular.copy( + $scope.customizationArgSpecs[i].default_value) + ) + }; + } + $scope.$broadcast('schemaBasedFormsShown'); + $scope.form = {}; + }; + + $scope.renameGadget = function(newGadgetName) { + var originalName = $scope.gadgetDict.gadget_name; + if (originalName !== newGadgetName) { + // Record the change. + explorationGadgetsService.renameGadget( + originalName, newGadgetName); + // Update the name's state within the customization modal. + $scope.gadgetDict.gadget_name = newGadgetName; + } + $scope.SHOW_GADGET_NAME_EDITOR = false; + }; + + $scope.openGadgetNameEditor = function() { + $scope.SHOW_GADGET_NAME_EDITOR = true; + // Prefill the rename input box with the current name. + $scope.newNameForRenamedGadget = $scope.gadgetDict.gadget_name; + }; + + $scope.cancelGadgetNameEditor = function() { + // Clear value. + $scope.newNameForRenamedGadget = ''; + // Hide the editor window. + $scope.SHOW_GADGET_NAME_EDITOR = false; + }; + + $scope.gadgetDict = gadgetDict; + if (gadgetDict.gadget_type) { + _initializeCustomizationArgs(gadgetDict.gadget_type); + gadgetDict.panel = GADGET_SPECS[ + gadgetDict.gadget_type].panel; + } + // If gadgetDict has a gadget_type attribute on initialization, the + // user is currently editing the gadget. Otherwise, they are adding + // a new one. + $scope.isEditingGadget = !!gadgetDict.gadget_type; + + $scope.allExplorationStateNames = + Object.keys(explorationStatesService.getStates()); + + $scope.onChangeGadgetType = function(newGadgetType) { + gadgetDict.gadget_type = newGadgetType; + gadgetDict.gadget_name = ( + explorationGadgetsService.getNewUniqueGadgetName(newGadgetType) + ); + _initializeCustomizationArgs(newGadgetType); + }; + + $scope.toggleVisibilityInState = function(stateName) { + var index = $scope.gadgetDict.visible_in_states.indexOf( + stateName); + if (index > -1) { + // Gadget is visible in this state, make it invisible. + $scope.gadgetDict.visible_in_states.splice(index, 1); + } else { + // Gadget is not visible in this state, make it visible. + $scope.gadgetDict.visible_in_states.push(stateName); + } + }; + + $scope.returnToGadgetSelector = function() { + gadgetDict.gadget_type = ''; + gadgetDict.gadget_name = ''; + }; + + $scope.cancel = function() { + $modalInstance.dismiss('cancel'); + }; + + $scope.save = function() { + $scope.gadgetDict.panel = GLOBALS.GADGET_SPECS[ + $scope.gadgetDict.gadget_type].panel; + + // When adding a new gadget do all the validation to check + // if it can be added before dismissing the modal. + if (!$scope.isEditingGadget && + !explorationGadgetsService.canAddGadgetToItsPanel( + $scope.gadgetDict)) { + return; + } + $modalInstance.close($scope.gadgetDict); + }; + } + ] + }).result.then(function(gadgetDict) { + successCallback(gadgetDict); + }, function() { + $log.info('Gadget modal closed'); + }); + }; + } +]); diff --git a/pool/shard001/JavaScript/0011847_service_config.js b/pool/shard001/JavaScript/0011847_service_config.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb9e6a298e27f90a0c2bc6a3c1d3c9b322859c1 --- /dev/null +++ b/pool/shard001/JavaScript/0011847_service_config.js @@ -0,0 +1,175 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var App = require('app'); + +App.ServiceConfig = Ember.Object.extend({ + serviceName: '', + configCategories: [], + configCategoriesMap: function() { + var categoriesMap = {}; + this.get('configCategories').forEach(function(c) { + if (!categoriesMap[c.get('name')]) categoriesMap[c.get('name')] = c; + }); + return categoriesMap; + }.property('configCategories.[]'), + configs: [], + restartRequired: false, + restartRequiredMessage: '', + restartRequiredHostsAndComponents: {}, + configGroups: [], + dependentServiceNames: [], + initConfigsLength: 0, // configs length after initialization in order to watch changes + + errorCount: Em.computed.alias('configsWithErrors.length'), + + /** + * Properties for which some aggregations should be calculated + * like configsWithErrors, changedConfigProperties etc. + * + * @type {Object[]} + */ + activeProperties: [], + + configsWithErrors: [], + + /** + * Collection of properties that were changed: + * for saved properties use - isNotDefaultValue + * for not saved properties (on wizards, for new services) use + * - isNotInitialValue + * for added properties use - isNotSaved + * @type {Object[]} + */ + changedConfigProperties: [], + + setActiveProperties: function() { + Em.run.once(this, 'setActivePropertiesOnce'); + }.observes('configs.@each.isActive', 'configs.@each.isRequiredByAgent', 'configs.@each.value', 'configs.@each.isUndefinedLabel'), + + setActivePropertiesOnce: function() { + if (this.get('isDestroyed')) return false; + var activeProperties = this.get('configs').filter(function(c) { + return (c.get('isActive') || c.get('isUndefinedLabel')) && (c.get('isRequiredByAgent') || c.get('isRequired')); + }); + this.set('activeProperties', activeProperties); + }, + + setChangedConfigProperties: function() { + Em.run.once(this, 'setChangedConfigPropertiesOnce'); + }.observes('activeProperties.@each.isNotDefaultValue', 'activeProperties.@each.isNotSaved', 'activeProperties.@each.isNotInitialValue'), + + setChangedConfigPropertiesOnce: function() { + var changedConfigProperties = this.get('activeProperties').filter(function(c) { + return c.get('isNotDefaultValue') || c.get('isNotSaved') || c.get('isNotInitialValue'); + }, this); + this.set('changedConfigProperties', changedConfigProperties); + }, + + setConfigsWithErrors: function() { + Em.run.once(this, 'setConfigsWithErrorsOnce'); + }.observes('activeProperties.@each.isValid', 'activeProperties.@each.isValidOverride', 'activeProperties.length'), + + setConfigsWithErrorsOnce: function() { + var configsWithErrors = this.get('activeProperties').filter(function(c) { + return (!c.get('isValid') || !c.get('isValidOverride')); + }); + this.set('configsWithErrors', configsWithErrors); + }, + + observeErrors: function() { + this.get('configCategories').setEach('errorCount', 0); + this.get('configsWithErrors').forEach(function(c) { + //configurations with widget shouldn't affect advanced category error counter + if (this.get('configCategoriesMap')[c.get('category')] && !c.get('isInDefaultTheme')) { + this.get('configCategoriesMap')[c.get('category')].incrementProperty('errorCount'); + } + }, this); + }.observes('configsWithErrors'), + + configTypes: function() { + return App.StackService.find(this.get('serviceName')).get('configTypeList') || []; + }.property('serviceName'), + + radioConfigs: Em.computed.filterBy('configs', 'displayType', 'radio button'), + + observeForeignKeys: function() { + //TODO refactor or move this logic to other place + Em.run.once(this, 'updateVisibilityByForeignKeys'); + }.observes('radioConfigs.@each.value'), + + updateVisibilityByForeignKeys: function() { + var configs = this.get('configs'); + configs.forEach(function (item) { + if (item.get('isVisible')) { + var options = item.get('options'); + if (options && options.someProperty('foreignKeys')) { + var options = options.filterProperty('foreignKeys'); + options.forEach(function (opt) { + opt.foreignKeys.forEach(function (key) { + var config = configs.findProperty('name', key); + if (config) { + config.set('isVisible', item.get('value') === opt.displayName); + } + }); + }); + } + } + }); + }, + + /** + * Config with overrides that has values that differs from saved + * + * @type {Object[]} + */ + configsWithChangedOverrides: Em.computed.filterBy('activeProperties', 'isOverrideChanged', true), + + /** + * Defines if some configs were added/removed + * @type {boolean} + */ + configsLengthWasChanged: Em.computed.notEqualProperties('configs.length', 'initConfigsLength'), + + /** + * @type {boolean} + */ + isPropertiesChanged: Em.computed.or( + 'configsLengthWasChanged', + 'changedConfigProperties.length', + 'configsWithChangedOverrides.length'), + + init: function() { + this._super(); + this.set('dependentServiceNames', App.StackService.find(this.get('serviceName')).get('dependentServiceNames') || []); + this.observeForeignKeys(); + this.setActiveProperties(); + }, + + hasConfigIssues: Em.computed.someBy('activeProperties', 'hasIssues', true) +}); + +App.ConfigSiteTag = Ember.Object.extend({ + site: DS.attr('string'), + tag: DS.attr('string'), + /** + * Object map of hostname->override-tag for overrides. + * Creators should set new object here. + */ + hostOverrides: null +}); diff --git a/pool/shard001/JavaScript/0011848_11706.js b/pool/shard001/JavaScript/0011848_11706.js new file mode 100644 index 0000000000000000000000000000000000000000..f7c0a83774c05325201b37e67ca11aa799a6dbc2 --- /dev/null +++ b/pool/shard001/JavaScript/0011848_11706.js @@ -0,0 +1,97 @@ +{ + if (options === void 0) options = {}; + var sfc = { + template: null, + script: null, + styles: [], + customBlocks: [] + }; + var depth = 0; + var currentBlock = null; + + function start(tag, attrs, unary, start, end) { + if (depth === 0) { + currentBlock = { + type: tag, + content: "", + start: end, + attrs: attrs.reduce(function(cumulated, ref) { + var name = ref.name; + var value = ref.value; + cumulated[name] = value || true; + return cumulated; + }, Object.create(null)) + }; + + if (isSpecialTag(tag)) { + checkAttrs(currentBlock, attrs); + + if (tag === "style") { + sfc.styles.push(currentBlock); + } else { + sfc[tag] = currentBlock; + } + } else { + sfc.customBlocks.push(currentBlock); + } + } + + if (!unary) { + depth++; + } + } + + function checkAttrs(block, attrs) { + for (var i = 0; i < attrs.length; i++) { + var attr = attrs[i]; + + if (attr.name === "lang") { + block.lang = attr.value; + } + + if (attr.name === "scoped") { + block.scoped = true; + } + + if (attr.name === "module") { + block.module = attr.value || true; + } + + if (attr.name === "src") { + block.src = attr.value; + } + } + } + + function end(tag, start, end) { + if (depth === 1 && currentBlock) { + currentBlock.end = start; + var text = deindent(content.slice(currentBlock.start, currentBlock.end)); + + if (currentBlock.type !== "template" && options.pad) { + text = padContent(currentBlock, options.pad) + text; + } + + currentBlock.content = text; + currentBlock = null; + } + + depth--; + } + + function padContent(block, pad) { + if (pad === "space") { + return content.slice(0, block.start).replace(replaceRE, " "); + } else { + var offset = content.slice(0, block.start).split(splitRE).length; + var padChar = block.type === "script" && !block.lang ? "//\n" : "\n"; + return Array(offset).join(padChar); + } + } + + parseHTML(content, { + start: start, + end: end + }); + return sfc; +} diff --git a/pool/shard001/JavaScript/0011849_memberoftag.js b/pool/shard001/JavaScript/0011849_memberoftag.js new file mode 100644 index 0000000000000000000000000000000000000000..15653a114070e961e49037dfcdff76196f98843a --- /dev/null +++ b/pool/shard001/JavaScript/0011849_memberoftag.js @@ -0,0 +1,83 @@ +/*global describe: true, expect: true, it: true, jasmine: true */ +describe("@memberof tag", function() { + + it('When a symbol has an @member tag, the doclet has a long name that includes the parent.', function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag.js'), + Data = docSet.getByLongname('mathlib.Data')[0], + point = docSet.getByLongname('mathlib.Data#point')[0]; + + expect(typeof Data).toEqual('object'); + expect(typeof point).toEqual('object'); + + expect(Data.memberof).toEqual('mathlib'); + expect(Data.name).toEqual('Data'); + }); + + it('A symbol within a namespace for which no scope is specified.', function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag4.js'), + doOtherStuff = docSet.getByLongname('doStuff.doOtherStuff')[0]; + + expect(doOtherStuff).toBeDefined(); + expect(doOtherStuff.scope).toEqual('static'); + }); + + it('A symbol in which name === memberof.', function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag4.js'), + doStuff = docSet.getByLongname('doStuff.doStuff')[0]; + + expect(doStuff).toBeDefined(); + expect(doStuff.scope).toEqual('static'); + }); + + describe ("static", function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag2.js'), + publish = docSet.getByLongname('Observable#publish')[0], + cache = docSet.getByLongname('Observable.cache')[0]; + + it('A symbol is documented as a static @memberof a class.', function() { + //it should appear as a static member of that class + expect(typeof cache).toEqual('object'); + expect(cache.memberof).toEqual('Observable'); + expect(cache.scope).toEqual('static'); + expect(cache.name).toEqual('cache'); + expect(cache.longname).toEqual('Observable.cache'); + }); + + it('A symbol is documented as a static @memberof a class prototype.', function() { + //it should appear as an instance member of that class + expect(typeof publish).toEqual('object'); + expect(publish.memberof).toEqual('Observable'); + expect(publish.scope).toEqual('instance'); + expect(publish.name).toEqual('publish'); + expect(publish.longname).toEqual('Observable#publish'); + }); + }); + + describe ("forced", function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftagforced.js'), + maproutes = docSet.getByLongname('map.routes')[0], + datapointy = docSet.getByLongname('Data#point.y')[0]; + + it('A nested symbol with a @memberof! tag set to .', function() { + expect(maproutes.name, 'map.routes', 'Has a shortname that includes the nested names.'); + }); + + it('A nested symbol with a @memberof! tag set to another symbol.', function() { + expect(datapointy.name, 'point.y', 'Has a shortname that includes the nested names.'); + }); + }); + + it('A symbol that is a nested class with a @memberof tag.', function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag3.js'), + tree = docSet.getByLongname('module:terrain.Forest#Tree')[0]; + + expect(tree.longname, 'module:terrain.Forest#Tree'); + }); + + it('A symbol that is an instance member of a nested class with a @memberof tag.', function() { + var docSet = jasmine.getDocSetFromFile('test/fixtures/memberoftag3.js'), + leaf = docSet.getByLongname('module:terrain.Forest#Tree#leaf')[0]; + + expect(leaf.longname, 'module:terrain.Forest#Tree#leaf'); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011850_role-view.js b/pool/shard001/JavaScript/0011850_role-view.js new file mode 100644 index 0000000000000000000000000000000000000000..18065af2a336a3dbdd27c8ca438cb927c693bd8d --- /dev/null +++ b/pool/shard001/JavaScript/0011850_role-view.js @@ -0,0 +1,227 @@ +define([ + 'jquery', + 'underscore', + 'oroui/js/mediator', + 'oroui/js/app/views/base/view' +], function($, _, mediator, BaseView) { + 'use strict'; + + var RoleView; + + /** + * @export orouser/js/views/role-view + */ + RoleView = BaseView.extend({ + options: { + elSelector: '', + formName: '', + formSelector: '', + privilegesSelector: '', + appendUsersSelector: '', + removeUsersSelector: '', + fields: '' + }, + privileges: null, + + $form: null, + $privileges: null, + $appendUsers: null, + $removeUsers: null, + $fields: null, + + events: { + 'click': 'onSubmit' + }, + + listen: { + 'securityAccessLevelsComponent:link:click mediator': 'onAccessLevelsLinkClicked' + }, + + /** + * Initialize + * + * @param {Object} options + */ + initialize: function(options) { + this.options = _.defaults(options || {}, this.options); + this.$el = $(this.options.elSelector); + this.$form = $(this.options.formSelector); + this.$privileges = $(this.options.privilegesSelector); + this.$appendUsers = $(this.options.appendUsersSelector); + this.$removeUsers = $(this.options.removeUsersSelector); + + var fields = {}; + _.each( + this.options.fields, + function(selector, name) { + fields[name] = $(selector); + } + ); + this.$fields = fields; + }, + + /** + * @inheritDoc + */ + dispose: function() { + if (this.disposed) { + return; + } + + delete this.$form; + delete this.$privileges; + delete this.$appendUsers; + delete this.$removeUsers; + delete this.$fields; + + RoleView.__super__.dispose.call(this); + }, + + /** + * onSubmit event listener + */ + onSubmit: function(event) { + var $form = this.$form; + var hasError = false; + _.each(this.$fields, function(field) { + hasError = hasError || !field.valid(); + }); + if (hasError) { + return; + } + if ($form.data('nohash') && !$form.data('sent')) { + $form.data('sent', true); + return; + } + if ($form.data('sent')) { + return; + } + + $form.data('sent', true); + + var action = $form.attr('action'); + var method = $form.attr('method'); + var url = (typeof action === 'string') ? $.trim(action) : ''; + url = url || window.location.href || ''; + if (url) { + url += '?input_action=' + $(event.target).attr('data-action'); + + // clean url (don't include hash value) + url = (url.match(/^([^#]+)/) || [])[1]; + } + + var data = this.getData(); + + var dataAction = $(event.target).attr('data-action'); + if (dataAction) { + data.input_action = dataAction; + } + + var options = { + url: url, + type: method || 'GET', + data: $.param(data) + }; + mediator.execute('submitPage', options); + }, + + /** + * @returns {Object} + */ + getData: function() { + var data = {}; + + var formName = this.options.formName; + _.each( + this.$fields, + function(element, name) { + var value = element.val(); + + if (element.attr('type') === 'checkbox') { + value = element.is(':checked') ? 1 : 0; + + if (value === 0) { // do not send the value of checkbox, + return; // it will be set as false in the backend + } + } + + data[formName + '[' + name + ']'] = value; + } + ); + + data[formName + '[privileges]'] = this.$privileges.val(); + data[formName + '[appendUsers]'] = this.$appendUsers.val(); + data[formName + '[removeUsers]'] = this.$removeUsers.val(); + + return data; + }, + + /** + * onClick event listener + */ + onAccessLevelsLinkClicked: function(data) { + if (this.disposed) { + return; + } + var obj = JSON.parse(this.$privileges.val()); + + var knownIdentities = _.reduce(obj, function(memo, group) { + memo = _.reduce(group, function(memo, item) { + memo[item.identity.id] = item; + return memo; + }, memo); + return memo; + }, {}); + + var identity = data.identityId; + var splittedIdentity = identity.split('::'); + var field; + if (typeof splittedIdentity[1] !== 'undefined') { + identity = splittedIdentity[0]; + field = splittedIdentity[1]; + } + + var privelege; + var fieldPrivelege; + if (identity in knownIdentities) { + privelege = knownIdentities[identity]; + } else { + // create privelege + privelege = { + identity: { + id: identity + }, + permissions: {} + }; + if (data.permissionName === 'EXECUTE') { + obj.action[Object.keys(knownIdentities).length] = privelege; + } else { + obj.entity[Object.keys(knownIdentities).length] = privelege; + } + } + + if (!field) { + if (!(data.permissionName in privelege.permissions)) { + privelege.permissions[data.permissionName] = { + name: data.permissionName + }; + } + var permission = privelege.permissions[data.permissionName]; + permission.accessLevel = data.accessLevel; + } else { + var knownFieldIdentities = _.reduce(privelege.fields, function(memo, item) { + memo[item.identity.id] = item; + return memo; + }, {}); + + fieldPrivelege = knownFieldIdentities[data.identityId]; + var fieldPermission = fieldPrivelege.permissions[data.permissionName]; + fieldPermission.accessLevel = data.accessLevel; + } + + this.$privileges.val(JSON.stringify(obj)).trigger('change'); + } + }); + + return RoleView; +}); diff --git a/pool/shard001/JavaScript/0011851_splitview.js b/pool/shard001/JavaScript/0011851_splitview.js new file mode 100644 index 0000000000000000000000000000000000000000..b6abfe64ce29016dd5b3f8f3f2baacbb714d8aff --- /dev/null +++ b/pool/shard001/JavaScript/0011851_splitview.js @@ -0,0 +1,183 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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. + +angular.module('mm.core') + +.constant('mmCoreSplitViewLoad', 'mmSplitView:load') + +/** + * Directive to create a split view layout. This directive should be used along with mm-split-view-link. + * + * @module mm.core + * @ngdoc directive + * @name mmSplitView + * @description + * Usage: + * + * + * + * + * To change the right pane contents (content pane), mmSplitViewLink directive is needed. + * mmSplitView will try to load the first mmSplitViewLink when the view is loaded. + * + * Accepts the following params: + * + * @param {String} [menuWidth] Width of the left menu. Can be specified in pixels ('200px') or in percentage ('30%'). + * + * @param {String} [loadWhen] Name of a scope variable. When that variable is set to true, the first mm-split-view-link + * found will be loaded in the contents pane. If not set, try to load it right at the start. + */ +.directive('mmSplitView', function($log, $state, $ionicPlatform, $timeout, mmCoreSplitViewLoad) { + + $log = $log.getInstance('mmSplitView'); + + /** + * Trigger click on a DOM element. + * + * @param {Object} link DOM element to trigger click. + * @return {Boolean} True if success, false otherwise. + */ + function triggerClick(link) { + if (link && link.length && link.triggerHandler) { + link.triggerHandler('click'); + return true; + } + return false; + } + + // Directive controller. + function controller() { + var self = this, + element, + menuState, + linkToLoad; + + /** + * Clears links marked as selected. + */ + this.clearMarkedLinks = function() { + angular.element(element.querySelectorAll('[mm-split-view-link]')).removeClass('mm-split-item-selected'); + }; + + /** + * Get split view menu's state name (left pane). + * + * @return {String} Menu state name. + */ + this.getMenuState = function() { + return menuState || $state.current.name; + }; + + /** + * Load a mm-split-view-link. + * + * @param {Boolean} retrying True if we're retrying because the function failed (link wasn't ready), false otherwise. + */ + this.loadLink = function(retrying) { + if ($ionicPlatform.isTablet()) { + if (!linkToLoad) { + // No link set. Get first link inside the directive. + linkToLoad = angular.element(element.querySelector('[mm-split-view-link]')); + } + + if (!triggerClick(linkToLoad)) { + // Link not found. Let's retry once in the next digest. + if (!retrying) { + linkToLoad = undefined; + $timeout(function() { + self.loadLink(true); + }); + } + } + } + }; + + /** + * Set directive's DOM element. + * + * @param {Object} el Directive's DOM element. + */ + this.setElement = function(el) { + element = el; + }; + + /** + * Set mm-split-view-link to load. Used to re-load last state if needed. + * + * @param {Object} link Link to set (DOM element). + */ + this.setLink = function(link) { + linkToLoad = link; + }; + + /** + * Set split view menu's state name (left pane). + * + * @param {String} state State name to set. + */ + this.setMenuState = function(state) { + menuState = state; + }; + } + + return { + restrict: 'E', + templateUrl: 'core/templates/splitview.html', + transclude: true, + controller: controller, + link: function(scope, element, attrs, controller) { + var el = element[0], + menu = angular.element(el.querySelector('.mm-split-pane-menu')), + menuState = $state.current.name, + menuWidth = attrs.menuWidth; + + controller.setElement(el); + controller.setMenuState(menuState); + + if (menuWidth && $ionicPlatform.isTablet()) { + menu.css('width', menuWidth); + menu.css('-webkit-flex-basis', menuWidth); + menu.css('-moz-flex-basis', menuWidth); + menu.css('-ms-flex-basis', menuWidth); + menu.css('flex-basis', menuWidth); + } + + // We'll set all the listeners even if it's not a tablet, to support change between tablet-smartphone mode. + + if (attrs.loadWhen) { + // Load link when variable is set to true. + scope.$watch(attrs.loadWhen, function(newValue) { + if (newValue) { + controller.loadLink(); + } + }); + } else { + controller.loadLink(); + } + + // Load last opened link when we re-enter the same state. We use $stateChangeSuccess instead of $ionicView.enter + // because $ionicView.enter is not triggered when going to the same state. + scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { + if (toState.name === menuState) { + controller.loadLink(); + } + }); + + // Listen for event to load link. + scope.$on(mmCoreSplitViewLoad, function() { + controller.loadLink(); + }); + } + }; +}); diff --git a/pool/shard001/JavaScript/0011859_AlwaysBeCasting.js b/pool/shard001/JavaScript/0011859_AlwaysBeCasting.js new file mode 100644 index 0000000000000000000000000000000000000000..7db58814f6786f65b94a8da81b73ed3c2cab3d1b --- /dev/null +++ b/pool/shard001/JavaScript/0011859_AlwaysBeCasting.js @@ -0,0 +1,66 @@ +import SPELLS from 'common/SPELLS'; +import CoreAlwaysBeCastingHealing from 'parser/shared/modules/AlwaysBeCastingHealing'; + +const debug = false; + +class AlwaysBeCasting extends CoreAlwaysBeCastingHealing { + static HEALING_ABILITIES_ON_GCD = [ + SPELLS.FLASH_OF_LIGHT.id, + SPELLS.HOLY_LIGHT.id, + SPELLS.HOLY_SHOCK_CAST.id, + SPELLS.LIGHT_OF_DAWN_CAST.id, + SPELLS.LIGHT_OF_THE_MARTYR.id, + SPELLS.BESTOW_FAITH_TALENT.id, + SPELLS.HOLY_PRISM_TALENT.id, + SPELLS.LIGHTS_HAMMER_TALENT.id, + ]; + + constructor(...args) { + super(...args); + + if (this.selectedCombatant.hasTalent(SPELLS.AVENGING_CRUSADER_TALENT.id)) { + this.constructor.HEALING_ABILITIES_ON_GCD.push(SPELLS.JUDGMENT_CAST.id); + this.constructor.HEALING_ABILITIES_ON_GCD.push(SPELLS.CRUSADER_STRIKE.id); + } else { + if (this.selectedCombatant.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id)) { + this.constructor.HEALING_ABILITIES_ON_GCD.push(SPELLS.CRUSADER_STRIKE.id); + } + if (this.selectedCombatant.hasTalent(SPELLS.JUDGMENT_OF_LIGHT_TALENT.id)) { + this.constructor.HEALING_ABILITIES_ON_GCD.push(SPELLS.JUDGMENT_CAST.id); + } + } + } + + countsAsHealingAbility(event) { + const spellId = event.ability.guid; + if (spellId === SPELLS.HOLY_SHOCK_CAST.id && !event.trigger.targetIsFriendly) { + debug && + console.log( + `%cABC: ${event.ability.name} (${spellId}) skipped for healing time; target is not friendly`, + 'color: orange', + ); + return false; + } + + // using crusdars might, count Crusader Strike healing spell, or if Avenging Crusdaer is active, count for healing // + if ( + spellId === SPELLS.CRUSADER_STRIKE.id && + !this.selectedCombatant.hasBuff(SPELLS.AVENGING_CRUSADER_TALENT.id, event.timestamp) && + !this.selectedCombatant.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id) + ) { + return false; + } + + // if judging light, always count as healing spell, or if Avenging Crusdaer is active, count for healing // + if ( + spellId === SPELLS.JUDGMENT_CAST.id && + !this.selectedCombatant.hasBuff(SPELLS.AVENGING_CRUSADER_TALENT.id, event.timestamp) && + !this.selectedCombatant.hasTalent(SPELLS.JUDGMENT_OF_LIGHT_TALENT.id) + ) { + return false; + } + return super.countsAsHealingAbility(event); + } +} + +export default AlwaysBeCasting; diff --git a/pool/shard001/JavaScript/0011862_data.js b/pool/shard001/JavaScript/0011862_data.js new file mode 100644 index 0000000000000000000000000000000000000000..dde12f47ad06c1bf5f91b5b79ffa0ae94464872b --- /dev/null +++ b/pool/shard001/JavaScript/0011862_data.js @@ -0,0 +1,113 @@ +/** + * @Overview 数据接口模块 + * 数据交互,如果接口很少可以放到logic中 + */ +(function(Q){ + + var $ = Q.$; + + /** + * 交互类 + * @param {object} param 要提交的数据 + * @param {Object} [ajaxOpt] ajax配置 + * @constructor + */ + var Sync = function(param, ajaxOpt) { + if(!param) { + return; + } + var protocol = this.protocol = 'http'; + + var ajaxOptDefault = { + url: protocol + '://'+location.host, + type: 'GET', + dataType: 'jsonp', + timeout: 20000 + }; + + this.protocol = protocol; + this.param = $.extend({}, param); + this.ajaxOpt = $.extend({data: this.param}, ajaxOptDefault, ajaxOpt); + this.HOST = protocol + '://'+location.host; + }; + + /* 示例:window.external.getSID(arg0)需要改为 external_call("getSID",arg0) 的形式进行调用 */ + function external_call(extName,arg0,arg1,arg2){ + var args = arguments, fun = args.callee, argsLen = args.length, funLen = fun.length; + if(argsLen>funLen){ + throw new Error("window.external_call仅接受"+funLen+"个形参,但当前(extName:"+extName+")传入了"+argsLen+"个实参,请适当调整external_call,以保证参数正常传递,避免丢失!"); + } + if(window.external_call_test){ + return window.external_call_test.apply(null,[].slice.apply(args)); + } + /* 这里的参数需要根据external_call的形参进行调整,以保证正常传递 + * IE系列external方法不支持apply、call... + * 甚至部分客户端对参数长度也要求必须严格按约定传入 + * 所以保证兼容性就必须人肉维护下面这么一坨.. + */ + if(argsLen==1)return window.external[extName](); + if(argsLen==2)return window.external[extName](arg0); + if(argsLen==3)return window.external[extName](arg0,arg1); + if(argsLen==4)return window.external[extName](arg0,arg1,arg2); + } + + $.extend(Sync.prototype, { + /** + * 通过get方式(jsonp)提交 + * @param {String} [url] 请求链接 + * @return {Object} promise对象 + */ + get: function(url) { + var self = this; + var send = $.ajax(url, this.ajaxOpt); + return send.then(this.done, function(statues) { + return self.fail(statues); + }); + }, + /** + * 通知客户端 + */ + informClient: function() { + var self = this; + var deferred = $.Deferred(); + var args = [].slice.apply(arguments); + try { + var data = external_call.apply(null, args); + deferred.resolve(data); + }catch (e) { + deferred.reject({ + errno: 10000, + errmsg: '通知客户端异常' + }); + } + return deferred.promise() + .then(self.done, self.fail); + }, + /** + * 收到响应时默认回调 + * @param {Object} data 数据 + * @return {Object} + */ + done: function (data) { + var deferred = $.Deferred(); + deferred.resolve(data); + return deferred.promise(); + }, + /** + * 未收到响应时默认回调 + * @param {Object} error 错误信息 + * @return {Object} + */ + fail: function(error) { + var deferred = $.Deferred(); + deferred.reject({ + errno: 999999, + errmsg: '网络超时,请稍后重试' + }); + return deferred.promise(); + } + }); + + QClient.Sync = Sync; + +})(QClient); diff --git a/pool/shard001/JavaScript/0011863_init.js b/pool/shard001/JavaScript/0011863_init.js new file mode 100644 index 0000000000000000000000000000000000000000..b52076c961fb27ff6a3aab043ebe25faaefb45f1 --- /dev/null +++ b/pool/shard001/JavaScript/0011863_init.js @@ -0,0 +1,17 @@ +'use strict'; +var DataSource = require('loopback-datasource-juggler').DataSource; + +var config = { + host: 'localhost', + port: 28015, + db: 'test' +}; + +global.getDataSource = global.getSchema = function(customConfig) { + var db = new DataSource(require('../'), customConfig || config); + db.log = function(a) { + console.log(a); //eslint-disable-line no-console + }; + + return db; +}; diff --git a/pool/shard001/JavaScript/0011864_Layout.js b/pool/shard001/JavaScript/0011864_Layout.js new file mode 100644 index 0000000000000000000000000000000000000000..0e8b4c6ecd00fcaa317ed9459fe9c2cef3228e4d --- /dev/null +++ b/pool/shard001/JavaScript/0011864_Layout.js @@ -0,0 +1,178 @@ +/* Layout() + * ======== + * Implements AdminLTE layout. + * Fixes the layout height in case min-height fails. + * + * @usage activated automatically upon window load. + * Configure any options by passing data-option="value" + * to the body tag. + */ ++function ($) { + 'use strict'; + + var DataKey = 'lte.layout'; + + var Default = { + slimscroll : true, + resetHeight: true + }; + + var Selector = { + wrapper : '.wrapper', + contentWrapper: '.content-wrapper', + layoutBoxed : '.layout-boxed', + mainFooter : '.main-footer', + mainHeader : '.main-header', + sidebar : '.sidebar', + controlSidebar: '.control-sidebar', + fixed : '.fixed', + sidebarMenu : '.sidebar-menu', + logo : '.main-header .logo' + }; + + var ClassName = { + fixed : 'fixed', + holdTransition: 'hold-transition' + }; + + var Layout = function (options) { + this.options = options; + this.bindedResize = false; + this.activate(); + }; + + Layout.prototype.activate = function () { + this.fix(); + this.fixSidebar(); + + $('body').removeClass(ClassName.holdTransition); + + if (this.options.resetHeight) { + $('body, html, ' + Selector.wrapper).css({ + 'height' : 'auto', + 'min-height': '100%' + }); + } + + if (!this.bindedResize) { + $(window).resize(function () { + this.fix(); + this.fixSidebar(); + + $(Selector.logo + ', ' + Selector.sidebar).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () { + this.fix(); + this.fixSidebar(); + }.bind(this)); + }.bind(this)); + + this.bindedResize = true; + } + + $(Selector.sidebarMenu).on('expanded.tree', function () { + this.fix(); + this.fixSidebar(); + }.bind(this)); + + $(Selector.sidebarMenu).on('collapsed.tree', function () { + this.fix(); + this.fixSidebar(); + }.bind(this)); + }; + + Layout.prototype.fix = function () { + // Remove overflow from .wrapper if layout-boxed exists + $(Selector.layoutBoxed + ' > ' + Selector.wrapper).css('overflow', 'hidden'); + + // Get window height and the wrapper height + var footerHeight = $(Selector.mainFooter).outerHeight() || 0; + var headerHeight = $(Selector.mainHeader).outerHeight() || 0; + var neg = headerHeight + footerHeight; + var windowHeight = $(window).height(); + var sidebarHeight = $(Selector.sidebar).height() || 0; + + // Set the min-height of the content and sidebar based on + // the height of the document. + if ($('body').hasClass(ClassName.fixed)) { + $(Selector.contentWrapper).css('min-height', windowHeight - footerHeight); + } else { + var postSetHeight; + + if (windowHeight >= sidebarHeight + headerHeight) { + $(Selector.contentWrapper).css('min-height', windowHeight - neg); + postSetHeight = windowHeight - neg; + } else { + $(Selector.contentWrapper).css('min-height', sidebarHeight); + postSetHeight = sidebarHeight; + } + + // Fix for the control sidebar height + var $controlSidebar = $(Selector.controlSidebar); + if (typeof $controlSidebar !== 'undefined') { + if ($controlSidebar.height() > postSetHeight) + $(Selector.contentWrapper).css('min-height', $controlSidebar.height()); + } + } + }; + + Layout.prototype.fixSidebar = function () { + // Make sure the body tag has the .fixed class + if (!$('body').hasClass(ClassName.fixed)) { + if (typeof $.fn.slimScroll !== 'undefined') { + $(Selector.sidebar).slimScroll({ destroy: true }).height('auto'); + } + return; + } + + // Enable slimscroll for fixed layout + if (this.options.slimscroll) { + if (typeof $.fn.slimScroll !== 'undefined') { + // Destroy if it exists + // $(Selector.sidebar).slimScroll({ destroy: true }).height('auto') + + // Add slimscroll + $(Selector.sidebar).slimScroll({ + height: ($(window).height() - $(Selector.mainHeader).height()) + 'px' + }); + } + } + }; + + // Plugin Definition + // ================= + function Plugin(option) { + return this.each(function () { + var $this = $(this); + var data = $this.data(DataKey); + + if (!data) { + var options = $.extend({}, Default, $this.data(), typeof option === 'object' && option); + $this.data(DataKey, (data = new Layout(options))); + } + + if (typeof option === 'string') { + if (typeof data[option] === 'undefined') { + throw new Error('No method named ' + option); + } + data[option](); + } + }); + } + + var old = $.fn.layout; + + $.fn.layout = Plugin; + $.fn.layout.Constuctor = Layout; + + // No conflict mode + // ================ + $.fn.layout.noConflict = function () { + $.fn.layout = old; + return this; + }; + + // Layout DATA-API + // =============== + $(window).on('load', function () { + Plugin.call($('body')); + }); +}(jQuery); diff --git a/pool/shard001/JavaScript/0011871_elide-double-hole-check-4.js b/pool/shard001/JavaScript/0011871_elide-double-hole-check-4.js new file mode 100644 index 0000000000000000000000000000000000000000..77eb57c22fc365744e24ef1d286f00af66e11993 --- /dev/null +++ b/pool/shard001/JavaScript/0011871_elide-double-hole-check-4.js @@ -0,0 +1,40 @@ +// Copyright 2013 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Flags: --allow-natives-syntax + +function f1(a, i) { + return a[i] + 0.5; +} +%PrepareFunctionForOptimization(f1); +var arr = [0.0,,2.5]; +assertEquals(0.5, f1(arr, 0)); +assertEquals(0.5, f1(arr, 0)); +%OptimizeFunctionOnNextCall(f1); +assertEquals(0.5, f1(arr, 0)); +Array.prototype[1] = 1.5; +assertEquals(2, f1(arr, 1)); diff --git a/pool/shard001/JavaScript/0011872_Enum.js b/pool/shard001/JavaScript/0011872_Enum.js new file mode 100644 index 0000000000000000000000000000000000000000..e6cd2456b1e5e04f73604796f68c5acaa9173c12 --- /dev/null +++ b/pool/shard001/JavaScript/0011872_Enum.js @@ -0,0 +1,143 @@ +/* eslint camelcase: ["off"] */ + +const constantRenameRegex = /([a-z])([A-Z])|([^\w])/g; + +const toCamelCaseRegex = /([a-z])[^a-z]+([a-z])/g; + +const Model = require('./Model'); + +function Enum_prototype_name () { + return this._name; +} + +const Enum = module.exports = Model.extend({ + prototype: { + value: function () { + return this.data; + }, + + name: Enum_prototype_name, + + toString: Enum_prototype_name, + + clean: function (options) { + const Type = this.Model; + return Type.clean ? Type.clean(this, options) : this._name; + } + } +}); + +Enum.toConstantName = function (str) { + return str.replace(constantRenameRegex, function (match, lowerCh, upperCh, specialCh) { + if (lowerCh) { + return lowerCh + '_' + upperCh; + } else { + return '_'; + } + }).toUpperCase(); +}; + +Enum.toCamelCase = function (str) { + return str.toLowerCase().replace(toCamelCaseRegex, function (match, ch1, ch2) { + return ch1 + ch2.toUpperCase(); + }); +}; + +Enum.toTitleCase = function (str) { + const title = Enum.toCamelCase(str); + return title.charAt(0).toUpperCase() + title.substring(1); +}; + +const NORMALIZE_LOWER_CASE = function (str) { + return str.toLowerCase(); +}; + +const NORMALIZE_UPPER_CASE = function (str) { + return str.toUpperCase(); +}; + +Enum.create = function (config) { + let normalize; + + if (Array.isArray(config)) { + config = { + values: config + }; + } + + const origCoerce = config.coerce; + let Type; + + config.coerce = function (value, options) { + if (origCoerce) { + const newValue = origCoerce.call(this, value, options); + if (newValue !== undefined) { + value = newValue; + } + } + + if ((value == null) || (value.constructor === Type)) { + return value; + } + + if (normalize !== undefined) { + value = normalize(value); + } + + const enumValue = Type[value]; + if (enumValue === undefined) { + this.coercionError(value, options); + } + return enumValue; + }; + + Type = Enum.extend(config); + + if (config.autoUpperCase) { + normalize = NORMALIZE_UPPER_CASE; + } else if (config.autoLowerCase) { + normalize = NORMALIZE_LOWER_CASE; + } + + const proto = Type.prototype; + + const values = config.values; + + Type.names = []; + Type.values = []; + + function createEnumValue (name, value, ordinal) { + Type.names.push(name); + + const enumValue = new Type(value); + enumValue._name = name; + + proto['is' + Enum.toTitleCase(name)] = function () { + return (this === enumValue); + }; + + Type[name] = Type[Enum.toConstantName(name)] = enumValue; + + Type[name].ordinal = function () { + return ordinal; + }; + + Type.values.push(enumValue); + + return enumValue; + } + + if (Array.isArray(values)) { + values.forEach(function (value, index) { + createEnumValue(value, value, index); + }); + } else { + Object.keys(values).forEach(function (name, index) { + createEnumValue(name, values[name], index); + }); + } + + Type.preventConstruction(); + + return Type; +}; diff --git a/pool/shard001/JavaScript/0011879_mutable_enumerable_test.js b/pool/shard001/JavaScript/0011879_mutable_enumerable_test.js new file mode 100644 index 0000000000000000000000000000000000000000..1cbc22a566cd2ea5ed60fbcec21a22e76de362d7 --- /dev/null +++ b/pool/shard001/JavaScript/0011879_mutable_enumerable_test.js @@ -0,0 +1,72 @@ +import MutableEnumerableTests from 'ember-runtime/tests/suites/mutable_enumerable'; +import MutableEnumerable from 'ember-runtime/mixins/mutable_enumerable'; +import EnumerableUtils from 'ember-metal/enumerable_utils'; +import EmberObject from 'ember-runtime/system/object'; +import {computed} from 'ember-metal/computed'; +import {get} from 'ember-metal/property_get'; +import {set} from 'ember-metal/property_set'; + +var indexOf = EnumerableUtils.indexOf; + +/* + Implement a basic fake mutable array. This validates that any non-native + enumerable can impl this API. +*/ +var TestMutableEnumerable = EmberObject.extend(MutableEnumerable, { + + _content: null, + + addObject: function(obj) { + if (indexOf(this._content, obj)>=0) return this; + this.enumerableContentWillChange(null, [obj]); + this._content.push(obj); + this.enumerableContentDidChange(null, [obj]); + }, + + removeObject: function(obj) { + var idx = indexOf(this._content, obj); + if (idx<0) return this; + + this.enumerableContentWillChange([obj], null); + this._content.splice(idx, 1); + this.enumerableContentDidChange([obj], null); + return this; + }, + + init: function(ary) { + this._content = ary || []; + }, + + nextObject: function(idx) { + return idx>=get(this, 'length') ? undefined : this._content[idx]; + }, + + length: computed(function() { + return this._content.length; + }), + + slice: function() { + return this._content.slice(); + } +}); + + +MutableEnumerableTests.extend({ + + name: 'Basic Mutable Array', + + newObject: function(ary) { + ary = ary ? ary.slice() : this.newFixture(3); + return new TestMutableEnumerable(ary); + }, + + // allows for testing of the basic enumerable after an internal mutation + mutate: function(obj) { + obj.addObject(this.getFixture(1)[0]); + }, + + toArray: function(obj) { + return obj.slice(); + } + +}).run(); diff --git a/pool/shard001/JavaScript/0011881_native_require.js b/pool/shard001/JavaScript/0011881_native_require.js new file mode 100644 index 0000000000000000000000000000000000000000..39cdc7cdb1d4488246a18f3a07c1869ad0b0ac8e --- /dev/null +++ b/pool/shard001/JavaScript/0011881_native_require.js @@ -0,0 +1,54 @@ + +var game_file_list = [ + //以下为自动修改,请勿修改 + //----auto game_file_list start---- + "libs/modules/egret/egret.js", + "libs/modules/egret/egret.native.js", + "bin-debug/Main.js", + //----auto game_file_list end---- +]; + +var window = this; + +egret_native.setSearchPaths([""]); + +egret_native.requireFiles = function () { + for (var key in game_file_list) { + var src = game_file_list[key]; + require(src); + } +}; + +egret_native.egretInit = function () { + egret_native.requireFiles(); + egret.TextField.default_fontFamily = "/system/fonts/DroidSansFallback.ttf"; + //egret.dom为空实现 + egret.dom = {}; + egret.dom.drawAsCanvas = function () { + }; +}; + +egret_native.egretStart = function () { + var option = { + //以下为自动修改,请勿修改 + //----auto option start---- + entryClassName: "Main", + frameRate: 30, + scaleMode: "showAll", + contentWidth: 640, + contentHeight: 1136, + showPaintRect: false, + showFPS: false, + fpsStyles: "x:0,y:0,size:30,textColor:0x00c200,bgAlpha:0.9", + showLog: false, + logFilter: "", + maxTouches: 2, + textureScaleFactor: 1 + //----auto option end---- + }; + + egret.native.NativePlayer.option = option; + egret.runEgret(); + egret_native.Label.createLabel(egret.TextField.default_fontFamily, 20, "", 0); + egret_native.EGTView.preSetOffScreenBufferEnable(true); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011883_user-route.js b/pool/shard001/JavaScript/0011883_user-route.js new file mode 100644 index 0000000000000000000000000000000000000000..28bd3669d1ed57c62dbdb84fb8b9be7643f07da2 --- /dev/null +++ b/pool/shard001/JavaScript/0011883_user-route.js @@ -0,0 +1,21 @@ +'use strict' + +const {Router} = require('express') +const jsonParser = require('body-parser').json() + +const auth = require('../lib/auth-middleware.js') +const User = require('../model/user.js') + +const authRouter = module.exports = new Router() + +authRouter.post('/api/signup', jsonParser, (req, res, next) => { + User.create(req.body) + .then(token => res.send(token)) + .catch(next) +}) + +authRouter.get('/api/signin', auth, (req, res, next) => { + req.user.createToken() + .then(token => res.send(token)) + .catch(next) +}) diff --git a/pool/shard001/JavaScript/0011884_form_group_directive.js b/pool/shard001/JavaScript/0011884_form_group_directive.js new file mode 100644 index 0000000000000000000000000000000000000000..c3a33705f81a5f2cf0b5942acb011590a8e43850 --- /dev/null +++ b/pool/shard001/JavaScript/0011884_form_group_directive.js @@ -0,0 +1,183 @@ +/** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +import { Directive, Inject, Input, Optional, Output, Self, forwardRef } from '@angular/core'; +import { EventEmitter } from '../../facade/async'; +import { ListWrapper } from '../../facade/collection'; +import { NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators } from '../../validators'; +import { ControlContainer } from '../control_container'; +import { ReactiveErrors } from '../reactive_errors'; +import { cleanUpControl, composeAsyncValidators, composeValidators, setUpControl, setUpFormContainer } from '../shared'; +export var formDirectiveProvider = { + provide: ControlContainer, + useExisting: forwardRef(function () { return FormGroupDirective; }) +}; +/** + * @whatItDoes Binds an existing {@link FormGroup} to a DOM element. + * + * @howToUse + * + * This directive accepts an existing {@link FormGroup} instance. It will then use this + * {@link FormGroup} instance to match any child {@link FormControl}, {@link FormGroup}, + * and {@link FormArray} instances to child {@link FormControlName}, {@link FormGroupName}, + * and {@link FormArrayName} directives. + * + * **Set value**: You can set the form's initial value when instantiating the + * {@link FormGroup}, or you can set it programmatically later using the {@link FormGroup}'s + * {@link AbstractControl.setValue} or {@link AbstractControl.patchValue} methods. + * + * **Listen to value**: If you want to listen to changes in the value of the form, you can subscribe + * to the {@link FormGroup}'s {@link AbstractControl.valueChanges} event. You can also listen to + * its {@link AbstractControl.statusChanges} event to be notified when the validation status is + * re-calculated. + * + * ### Example + * + * In this example, we create form controls for first name and last name. + * + * {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'} + * + * **npm package**: `@angular/forms` + * + * **NgModule**: {@link ReactiveFormsModule} + * + * @stable + */ +export var FormGroupDirective = (function (_super) { + __extends(FormGroupDirective, _super); + function FormGroupDirective(_validators, _asyncValidators) { + _super.call(this); + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this._submitted = false; + this.directives = []; + this.form = null; + this.ngSubmit = new EventEmitter(); + } + FormGroupDirective.prototype.ngOnChanges = function (changes) { + this._checkFormPresent(); + if (changes.hasOwnProperty('form')) { + this._updateValidators(); + this._updateDomValue(); + this._updateRegistrations(); + } + }; + Object.defineProperty(FormGroupDirective.prototype, "submitted", { + get: function () { return this._submitted; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FormGroupDirective.prototype, "formDirective", { + get: function () { return this; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FormGroupDirective.prototype, "control", { + get: function () { return this.form; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FormGroupDirective.prototype, "path", { + get: function () { return []; }, + enumerable: true, + configurable: true + }); + FormGroupDirective.prototype.addControl = function (dir) { + var ctrl = this.form.get(dir.path); + setUpControl(ctrl, dir); + ctrl.updateValueAndValidity({ emitEvent: false }); + this.directives.push(dir); + return ctrl; + }; + FormGroupDirective.prototype.getControl = function (dir) { return this.form.get(dir.path); }; + FormGroupDirective.prototype.removeControl = function (dir) { ListWrapper.remove(this.directives, dir); }; + FormGroupDirective.prototype.addFormGroup = function (dir) { + var ctrl = this.form.get(dir.path); + setUpFormContainer(ctrl, dir); + ctrl.updateValueAndValidity({ emitEvent: false }); + }; + FormGroupDirective.prototype.removeFormGroup = function (dir) { }; + FormGroupDirective.prototype.getFormGroup = function (dir) { return this.form.get(dir.path); }; + FormGroupDirective.prototype.addFormArray = function (dir) { + var ctrl = this.form.get(dir.path); + setUpFormContainer(ctrl, dir); + ctrl.updateValueAndValidity({ emitEvent: false }); + }; + FormGroupDirective.prototype.removeFormArray = function (dir) { }; + FormGroupDirective.prototype.getFormArray = function (dir) { return this.form.get(dir.path); }; + FormGroupDirective.prototype.updateModel = function (dir, value) { + var ctrl = this.form.get(dir.path); + ctrl.setValue(value); + }; + FormGroupDirective.prototype.onSubmit = function () { + this._submitted = true; + this.ngSubmit.emit(null); + return false; + }; + FormGroupDirective.prototype.onReset = function () { this.resetForm(); }; + FormGroupDirective.prototype.resetForm = function (value) { + if (value === void 0) { value = undefined; } + this.form.reset(value); + this._submitted = false; + }; + /** @internal */ + FormGroupDirective.prototype._updateDomValue = function () { + var _this = this; + this.directives.forEach(function (dir) { + var newCtrl = _this.form.get(dir.path); + if (dir._control !== newCtrl) { + cleanUpControl(dir._control, dir); + if (newCtrl) + setUpControl(newCtrl, dir); + dir._control = newCtrl; + } + }); + this.form._updateTreeValidity({ emitEvent: false }); + }; + FormGroupDirective.prototype._updateRegistrations = function () { + var _this = this; + this.form._registerOnCollectionChange(function () { return _this._updateDomValue(); }); + if (this._oldForm) + this._oldForm._registerOnCollectionChange(function () { }); + this._oldForm = this.form; + }; + FormGroupDirective.prototype._updateValidators = function () { + var sync = composeValidators(this._validators); + this.form.validator = Validators.compose([this.form.validator, sync]); + var async = composeAsyncValidators(this._asyncValidators); + this.form.asyncValidator = Validators.composeAsync([this.form.asyncValidator, async]); + }; + FormGroupDirective.prototype._checkFormPresent = function () { + if (!this.form) { + ReactiveErrors.missingFormException(); + } + }; + FormGroupDirective.decorators = [ + { type: Directive, args: [{ + selector: '[formGroup]', + providers: [formDirectiveProvider], + host: { '(submit)': 'onSubmit()', '(reset)': 'onReset()' }, + exportAs: 'ngForm' + },] }, + ]; + /** @nocollapse */ + FormGroupDirective.ctorParameters = [ + { type: Array, decorators: [{ type: Optional }, { type: Self }, { type: Inject, args: [NG_VALIDATORS,] },] }, + { type: Array, decorators: [{ type: Optional }, { type: Self }, { type: Inject, args: [NG_ASYNC_VALIDATORS,] },] }, + ]; + FormGroupDirective.propDecorators = { + 'form': [{ type: Input, args: ['formGroup',] },], + 'ngSubmit': [{ type: Output },], + }; + return FormGroupDirective; +}(ControlContainer)); +//# sourceMappingURL=form_group_directive.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011885_text-field.android.js b/pool/shard001/JavaScript/0011885_text-field.android.js new file mode 100644 index 0000000000000000000000000000000000000000..2c7ffd8e066fc54ebe43cb972460e6eefb69e511 --- /dev/null +++ b/pool/shard001/JavaScript/0011885_text-field.android.js @@ -0,0 +1,49 @@ +var common = require("./text-field-common"); +function onSecurePropertyChanged(data) { + var textField = data.object; + if (!textField.android) { + return; + } + var currentInputType = textField.android.getInputType(); + var currentClass = currentInputType & android.text.InputType.TYPE_MASK_CLASS; + var currentFlags = currentInputType & android.text.InputType.TYPE_MASK_FLAGS; + var newInputType = currentInputType; + if (data.newValue) { + if (currentClass === android.text.InputType.TYPE_CLASS_TEXT) { + newInputType = currentClass | currentFlags | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD; + } + else if (currentClass === android.text.InputType.TYPE_CLASS_NUMBER) { + newInputType = currentClass | currentFlags | android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD; + } + newInputType = newInputType & ~28672; + } + else { + if (currentClass === android.text.InputType.TYPE_CLASS_TEXT) { + newInputType = currentClass | currentFlags | android.text.InputType.TYPE_TEXT_VARIATION_NORMAL; + } + else if (currentClass === android.text.InputType.TYPE_CLASS_NUMBER) { + newInputType = currentClass | currentFlags | android.text.InputType.TYPE_NUMBER_VARIATION_NORMAL; + } + } + textField.android.setInputType(newInputType); +} +common.secureProperty.metadata.onSetNativeValue = onSecurePropertyChanged; +global.moduleMerge(common, exports); +var TextField = (function (_super) { + __extends(TextField, _super); + function TextField() { + _super.apply(this, arguments); + } + TextField.prototype._configureEditText = function () { + this.android.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_NORMAL | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); + this.android.setLines(1); + this.android.setMaxLines(1); + this.android.setHorizontallyScrolling(true); + }; + TextField.prototype._onReturnPress = function () { + this.notify({ eventName: TextField.returnPressEvent, object: this }); + }; + return TextField; +}(common.TextField)); +exports.TextField = TextField; +//# sourceMappingURL=text-field.android.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011887_routes.js b/pool/shard001/JavaScript/0011887_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..d4b6c12dc5214749f1bdf42805115cf700297239 --- /dev/null +++ b/pool/shard001/JavaScript/0011887_routes.js @@ -0,0 +1,86 @@ +App.AuthenticatedRoute = Ember.Route.extend({ + + beforeModel: function(transition) { + if (!App.get("session_token")) { + this.redirectToLogin(transition); + } + }, + + redirectToLogin: function(transition) { + var signinController = this.controllerFor('person'); + signinController.set('attemptedTransition', transition); + this.transitionTo('employees'); + }, + + actions: { + error: function(reason, transition){ + if(reason.status === 401){ + this.redirectToLogin(transition); + } + } + } +}); + +App.PersonRoute = Ember.Route.extend({ + + model: function(){ + return this.store.fetchAll('person'); + }, + + renderTemplate: function(controller) { + this.render('persons', {controller: controller}); + }, + + setupController: function(controller) { + controller.send('resetmsg'); + controller.set('employees', this._filterByRole(1)); + controller.set('managers', this._filterByRole(2)); + controller.set('managersadmins', this._filterByRole(6)); + controller.set('employeesadmins', this._filterByRole(5)); + }, + + _filterByRole: function(role){ + var self = this; + return self.store.filter('person', this._getFilterCallback(role)); + }, + + _filterByRoleHelper: function(person, role){ + return person.get('roles') === role; + //return person.isInRole(role); + }, + + _getFilterCallback: function(role) { + var self = this; + return function(person) { + return self._filterByRoleHelper(person, role); + }; + } +}); + +App.ManagersRoute = App.PersonRoute.extend({ + setupController: function(controller) { + this._super(controller); + controller.set('model', controller.managers); + } +}); + +App.ManadminsRoute = App.PersonRoute.extend({ + setupController: function(controller) { + this._super(controller); + controller.set('model', controller.managersadmins); + } +}); + +App.EmployeesRoute = App.PersonRoute.extend({ + setupController: function(controller) { + this._super(controller); + controller.set('model', controller.employees); + } +}); + +App.EmpadminsRoute = App.PersonRoute.extend({ + setupController: function(controller) { + this._super(controller); + controller.set('model', controller.employeesadmins); + } +}); diff --git a/pool/shard001/JavaScript/0011891_runScript.js b/pool/shard001/JavaScript/0011891_runScript.js new file mode 100644 index 0000000000000000000000000000000000000000..ccef13c49e4c2af50a3d385352a795f32b64919f --- /dev/null +++ b/pool/shard001/JavaScript/0011891_runScript.js @@ -0,0 +1,68 @@ +var ws = new WebSocket((useSSL ? "wss://" : "ws://") + window.location.host + "/runScriptWebSocket"); + +var username = "likedSavedBrowserClient"; + +// As soon as the websocket opens, request the initial image +ws.onopen = function(event) { + var serverStatus = document.getElementById("serverStatus"); + // Hide it if the socket is open, so it doesn't get in the way + serverStatus.innerHTML = ""; +} + +// As soon as the websocket opens, request the initial image +ws.onclose = function(event) { + var serverStatus = document.getElementById("serverStatus"); + // Hide it if the socket is open, so it doesn't get in the way + serverStatus.innerHTML = "Connection to server lost. Reload the page to attempt to reconnect."; +} + +function sendMessage(message) { + var payload = { + "command": message, + "user": username + } + + // Make the request to the WebSocket. + ws.send(JSON.stringify(payload)); +} + +ws.onmessage = function(evt) { + var messageDict = JSON.parse(evt.data); + + if (messageDict.action == "printMessage") { + document.getElementById("messages").innerText += messageDict.message + } else if (messageDict.action == "scriptFinished") { + document.getElementById("runScriptButton").style.display = "block"; + } +}; + +function onRunScriptClicked() { + document.getElementById("messages").innerText = ""; + sendMessage("runScript"); + document.getElementById("runScriptButton").style.display = "none"; +} + +function onExplicitDownloadClicked() { + document.getElementById("messages").innerText = ""; + // document.getElementById("runScriptButton").style.display = "none"; + + explicitDownloadText = document.getElementById("explicitDownloadUrls").value; + var payload = { + "command": "explicitDownloadUrls", + "urls": explicitDownloadText + } + + // Make the request to the WebSocket. + ws.send(JSON.stringify(payload)); +} + +function clearExplicitDownloadClicked() { + urls = document.getElementById("explicitDownloadUrls") + urls.value = ''; +} + +function smartClearBox() { + urls = document.getElementById("explicitDownloadUrls") + if (urls.value =="Enter URLs here") + urls.value = ''; +} diff --git a/pool/shard001/JavaScript/0011892_video_list_item.js b/pool/shard001/JavaScript/0011892_video_list_item.js new file mode 100644 index 0000000000000000000000000000000000000000..5d3ad6afd7805634bbf37909b797479bd76014c0 --- /dev/null +++ b/pool/shard001/JavaScript/0011892_video_list_item.js @@ -0,0 +1,22 @@ +import React from 'react'; + +const VideoListItem = ({video, onVideoSelect}) => { + // below replaced with es6 call of ({video}) above + // const video = props.video; + const imageUrl = video.snippet.thumbnails.default.url; + + return ( +
    • onVideoSelect(video)} className="list-group-item"> +
      +
      + +
      +
      +
      {video.snippet.title}
      +
      +
      +
    • + ); +}; + +export default VideoListItem; diff --git a/pool/shard001/JavaScript/0011894_config-actions.js b/pool/shard001/JavaScript/0011894_config-actions.js new file mode 100644 index 0000000000000000000000000000000000000000..f25dfdf1ce932a41019d5312cbcde054657c2a88 --- /dev/null +++ b/pool/shard001/JavaScript/0011894_config-actions.js @@ -0,0 +1,144 @@ +/* + * Copyright © 2015 Cask Data, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +class ConfigActionsFactory { + constructor(ConfigDispatcher, myPipelineApi, $state, ConfigStore, mySettings, ConsoleActionsFactory, HydratorErrorFactory, EventPipe, myAppsApi, GLOBALS) { + this.ConfigStore = ConfigStore; + this.mySettings = mySettings; + this.$state = $state; + this.myPipelineApi = myPipelineApi; + this.ConsoleActionsFactory = ConsoleActionsFactory; + this.HydratorErrorFactory = HydratorErrorFactory; + this.EventPipe = EventPipe; + this.myAppsApi = myAppsApi; + this.GLOBALS = GLOBALS; + + this.dispatcher = ConfigDispatcher.getDispatcher(); + } + initializeConfigStore(config) { + this.dispatcher.dispatch('onInitialize', config); + } + setMetadataInfo(name, description) { + this.dispatcher.dispatch('onMetadataInfoSave', name, description); + } + setDescription(description) { + this.dispatcher.dispatch('onDescriptionSave', description); + } + setConfig(config) { + this.dispatcher.dispatch('onConfigSave', config); + } + savePlugin(plugin, type) { + this.dispatcher.dispatch('onPluginSave', {plugin: plugin, type: type}); + } + saveAsDraft(config) { + this.dispatcher.dispatch('onSaveAsDraft', config); + } + setArtifact(artifact) { + this.dispatcher.dispatch('onArtifactSave', artifact); + } + addPlugin (plugin, type) { + this.dispatcher.dispatch('onPluginAdd', plugin, type); + } + editPlugin(pluginId, pluginProperties) { + this.dispatcher.dispatch('onPluginEdit', pluginId, pluginProperties); + } + setSchedule(schedule) { + this.dispatcher.dispatch('onSetSchedule', schedule); + } + setInstance(instance) { + this.dispatcher.dispatch('onSetInstance', instance); + } + publishPipeline() { + this.ConsoleActionsFactory.resetMessages(); + let error = this.HydratorErrorFactory.isModelValid(); + + if (!error) { return; } + this.EventPipe.emit('showLoadingIcon', 'Publishing Pipeline to CDAP'); + + let removeFromUserDrafts = (adapterName) => { + this.mySettings + .get('adapterDrafts') + .then( + (res) => { + if (angular.isObject(res)) { + delete res[adapterName]; + return this.mySettings.set('adapterDrafts', res); + } + }, + (err) => { + this.ConsoleActionsFactory.addMessage({ + type: 'error', + content: err + }); + return this.$q.reject(false); + } + ) + .then( + () => { + this.EventPipe.emit('hideLoadingIcon.immediate'); + this.$state.go('hydrator.detail', { pipelineId: adapterName }); + } + ); + }; + + let publish = (pipelineName) => { + this.myPipelineApi.save( + { + namespace: this.$state.params.namespace, + pipeline: pipelineName + }, + config + ) + .$promise + .then( + removeFromUserDrafts.bind(this, pipelineName), + (err) => { + this.EventPipe.emit('hideLoadingIcon.immediate'); + this.ConsoleActionsFactory.addMessage({ + type: 'error', + content: err + }); + } + ); + }; + + + var config = this.ConfigStore.getConfigForExport(); + + // Checking if Pipeline name already exist + this.myAppsApi + .list({ namespace: this.$state.params.namespace }) + .$promise + .then( (apps) => { + var appNames = apps.map( (app) => { return app.name; } ); + + if (appNames.indexOf(config.name) !== -1) { + this.ConsoleActionsFactory.addMessage({ + type: 'error', + content: this.GLOBALS.en.hydrator.studio.pipelineNameAlreadyExistError + }); + this.EventPipe.emit('hideLoadingIcon.immediate'); + } else { + publish(config.name); + } + }); + + } +} + +ConfigActionsFactory.$inject = ['ConfigDispatcher', 'myPipelineApi', '$state', 'ConfigStore', 'mySettings', 'ConsoleActionsFactory', 'HydratorErrorFactory', 'EventPipe', 'myAppsApi', 'GLOBALS']; +angular.module(`${PKG.name}.feature.hydrator`) + .service('ConfigActionsFactory', ConfigActionsFactory); diff --git a/pool/shard001/JavaScript/0011897_PolymerPrototypeBuilder.js b/pool/shard001/JavaScript/0011897_PolymerPrototypeBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..d5d66d27d9014197515564046e1fddf5884b576c --- /dev/null +++ b/pool/shard001/JavaScript/0011897_PolymerPrototypeBuilder.js @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +CLASS({ + name: 'PolymerPrototypeBuilder', + package: 'foam.ui.polymer.gen', + + requires: [ + 'foam.ui.polymer.gen.Component', + 'foam.ui.polymer.gen.FunctionWrapper', + 'foam.ui.polymer.gen.PolymerPrototype' + ], + + imports: [ + 'prototypeDAO as dao' + ], + + properties: [ + { + model_: 'FunctionProperty', + name: 'polymerFnImpl', + factory: function() { + return function(name, proto) { + // Follow polymer's name+proto parameter matching. + if (typeof name !== 'string') { + var script = proto || document._currentScript; + proto = name; + name = (script && + script.parentNode && + script.parentNode.getAttribute) ? + script.parentNode.getAttribute('name') : ''; + } + // Store name+proto in polymers queue for processing by + // ModelGenerator. + this.dao.put(this.PolymerPrototype.create({ + tagName: name, + proto: proto + })); + }.bind(this); + }, + hidden: true + }, + { + type: 'foam.ui.polymer.gen.FunctionWrapper', + name: 'polymerFn', + factory: function() { + var fn = this.FunctionWrapper.create({ + name: 'Polymer' + }); + fn.object[fn.name] = this.polymerFnImpl; + return fn; + }, + hidden: true + } + ] +}); diff --git a/pool/shard001/JavaScript/0011900_functions.js b/pool/shard001/JavaScript/0011900_functions.js new file mode 100644 index 0000000000000000000000000000000000000000..e5874a484e1d6a69f59fc67471959e2fa5225f9a --- /dev/null +++ b/pool/shard001/JavaScript/0011900_functions.js @@ -0,0 +1,46 @@ +function dump(arr, level) { + var dumped_text = ""; + level || (level = 0); + var level_padding = ""; + for (var j = 0; level + 1 > j; j++) level_padding += " "; + if ("object" == typeof arr) for (var item in arr) { + var value = arr[item]; + if ("object" == typeof value) { + dumped_text += level_padding + "'" + item + "' ...\n"; + dumped_text += dump(value, level + 1); + } else dumped_text += level_padding + "'" + item + "' => \"" + value + '"\n'; + } else dumped_text = "===>" + arr + "<===(" + typeof arr + ")"; + return dumped_text; +} + +function getJsonData(jsonURL) { + var xhr = Titanium.Network.createHTTPClient(); + xhr.onload = function() { + Ti.API.info("got data from the network: " + this.responseText); + var defaultData = JSON.parse(this.responseText); + return defaultData; + }; + xhr.open("GET", jsonURL); + xhr.send(); + return xhr.onload; +} + +function clearCollectionData() {} + +function updateFIXDataOfTable(tableName) { + Ti.API.info("Going to Update: " + tableName); + clearCollectionData(tableName); + var jsonURL = "?tableName=" + tableName; + var tableArray = getJsonData(jsonURL); + tableArray.forEach(function(eachRow) { + var modelElement = Alloy.createModel(tableName); + eachRow.forEach(function(eachField) { + modelElement.set({ + index: eachField + }); + }); + modelElement.save(); + }); +} + +Ti.API.info("!!functions.js LOADED"); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011901_anychart-map-data.js b/pool/shard001/JavaScript/0011901_anychart-map-data.js new file mode 100644 index 0000000000000000000000000000000000000000..68a1fda180f12f116a5cc6effd1a9790ed4cf8ba --- /dev/null +++ b/pool/shard001/JavaScript/0011901_anychart-map-data.js @@ -0,0 +1,84 @@ +/* + # + #autores + #Fatima Talavera fa.talavera95@gmail.com + #Jerson Paniagua diazpany@gmail.com + # + */ + +anychart.onDocumentReady(function() { + map = anychart.map(); + var data = {}; + $.ajax({ + method: "POST", + url: "search/map", + data: {} + }) + .done(function( msg ) { + //self.prop('disabled', false); + map_start(map,msg); + }); + $( "#item-map" ).click(function() { + //initiate map drawing + map.draw(); + }); +}); +function format_currency (number) { + return 'Gs. ' + parseFloat(number).toFixed(0).replace(/./g, function(c, i, a) { + return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c; + }); +}; +function map_start (map,data) { + // create map + // create data set + // value = pagado + var dataSet = anychart.data.set([ + {'id': 'PY.AS', 'value': data[0][6]*data[0][2]/100, 'data': data[0]}, + {'id': 'PY.AG', 'value': data[1][6]*data[1][2]/100, 'data': data[1]}, + {'id': 'PY.BQ', 'value': data[2][6]*data[2][2]/100, 'data': data[2]}, + {'id': 'PY.CN', 'value': data[3][6]*data[3][2]/100, 'data': data[3]}, + {'id': 'PY.CR', 'value': data[4][6]*data[4][2]/100, 'data': data[4]}, + {'id': 'PY.PH', 'value': data[5][6]*data[5][2]/100, 'data': data[5]}, + {'id': 'PY.SP', 'value': data[6][6]*data[6][2]/100, 'data': data[6]}, + {'id': 'PY.CE', 'value': data[7][6]*data[7][2]/100, 'data': data[7]}, + {'id': 'PY.GU', 'value': data[8][6]*data[8][2]/100, 'data': data[8]}, + {'id': 'PY.MI', 'value': data[9][6]*data[9][2]/100, 'data': data[9]}, + {'id': 'PY.NE', 'value': data[10][6]*data[10][2]/100,'data': data[10]}, + {'id': 'PY.PG', 'value': data[11][6]*data[11][2]/100,'data': data[11]}, + {'id': 'PY.AM', 'value': data[12][6]*data[12][2]/100,'data': data[12]}, + {'id': 'PY.AA', 'value': data[13][6]*data[13][2]/100,'data': data[13]}, + {'id': 'PY.CG', 'value': data[14][6]*data[14][2]/100,'data': data[14]}, + {'id': 'PY.CZ', 'value': data[15][6]*data[15][2]/100,'data': data[15]}, + {'id': 'PY.CY', 'value': data[16][6]*data[16][2]/100,'data': data[16]}, + {'id': 'PY.IT', 'value': data[17][6]*data[17][2]/100,'data': data[17]}, + ]); + + // create choropleth series + series = map.choropleth(dataSet); + + //enable the tooltips and format them at once + series.tooltip().format(function(e){ + return "Presupuesto aprobado: " + format_currency(e.getData('data')[1]) +"\n"+ + "Presupuesto vigente: " + format_currency(e.getData('data')[2]) +"\n"+ + "Monto planificado: " + format_currency(e.getData('data')[3]) +"\n"+ + "Monto ejecutado: " + format_currency(e.getData('data')[4]) +"\n"+ + "Monto transferido: " + format_currency(e.getData('data')[5]) +"\n"+ + "Monto abonado: " + format_currency(e.getData('data')[6]); + }); + + // set map color settings + series.colorScale(anychart.scales.linearColor('#c6eeef', '#1a9da3')); + series.hoverFill('#addd8e'); + + // disable series labels + series.labels(false); + + // set geo data, you can find this map in our geo maps collection + // https://cdn.anychart.com/#maps-collection + map.geoData(anychart.maps['paraguay']); + + //set map container id (div) + map.container('heat-map'); + + +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011905_ResultWidget.js b/pool/shard001/JavaScript/0011905_ResultWidget.js new file mode 100644 index 0000000000000000000000000000000000000000..5c25e2e0bf3ebe04c6a4b9ab81a56fc08ded3caa --- /dev/null +++ b/pool/shard001/JavaScript/0011905_ResultWidget.js @@ -0,0 +1,60 @@ +(function ($) { + +AjaxSolr.ResultWidget = AjaxSolr.AbstractWidget.extend({ + beforeRequest: function () { + $(this.target).html($('
      ', {class: "result_loader"})); + }, + + facetLinks: function (facet_field, facet_values) { + var links = []; + if (facet_values) { + for (var i = 0, l = facet_values.length; i < l; i++) { + links.push(AjaxSolr.theme('facet_link', facet_values[i], this.facetHandler(facet_field, facet_values[i]))); + } + } + return links; + }, + + facetHandler: function (facet_field, facet_value) { + var self = this; + return function () { + //self.manager.store.remove('fq'); + self.manager.store.addByValue('fq', facet_field + ':' + AjaxSolr.Parameter.escapeValue(facet_value)); + self.manager.doRequest(0); + return false; + }; + }, + + afterRequest: function () { + $(this.target).empty(); + for (var i = 0, l = this.manager.response.response.docs.length; i < l; i++) { + var doc = this.manager.response.response.docs[i]; + $(this.target).append(AjaxSolr.theme('result', doc, AjaxSolr.theme('snippet', doc))); + + var items = []; + items = items.concat(this.facetLinks('organisation', doc.organisation)); + + items = items.concat(this.facetLinks('ort', doc.ort)); + items = items.concat(this.facetLinks('bundesland', doc.bundesland)); + items = items.concat(this.facetLinks('land', doc.land)); + + AjaxSolr.theme('list_items', '#links_' + doc.id, items); + } + }, + + init: function () { + $('a.more').livequery(function () { + $(this).toggle(function () { + $(this).parent().find('span').show(); + $(this).text('[read less]'); + return false; + }, function () { + $(this).parent().find('span').hide(); + $(this).text('[read more]'); + return false; + }); + }); + } +}); + +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011908_test-insert-many.js b/pool/shard001/JavaScript/0011908_test-insert-many.js new file mode 100644 index 0000000000000000000000000000000000000000..aa4222732266e125d3f24365c3a39c11e160a7e1 --- /dev/null +++ b/pool/shard001/JavaScript/0011908_test-insert-many.js @@ -0,0 +1,16 @@ +var test = require('./tape') +var mongojs = require('../index') +var db = mongojs('test', ['a', 'b']) + +test('insertMany', function (t) { + db.a.insertMany([{ name: 'Squirtle' }, { name: 'Charmander' }, { name: 'Bulbasaur' }], function (err, docs) { + t.error(err) + t.ok(docs[0]._id) + t.ok(docs[1]._id) + t.ok(docs[2]._id) + + db.a.remove(function () { + db.close(t.end.bind(t)) + }) + }) +}) diff --git a/pool/shard001/JavaScript/0011912_colors.js b/pool/shard001/JavaScript/0011912_colors.js new file mode 100644 index 0000000000000000000000000000000000000000..21d929c77ab4c4aadbe70fd640c7781d30092659 --- /dev/null +++ b/pool/shard001/JavaScript/0011912_colors.js @@ -0,0 +1,10 @@ +function hexToRgb(hex) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null; +} + +export const GOOGLE_COLORS = ['#3369e8', '#d50f25', '#eeb211', '#009925', '#FFFFFF'].map(hexToRgb); diff --git a/pool/shard001/JavaScript/0011914_gulpfile.js b/pool/shard001/JavaScript/0011914_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b0ade1aa0e1d2c5b78c9450c1079a02a524fa986 --- /dev/null +++ b/pool/shard001/JavaScript/0011914_gulpfile.js @@ -0,0 +1,108 @@ +var gulp = require('gulp'), + karma = require('karma').server, + concat = require('gulp-concat'), + uglify = require('gulp-uglify'), + rename = require('gulp-rename'), + jshint = require('gulp-jshint'), + ngAnnotate = require('gulp-ng-annotate'), + sourceFiles = [ + 'src/angularStorage/angularStorage.prefix', + 'src/angularStorage/angularStorage.js', + 'src/angularStorage/directives/**/*.js', + 'src/angularStorage/filters/**/*.js', + 'src/angularStorage/services/**/*.js', + 'src/angularStorage/angularStorage.suffix' + ], + lintFiles = [ + 'src/angularStorage/**/*.js', + 'test/**/*.js', + 'gulpfile.js' + ]; + +gulp.task('lint', function() { + return gulp.src(lintFiles) + .pipe(jshint()) + .pipe(jshint.reporter('jshint-stylish')); +}); + +gulp.task('build', function() { + gulp.src(sourceFiles) + .pipe(concat('angular-storage.js')) + .pipe(ngAnnotate()) + .pipe(gulp.dest('./dist/')) + .pipe(uglify()) + .pipe(rename('angular-storage.min.js')) + .pipe(gulp.dest('./dist')); +}); + +/** + * Run test once and exit + */ +gulp.task('test', function (done) { + karma.start({ + configFile: __dirname + '/karma-src.conf.js', + singleRun: true + }, done); +}); + +/** + * Run test once in all available browsers and exit + */ +gulp.task('test-all', function (done) { + karma.start({ + configFile: __dirname + '/karma-src-all.conf.js', + singleRun: true + }, done); +}); + +gulp.task('test-debug', function (done) { + karma.start({ + configFile: __dirname + '/karma-src.conf.js', + singleRun: false, + autoWatch: true + }, done); +}); + +/** + * Run test once and exit + */ +gulp.task('test-dist-concatenated', function (done) { + karma.start({ + configFile: __dirname + '/karma-dist-concatenated.conf.js', + singleRun: true + }, done); +}); + +/** + * Run test once and exit + */ +gulp.task('test-dist-minified', function (done) { + karma.start({ + configFile: __dirname + '/karma-dist-minified.conf.js', + singleRun: true + }, done); +}); + +/** + * Run code coverage tests once and exit + */ +gulp.task('cover', function (done) { + karma.start({ + configFile: __dirname + '/karma-src.conf.js', + singleRun: true, + preprocessors: { + 'src/**/*.js': 'coverage' + }, + coverageReporter: { + type: 'html', + dir: 'reports/coverage' + }, + reporters: ['mocha', 'coverage'] + }, function() { + console.log('Code coverage report created: %s', require('path').join(process.cwd(), 'reports', 'coverage')); + done(); + }); +}); + +gulp.task('default', ['lint', 'test', 'build']); +gulp.task('dist', ['test-dist-concatenated', 'test-dist-minified']); diff --git a/pool/shard001/JavaScript/0011917_webpack.api.test.js b/pool/shard001/JavaScript/0011917_webpack.api.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a86ab844c4e32ef5130b9cc9425c99eab2ec0591 --- /dev/null +++ b/pool/shard001/JavaScript/0011917_webpack.api.test.js @@ -0,0 +1,168 @@ +const helpers = require('./helpers'); +const path = require('path'); + +/** + * Webpack Plugins + */ +const ProvidePlugin = require('webpack/lib/ProvidePlugin'); +const DefinePlugin = require('webpack/lib/DefinePlugin'); +const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); +const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'); + +/** + * Webpack Constants + */ +const ENV = process.env.ENV = process.env.NODE_ENV = 'test'; + +/** + * Webpack configuration + * + * See: http://webpack.github.io/docs/configuration.html#cli + */ +module.exports = function(options) { + return { + /** + * Source map for Karma from the help of karma-sourcemap-loader & karma-webpack + * + * Do not change, leave as is or it wont work. + * See: https://github.com/webpack/karma-webpack#source-maps + */ + devtool: 'inline-source-map', + + /** + * Options affecting the resolving of modules. + * + * See: http://webpack.github.io/docs/configuration.html#resolve + */ + resolve: { + + /** + * An array of extensions that should be used to resolve modules. + * + * See: http://webpack.github.io/docs/configuration.html#resolve-extensions + */ + extensions: ['.ts', '.js'], + + /** + * Make sure root is src + */ + modules: [ helpers.root('src'), 'node_modules' ] + + }, + + /** + * Options affecting the normal modules. + * + * See: http://webpack.github.io/docs/configuration.html#module + */ + module: { + + /** + * An array of automatically applied loaders. + * + * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to. + * This means they are not resolved relative to the configuration file. + * + * See: http://webpack.github.io/docs/configuration.html#module-loaders + */ + rules: [ + + + { + test: /\.ts$/, + use: [ + { + loader: 'awesome-typescript-loader', + options: { + configFileName: 'tsconfig.webpack.json' + } + } + ], + exclude: [/\.(spec|e2e)\.ts$/] + }, + /** + * Json loader support for *.json files. + * + * See: https://github.com/webpack/json-loader + */ + { + test: /\.json$/, + loader: 'json-loader', + exclude: [helpers.root('src/index.html')] + }, + ] + }, + + /** + * Add additional plugins to the compiler. + * + * See: http://webpack.github.io/docs/configuration.html#plugins + */ + plugins: [ + + + /** + * Plugin LoaderOptionsPlugin (experimental) + * + * See: https://gist.github.com/sokra/27b24881210b56bbaff7 + */ + new LoaderOptionsPlugin({ + debug: true, + options: { + context: __dirname, + output: { + path: helpers.root('dist/api') + }, + /** + * Static analysis linter for TypeScript advanced options configuration + * Description: An extensible linter for the TypeScript language. + * + * See: https://github.com/wbuchwalter/tslint-loader + */ + tslint: { + emitErrors: false, + failOnHint: false, + resourcePath: 'src' + }, + + } + }), + /** + * Plugin: DefinePlugin + * Description: Define free variables. + * Useful for having development builds with debug logging or adding global constants. + * + * Environment helpers + * + * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin + */ + // NOTE: when adding more properties make sure you include them in custom-typings.d.ts + new DefinePlugin({ + 'ENV': JSON.stringify(ENV), + 'process.env': { + 'ENV': JSON.stringify(ENV), + 'NODE_ENV': JSON.stringify(ENV), + 'HMR': false, + } + }), + + ], + + /** + * Include polyfills or mocks for various node stuff + * Description: Node configuration + * + * See: https://webpack.github.io/docs/configuration.html#node + */ + node: { + global: true, + process: true, + crypto: 'empty', + module: false, + clearImmediate: false, + setImmediate: false + } + + }; + +}; diff --git a/pool/shard001/JavaScript/0011920_get_person_group_training_status.js b/pool/shard001/JavaScript/0011920_get_person_group_training_status.js new file mode 100644 index 0000000000000000000000000000000000000000..d4e73d774185bdce105d4750f3f06569b20a2262 --- /dev/null +++ b/pool/shard001/JavaScript/0011920_get_person_group_training_status.js @@ -0,0 +1,35 @@ +/** + * + */ + +var constValues = require('./const/const.js') + ,request = require('request') + ,headers = { + 'Content-Type':'application/json', + 'Ocp-Apim-Subscription-Key':constValues.APIKEY +} + + + + +var options = { + url: 'https://api.projectoxford.ai/face/v1.0/persongroups/' + constValues.GROUPNAME + '/training', + method: 'GET', + headers: headers, + json:{ + "name":"sample-group", + + } + + +} + +//send request +request(options, function (error, response, body) { + if(error){ + console.log(error); + } + console.log(body); + + +})    \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011921_ConnectionHistoryEntry.js b/pool/shard001/JavaScript/0011921_ConnectionHistoryEntry.js new file mode 100644 index 0000000000000000000000000000000000000000..355f8084a347c6d2ee599a65ee97dde908276ebf --- /dev/null +++ b/pool/shard001/JavaScript/0011921_ConnectionHistoryEntry.js @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2014 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * Service which defines the ConnectionHistoryEntry class. + */ +angular.module('rest').factory('ConnectionHistoryEntry', [function defineConnectionHistoryEntry() { + + /** + * The object returned by REST API calls when representing the data + * associated with an entry in a connection's usage history. Each history + * entry represents the time at which a particular started using a + * connection and, if applicable, the time that usage stopped. + * + * @constructor + * @param {ConnectionHistoryEntry|Object} [template={}] + * The object whose properties should be copied within the new + * ConnectionHistoryEntry. + */ + var ConnectionHistoryEntry = function ConnectionHistoryEntry(template) { + + // Use empty object by default + template = template || {}; + + /** + * The identifier of the connection associated with this history entry. + * + * @type String + */ + this.connectionIdentifier = template.connectionIdentifier; + + /** + * The name of the connection associated with this history entry. + * + * @type String + */ + this.connectionName = template.connectionName; + + /** + * The time that usage began, in seconds since 1970-01-01 00:00:00 UTC. + * + * @type Number + */ + this.startDate = template.startDate; + + /** + * The time that usage ended, in seconds since 1970-01-01 00:00:00 UTC. + * The absence of an endDate does NOT necessarily indicate that the + * connection is still in use, particularly if the server was shutdown + * or restarted before the history entry could be updated. To determine + * whether a connection is still active, check the active property of + * this history entry. + * + * @type Number + */ + this.endDate = template.endDate; + + /** + * The remote host that initiated this connection, if known. + * + * @type String + */ + this.remoteHost = template.remoteHost; + + /** + * The username of the user associated with this particular usage of + * the connection. + * + * @type String + */ + this.username = template.username; + + /** + * Whether this usage of the connection is still active. Note that this + * is the only accurate way to check for connection activity; the + * absence of endDate does not necessarily imply the connection is + * active, as the history entry may simply be incomplete. + * + * @type Boolean + */ + this.active = template.active; + + }; + + /** + * All possible predicates for sorting ConnectionHistoryEntry objects using + * the REST API. By default, each predicate indicates ascending order. To + * indicate descending order, add "-" to the beginning of the predicate. + * + * @type Object. + */ + ConnectionHistoryEntry.SortPredicate = { + + /** + * The date and time that the connection associated with the history + * entry began (connected). + */ + START_DATE : 'startDate' + + }; + + /** + * Value/unit pair representing the length of time that a connection was + * used. + * + * @constructor + * @param {Number} milliseconds + * The number of milliseconds that the associated connection was used. + */ + ConnectionHistoryEntry.Duration = function Duration(milliseconds) { + + /** + * The provided duration in seconds. + * + * @type Number + */ + var seconds = milliseconds / 1000; + + /** + * Rounds the given value to the nearest tenth. + * + * @param {Number} value The value to round. + * @returns {Number} The given value, rounded to the nearest tenth. + */ + var round = function round(value) { + return Math.round(value * 10) / 10; + }; + + // Days + if (seconds >= 86400) { + this.value = round(seconds / 86400); + this.unit = 'day'; + } + + // Hours + else if (seconds >= 3600) { + this.value = round(seconds / 3600); + this.unit = 'hour'; + } + + // Minutes + else if (seconds >= 60) { + this.value = round(seconds / 60); + this.unit = 'minute'; + } + + // Seconds + else { + + /** + * The number of seconds (or minutes, or hours, etc.) that the + * connection was used. The units associated with this value are + * represented by the unit property. + * + * @type Number + */ + this.value = round(seconds); + + /** + * The units associated with the value of this duration. Valid + * units are 'second', 'minute', 'hour', and 'day'. + * + * @type String + */ + this.unit = 'second'; + + } + + }; + + return ConnectionHistoryEntry; + +}]); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011922_textarea_component.js b/pool/shard001/JavaScript/0011922_textarea_component.js new file mode 100644 index 0000000000000000000000000000000000000000..00cf4c35d8004c3a5820dfb9787b1c3e2d8f4166 --- /dev/null +++ b/pool/shard001/JavaScript/0011922_textarea_component.js @@ -0,0 +1,79 @@ +/* + |--------------------------- + | TextArea Component + |--------------------------- +*/ +Exyht.AutoExpandingTextAreaComponent = Ember.TextArea.extend({ + didInsertElement: function(){ + + Ember.run.next(function() { + // This check function check for code block matches + var isInCode = false; + function check(text) { + var match; + match = text.match(/`{3,}/g); + if (match && match.length % 2) { + isInCode = true; + } else { + match = text.match(/`/g); + if (match && match.length % 2) { + isInCode = true; + } else { + isInCode = false; + } + } + } + // Focus the text area + this.$().focus(); + + this.$().textcomplete([ + { // emoji strategy + match: /\B:([\-+\w]*)$/, + search: function (term, callback) { + callback($.map(emojies, function (emoji) { + return emoji.indexOf(term) === 0 ? emoji : null; + })); + }, + template: function (value) { + return new Ember.Handlebars.SafeString(emoji.replace_colons(':'+value.toLowerCase()+':') +' :'+ value+':'); + }, + replace: function (value) { + return ':' + value + ': '; + }, + index: 1, + context: function (text) { + check(text); + return !isInCode; + } + }, + { // words strategy + match: /\b(\w{2,})$/, + search: function (term, callback) { + callback($.map(words, function (word) { + return word.indexOf(term) === 0 ? word : null; + })); + }, + index: 1, + replace: function (word) { + return word + ' '; + }, + context: function () { return isInCode; } + } +]); + // Animate scrolltop of div with scrolltop of textarea + this.$().scroll(function() { + + var scroll = $(this).scrollTop(); + + if(scroll === 0){ + scroll = scroll; + }else{ + scroll += 5; + } + + $('div#typingCommentDiv').stop().animate({ scrollTop: scroll }, 500); + }); + + }.bind(this)); +} +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011924_PickerSample.js b/pool/shard001/JavaScript/0011924_PickerSample.js new file mode 100644 index 0000000000000000000000000000000000000000..bc4e89c417062ed1f9a62d0c3480cd975b86797d --- /dev/null +++ b/pool/shard001/JavaScript/0011924_PickerSample.js @@ -0,0 +1,102 @@ +enyo.kind({ + name: "onyx.sample.PickerSample", + kind: "FittableRows", + classes: "onyx onyx-sample", + handlers: { + onSelect: "itemSelected" + }, + components: [ + {content: "Default Picker", classes:"onyx-sample-divider"}, + {kind: "onyx.PickerDecorator", components: [ + {}, + {kind: "onyx.Picker", components: [ + {content: "Gmail", active: true}, + {content: "Yahoo"}, + {content: "Outlook"}, + {content: "Hotmail"} + ]} + ]}, + {tag: "br"}, + {content: "Picker with Static Button", classes:"onyx-sample-divider"}, + {kind: "onyx.PickerDecorator", components: [ + {kind: "onyx.Button", content: "Pick One...", style: "width: 200px"}, + {kind: "onyx.Picker", components: [ + {content: "Hello!"}, + {content: "I am busy."}, + {content: "Good Bye."} + ]} + ]}, + {tag: "br"}, + {content: "Other Pickers", classes:"onyx-sample-divider"}, + {classes: "onyx-toolbar-inline", components: [ + {content: "Integer", classes: "onyx-sample-label"}, + {kind: "onyx.PickerDecorator", components: [ + {style: "min-width: 60px;"}, + {name: "integerPicker", kind: "onyx.Picker"} + ]} + ]}, + {tag: "br"}, + {classes: "onyx-toolbar-inline", components: [ + {content: "Date", classes: "onyx-sample-label"}, + {kind: "onyx.PickerDecorator", components: [ + {}, + {name: "monthPicker", kind: "onyx.Picker"} + ]}, + {kind: "onyx.PickerDecorator", components: [ + {style: "min-width: 60px;"}, + {name: "dayPicker", kind: "onyx.Picker"} + ]}, + {content: "Year", classes: "onyx-sample-label"}, + {kind: "onyx.PickerDecorator", components: [ + {style: "min-width: 80px;"}, + {name: "yearPicker", kind: "onyx.FlyweightPicker", count: 200, onSetupItem: "setupYear", components: [ + {name: "year"} + ]} + ]} + ]}, + {tag: "br"}, + {classes: "onyx-toolbar-inline", components: [ + {kind: "onyx.PickerDecorator", components: [ + {}, + {kind: "onyx.Picker", components: [ + {content: "Gmail"}, + {content: "Yahoo"}, + {content: "Outlook"}, + {content: "Hotmail", active: true} + ]} + ]}, + ]}, + {tag: "br"}, + {kind: "onyx.Groupbox", classes:"onyx-sample-result-box", components: [ + {kind: "onyx.GroupboxHeader", content: "Selection"}, + {name:"pickerSelection", classes:"onyx-sample-result", content: "Nothing picked yet."} + ]} + ], + create: function() { + this.inherited(arguments); + // integer + for (var i=0; i<10; i++) { + this.$.integerPicker.createComponent({content: i, active: !i}); + } + // month + var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; + var d = new Date(); + for (var i=0,m; m=months[i]; i++) { + this.$.monthPicker.createComponent({content: m, active: i==d.getMonth()}); + } + // day + for (var i=0; i<30; i++) { + this.$.dayPicker.createComponent({content: i+1, active: i==d.getDate()-1}); + } + // year + var y = d.getYear(); + this.$.yearPicker.setSelected(y); + this.$.year.setContent(1900+y); + }, + setupYear: function(inSender, inEvent) { + this.$.year.setContent(1900+inEvent.index); + }, + itemSelected: function(inSender, inEvent) { + this.$.pickerSelection.setContent(inEvent.selected.content); + } +}); diff --git a/pool/shard001/JavaScript/0011927_try_catch.js b/pool/shard001/JavaScript/0011927_try_catch.js new file mode 100644 index 0000000000000000000000000000000000000000..57f81f2a0074a7b3cb89a88515813864ad2df527 --- /dev/null +++ b/pool/shard001/JavaScript/0011927_try_catch.js @@ -0,0 +1,175 @@ +// Copyright 2020 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Try catch wrapper. + */ + +const babelTypes = require('@babel/types'); + +const common = require('./common.js'); +const mutator = require('./mutator.js'); +const random = require('../random.js'); + +// Default target probability for skipping try-catch completely. +const DEFAULT_SKIP_PROB = 0.2; + +// Default target probability to wrap only on toplevel, i.e. to not nest +// try-catch. +const DEFAULT_TOPLEVEL_PROB = 0.3; + +// Probability to deviate from defaults and use extreme cases. +const IGNORE_DEFAULT_PROB = 0.05; + +// Member expressions to be wrapped. List of (object, property) identifier +// tuples. +const WRAPPED_MEMBER_EXPRESSIONS = [ + ['WebAssembly', 'Module'], + ['WebAssembly', 'Instantiate'], +]; + +function wrapTryCatch(node) { + return babelTypes.tryStatement( + babelTypes.blockStatement([node]), + babelTypes.catchClause( + babelTypes.identifier('e'), + babelTypes.blockStatement([]))); +} + +function wrapTryCatchInFunction(node) { + const ret = wrapTryCatch(babelTypes.returnStatement(node)); + const anonymousFun = babelTypes.functionExpression( + null, [], babelTypes.blockStatement([ret])); + return babelTypes.callExpression(anonymousFun, []); +} + +// Wrap particular member expressions after `new` that are known to appear +// in initializer lists of `let` and `const`. +function replaceNewExpression(path) { + const callee = path.node.callee; + if (!babelTypes.isMemberExpression(callee) || + !babelTypes.isIdentifier(callee.object) || + !babelTypes.isIdentifier(callee.property)) { + return; + } + if (WRAPPED_MEMBER_EXPRESSIONS.some( + ([object, property]) => callee.object.name === object && + callee.property.name === property)) { + path.replaceWith(wrapTryCatchInFunction(path.node)); + path.skip(); + } +} + +function replaceAndSkip(path) { + if (!babelTypes.isLabeledStatement(path.parent) || + !babelTypes.isLoop(path.node)) { + // Don't wrap loops with labels as it makes continue + // statements syntactically invalid. We wrap the label + // instead below. + path.replaceWith(wrapTryCatch(path.node)); + } + // Prevent infinite looping. + path.skip(); +} + +class AddTryCatchMutator extends mutator.Mutator { + callWithProb(path, fun) { + const probability = random.random(); + if (probability < this.skipProb * this.loc) { + // Entirely skip try-catch wrapper. + path.skip(); + } else if (probability < (this.skipProb + this.toplevelProb) * this.loc) { + // Only wrap on top-level. + fun(path); + } + } + + get visitor() { + const thisMutator = this; + const accessStatement = { + enter(path) { + thisMutator.callWithProb(path, replaceAndSkip); + }, + exit(path) { + // Apply nested wrapping (is only executed if not skipped above). + replaceAndSkip(path); + } + }; + return { + Program: { + enter(path) { + // Track original source location fraction in [0, 1). + thisMutator.loc = 0; + // Target probability for skipping try-catch. + thisMutator.skipProb = DEFAULT_SKIP_PROB; + // Target probability for not nesting try-catch. + thisMutator.toplevelProb = DEFAULT_TOPLEVEL_PROB; + // Maybe deviate from target probability for the entire test. + if (random.choose(IGNORE_DEFAULT_PROB)) { + thisMutator.skipProb = random.uniform(0, 1); + thisMutator.toplevelProb = random.uniform(0, 1); + thisMutator.annotate( + path.node, + 'Target skip probability ' + thisMutator.skipProb + + ' and toplevel probability ' + thisMutator.toplevelProb); + } + } + }, + Noop: { + enter(path) { + if (common.getSourceLoc(path.node)) { + thisMutator.loc = common.getSourceLoc(path.node); + } + }, + }, + ExpressionStatement: accessStatement, + IfStatement: accessStatement, + LabeledStatement: { + enter(path) { + // Apply an extra try-catch around the label of a loop, since we + // ignore the loop itself if it has a label. + if (babelTypes.isLoop(path.node.body)) { + thisMutator.callWithProb(path, replaceAndSkip); + } + }, + exit(path) { + // Apply nested wrapping (is only executed if not skipped above). + if (babelTypes.isLoop(path.node.body)) { + replaceAndSkip(path); + } + }, + }, + // This covers {While|DoWhile|ForIn|ForOf|For}Statement. + Loop: accessStatement, + NewExpression: { + enter(path) { + thisMutator.callWithProb(path, replaceNewExpression); + }, + exit(path) { + // Apply nested wrapping (is only executed if not skipped above). + replaceNewExpression(path); + } + }, + SwitchStatement: accessStatement, + VariableDeclaration: { + enter(path) { + if (path.node.kind !== 'var' || babelTypes.isLoop(path.parent)) + return; + thisMutator.callWithProb(path, replaceAndSkip); + }, + exit(path) { + if (path.node.kind !== 'var' || babelTypes.isLoop(path.parent)) + return; + // Apply nested wrapping (is only executed if not skipped above). + replaceAndSkip(path); + } + }, + WithStatement: accessStatement, + }; + } +} + +module.exports = { + AddTryCatchMutator: AddTryCatchMutator, +} diff --git a/pool/shard001/JavaScript/0011931_editor_plugin_src.js b/pool/shard001/JavaScript/0011931_editor_plugin_src.js new file mode 100644 index 0000000000000000000000000000000000000000..2062b8dcd87c3b7a615ed973952ed7e4569264d8 --- /dev/null +++ b/pool/shard001/JavaScript/0011931_editor_plugin_src.js @@ -0,0 +1,173 @@ +/** + * $Id: editor_plugin_src.js,v 1.1 2014/09/02 15:27:51 leire Exp $ + * + * @author Moxiecode + * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved. + */ + +tinyMCE.importPluginLanguagePack('searchreplace'); + +var TinyMCE_SearchReplacePlugin = { + getInfo : function() { + return { + longname : 'Search/Replace', + author : 'Moxiecode Systems AB', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace', + version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion + }; + }, + + initInstance : function (inst) { + inst.addShortcut('ctrl', 'f', 'lang_searchreplace_search_desc', 'mceSearch', true); + // No CTRL+R for "replace" because browsers will reload page instead of executing plugin + }, + + getControlHTML : function (cn) { + switch (cn) { + case "search" : + return tinyMCE.getButtonHTML(cn, 'lang_searchreplace_search_desc', '{$pluginurl}/images/search.gif','mceSearch', true); + + case "replace" : + return tinyMCE.getButtonHTML(cn, 'lang_searchreplace_replace_desc', '{$pluginurl}/images/replace.gif', 'mceSearchReplace', true); + } + + return ""; + }, + + execCommand : function (editor_id, element, command, user_interface, value) { + var inst = tinyMCE.getInstanceById(editor_id), selectedText = inst.selection.getSelectedText(), rng; + + function defValue(key, default_value) { + value[key] = typeof(value[key]) == "undefined" ? default_value : value[key]; + } + + function replaceSel(search_str, str, back) { + if (!inst.selection.isCollapsed()) { + if (tinyMCE.isRealIE) + inst.selection.getRng().duplicate().pasteHTML(str); // Needs to be duplicated due to selection bug in IE + else + inst.execCommand('mceInsertContent', false, str); + } + } + + if (!value) + value = []; + + defValue("editor_id", editor_id); + defValue("searchstring", selectedText); + defValue("replacestring", null); + defValue("replacemode", "none"); + defValue("casesensitive", false); + defValue("backwards", false); + defValue("wrap", false); + defValue("wholeword", false); + defValue("inline", "yes"); + defValue("resizable", "no"); + + switch (command) { + case "mceSearch" : + if (user_interface) { + var template = new Array(); + + template['file'] = '../../plugins/searchreplace/searchreplace.htm'; + template['width'] = 380; + template['height'] = 155 + (tinyMCE.isNS7 ? 20 : 0) + (tinyMCE.isMSIE ? 15 : 0); + template['width'] += tinyMCE.getLang('lang_searchreplace_delta_width', 0); + template['height'] += tinyMCE.getLang('lang_searchreplace_delta_height', 0); + + inst.selection.collapse(true); + + tinyMCE.openWindow(template, value); + } else { + var win = tinyMCE.getInstanceById(editor_id).contentWindow; + var doc = tinyMCE.getInstanceById(editor_id).contentWindow.document; + var body = tinyMCE.getInstanceById(editor_id).contentWindow.document.body; + var awin = value.win, found; + + if (body.innerHTML == "") { + awin.alert(tinyMCE.getLang('lang_searchreplace_notfound')); + return true; + } + + if (value['replacemode'] == "current") { + replaceSel(value['string'], value['replacestring'], value['backwards']); + value['replacemode'] = "none"; + //tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value); + //return true; + } + + inst.selection.collapse(value['backwards']); + + if (tinyMCE.isMSIE) { + var rng = inst.selection.getRng(); + var flags = 0; + if (value['wholeword']) + flags = flags | 2; + + if (value['casesensitive']) + flags = flags | 4; + + if (!rng.findText) { + awin.alert('This operation is currently not supported by this browser.'); + return true; + } + + if (value['replacemode'] == "all") { + found = false; + + while (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) { + found = true; + rng.scrollIntoView(); + rng.select(); + replaceSel(value['string'], value['replacestring'], value['backwards']); + } + + if (found) + awin.alert(tinyMCE.getLang('lang_searchreplace_allreplaced')); + else + awin.alert(tinyMCE.getLang('lang_searchreplace_notfound')); + + return true; + } + + if (rng.findText(value['string'], value['backwards'] ? -1 : 1, flags)) { + rng.scrollIntoView(); + rng.select(); + } else + awin.alert(tinyMCE.getLang('lang_searchreplace_notfound')); + } else { + if (value['replacemode'] == "all") { + found = false; + + while (win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false)) { + found = true; + replaceSel(value['string'], value['replacestring'], value['backwards']); + } + + if (found) + awin.alert(tinyMCE.getLang('lang_searchreplace_allreplaced')); + else + awin.alert(tinyMCE.getLang('lang_searchreplace_notfound')); + + return true; + } + + if (!win.find(value['string'], value['casesensitive'], value['backwards'], value['wrap'], value['wholeword'], false, false)) + awin.alert(tinyMCE.getLang('lang_searchreplace_notfound')); + } + } + + return true; + + case "mceSearchReplace" : + value['replacestring'] = ""; + tinyMCE.execInstanceCommand(editor_id, 'mceSearch', user_interface, value, false); + return true; + } + + return false; + } +}; + +tinyMCE.addPlugin("searchreplace", TinyMCE_SearchReplacePlugin); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011939_directorypicker.client.directive.js b/pool/shard001/JavaScript/0011939_directorypicker.client.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..bc5ff58b05046c8673de41971878e04a99896975 --- /dev/null +++ b/pool/shard001/JavaScript/0011939_directorypicker.client.directive.js @@ -0,0 +1,51 @@ +'use strict'; + +angular.module('folders').directive('directoryPicker', ['$compile', '$timeout', + function ($compile, $timeout) { + return { + restrict : 'E', + replace : true, + require : '?ngModel', + templateUrl : 'modules/folders/templates/directorypicker.client.template.html', + link : function (scope, element, attrs, controller) { + if (typeof process === 'object') { // node context + var span = element.find('span'), + button = element.find('button'); + + var setPath = function (val) { + span.text(val || attrs.placeholder); + if (val) { + controller.$setViewValue(val); + // http://stackoverflow.com/a/17958847/218882 + $timeout(function () { + // to update the model into the scope - http://stackoverflow.com/a/18264323/218882 + scope.$apply(); + }); + } + }; + + scope.$watch(attrs.ngModel, function (newVal) { + setPath(newVal); + }, true); + + button.on('click', function () { + var ipc = require('ipc'); + ipc.on('directory-picker-closed', function(selectedDirectory){ + setPath(selectedDirectory); + }); + ipc.send('open-directory-picker', { + title: 'Select folder to add to the library', + defaultPath: controller.$viewValue || '' + }); + }); + } else { // web app + // FIXME: This below else is only for trying out the app from without the electronjs container + var html = ''; + var e = $compile(html)(scope); + element.replaceWith(e); + } + } + }; + } +]); diff --git a/pool/shard001/JavaScript/0011943_assetslib.js b/pool/shard001/JavaScript/0011943_assetslib.js new file mode 100644 index 0000000000000000000000000000000000000000..fd740e522e62cf9700e82b0a1202a5fd4683caff --- /dev/null +++ b/pool/shard001/JavaScript/0011943_assetslib.js @@ -0,0 +1,16 @@ +var assetslib = { + + getAllPhotos:function(successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AssetsLib", "getAllPhotos", []); + }, + + getPhotoMetadata:function(urlList, successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AssetsLib", "getPhotoMetadata", [urlList]); + }, + + getThumbnails:function(urlList, successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AssetsLib", "getThumbnails", [urlList]); + } +} + +module.exports = assetslib; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011944_common.js b/pool/shard001/JavaScript/0011944_common.js new file mode 100644 index 0000000000000000000000000000000000000000..e11a92bb58750ffcc0984ba8c21116e5bd06eb53 --- /dev/null +++ b/pool/shard001/JavaScript/0011944_common.js @@ -0,0 +1,72 @@ +function showPopover(width, height, node) { + var popover = document.createElement('div'); + document.body.appendChild(popover); + popover.style.position = 'absolute'; + popover.style.zIndex = 99999; + popover.style.top = 0; + popover.style.left = 0; + popover.style.width = width; + popover.style.height = height; + + var paddingDiv = document.createElement('div'); + popover.appendChild(paddingDiv); + + paddingDiv.style.paddingTop = '20px'; + paddingDiv.style.paddingLeft = '20px'; + paddingDiv.style.paddingRight = '40px'; + paddingDiv.style.paddingBottom = '20px'; + + var bg = document.createElement('div'); + paddingDiv.appendChild(bg); + + bg.style.color = '#fff'; + bg.style.background = '#000'; + bg.style.opacity = 0.8; + bg.style.width = '100%'; + bg.style.height = '100%'; + bg.style.padding = '10px'; + bg.style.border = '0 none'; + bg.style.borderRadius = '6px'; + bg.style.boxShadow = '0 0 8px rgba(0,0,0,.8)'; + + bg.appendChild(node); + + popover.onclick = function(e) { e.stopPropagation(); } + document.body.onclick = function() { popover.parentNode.removeChild(popover); } +} + +function getFormsJson() { + var address = document.URL; + var name = document.title; + var text = ""; + + for (var i = 0; i < document.forms.length; i++) { + var form = document.forms[i]; + + var form_elements = ""; + for (var j = 0; j < form.elements.length; j++) { + var el = form.elements[j]; + + if (el.name == "") + continue; + + if (form_elements == "") + form_elements = '\t\t\t"' + el.name + '": "' + el.value + '"'; + else + form_elements += ',\n\t\t\t"' + el.name + '": "' + el.value + '"'; + } + + var form_text = '\t\t"action": "' + form.action + '",\n\t\t"method": "' + form.method + '",\n\t\t"fields":\n\t\t{\n' + form_elements + '\n\t\t}'; + + if (text == "") + text += '[\n'; + else + text += ',\n'; + text += '{\n\t"type":"login",\n\t"name": "' + name + '",\n\t"address": "' + address + '",\n\t"form":\n\t{\n' + form_text + '\n\t}\n}\n'; + } + + if (text) + text += "]"; + + return text; +} diff --git a/pool/shard001/JavaScript/0011945_RactiveEvent.js b/pool/shard001/JavaScript/0011945_RactiveEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..636515300d54fa8cea3b8f087afcc81f587ed5ef --- /dev/null +++ b/pool/shard001/JavaScript/0011945_RactiveEvent.js @@ -0,0 +1,32 @@ +export default class RactiveEvent { + + constructor ( ractive, name ) { + this.ractive = ractive; + this.name = name; + this.handler = null; + } + + listen ( directive ) { + const ractive = this.ractive; + + this.handler = ractive.on( this.name, function () { + let event; + + // semi-weak test, but what else? tag the event obj ._isEvent ? + if ( arguments.length && arguments[0] && arguments[0].node ) { + event = Array.prototype.shift.call( arguments ); + event.component = ractive; + } + + const args = Array.prototype.slice.call( arguments ); + directive.fire( event, args ); + + // cancel bubbling + return false; + }); + } + + unlisten () { + this.handler.cancel(); + } +} diff --git a/pool/shard001/JavaScript/0011949_index.js b/pool/shard001/JavaScript/0011949_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b46c573f60675d0bcc86a2cbdfe978fa4764230d --- /dev/null +++ b/pool/shard001/JavaScript/0011949_index.js @@ -0,0 +1,82 @@ +/** +send mail based kue example + +make sure started redis-server on localhost:6379 + +and then +``` +cd examples/kuemailer +node index.js +``` + +open new terminal +``` +$ curl -H "Content-Type: application/json" -X POST -d \ + '{ + "type": "postbox", + "data": { + "title": "Mangia gli spaghetti con polpette!", + "to": "mamma.mia@spaghetti.com", + "template": "newsletter", + "params": { + "name": { + "first": "Mamma", + "last": "Mia" + } + } + }, + "options" : { + "attempts": 5, + "priority": "high" + } + }' http://localhost:3000/job + +``` + +PS: mail is not really send, because SMTP config is wrong. + +*/ +var path = require('path') +var templatesDir = path.resolve(__dirname, '..', 'templates') +var EmailTemplate = require('../../').EmailTemplate +var nodemailer = require('nodemailer') +var kue = require('kue') +var EventEmitter = require('events').EventEmitter + +var deliver = new EventEmitter() +var jobs = kue.createQueue() +kue.app.listen(3000) + +jobs.process('postbox', function (job, done) { + deliver.emit(job.data.template, job.data, done) +}) + +var template = new EmailTemplate(path.join(templatesDir, 'newsletter')) +var transport = nodemailer.createTransport({ + service: 'Gmail', + auth: { + user: 'some-user@gmail.com', + pass: 'some-password' + } +}) + +deliver.on('newsletter', function (data, done) { + template.render(data.params, function (err, results) { + if (err) return done(err) + + transport.sendMail({ + from: 'Spicy Meatball ', + to: data.to, + subject: data.title, + html: results.html, + text: results.text + }, function (err, responseStatus) { + if (err) { + console.error(err) + return done(err) + } + console.log(responseStatus.message) + done() + }) + }) +}) diff --git a/pool/shard001/JavaScript/0011952_CSSKeyframeRule.js b/pool/shard001/JavaScript/0011952_CSSKeyframeRule.js new file mode 100644 index 0000000000000000000000000000000000000000..c1f174fb4f8443debd88bd9cb30941925372094d --- /dev/null +++ b/pool/shard001/JavaScript/0011952_CSSKeyframeRule.js @@ -0,0 +1,18 @@ +/* */ +var CSSOM = { + CSSRule: require('./CSSRule').CSSRule, + CSSStyleDeclaration: require('./CSSStyleDeclaration').CSSStyleDeclaration +}; +CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { + CSSOM.CSSRule.call(this); + this.keyText = ''; + this.style = new CSSOM.CSSStyleDeclaration(); + this.style.parentRule = this; +}; +CSSOM.CSSKeyframeRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; +CSSOM.CSSKeyframeRule.prototype.type = 9; +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", {get: function() { + return this.keyText + " {" + this.style.cssText + "} "; + }}); +exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; diff --git a/pool/shard001/JavaScript/0011954_users.js b/pool/shard001/JavaScript/0011954_users.js new file mode 100644 index 0000000000000000000000000000000000000000..bbc00c99064e205461427bf6b03f23e5244ff836 --- /dev/null +++ b/pool/shard001/JavaScript/0011954_users.js @@ -0,0 +1,286 @@ +/** + * Created by beuttlerma on 05.07.17. + */ + +const express = require('express'); +const router = express.Router(); +const marketplaceCore = require('../adapter/marketplace_core_adapter'); +const authService = require('../adapter/auth_service_adapter'); +const logger = require('../global/logger'); +const helper = require('../services/helper_service'); +const encryption = require('../services/encryption_service'); +const recipeLimitService = require('../services/recipe_limit_service'); +const imageService = require('../services/image_service'); +const authenticationService = require('../services/authentication_service'); + +const CONFIG = require('../config/config_loader'); + +const {Validator, ValidationError} = require('express-json-validator-middleware'); +const validator = new Validator({allErrors: true}); +const validate = validator.validate; +const validation_schema = require('../schema/users_schema'); +const validation_schema_recipe = require('../schema/recipe_schema'); + +// router.use('/:id', authenticationService.paramIsEqualToSessionUser('id')); + +/** + * Retrieves the user information for the logged in user + */ +router.get('/me', validate({ + query: validation_schema.Empty, + body: validation_schema.Empty +}), function (req, res, next) { + + authService.getUserInfoForToken(req.user.token.accessToken, function (err, data) { + if (err) { + return next(err); + } + + res.json(data); + }); + +}); + +router.all('/me/*', function (req, res, next) { + + const redirectPath = req.originalUrl.replace('/me/', '/' + req.user.token.user + '/'); + + res.redirect(307, redirectPath); +}); + +router.get('/', validate({ + query: validation_schema.Users_Query, + body: validation_schema.Empty +}), function (req, res, next) { + + logger.warn('[routes/recipes] NOT IMPLEMENTED YET'); + res.send('NOT IMPLEMENTED YET'); +}); + +/** + * Retrieves the user information for a specific user + */ +router.get('/:id', authenticationService.paramIsEqualToSessionUser('id'), validate({ + query: validation_schema.Empty, + body: validation_schema.Empty +}), function (req, res, next) { + + logger.warn('[routes/recipes] NOT IMPLEMENTED YET'); + res.send('NOT IMPLEMENTED YET'); +}); + + +/** + * Returns the limit of recipes the user can publish on the marketplace + */ +router.get('/:id/recipes/limit', authenticationService.paramIsEqualToSessionUser('id'), validate({ + query: validation_schema.Empty, + body: validation_schema.Empty +}), function (req, res, next) { + marketplaceCore.getActivatedLicenseCountForUser(req.params['id'], req.user.token.accessToken, function (err, activatedLicenses) { + if (err) { + return next(err); + } + + return res.json({limit: recipeLimitService.calculateRecipeLimit(activatedLicenses)}); + + }); +}); +/** + * Returns the amount of recipes the user already published on the marketplace + */ +router.get('/:id/recipes/count', authenticationService.paramIsEqualToSessionUser('id'), validate({ + query: validation_schema.Empty, + body: validation_schema.Empty +}), function (req, res, next) { + const language = req.cookies.language; + marketplaceCore.getRecipesForUser(language, req.params['id'], req.user.token.accessToken, function (err, recipes) { + if (err) { + return next(err); + } + return res.json({count: recipes.length}); + }); +}); +/** + * Saves a recipe for a specific user + */ +router.post('/:id/recipes', authenticationService.paramIsEqualToSessionUser('id'), validate({ + query: validation_schema.Empty, + body: validation_schema_recipe.Recipe_Body +}), function (req, res, next) { + // Check if user can still publish recipes or if his limit is reached. + const language = req.cookies.language; + marketplaceCore.getRecipesForUser(language, req.params['id'], req.user.token.accessToken, function (err, recipes) { + if (err) { + return next(err); + } + marketplaceCore.getActivatedLicenseCountForUser(req.params['id'], req.user.token.accessToken, function (err, activatedLicenses) { + if (err) { + return next(err); + } + + const limit = recipeLimitService.calculateRecipeLimit(activatedLicenses); + + if (recipes.length >= limit) { + logger.info('Recipe limit reached. Only a maximum of ' + limit + ' recipes is allowed per user.'); + res.status(400); + return res.send('Sie haben bereits ihr Limit von ' + limit + ' Rezepten am Marktplatz erreicht.'); + } + + // Save recipe for user + const recipe = req.body; + + // recipe information for further processing + const name = recipe['name'].trim(); + const description = recipe['description'].trim(); + const licenseFee = recipe['licenseFee']; + + // check metadata + let valid = true; + let validText; + if (!name || name.length < 1) { + logger.warn('Submitted recipe: Name is missing'); + validText = 'Name fehlt.'; + valid = false; + } + if (!description || description.length < 1) { + logger.warn('Submitted recipe: Description is missing'); + validText = 'Beschreibung fehlt.'; + valid = false; + } + if (!licenseFee) { + logger.warn('Submitted recipe: License Fee is missing'); + validText = 'Lizenzgebühr fehlt.'; + valid = false; + } + + if (!valid) { + logger.warn('Submitted recipe: Invalid metadata'); + res.status(400); + return res.send('Ungültige Metadaten: ' + validText); + } + + // check total amount + let totalAmount = 0; + let totalPause = 0; + const minTotalAmount = 90; + const maxTotalAmount = 130; + const maxTotalPause = 5001; + + const machineProgram = recipe['program']; + const lines = machineProgram['recipe']['lines']; + var ingredients = {}; + lines.forEach(function (line) { + const components = line['components']; + totalPause += line['sleep']; + components.forEach(function (component) { + totalAmount += component['amount']; + if (component['ingredient']) { + ingredients[component['ingredient']] = ingredients[component['ingredient']] + 1; + } else { + ingredients[component['ingredient']] = 1; + } + }); + }); + + const componentIds = Object.keys(ingredients); + + if (totalAmount > maxTotalAmount) { + logger.warn('Submitted program exceeding max total amount size'); + validText = 'Maximal-Menge (' + maxTotalAmount + ') überschritten'; + valid = false; + } + + if (totalAmount < minTotalAmount) { + logger.warn('Submitted program is less than min total amount'); + validText = 'Minimal-Menge (' + minTotalAmount + ') unterschritten'; + valid = false; + } + + if (totalPause > maxTotalPause) { + logger.warn('Submitted program exceeding max total pause size'); + validText = 'Maximale Pausenlänge (' + maxTotalPause + ') überschritten'; + valid = false; + } + + if (!valid) { + logger.warn('Submitted program not valid.'); + res.status(400); + return res.send('Ungültiges Rezept: ' + validText); + } + + let encryptedProgram; + // Encrypt the recipe using our own encryption before passing it to the marketplace core + try { + const machineProgramString = JSON.stringify(machineProgram); + encryptedProgram = encryption.encryptData(machineProgramString); + } + catch (err) { + return res.sendStatus(500); + } + + const coreData = {}; + + coreData.technologyDataName = name; + coreData.technologyData = encryptedProgram; + coreData.technologyDataDescription = description; + coreData.technologyUUID = CONFIG.TECHNOLOGY_UUID; + coreData.licenseFee = licenseFee; + coreData.componentList = componentIds; + coreData.backgroundColor = recipe.backgroundColor; + coreData.image = recipe.imageRef ? imageService.loadImage(recipe.imageRef + '.svg'): undefined; + + marketplaceCore.saveRecipeForUser(req.user.token, coreData, function (err, recipeId) { + if (err && err.statusCode === 409) { + res.status(409); + return res.send('Ein Rezept mit diesem Namen existiert bereits.') + } + + if (err) { + return next(err); + } + + const fullUrl = helper.buildFullUrlFromRequest(req); + res.set('Location', fullUrl + 'recipes/' + recipeId); + res.sendStatus(201); + }); + + }); + }); +}); + +/** + * Retrieves the user image + */ +router.get('/:user_id/image', authenticationService.paramIsEqualToSessionUser('user_id'), validate({ + query: validation_schema.Empty, + body: validation_schema.Empty +}), function (req, res, next) { + authService.getImageForUser(req.params['user_id'], req.user.token, function (err, data) { + if (err) { + next(err); + return; + } + + if (!data) { + res.sendStatus(404); + return; + } + + res.set('Content-Type', data.contentType); + res.send(data.imageBuffer); + }); +}); +router.put('/:user_id/image', authenticationService.paramIsEqualToSessionUser('user_id'), validate({ + query: validation_schema.Empty +}), function (req, res, next) { + logger.warn('[routes/recipes] NOT IMPLEMENTED YET'); + res.send('NOT IMPLEMENTED YET'); +}); + + +router.use('/:user_id/recipes', authenticationService.paramIsEqualToSessionUser('user_id'), require('./recipes')); +router.use('/:id/reports', authenticationService.paramIsEqualToSessionUser('id'), require('./user_reports')); +router.use('/:id/vault', authenticationService.paramIsEqualToSessionUser('id'), require('./vault')); + +module.exports = router; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011956_admin-item.spec.js b/pool/shard001/JavaScript/0011956_admin-item.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e26ecdab7dac2e4142a8fd79437c98b53a3ad48a --- /dev/null +++ b/pool/shard001/JavaScript/0011956_admin-item.spec.js @@ -0,0 +1,44 @@ +import mq from 'mithril-query'; +import m from 'mithril'; +import adminItem from '../../src/c/admin-item'; + +describe('AdminItem', () => { + let item, $output, ListItemMock, ListDetailMock; + + beforeAll(() => { + ListItemMock = { + view: (ctrl, args) => { + return m('.list-item-mock'); + } + }; + ListDetailMock = { + view: (ctrl, args) => { + return m('.list-detail-mock'); + } + }; + }); + + describe('view', () => { + beforeEach(() => { + $output = mq(adminItem, { + listItem: ListItemMock, + listDetail: ListDetailMock, + item: item + }); + }); + + it('should render list item', () => { + $output.should.have('.list-item-mock'); + }); + + it('should render list detail when toggle details is true', () => { + $output.click('button'); + $output.should.have('.list-detail-mock'); + }); + + it('should not render list detail when toggle details is false', () => { + $output.should.not.have('.list-detail-mock'); + }); + }); + +}); diff --git a/pool/shard001/JavaScript/0011958_transform.js b/pool/shard001/JavaScript/0011958_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..244c1af632d4971f14bfb4c30526046e811c31dd --- /dev/null +++ b/pool/shard001/JavaScript/0011958_transform.js @@ -0,0 +1,61 @@ +/** + * @author Titus Wormer + * @copyright 2015 Titus Wormer + * @license MIT + * @module mdast:cli:file-pipeline:transform + * @version 2.3.2 + * @fileoverview Transform an AST associated with a file. + */ + +'use strict'; + +/* eslint-env node */ + +/* + * Dependencies. + */ + +var debug = require('debug')('mdast:cli:file-pipeline:transform'); + +/** + * Transform the `ast` associated with a file with + * configured plug-ins. + * + * @example + * var file = new File(); + * + * file.namespace('mdast').tree = { + * 'type': 'paragraph', + * 'children': [{ + * 'type': 'text', + * 'value': 'Foo.' + * }] + * }; + * + * transform({'file': file}, console.log); + * + * @param {Object} context + * @param {function(Error?)} done + */ +function transform(context, done) { + var file = context.file; + + if (file.hasFailed()) { + done(); + return; + } + + debug('Transforming document', file.filePath()); + + context.processor.run(file.namespace('mdast').tree, file, function (err) { + debug('Transformed document (error: %s)', err); + + done(err); + }); +} + +/* + * Expose. + */ + +module.exports = transform; diff --git a/pool/shard001/JavaScript/0011960_clone-object.js b/pool/shard001/JavaScript/0011960_clone-object.js new file mode 100644 index 0000000000000000000000000000000000000000..09716d955372b1adddf13e11e021fc1b4aa01027 --- /dev/null +++ b/pool/shard001/JavaScript/0011960_clone-object.js @@ -0,0 +1,38 @@ +describe('clone object', function () { + it('should clone an object', function () { + var expected = {name: 'Ahmed', age: 27, skills: ['cycling', 'walking', 'eating']}, + obj = {}; + + expect(obj).toEqual(expected); + expect(obj).not.toBe(expected); + }); +}); + +function describe(obj) { + + var expected = {name: 'Ahmed', age: 27, skills: ['cycling', 'walking', 'eating']} + + if (null == obj || "object" != typeof obj) return obj; + if (obj instanceof Date) { + copy = new Date(); + copy.setTime(obj.getTime()); + return copy; + } + if (obj instanceof Array) { + copy = []; + for (var i = 0, len = obj.length; i < len; i++) { + copy[i] = clone(obj[i]); + } + return copy; + } + + if (obj instanceof Object) { + copy = {}; + for (var attr in obj) { + if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); + } + return copy; + } + + throw new Error("Not supported."); +} diff --git a/pool/shard001/JavaScript/0011963_sketch.js b/pool/shard001/JavaScript/0011963_sketch.js new file mode 100644 index 0000000000000000000000000000000000000000..daefca789cc08b3128d33b4ebceff3d25b49c626 --- /dev/null +++ b/pool/shard001/JavaScript/0011963_sketch.js @@ -0,0 +1,48 @@ +// Define balls array +var balls = []; + +function setup() { + // Create the canvas: https://p5js.org/reference/#/p5/createCanvas + createCanvas(500, 500); + // Set backround color: https://p5js.org/reference/#/p5/background + background(200); + + strokeWeight(0); +} + +function draw(){ + // Clear background + background(200); + + for (var k=0; k + fn.apply( + this, + Array.prototype.slice + .call(arguments) + .concat((err, out) => (err ? reject(err) : resolve(out))) + ) + ); + }; +} + +var exec = promisify(child_process.exec); +var readdir = promisify(fs.readdir); +var readFile = promisify(fs.readFile); + +var perfDir = path.resolve(__dirname, '../perf/'); + +Promise.all([ + readFile(path.resolve(__dirname, '../dist/immutable.js'), { + encoding: 'utf8', + }), + exec('git show master:dist/immutable.js'), +]) + .then(function(args) { + var newSrc = args[0]; + var oldSrc = args[1].toString({ encoding: 'utf8' }).slice(0, -1); // wtf, comma? + return newSrc === oldSrc ? [newSrc] : [newSrc, oldSrc]; + }) + .then(function(sources) { + return sources.map(function(source) { + var sourceExports = {}; + var sourceModule = { exports: sourceExports }; + vm.runInNewContext( + source, + { + require: require, + module: sourceModule, + exports: sourceExports, + }, + 'immutable.js' + ); + return sourceModule.exports; + }); + }) + .then(function(modules) { + return readdir(perfDir) + .then(function(filepaths) { + return Promise.all( + filepaths.map(function(filepath) { + return readFile(path.resolve(perfDir, filepath)).then(function( + source + ) { + return { + path: filepath, + source: source, + }; + }); + }) + ); + }) + .then(function(sources) { + var tests = {}; + + modules.forEach(function(Immutable, version) { + sources.forEach(function(source) { + var description = []; + var beforeStack = []; + var beforeFn; + var prevBeforeFn; + + function describe(name, fn) { + description.push(name); + beforeStack.push(prevBeforeFn); + prevBeforeFn = beforeFn; + fn(); + beforeFn = prevBeforeFn; + prevBeforeFn = beforeStack.pop(); + description.pop(); + } + + function beforeEach(fn) { + beforeFn = !prevBeforeFn + ? fn + : (function(prevBeforeFn) { + return function() { + prevBeforeFn(); + fn(); + }; + })(prevBeforeFn); + } + + function it(name, test) { + var fullName = description.join(' > ') + ' ' + name; + ( + tests[fullName] || + (tests[fullName] = { + description: fullName, + tests: [], + }) + ).tests[version] = { + before: beforeFn, + test: test, + }; + } + + vm.runInNewContext( + source.source, + { + describe: describe, + it: it, + beforeEach: beforeEach, + console: console, + Immutable: Immutable, + }, + source.path + ); + }); + }); + + // Array<{ + // description: String, + // tests: Array<{ + // before: Function, + // test: Function + // }> // one per module, [new,old] or just [new] + // }> + return Object.keys(tests).map(function(key) { + return tests[key]; + }); + }); + }) + .then(function(tests) { + var suites = []; + + tests.forEach(function(test) { + var suite = new Benchmark.Suite(test.description, { + onStart: function(event) { + console.log(event.currentTarget.name.bold); + process.stdout.write(' ...running... '.gray); + }, + onComplete: function(event) { + process.stdout.write('\r\x1B[K'); + var stats = Array.prototype.map.call(event.currentTarget, function( + target + ) { + return target.stats; + }); + + function pad(n, s) { + return Array(Math.max(0, 1 + n - s.length)).join(' ') + s; + } + + function fmt(b) { + return Math.floor(b) + .toString() + .replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + function pct(p) { + return Math.floor(p * 10000) / 100 + '%'; + } + + var dualRuns = stats.length === 2; + + if (dualRuns) { + var prevMean = 1 / stats[1].mean; + var prevLow = 1 / (stats[1].mean + stats[1].deviation * 2); + var prevHigh = 1 / (stats[1].mean - stats[1].deviation * 2); + + // console.log( + // (dualRuns ? ' Old: '.bold.gray : ' ') + + // ( + // pad(9, fmt(prevLow)) + ' ' + + // pad(9, fmt(prevMean)) + ' ' + + // pad(9, fmt(prevHigh)) + ' ops/sec' + // ) + // ); + + var prevLowmoe = 1 / (stats[1].mean + stats[1].moe); + var prevHighmoe = 1 / (stats[1].mean - stats[1].moe); + + console.log( + (dualRuns ? ' Old: '.bold.gray : ' ') + + (pad(9, fmt(prevLowmoe)) + + ' ' + + pad(9, fmt(prevMean)) + + ' ' + + pad(9, fmt(prevHighmoe)) + + ' ops/sec') + ); + } + + var mean = 1 / stats[0].mean; + var low = 1 / (stats[0].mean + stats[0].deviation * 2); + var high = 1 / (stats[0].mean - stats[0].deviation * 2); + + // console.log( + // (dualRuns ? ' New: '.bold.gray : ' ') + + // ( + // pad(9, fmt(low)) + ' ' + + // pad(9, fmt(mean)) + ' ' + + // pad(9, fmt(high)) + ' ops/sec' + // ) + // ); + + var lowmoe = 1 / (stats[0].mean + stats[0].moe); + var highmoe = 1 / (stats[0].mean - stats[0].moe); + + console.log( + (dualRuns ? ' New: '.bold.gray : ' ') + + (pad(9, fmt(lowmoe)) + + ' ' + + pad(9, fmt(mean)) + + ' ' + + pad(9, fmt(highmoe)) + + ' ops/sec') + ); + + if (dualRuns) { + var diffMean = (mean - prevMean) / prevMean; + + var comparison = event.currentTarget[1].compare( + event.currentTarget[0] + ); + var comparison2 = event.currentTarget[0].compare( + event.currentTarget[1] + ); + console.log(' compare: ' + comparison + ' ' + comparison2); + + console.log(' diff: ' + pct(diffMean)); + + function sq(p) { + return p * p; + } + + var rme = Math.sqrt( + (sq(stats[0].rme / 100) + sq(stats[1].rme / 100)) / 2 + ); + // console.log('rmeN: ' + stats[0].rme); + // console.log('rmeO: ' + stats[1].rme); + console.log(' rme: ' + pct(rme)); + } + + // console.log(stats); + }, + }); + + test.tests.forEach(function(run) { + suite.add({ + fn: run.test, + onStart: run.before, + onCycle: run.before, + }); + }); + + suites.push(suite); + }); + + var onBenchComplete; + var promise = new Promise(function(_resolve) { + onBenchComplete = _resolve; + }); + + Benchmark.invoke(suites, 'run', { onComplete: onBenchComplete }); + + return onBenchComplete; + }) + .then(function() { + console.log('all done'); + }) + .catch(function(error) { + console.log('ugh', error.stack); + }); diff --git a/pool/shard001/JavaScript/0011971_webaudiofluidpianonode.js b/pool/shard001/JavaScript/0011971_webaudiofluidpianonode.js new file mode 100644 index 0000000000000000000000000000000000000000..c051edbe69aad7d9b640c6ab071cc2f6eaf6d239 --- /dev/null +++ b/pool/shard001/JavaScript/0011971_webaudiofluidpianonode.js @@ -0,0 +1,74 @@ +define(['WebAudioInstructmentNode'], function(WebAudioInstructmentNode) { + + var audioctx = new AudioContext(); + + var buffer = {}; + + function loadSample(ctx, note, callback) { + var url = '/midiPianoOnline/sf/fluid/piano/' + noteToName(note) + '.mp3'; + var req = new XMLHttpRequest(); + req.open("GET", url, true); + req.responseType = "arraybuffer"; + req.onload = function() { + if(req.response) { + ctx.decodeAudioData(req.response, function(b) { + buffer[note] = b; + callback(); + }); + } + }; + req.send(); + } + + function WebAudioFluidPianoNode(context, note, volume, channelId) { + if(typeof buffer[note] !== 'undefined') { + this.src = context.createBufferSource(); + this.src.buffer = buffer[note]; + this.invalid = false; + } else { + this.invalid = true; + return; + } + + this.envelope = context.createGain(); + this.envelope.gain.value = volume * 8; + + this.src.connect(this.envelope); + } + + WebAudioFluidPianoNode.prototype.connect = function (webAudioNode) { + if(this.invalid) return; + this.envelope.connect(webAudioNode); + }; + + WebAudioFluidPianoNode.prototype.start = function (when) { + if(this.invalid) return; + if (typeof when == 'undefined') when = 0; + this.src.start(when); + }; + + WebAudioFluidPianoNode.prototype.stop = function (when) { + if(this.invalid) return; + if (typeof when == 'undefined') when = 0; + this.src.stop(when); + }; + + WebAudioFluidPianoNode.prototype.disconnect = function () { + if(this.invalid) return; + this.src.disconnect(); + this.envelope.disconnect(); + }; + + var counter = 0; + for(var i=21; i<108; i++) { + loadSample(audioctx, i, function() { + counter ++; + }); + } + + var ret = New(WebAudioFluidPianoNode); + + WebAudioInstructmentNode.registerInstructmentId(0, ret); + + return ret; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0011972_SpecialtyGeneSummary.js b/pool/shard001/JavaScript/0011972_SpecialtyGeneSummary.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9ad2800694ba3fcd6ada9b5eb630b4edd27b45 --- /dev/null +++ b/pool/shard001/JavaScript/0011972_SpecialtyGeneSummary.js @@ -0,0 +1,105 @@ +define([ + 'dojo/_base/declare', 'dojo/_base/lang', + 'dojo/dom-class', 'dojo/dom-construct', 'dojo/on', 'dojo/request', + 'dojo/fx/easing', + 'dijit/_WidgetBase', + 'dojox/charting/Chart2D', './PATRICTheme', 'dojox/charting/action2d/MoveSlice', 'dojox/charting/action2d/Tooltip', + 'dojox/charting/plot2d/Bars', './SummaryWidget' + +], function ( + declare, lang, + domClass, domConstruct, on, xhr, + easing, + WidgetBase, + Chart2D, Theme, MoveSlice, ChartTooltip, + Bars, SummaryWidget +) { + + return declare([SummaryWidget], { + dataModel: 'sp_gene', + query: '', + view: 'table', + baseQuery: '&limit(1)&facet((field,property_source),(mincount,1))&json(nl,map)', + columns: [ + { label: ' ', field: 'category' }, + { label: 'Source', field: 'source_x' }, + { + label: 'Genes', + field: 'y', + renderCell: function (obj, val, node) { + node.innerHTML = '' + val + ''; + } + } + ], + processData: function (res) { + var chartLabels = this._chartLabels = []; + + if (!res || !res.facet_counts || !res.facet_counts.facet_fields || !res.facet_counts.facet_fields.property_source) { + console.error('INVALID SUMMARY DATA'); + return; + } + var d = res.facet_counts.facet_fields.property_source; // now key-value pair + + var data = this._tableData = []; + Object.keys(d).forEach(function (key, idx) { + chartLabels.push({ text: key, value: idx + 1 }); + var val = key.split(': '); + var cat = val[0]; + var source = val[1]; + + data.push({ + category: cat, source_x: source, y: d[key], property_source: key + }); + }); + + this.set('data', data); + }, + + render_chart: function () { + + if (!this.chart) { + this.chart = new Chart2D(this.chartNode) + .setTheme(Theme) + .addPlot('default', { + type: Bars, + markers: true, + gap: 3, + animate: { duration: 1000, easing: easing.linear } + }) + .addAxis('x', { + vertical: true, + majorLabels: true, + minorTicks: false, + minorLabels: false, + microTicks: false, + labels: this._chartLabels + }) + .addAxis('y', { + minorTicks: false + }) + .addSeries('source', this.data); + + new ChartTooltip(this.chart, 'default', { + text: function (o) { + var d = o.run.data[o.index]; + return d.property_source + ' (' + d.y + ')'; + } + }); + + this.chart.render(); + } else { + + this.chart.updateSeries('source', this.data); + this.chart.render(); + } + }, + + render_table: function () { + this.inherited(arguments); + + this.grid.refresh(); + this.grid.renderArray(this._tableData); + this.grid.sort([{ attribute: 'category', descending: true }]); + } + }); +}); diff --git a/pool/shard001/JavaScript/0011978_Login.js b/pool/shard001/JavaScript/0011978_Login.js new file mode 100644 index 0000000000000000000000000000000000000000..4ac70c8b11a70ef0087153a788408cdb4ba40acc --- /dev/null +++ b/pool/shard001/JavaScript/0011978_Login.js @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2011-2013 sMap Project and its contributors. + * See the NOTICE file for details. + * + * 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. + */ + + + +/** + * @requires sMap/Module.js + */ + +sMap.Module.Login = OpenLayers.Class(sMap.Module, { + + /** + * The events that this module will listen to. Each event listener + * is connected to a method defined in this module, with the same + * name as the event. When another module triggers this event, the + * method will be called (and other modules which are listening + * to the same event). + * + * Look at the event listeners as a public API of the module. + */ + EVENT_LISTENERS : ["initlogin"], + + /** + * The events triggered from this module. Note that some modules + * both listens to and trigger events. + */ + EVENT_TRIGGERS : [], + + initialize : function(options) { + options = options || {}; + + this.EVENT_LISTENERS = + sMap.Module.Login.prototype.EVENT_LISTENERS.concat( + sMap.Module.prototype.EVENT_LISTENERS + ); + this.EVENT_TRIGGERS = + sMap.Module.Login.prototype.EVENT_TRIGGERS.concat( + sMap.Module.prototype.EVENT_TRIGGERS + ); + + // This allows your control to be extended by sending in a parameter hash object + // For example overriding a method in this class or in the parent class (see next step). + OpenLayers.Util.extend(this, options); + // This calls the parent class's constructor and allows to + // extend it (e.g. override methods). + sMap.Module.prototype.initialize.apply(this, [options]); + + }, + + activate : function() { + if (this.active===true) { + return false; + } + + this.makeLoginDialog(); + + // Call the activate function of the parent class + return sMap.Module.prototype.activate.apply( + this, arguments); + }, + + deactivate : function() { + if (this.active!==true) { + return false; + } + // Call the deactivate function of the parent class + return sMap.Module.prototype.deactivate.apply( + this, arguments + ); + }, + + destroy : function() { + // Handler are automatically deactivated and destroyed + // by the parent class module's destroy method. However, + // this is only the case if the handlers are stored like + // below (the example shows how to deactivate them manually): + // -> this.handlers["click"].deactivate(); // For many handlers... + // -> this.handler.deactivate(); // For single handler + // Therefore you should always store handler(s) like in this example. + + return sMap.Module.prototype.destroy.apply(this, arguments); + }, + + /** + * Draws the non-default HTML-content. Called when all modules + * are initialized. All initial HTML should be produced from here. + * @returns {void} + */ + drawContent : function() { + sMap.events.triggerEvent("addtoolbutton", this, { + index : this.toolbarIndex, + iconCSS : null, //this.toolImg, + label : this.lang.labelButtonSubmit, + tagID : "login-btn" + }); + + }, + + makeLoginDialog : function() { + + var dialogDiv = $("
      "); + this.dialogDiv = dialogDiv; + var body = $("body"); + $("body").append(dialogDiv); //same $("")if fetched body.append(dialogDiv); + + var form = $('
      '); + dialogDiv.append(form); + + var fieldset = $("
      "); + form.append(fieldset); + //var legend = $(""); + //legend.text(this.lang.loginTitle); + //fieldset.append(legend); + + var usernamelabel = $(''); //var label = $("