diff --git a/pool/shard000/JavaScript/0003799_worker-testharness.js b/pool/shard000/JavaScript/0003799_worker-testharness.js new file mode 100644 index 0000000000000000000000000000000000000000..fdf5868e33e2fe35344818ec3f1a2e068b90996d --- /dev/null +++ b/pool/shard000/JavaScript/0003799_worker-testharness.js @@ -0,0 +1,49 @@ +/* + * worker-test-harness should be considered a temporary polyfill around + * testharness.js for supporting Service Worker based tests. It should not be + * necessary once the test harness is able to drive worker based tests natively. + * See https://github.com/w3c/testharness.js/pull/82 for status of effort to + * update upstream testharness.js. Once the upstreaming is complete, tests that + * reference worker-test-harness should be updated to directly import + * testharness.js. + */ + +importScripts('/resources/testharness.js'); + +(function() { + var next_cache_index = 1; + + // Returns a promise that resolves to a newly created Cache object. The + // returned Cache will be destroyed when |test| completes. + function create_temporary_cache(test) { + var uniquifier = String(++next_cache_index); + var cache_name = self.location.pathname + '/' + uniquifier; + + test.add_cleanup(function() { + self.caches.delete(cache_name); + }); + + return self.caches.delete(cache_name) + .then(function() { + return self.caches.open(cache_name); + }); + } + + self.create_temporary_cache = create_temporary_cache; +})(); + +// Runs |test_function| with a temporary unique Cache passed in as the only +// argument. The function is run as a part of Promise chain owned by +// promise_test(). As such, it is expected to behave in a manner identical (with +// the exception of the argument) to a function passed into promise_test(). +// +// E.g.: +// cache_test(function(cache) { +// // Do something with |cache|, which is a Cache object. +// }, "Some Cache test"); +function cache_test(test_function, description) { + promise_test(function(test) { + return create_temporary_cache(test) + .then(test_function); + }, description); +} diff --git a/pool/shard000/JavaScript/0003801_update.js b/pool/shard000/JavaScript/0003801_update.js new file mode 100644 index 0000000000000000000000000000000000000000..734434ab4d5c3af84b5a27cd6a274eae8f016cbf --- /dev/null +++ b/pool/shard000/JavaScript/0003801_update.js @@ -0,0 +1,69 @@ +'use strict'; + +module.exports = function (wikifs, fixture, promise, test, isBinary) { + var updates = isBinary ? fixture.binaryFiles : fixture.textFiles; + var p = promise.then(function () { + return wikifs.createFile( + updates[0].path, updates[0].content, updates[0].commit_message, + updates[0].user_defined, isBinary + ); + }).then(wikifs.readFile).catch(function (err) { + console.error(err); test.ok(false); + }); + + // update wikifs and assert it's attributes in sequence. + updates.forEach(function (update, index) { + // updates[0] was used to create a file + if (index === 0) { + return; + } + + p = p.then(function (file) { + return wikifs.updateFile( + file.id, update.content, file.version, + update.commit_message + ); + }).then(function (id) { + return wikifs.readFile(id).then(function (file) { + test.deepEqual( + file.content, + update.content + ); + test.deepEqual(file.commit_message, update.commit_message); + // when created, version already 1. + test.equal(file.version, index + 1); + return file; + }); + }).catch(function (err) { console.error(err); test.ok(false); }); + }); + + // read old version and compare it + updates.forEach(function (update, index) { + p = p.then(function () { + return wikifs.readFile(updates[0].path, index + 1); + }).then(function (file) { + test.deepEqual(file.content, update.content); + test.deepEqual(file.commit_message, update.commit_message); + test.equal(file.version, index + 1); + }).catch(function (err) { + console.error(err); test.ok(false); }); + }); + + // read history data. + p = p.then(function () { + return wikifs.readFileHistory(updates[0].path).then(function (history) { + history.forEach(function (commit, index) { + if (index === 0) { + return; + } + test.deepEqual( + commit.commit_message, + updates[index].commit_message + ); + test.equal(commit.size, updates[index].content.length); + }); + }).catch(function (err) { console.error(err); test.ok(false); }); + }); + p.then(function () { test.done(); wikifs.disconnect(); }); +}; + diff --git a/pool/shard000/JavaScript/0003802_update-feed-widget.js b/pool/shard000/JavaScript/0003802_update-feed-widget.js new file mode 100644 index 0000000000000000000000000000000000000000..b4d6bcd5e8d80a98068a3dcb82a7aae9ded7c548 --- /dev/null +++ b/pool/shard000/JavaScript/0003802_update-feed-widget.js @@ -0,0 +1,98 @@ +import { Template } from 'meteor/templating'; +import { Tracker } from 'meteor/tracker'; +import SimpleSchema from 'simpl-schema'; +import { moment } from 'meteor/momentjs:moment'; +import { _ } from 'meteor/erasaur:meteor-lodash'; +import { Roles } from 'meteor/alanning:roles'; +import { Feeds } from '../../../api/feed/FeedCollection'; +import { updateMethod } from '../../../api/base/BaseCollection.methods'; +import { Semesters } from '../../../api/semester/SemesterCollection.js'; +import { Courses } from '../../../api/course/CourseCollection.js'; +import { Opportunities } from '../../../api/opportunity/OpportunityCollection.js'; +import * as FormUtils from '../form-fields/form-field-utilities.js'; +import { ROLE } from '../../../api/role/Role'; + +const updateSchema = new SimpleSchema({ + description: { type: String, optional: true }, + picture: { type: String, optional: true }, + users: { type: Array }, 'users.$': String, + opportunity: { type: String, optional: true }, + course: { type: String, optional: true }, + semester: { type: String, optional: true }, + retired: Boolean, +}, { tracker: Tracker }); + +Template.Update_Feed_Widget.onCreated(function onCreated() { + FormUtils.setupFormWidget(this, updateSchema); +}); + +Template.Update_Feed_Widget.helpers({ + semesters() { + return Semesters.findNonRetired({}, { sort: { semesterNumber: 1 } }); + }, + feedTypes() { + return [ + Feeds.NEW_COURSE, + Feeds.NEW_OPPORTUNITY, + Feeds.VERIFIED_OPPORTUNITY, + Feeds.NEW_COURSE_REVIEW, + Feeds.NEW_OPPORTUNITY_REVIEW, + Feeds.NEW_USER, + Feeds.NEW_LEVEL, + ]; + }, + timestamp() { + const feed = Feeds.findDoc(Template.currentData().updateID.get()); + return moment(feed.timestamp).format(); + }, + feed() { + return Feeds.findDoc(Template.currentData().updateID.get()); + }, + opportunities() { + return Opportunities.find({}, { sort: { name: 1 } }); + }, + courses() { + return Courses.findNonRetired({}, { sort: { number: 1 } }); + }, + users() { + const students = Roles.getUsersInRole([ROLE.STUDENT]).fetch(); + const sorted = _.sortBy(students, 'lastName'); + return sorted; + }, + falseValueRetired() { + const plan = Feeds.findDoc(Template.currentData() + .updateID + .get()); + return !plan.retired; + }, + trueValueRetired() { + const plan = Feeds.findDoc(Template.currentData() + .updateID + .get()); + return plan.retired; + }, +}); + +Template.Update_Feed_Widget.events({ + submit(event, instance) { + event.preventDefault(); + const updateData = FormUtils.getSchemaDataFromEvent(updateSchema, event); + instance.context.reset(); + updateSchema.clean(updateData, { mutate: true }); + updateData.retired = updateData.retired === 'true'; + instance.context.validate(updateData); + if (instance.context.isValid()) { + updateData.id = instance.data.updateID.get(); + updateMethod.call({ collectionName: Feeds.getCollectionName(), updateData }, (error) => { + if (error) { + FormUtils.indicateError(instance, error); + } else { + FormUtils.indicateSuccess(instance, event); + } + }); + } else { + FormUtils.indicateError(instance); + } + }, + 'click .jsCancel': FormUtils.processCancelButtonClick, +}); diff --git a/pool/shard000/JavaScript/0003805_budget.js b/pool/shard000/JavaScript/0003805_budget.js new file mode 100644 index 0000000000000000000000000000000000000000..45895a7d37fe70d4c169aa10ad32baa653fb76fb --- /dev/null +++ b/pool/shard000/JavaScript/0003805_budget.js @@ -0,0 +1,23 @@ +var Mystique = require('mystique'); + +var BudgetTransformer = Mystique.Transformer.extend({ + resourceName: 'budget', + mapOut: function(budget) { + return { + id: budget.id, + name: budget.name, + startDate: budget.startDate, + remaining: budget.remaining, + }; + }, + + mapIn(req) { + return { + name: req.body.budget.name, + startDate: req.body.budget.startDate, + remaining: req.body.budget.remaining, + }; + }, +}); + +Mystique.registerTransformer('Budget', BudgetTransformer); diff --git a/pool/shard000/JavaScript/0003806_seed.js b/pool/shard000/JavaScript/0003806_seed.js new file mode 100644 index 0000000000000000000000000000000000000000..0741510b53f6de5e226349a76379267692d11d83 --- /dev/null +++ b/pool/shard000/JavaScript/0003806_seed.js @@ -0,0 +1,30 @@ +var mongoose = require('mongoose'), + Course = require('./../models/course.js'), + User = require('./../models/user.js'); + +exports.init = function(connectionString, cb) { + mongoose.connect(connectionString); + var user = new User({_id: '11e42af15f9b16241a4a80f8', name : "chibolo pulpin"}); + user.save(function(err) { + if (err) return cb(err); + var fm = '{"isEditable":false,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[{"isEditable":true,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[]},{"isEditable":true,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[]}]}'; + var coursesNames = ['Fisica 1','Calculo 1','Quimica 1','Teología','Mate basicas']; + var userId = user._id; + for (var i = 0; i < coursesNames.length; i++) { + + //console.log("formula",fm); + Course.create({name: coursesNames[i], + formula: '{"isEditable":false,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[{"isEditable":true,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[]},{"isEditable":true,"decimals":2,"label":null,"bounds":{"upper":20,"lower":0},"trunk":0,"deleteMin":0,"children":[]}]}', + userId: userId}, + function(err, course) { + if (err) return cb(err); + Course.share({ + courseId: course._id, + userId: '11e42af15f9b16241a4a80f8' + }, function(err) { + if (err) return cb(err); + }) + }); + } + }); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003808_app-services.js b/pool/shard000/JavaScript/0003808_app-services.js new file mode 100644 index 0000000000000000000000000000000000000000..9ba6ca3fc339238abe8075fdea2079b007eeaf33 --- /dev/null +++ b/pool/shard000/JavaScript/0003808_app-services.js @@ -0,0 +1,98 @@ +(function (window, angular, console) { + + 'use strict'; + + /* Services */ + + + // Demonstrate how to register services + // In this case it is a simple value service. + angular.module('myApp.services', []).value('version', '0.1').factory('admin', ['$rootScope', + function ($rootScope) { + return { + allowed: function (menu) { + if ($rootScope.user.roles.indexOf('_admin') === -1 && $rootScope.user.roles.indexOf('sys') === -1 && menu === "delete") { + return false; + } + return true; + } + }; + } + ]).factory('auth', ['$q', '$http', 'md5', '$rootScope', + function ($q, $http, md5, $rootScope) { + $rootScope.profile = null; + var avatar = function (user, $route) { + $rootScope.profile = { + user: user, + hash: md5.createHash(user.name) + }; + checkOrganization(); + $http.jsonp("http://www.gravatar.com/" + $rootScope.profile.hash + ".json?callback=JSON_CALLBACK"). + success(function (data, status, headers, config) { + if (data.entry && data.entry.length > 0 && data.entry[0].name && data.entry[0].name.formatted) { + $rootScope.profile.gravatar = data.entry[0].name.formatted; + } + }). + error(function (data, status, headers, config) { + $rootScope.profile.gravatar = ""; + }); + }; + var checkOrganization = function () { + $rootScope.admin = $rootScope.profile.user.roles.indexOf('_admin') !== -1 || $rootScope.profile.user.roles.indexOf('sys') !== -1; + if ($rootScope.organizationId) { + for (var i = 0; i < $rootScope.profile.user.organizations.length; i++) { + var organization = $rootScope.profile.user.organizations[i]; + if (organization.id === $rootScope.organizationId) { + $rootScope.organization = organization; + $rootScope.admin = + $rootScope.profile.user.roles.indexOf('_admin') !== -1 || $rootScope.profile.user.roles.indexOf('sys') !== -1 || $rootScope.profile.user.roles.indexOf('admin_' + organization.id) !== -1; + break; + } + } + } + }; + return { + getUser: function () { + var deferred = $q.defer(); + if ($rootScope.profile) { + checkOrganization(); + return true; + } else { + $http.get("/api/session"). + success(function (data, status, headers, config) { + console.log(data); + avatar(data.user); + deferred.resolve(); + }). + error(function (data, status, headers, config) { + deferred.reject(); + }); + } + return deferred.promise; + }, + setUser: function (data) { + avatar(data); + }, + authorize: function () { + var deferred = $q.defer(); + /**if ($rootScope.profile) { + checkOrganization(); + window.setTimeout(function () { + deferred.resolve(); + }, 0); + } else {*/ + $http.get("/api/session"). + success(function (data, status, headers, config) { + console.log(data); + avatar(data.user); + deferred.resolve(); + }). + error(function (data, status, headers, config) { + deferred.reject(); + }); + //} + return deferred.promise; + } + }; + }]); +})(this, this.angular, this.console); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003810_post_image_view.js b/pool/shard000/JavaScript/0003810_post_image_view.js new file mode 100644 index 0000000000000000000000000000000000000000..de59e1416530c7a0063955c8488eacdc7d4585ea --- /dev/null +++ b/pool/shard000/JavaScript/0003810_post_image_view.js @@ -0,0 +1,118 @@ +var args = arguments[0] || {}; + + +var photoData; + +var setImageEvent = "setImage"; + +function showCamera() { + + Titanium.Media.showCamera({ + success : function(event) { + Ti.API.debug("picture was taken"); + //imageView.image = event.media; + photoData = event.media; + $.photo.image = event.media; + $.trigger(setImageEvent,{photo : photoData}); + }, + cancel : function() { + + }, + error : function(error) { + var a = Titanium.UI.createAlertDialog({ + title : 'Camera' + }); + if (error.code == Titanium.Media.NO_CAMERA) { + //a.setMessage('No camera'); + //a.show(); + showGallery(); + } else { + a.setMessage('Unexpected error: ' + error.code); + a.show(); + } + }, + //overlay : overlay, + saveToPhotoGallery:false, + mediaTypes : Ti.Media.MEDIA_TYPE_PHOTO, + allowEditing : true + }); +} + +function showGallery(){ + Titanium.Media.openPhotoGallery({ + success : function(event) { + photoData = event.media; + $.photo.image = event.media; + $.trigger(setImageEvent,{photo : photoData}); + } + }); +} + +function postData(data) { + if (Ti.Platform.name === 'iPhone OS'){ + style = Ti.UI.iPhone.ActivityIndicatorStyle.PLAIN; + } + else { + style = Ti.UI.ActivityIndicatorStyle.PLAIN; + } + var activityIndicator = Ti.UI.createActivityIndicator({ + color: 'white', + font: {fontFamily:'Helvetica Neue', fontSize:26, fontWeight:'bold'}, + message: 'Uploading...', + indicatorDiameter : "50dp", + style:style, + height:Ti.UI.SIZE, + width:Ti.UI.SIZE + }); + var currentWindow = Alloy.Globals.naviCon.getCurrentWindow(); + var coverWindow = Ti.UI.createWindow({ + backgroundColor: '#555555', + fullscreen : true, + opacity : 0.6 + }); + var indicatorWindow = Ti.UI.createWindow({ + fullscreen: true + }); + indicatorWindow.add(activityIndicator); + indicatorWindow.addEventListener("open",function(){ + activityIndicator.show(); + }); + coverWindow.open(); + indicatorWindow.open(); + + Alloy.Globals.api.postManager.post(photoData,data,function(result){ + indicatorWindow.close(); + coverWindow.close(); + activityIndicator.hide(); + + if(result){ + Alloy.Globals.lastPost = result; + Alloy.Globals.post = result; + var dialog = Titanium.UI.createAlertDialog({ + title : "投稿完了", + message : '投稿ありがとうございます。' + }); + Alloy.Globals.naviCon.home(); + dialog.show(); + }else{ + var dialog = Titanium.UI.createAlertDialog({ + title : "投稿失敗", + message : '投稿に失敗しました。ネットワークを確認して、再度投稿してください' + }); + dialog.show(); + + } + + }); + + +} + +exports.showCamera = showCamera; +exports.showGallery = showGallery; +exports.postData = postData; + +/* +$.post_image_view.addEventListener("open",function(){ + showCamera(); +});*/ diff --git a/pool/shard000/JavaScript/0003812_index.js b/pool/shard000/JavaScript/0003812_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a44da98be8d2f61e650040aa6176af73c8cbbc77 --- /dev/null +++ b/pool/shard000/JavaScript/0003812_index.js @@ -0,0 +1,21 @@ +function createReducer (initialState, handlers) { + return function (state, action) { + if (state === undefined) { + state = initialState + } + if (action === undefined) { + action = {} + } + + if ('type' in action) { + return handlers[action.type] + ? handlers[action.type](state, action) + : state + } + + return state + } +} + +module.exports = createReducer + diff --git a/pool/shard000/JavaScript/0003813_lazy-box.js b/pool/shard000/JavaScript/0003813_lazy-box.js new file mode 100644 index 0000000000000000000000000000000000000000..b76af35c81e1427367da037d1fc43a3ee62083da --- /dev/null +++ b/pool/shard000/JavaScript/0003813_lazy-box.js @@ -0,0 +1,124 @@ + +function safeAutorun(f){ + return Tracker.nonreactive(function(){ + return Tracker.autorun(f); + }); +} + + +LazyBox = function (func, equals) { + var self = this; + + // state tracking + self.stopped = false; + + self.func = func; + self.equals = equals; + + self.curResult = null; + + self.dep = new Tracker.Dependency; + + // Don't initialise a computation until required. + self.resultComputation = null; + + // bind functions so they're only created once + self._computation = self._computation.bind(self); + self._onInvalidate = self._onInvalidate.bind(self); + self._pauseAfterFlush = self._pauseAfterFlush.bind(self); +}; + +LazyBox.prototype._computation = function (c) { + var self = this; + var func = self.func; + + var newResult = func(); + + if (! c.firstRun) { + var equals = self.equals; + var oldResult = self.curResult; + + if (equals ? equals(newResult, oldResult) : + newResult === oldResult) { + // same as last time + return; + } + } + + self.curResult = newResult; + self.dep.changed(); +}; + +LazyBox.prototype._onInvalidate = function(){ + var self = this; + if (self.stopped){ + return; + } + // when it's invalidated, Tracker will flush to recompute + Tracker.afterFlush(self._pauseAfterFlush); +}; + +LazyBox.prototype._pauseAfterFlush = function(){ + var self = this; + if (self.stopped || self.resultComputation == null){ + return; + } + if (!self.dep.hasDependents()){ + // pause + self.resultComputation.stop(); + self.resultComputation = null; + } +}; + +LazyBox.prototype.depend = function(){ + var self = this; + if (!Tracker.active){ + // TODO: Warn users calling LazyBox.get without a current computation. Will cause a lot of stop/starting. + if (!self.dep.hasDependents()){ + self.resultComputation.stop(); + self.resultComputation = null; + } + return; + } + if (self.dep.depend()) { + Tracker.currentComputation.onInvalidate(self._onInvalidate); + } +}; + +LazyBox.prototype.stop = function () { + var self = this; + if (self.stopped){ + return; + } + if (self.resultComputation != null) { + self.resultComputation.stop(); + self.resultComputation = null; + } + self.func = null; + self.equals = null; + self.curResult = null; + self.dep = null; + self._computation = null; + self._onInvalidate = null; + self._pauseAfterFlush = null; + self.stopped = true; +}; + +LazyBox.prototype.get = function () { + var self = this; + if (self.stopped){ + throw new Error('LazyBox#get() called after stopped.'); + } + // Check if the computation is running + if (self.resultComputation == null){ + // restart as necessary + self.resultComputation = safeAutorun(self._computation); + } else if (self.resultComputation.invalidated) { + // or recompute if invalidated + self.resultComputation._recompute(); + } + + self.depend(); + + return self.curResult; +}; diff --git a/pool/shard000/JavaScript/0003817_jquery.metadata.js b/pool/shard000/JavaScript/0003817_jquery.metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..e361d960bf7821ec092662be3b7bdd39c0ddc003 --- /dev/null +++ b/pool/shard000/JavaScript/0003817_jquery.metadata.js @@ -0,0 +1,122 @@ +/* + * Metadata - jQuery plugin for parsing metadata from elements + * + * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.metadata.js,v 1.1 2009-09-02 20:58:49 hexbinary Exp $ + * + */ + +/** + * Sets the type of metadata to use. Metadata is encoded in JSON, and each property + * in the JSON will become a property of the element itself. + * + * There are three supported types of metadata storage: + * + * attr: Inside an attribute. The name parameter indicates *which* attribute. + * + * class: Inside the class attribute, wrapped in curly braces: { } + * + * elem: Inside a child element (e.g. a script tag). The + * name parameter indicates *which* element. + * + * The metadata for an element is loaded the first time the element is accessed via jQuery. + * + * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements + * matched by expr, then redefine the metadata type and run another $(expr) for other elements. + * + * @name $.metadata.setType + * + * @example

This is a p

+ * @before $.metadata.setType("class") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from the class attribute + * + * @example

This is a p

+ * @before $.metadata.setType("attr", "data") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from a "data" attribute + * + * @example

This is a p

+ * @before $.metadata.setType("elem", "script") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from a nested script element + * + * @param String type The encoding type + * @param String name The name of the attribute to be used to get metadata (optional) + * @cat Plugins/Metadata + * @descr Sets the type of encoding to be used when loading metadata for the first time + * @type undefined + * @see metadata() + */ + +(function($) { + +$.extend({ + metadata : { + defaults : { + type: 'class', + name: 'metadata', + cre: /({.*})/, + single: 'metadata' + }, + setType: function( type, name ){ + this.defaults.type = type; + this.defaults.name = name; + }, + get: function( elem, opts ){ + var settings = $.extend({},this.defaults,opts); + // check for empty string in single property + if ( !settings.single.length ) settings.single = 'metadata'; + + var data = $.data(elem, settings.single); + // returned cached data if it already exists + if ( data ) return data; + + data = "{}"; + + if ( settings.type == "class" ) { + var m = settings.cre.exec( elem.className ); + if ( m ) + data = m[1]; + } else if ( settings.type == "elem" ) { + if( !elem.getElementsByTagName ) + return undefined; + var e = elem.getElementsByTagName(settings.name); + if ( e.length ) + data = $.trim(e[0].innerHTML); + } else if ( elem.getAttribute != undefined ) { + var attr = elem.getAttribute( settings.name ); + if ( attr ) + data = attr; + } + + if ( data.indexOf( '{' ) <0 ) + data = "{" + data + "}"; + + data = eval("(" + data + ")"); + + $.data( elem, settings.single, data ); + return data; + } + } +}); + +/** + * Returns the metadata object for the first member of the jQuery object. + * + * @name metadata + * @descr Returns element's metadata object + * @param Object opts An object contianing settings to override the defaults + * @type jQuery + * @cat Plugins/Metadata + */ +$.fn.metadata = function( opts ){ + return $.metadata.get( this[0], opts ); +}; + +})(jQuery); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003819_crawl.js b/pool/shard000/JavaScript/0003819_crawl.js new file mode 100644 index 0000000000000000000000000000000000000000..057254165133033f2e1ed11b0d7d62db577f39fb --- /dev/null +++ b/pool/shard000/JavaScript/0003819_crawl.js @@ -0,0 +1,77 @@ +/** + * Copyright 2015 IBM Corp. 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. + */ + +const TwitterCrawler = require('../lib/twitter-crawler'); +const fs = require('fs'); +const log = require('winston'); +const Promise = require('bluebird'); + +const getEnvCredentials = () => + process.env.TWITTER_CREDENTIALS ? JSON.parse(process.env.TWITTER_CREDENTIALS) : []; + +const credentials = [ + { + consumer_key : "", + consumer_secret : "", + access_token_key : "", + access_token_secret : "", + enabled : false + } + ].concat(getEnvCredentials()); + + +const bind = (object, method) => object[method].bind(object); + +function saveOutput(obj, filename) { + fs.writeFile(`${__dirname}/output/${filename}`, JSON.stringify(obj, null, ' ')); +} + + +const crawler = new TwitterCrawler(credentials); +const crawlList = [ + 'ladygaga', + '19397785', + 'KingJames' +]; + + +module.exports = Promise.all(crawlList.map((twitterHandle) => { + // Get user + log.info(`Obtaining user with id ${twitterHandle}...`); + return crawler.getUser(twitterHandle) + .then((user) => { + log.info( + `Obtained info for user ${user.name} (${user.id}). ` + + `Storing in output/${twitterHandle}_user.json` + ); + + saveOutput(user, `${twitterHandle}_user.json`); + + // Crawl tweets + log.info('Obtaining tweets...'); + return crawler.getTweets(twitterHandle, { min_tweets: 50, limit : 300 }) + .then((tweets) => { + log.info( + `Obtained ${tweets.length} tweets for user ${user.name} (${user.id}). ` + + `Storing in output/${twitterHandle}_tweets.json` + ); + + saveOutput(tweets, `${twitterHandle}_tweets.json`); + log.info('Crawling finished.'); + }); + }) + .catch(bind(log, 'error')); +})); diff --git a/pool/shard000/JavaScript/0003821_platform_viewports.js b/pool/shard000/JavaScript/0003821_platform_viewports.js new file mode 100644 index 0000000000000000000000000000000000000000..f6590810c97fe29d85d463bcc28dda2b3a266336 --- /dev/null +++ b/pool/shard000/JavaScript/0003821_platform_viewports.js @@ -0,0 +1,112 @@ +import { Mongo } from 'meteor/mongo'; +import { SimpleSchema } from 'meteor/aldeed:simple-schema'; +import { Auth } from '../auth.js'; +import { ChangeTracker } from '../change_tracker/change_tracker.js'; +import { SchemaHelpers } from '../schema_helpers.js'; + +/** + * ============================================================================ + * PlatformViewports + * ============================================================================ + */ +export const PlatformViewport = new SimpleSchema({ + // Link to the project to which this test belongs + projectId : { + type : String, + denyUpdate: true + }, + // Link to the project version to which this test belongs + projectVersionId: { + type : String, + denyUpdate: true + }, + // Link to the platform configuration record + platformId : { + type : String, + denyUpdate: true + }, + title : { + type: String, + }, + width : { + type : Number, + defaultValue: 1024 + }, + height : { + type : Number, + defaultValue: 768 + }, + aspectRatio : { + type : Number, + decimal: true, + optional: true + }, + // Mark the default viewport for a platform + default: { + type: Boolean, + defaultValue: false + }, + // Standard tracking fields + dateCreated : { + type : Date, + autoValue : SchemaHelpers.autoValueDateCreated, + denyUpdate: true + }, + createdBy : { + type : String, + autoValue : SchemaHelpers.autoValueCreatedBy, + denyUpdate: true + }, + dateModified : { + type : Date, + autoValue: SchemaHelpers.autoValueDateModified + }, + modifiedBy : { + type : String, + autoValue: SchemaHelpers.autoValueModifiedBy + } +}); + +export const PlatformViewports = new Mongo.Collection("platform_viewports"); +PlatformViewports.attachSchema(PlatformViewport); +PlatformViewports.deny(Auth.ruleSets.deny.ifNotTester); +PlatformViewports.allow(Auth.ruleSets.allow.ifAuthenticated); +ChangeTracker.TrackChanges(PlatformViewports, "platform_viewports"); + +// Listed for changes and update the aspect ratio +if (Meteor.isServer) { + // Maintain the aspect ratio + PlatformViewports.before.insert(function (userId, doc) { + doc.aspectRatio = doc.width / doc.height; + }); + PlatformViewports.before.update(function (userId, doc, changedFields, modifier) { + modifier.$set = modifier.$set || {}; + if (_.contains(changedFields, 'width') || _.contains(changedFields, 'height')) { + let width = modifier.$set.width || doc.width, + height = modifier.$set.height || doc.height; + console.log("PlatformViewports.before.update setting aspectRatio:", width / height); + modifier.$set.aspectRatio = width / height; + } + }); + + // Maintain the default flag + PlatformViewports.after.update(function (userId, doc, changedFields, modifier) { + // If the default flag is set to true + if (_.contains(changedFields, 'default') && doc.default == true) { + // Set the other viewports for this platform to default = false + PlatformViewports.find({ + _id: { $ne: doc._id }, + platformId: doc.platformId, + default: true + }).forEach((viewport) => { + console.log("Setting default from true to false:", viewport); + PlatformViewports.update({_id: viewport._id}, {$set: {default: false}}); + }); + } + }); +} + +/** + * Helpers + */ +PlatformViewports.helpers({}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003822_ace_widget.js b/pool/shard000/JavaScript/0003822_ace_widget.js new file mode 100644 index 0000000000000000000000000000000000000000..713865e812031c320dea58e710ce7f2525c04289 --- /dev/null +++ b/pool/shard000/JavaScript/0003822_ace_widget.js @@ -0,0 +1,245 @@ +$(function(){ + var EDITOR_DICT = {}; + + var set_santa_clara_text_editor = function(jq_object){ + var ta_id=jq_object.data("ta_id"); + var name=jq_object.data("ta_name"); + var santa_clara_text_editor_id=jq_object.attr("id"); + + var editor=ace.edit(santa_clara_text_editor_id); + var jq_editor_box=jq_object.parent(); + + EDITOR_DICT[santa_clara_text_editor_id]=editor; + + editor.setTheme("ace/theme/eclipse"); + editor.getSession().setMode("ace/mode/plain_text"); + + editor.getSession().setUseWrapMode(true); + editor.setShowPrintMargin(false); + + editor.on("change",function(event){ + jq_editor_box.addClass("santa_clara_text_editor_box_modified"); + }); + + editor.commands.addCommand({ + name: 'Move to cursor to the start of the current line.', + bindKey: {win: 'Ctrl-B', mac: 'Command-B'}, + exec: function(editor) { + editor.navigateLineStart(); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + editor.commands.addCommand({ + name: 'Move to cursor to the end of the current line.', + bindKey: {win: 'Ctrl-E', mac: 'Command-E'}, + exec: function(editor) { + editor.navigateLineEnd(); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + editor.commands.addCommand({ + name: 'Move to cursor to the end of the current file.', + bindKey: {win: 'Ctrl-G', mac: 'Command-G'}, + exec: function(editor) { + editor.gotoLine(editor.getSession().getLength()); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + editor.commands.addCommand({ + name: 'Move to cursor to the start of the current file.', + bindKey: {win: 'Ctrl-<', mac: 'Command-<'}, + exec: function(editor) { + editor.gotoLine(0); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + editor.commands.addCommand({ + name: 'Remove to line end.', + bindKey: {win: 'Ctrl-k', mac: 'Command-k'}, + exec: function(editor) { + editor.removeToLineEnd(); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + editor.commands.addCommand({ + name: 'Remove word right.', + bindKey: {win: 'Alt-d', mac: 'Alt-d'}, + exec: function(editor) { + editor.removeWordRight(); + editor.focus(); + }, + readOnly: false // false if this command should not apply in readOnly mode + }); + + var form=jq_object.closest("form"); + var ta_name=jq_object.data("ta_name"); + var ta_id=jq_object.data("ta_id"); + + form.submit( function(event){ + var text=editor.getSession().toString(); + var ta_html=""; + $(this).append(ta_html); + $(this).find('#'+ta_id).hide(); + return true; + }); + }; + + var action_santa_clara_text_editor_button_simple=function(jq_object,event){ + var tag=jq_object.data("tag"); + var parent=jq_object.parent(); + var santa_clara_text_editor_id=parent.data("santa_clara_text_editor_id"); + var editor=EDITOR_DICT[santa_clara_text_editor_id]; + + var range=editor.getSelectionRange(); + + editor.clearSelection(); + + editor.moveCursorTo(range.end.row,range.end.column,true); + editor.insert("[/"+tag+"]"); + + editor.moveCursorTo(range.start.row,range.start.column,true); + editor.insert("["+tag+"]"); + + editor.moveCursorTo(range.end.row,range.end.column+5+2*tag.length,true); + editor.focus(); + }; + + var action_santa_clara_text_editor_button_single=function(jq_object,event){ + var tag=jq_object.data("tag"); + var parent=jq_object.parent(); + var santa_clara_text_editor_id=parent.data("santa_clara_text_editor_id"); + var editor=EDITOR_DICT[santa_clara_text_editor_id]; + editor.insert("["+tag+"/]"); + editor.focus(); + }; + + var action_santa_clara_text_editor_button_function=function(jq_object,event){ + var tag=jq_object.data("tag"); + var parent=jq_object.parent(); + var santa_clara_text_editor_id=parent.data("santa_clara_text_editor_id"); + var editor=EDITOR_DICT[santa_clara_text_editor_id]; + switch (tag) { + case "action_upper": + editor.toUpperCase(); + break; + case "action_lower": + editor.toLowerCase(); + break; + case "action_bracket": + var range=editor.getSelectionRange(); + editor.clearSelection(); + editor.moveCursorTo(range.end.row,range.end.column,true); + editor.insert("]]"); + editor.moveCursorTo(range.start.row,range.start.column,true); + editor.insert("[["); + editor.moveCursorTo(range.end.row,range.end.column+4,true); + editor.focus(); + } + }; + + /**/ + + $(".santa_clara_text_editor").each(function(){ + set_santa_clara_text_editor($(this)); + }); + + $(".santa_clara_text_editor_button_simple").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_simple($(this),event); + }); + + $(".santa_clara_text_editor_button_single").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_single($(this),event); + }); + + $(".santa_clara_text_editor_button_function").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_function($(this),event); + }); + + + + /**/ + + var replace_prefix_in_data = function (object,data_key,new_prefix) { + var old_val=object.data(data_key); + var new_val=old_val.replace('__prefix__',new_prefix); + object.data(data_key,new_val); + }; + + var mutationHandler = function (mutationRecords) { + mutationRecords.forEach ( function (mutation) { + if (mutation.type!="childList") return; + if (mutation.addedNodes.length==0) return; + + $(mutation.addedNodes).each(function(){ + + $(this).find(".santa_clara_text_editor_box").each(function(){ + var box_id=$(this).attr("id"); + var ta_id_temp=$(this).data("ta_id"); + var ta_name_temp=$(this).data("ta_name"); + var ta_id_real=box_id.replace(/^santa_clara_text_editor_box_/,''); + var rexp=RegExp('^'+ta_id_temp.replace('__prefix__','(.*)')+'$'); + var prefix_real=ta_id_real.replace(rexp,'$1'); + replace_prefix_in_data($(this),"ta_id",prefix_real); + replace_prefix_in_data($(this),"ta_name",prefix_real); + $(this).find(".santa_clara_text_editor_button_bar").each(function(){ + replace_prefix_in_data($(this),"santa_clara_text_editor_box_id",prefix_real); + replace_prefix_in_data($(this),"santa_clara_text_editor_id",prefix_real); + }); + $(this).find(".santa_clara_text_editor").each(function(){ + replace_prefix_in_data($(this),"ta_id",prefix_real); + replace_prefix_in_data($(this),"ta_name",prefix_real); + }); + }); + + $(this).find(".santa_clara_text_editor").each(function(){ + set_santa_clara_text_editor($(this)); + }); + + $(this).find(".santa_clara_text_editor_button_simple").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_simple($(this),event); + }); + + $(this).find(".santa_clara_text_editor_button_single").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_single($(this),event); + }); + + $(this).find(".santa_clara_text_editor_button_function").click(function(event){ + event.preventDefault(); + action_santa_clara_text_editor_button_function($(this),event); + }); + + }); + + }); + }; + + var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; + var myObserver = new MutationObserver (mutationHandler); + var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true }; + + $("form").each( function () { + myObserver.observe (this, obsConfig); + }); + + + +}); + diff --git a/pool/shard000/JavaScript/0003824_bootstrap-typeahead.js b/pool/shard000/JavaScript/0003824_bootstrap-typeahead.js new file mode 100644 index 0000000000000000000000000000000000000000..8c30c318651ebeb50ea5c3869de51be9e37dc460 --- /dev/null +++ b/pool/shard000/JavaScript/0003824_bootstrap-typeahead.js @@ -0,0 +1,44 @@ +define(function(require) { + 'use strict'; + + var $ = require('jquery'); + require('bootstrap'); + + /** + * This customization allows to define own click, render, show functions for Typeahead + */ + var Typeahead; + var origTypeahead = $.fn.typeahead.Constructor; + var origFnTypeahead = $.fn.typeahead; + + Typeahead = function(element, options) { + var opts = $.extend({}, $.fn.typeahead.defaults, options); + this.click = opts.click || this.click; + this.render = opts.render || this.render; + this.show = opts.show || this.show; + this.hide = opts.hide || this.hide; + this.$holder = $(opts.holder || ''); + origTypeahead.apply(this, arguments); + }; + + Typeahead.prototype = origTypeahead.prototype; + Typeahead.prototype.constructor = Typeahead; + + $.fn.typeahead = function(option) { + return this.each(function() { + var $this = $(this); + var data = $this.data('typeahead'); + var options = typeof option === 'object' && option; + if (!data) { + $this.data('typeahead', (data = new Typeahead(this, options))); + } + if (typeof option === 'string') { + data[option](); + } + }); + }; + + $.fn.typeahead.defaults = origFnTypeahead.defaults; + $.fn.typeahead.Constructor = Typeahead; + $.fn.typeahead.noConflict = origFnTypeahead.noConflict; +}); diff --git a/pool/shard000/JavaScript/0003825_orient.test.js b/pool/shard000/JavaScript/0003825_orient.test.js new file mode 100644 index 0000000000000000000000000000000000000000..cc481c01fd3a9a5cc336f4aa93597b7b7f568b2d --- /dev/null +++ b/pool/shard000/JavaScript/0003825_orient.test.js @@ -0,0 +1,161 @@ +import _ol_geom_flat_orient_ from '../../../../../src/ol/geom/flat/orient.js'; + + +describe('ol.geom.flat.orient', function() { + + describe('ol.geom.flat.orient.linearRingIsClockwise()', function() { + + it('identifies clockwise rings', function() { + const flatCoordinates = [0, 1, 1, 4, 4, 3, 3, 0]; + const isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( + flatCoordinates, 0, flatCoordinates.length, 2); + expect(isClockwise).to.be(true); + }); + + it('identifies anti-clockwise rings', function() { + const flatCoordinates = [2, 2, 3, 2, 3, 3, 2, 3]; + const isClockwise = _ol_geom_flat_orient_.linearRingIsClockwise( + flatCoordinates, 0, flatCoordinates.length, 2); + expect(isClockwise).to.be(false); + }); + + }); + + describe('ol.geom.flat.orient.linearRingsAreOriented()', function() { + const oriented = _ol_geom_flat_orient_.linearRingsAreOriented; + + const rightCoords = [ + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45 + ]; + + const leftCoords = [ + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45 + ]; + + const ends = [10, 20]; + + it('checks for left-hand orientation by default', function() { + expect(oriented(rightCoords, 0, ends, 2)).to.be(false); + expect(oriented(leftCoords, 0, ends, 2)).to.be(true); + }); + + it('can check for right-hand orientation', function() { + expect(oriented(rightCoords, 0, ends, 2, true)).to.be(true); + expect(oriented(leftCoords, 0, ends, 2, true)).to.be(false); + }); + + }); + + describe('ol.geom.flat.orient.linearRingssAreOriented()', function() { + const oriented = _ol_geom_flat_orient_.linearRingssAreOriented; + + const rightCoords = [ + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45, + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45 + ]; + + const leftCoords = [ + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45, + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45 + ]; + + const ends = [[10, 20], [30, 40]]; + + it('checks for left-hand orientation by default', function() { + expect(oriented(rightCoords, 0, ends, 2)).to.be(false); + expect(oriented(leftCoords, 0, ends, 2)).to.be(true); + }); + + it('can check for right-hand orientation', function() { + expect(oriented(rightCoords, 0, ends, 2, true)).to.be(true); + expect(oriented(leftCoords, 0, ends, 2, true)).to.be(false); + }); + + }); + + describe('ol.geom.flat.orient.orientLinearRings()', function() { + const orient = _ol_geom_flat_orient_.orientLinearRings; + + const rightCoords = [ + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45 + ]; + + const leftCoords = [ + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45 + ]; + + const ends = [10, 20]; + + it('orients using the left-hand rule by default', function() { + const rightClone = rightCoords.slice(); + orient(rightClone, 0, ends, 2); + expect(rightClone).to.eql(leftCoords); + + const leftClone = leftCoords.slice(); + orient(leftClone, 0, ends, 2); + expect(leftClone).to.eql(leftCoords); + }); + + it('can orient using the right-hand rule', function() { + const rightClone = rightCoords.slice(); + orient(rightClone, 0, ends, 2, true); + expect(rightClone).to.eql(rightCoords); + + const leftClone = leftCoords.slice(); + orient(leftClone, 0, ends, 2, true); + expect(leftClone).to.eql(rightCoords); + }); + + }); + + describe('ol.geom.flat.orient.orientLinearRingss()', function() { + const orient = _ol_geom_flat_orient_.orientLinearRingss; + + const rightCoords = [ + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45, + -180, -90, 180, -90, 180, 90, -180, 90, -180, -90, + -100, -45, -100, 45, 100, 45, 100, -45, -100, -45 + ]; + + const leftCoords = [ + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45, + -180, -90, -180, 90, 180, 90, 180, -90, -180, -90, + -100, -45, 100, -45, 100, 45, -100, 45, -100, -45 + ]; + + const ends = [[10, 20], [30, 40]]; + + it('orients using the left-hand rule by default', function() { + const rightClone = rightCoords.slice(); + orient(rightClone, 0, ends, 2); + expect(rightClone).to.eql(leftCoords); + + const leftClone = leftCoords.slice(); + orient(leftClone, 0, ends, 2); + expect(leftClone).to.eql(leftCoords); + }); + + it('can orient using the right-hand rule', function() { + const rightClone = rightCoords.slice(); + orient(rightClone, 0, ends, 2, true); + expect(rightClone).to.eql(rightCoords); + + const leftClone = leftCoords.slice(); + orient(leftClone, 0, ends, 2, true); + expect(leftClone).to.eql(rightCoords); + }); + + }); + + +}); diff --git a/pool/shard000/JavaScript/0003826_watcher.js b/pool/shard000/JavaScript/0003826_watcher.js new file mode 100644 index 0000000000000000000000000000000000000000..dc307e37a80afcf3cf8271b6e32887a664a54671 --- /dev/null +++ b/pool/shard000/JavaScript/0003826_watcher.js @@ -0,0 +1,171 @@ +import { join, relative } from 'path' +import chalk from 'chalk' +import { FSWatcher } from 'chokidar' +import _debug from 'debug' +import Builder from './builder' + +const debug = _debug('api:watch') +debug.color = 2 // Green + +const watchers = [] + +export default class Watcher { + constructor (builder) { + /* istanbul ignore if */ + if (!(builder instanceof Builder)) { + throw new TypeError('Usage: new Watcher(builder: Builder)') + } + + debug.enabled = true + + this.builder = builder + this.router = builder.router + + this.isWatched = false + + // Chokidar instance + this.fsWatcher = new FSWatcher({ ignoreInitial: true }) + + // Dependents from transformed files + this.dependents = {} + + // Extra files to watch from imports + this.extraWatches = {} + } + + static closeAll () { + for (let watcher of watchers) { + watcher.close() + } + } + + close () { + this.fsWatcher.close() + } + + async watch () { + /* istanbul ignore if */ + if (this.isWatched) { + return + } + + watchers.push(this) + this.isWatched = true + + const listeners = [{ + event: 'add', + verb: 'created', + callback: this._add + }, { + event: 'unlink', + verb: 'removed', + callback: this._unlink + }, { + event: 'change', + verb: 'modified', + callback: this._change + }] + + listeners.forEach(({ event, verb, callback }) => { + this.fsWatcher.on(event, filename => { + debug(chalk`{magenta ${relative(this.router.options.src, filename)}} has been {red ${verb}}.`) + callback.call(this, filename) + }) + }) + + const exts = this.builder.extensions.join('|') + const watchDir = join(this.router.options.entry, `**/*.@(${exts})`) + this.fsWatcher.add(watchDir) + + // Update route handle if file is under `entry`, otherwise watching changes of it + this.builder.plugin('afterFetch', (filename, exports) => { + if (filename.startsWith(this.router.options.entry)) { + this.router.set(relative(this.router.options.entry, filename), exports) + } else { + this._watchFile(filename) + } + }) + + // Save dependent if request is not a module + this.builder.plugin('afterTransform', (filename, result) => { + result.imports.forEach(value => { + /* istanbul ignore else */ + if (value[0] === '~' || value[0] === '.') { + const from = this.router.resolve(value, filename) + this.dependents[from] = this.dependents[from] || [] + this.dependents[from].push(filename) + } + }) + }) + + // TODO Better dev message + debug('Start watching [ \'%s\' ]', relative(this.router.options.src, watchDir)) + } + + _watchFile (filename) { + const exists = this.extraWatches[filename] + + if (!exists) { + this.fsWatcher.add(filename) + this.extraWatches[filename] = true + } + + return this + } + + _unwatchFile (filename) { + const exists = this.extraWatches[filename] + + /* istanbul ignore else */ + if (exists) { + this.fsWatcher.unwatch(filename) + delete this.extraWatches[filename] + } + + return this + } + + _add (filename) { + this.builder.fetch(filename) + } + + _unlink (filename) { + const refetchList = this._purge(filename) + + if (filename.startsWith(this.router.options.entry)) { + this.router.unset(relative(this.router.options.entry, filename)) + } else { + this._unwatchFile(filename) + } + + if (refetchList[0] === filename) { + refetchList.shift() + } + + refetchList.forEach(filename => this.builder.fetch(filename)) + } + + _change (filename) { + this._unlink(filename) + this.builder.fetch(filename) + } + + _purge (filename, refetchList = []) { + const dependents = this.dependents[filename] + + if (dependents !== undefined) { + dependents.forEach(dependent => { + this._purge(dependent, refetchList) + }) + delete this.dependents[filename] + } + + delete this.builder.handles[filename] + + if (filename.startsWith(this.router.options.entry)) { + refetchList.push(filename) + } + + return refetchList + } +} diff --git a/pool/shard000/JavaScript/0003827_Config.js b/pool/shard000/JavaScript/0003827_Config.js new file mode 100644 index 0000000000000000000000000000000000000000..407111b865f49def9a5c37827ae820189fa5fe53 --- /dev/null +++ b/pool/shard000/JavaScript/0003827_Config.js @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2015, YourNameHere. All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ +"use strict"; +/* global module,require,__filename */ + +var loadJson = require('./JsonLoader'), + logError = require('./LogError')(__filename); + +var validateKeyName = name => { + if (['load', 'assign', 'merge'].indexOf(name) > -1) { + throw logError('Configuration key "' + name + '" is reserved and can\'t be used as root config key.', new Error('Configuration Reserved Keyword Error')); + } else { + return true; + } +}; + +var Config = { + load: (jsonFileName, defaultConfig) => { + jsonFileName = jsonFileName || 'config.json'; + defaultConfig = defaultConfig || {}; + return loadJson(jsonFileName).then(json => { + Config.merge(defaultConfig); + for (var name in json) { + if (json.hasOwnProperty(name)) { + if (validateKeyName(name)) { + Config[name] = json[name]; + } + } + } + + return Config; + }); + }, + assign: (dest, conf) => { + conf = conf || {}; + dest = dest || {}; + for (var name in conf) { + if (conf.hasOwnProperty(name)) { + var val = conf[name]; + if (val && typeof val === 'object') { + dest[name] = Config.assign(dest[name], val); + } else { + dest[name] = conf[name]; + } + } + } + return dest; + }, + merge: conf => { + conf = conf || {}; + for (var name in conf) { + if (conf.hasOwnProperty(name)) { + validateKeyName(name); + } + } + return Config.assign(Config, conf); + } +}; + +module.exports = Config; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003830_context-menu.js b/pool/shard000/JavaScript/0003830_context-menu.js new file mode 100644 index 0000000000000000000000000000000000000000..6726bbe128817e2e9c9498690675b5af4fa24d33 --- /dev/null +++ b/pool/shard000/JavaScript/0003830_context-menu.js @@ -0,0 +1,33 @@ +const {Menu} = require('electron') + +module.exports = +class ContextMenu { + constructor (template, atomWindow) { + this.atomWindow = atomWindow + this.createClickHandlers(template) + const menu = Menu.buildFromTemplate(template) + menu.popup(this.atomWindow.browserWindow, {async: true}) + } + + // It's necessary to build the event handlers in this process, otherwise + // closures are dragged across processes and failed to be garbage collected + // appropriately. + createClickHandlers (template) { + template.forEach(item => { + if (item.command) { + if (!item.commandDetail) item.commandDetail = {} + item.commandDetail.contextCommand = true + item.commandDetail.atomWindow = this.atomWindow + item.click = () => { + global.atomApplication.sendCommandToWindow( + item.command, + this.atomWindow, + item.commandDetail + ) + } + } else if (item.submenu) { + this.createClickHandlers(item.submenu) + } + }) + } +} diff --git a/pool/shard000/JavaScript/0003831_inject.js b/pool/shard000/JavaScript/0003831_inject.js new file mode 100644 index 0000000000000000000000000000000000000000..70468a1c988a830896202ba4feca2bdf8111b9b6 --- /dev/null +++ b/pool/shard000/JavaScript/0003831_inject.js @@ -0,0 +1,45 @@ +/* globals Inject */ + +// Inject.rawBody('page-loading', ` +//
+//
+//
+//
+//
+//
+//
+//
+//
` +// ); +// Inject.rawModHtml('moveScriptsToBottom', function(html) { +// console.log("moveScriptsToBottom callled"); +// // get all scripts +// var scripts = html.match(/ diff --git a/pool/shard000/JavaScript/0004227_elqImg.js b/pool/shard000/JavaScript/0004227_elqImg.js new file mode 100644 index 0000000000000000000000000000000000000000..c3800991a7706703d98409238359d5c2da693b22 --- /dev/null +++ b/pool/shard000/JavaScript/0004227_elqImg.js @@ -0,0 +1,33 @@ +var trackURL = document.URL; +if (trackURL.indexOf("?") != -1) { + trackURL += "&async=true"; +} +else { + trackURL += "?async=true"; +} + +var _elqQ = _elqQ || []; + +_elqQ.push(['elqSetSiteId', '1795']); + +_elqQ.push(['elqTrackPageView', trackURL]); + + + +(function () { + + function async_load() { + + var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; + + s.src = '//img.en25.com/i/elqCfg.min.js'; + + var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); + + } + + if (window.addEventListener) window.addEventListener('DOMContentLoaded', async_load, false); + + else if (window.attachEvent) window.attachEvent('onload', async_load); + +})(); diff --git a/pool/shard000/JavaScript/0004230_produto-add.controller.js b/pool/shard000/JavaScript/0004230_produto-add.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..21224edcac6e7ed21f769d82c4276ccccf3beeae --- /dev/null +++ b/pool/shard000/JavaScript/0004230_produto-add.controller.js @@ -0,0 +1,115 @@ +var produtoAddCtrl = function (crudService, $state) { + var vm = this; + vm.formData = {}; + vm.htmlData = {}; + + vm.htmlData.title = 'Adicionar novos produtos'; + vm.htmlData.subtitle = 'Adicionar Novos Produtos'; + vm.htmlData.submit = 'Adicionar Novos Produtos'; + + vm.htmlData.forms = [{ + name: 'Nome', + type: 'text', + model: '', + isRequired: true + }, + { + name: 'Valor', + type: 'number', + model: '', + isRequired: true + }, + { + name: 'Descricao', + type: 'text', + model: '', + isRequired: true + }, + { + name: 'Peso', + type: 'number', + model: '', + isRequired: true + }, + { + name: 'Fabricante', + type: 'text', + model: '', + isRequired: true + }, + { + name: 'Tamanho', + type: 'text', + model: '', + isRequired: true + }, + { + name: 'Quantidade', + type: 'number', + model: '', + isRequired: true + }, + { + name: 'Tipo', + type: 'text', + model: '', + isRequired: true + }, + { + name: 'Genero', + type: 'number', + model: '', + isRequired: true + }, + { + name: 'Imagem', + type: 'text', + model: '', + isRequired: true + }] + + vm.fillForm = function(){ + + vm.formData.nome = "Novo"; + vm.formData.valor = 999; + vm.formData.descricao = "Tenis de couro com muito gliter,"; + vm.formData.peso = 999; + vm.formData.fabricante = "Chineis"; + vm.formData.tamanho = 1; + vm.formData.quantidade = 99; + vm.formData.tipo = "Corrida" + vm.formData.genero = 1 + vm.formData.imagem = 'http://static1.netshoes.net/Produtos/chuteira-adidas-ace-164-fxg-campo/78/D13-3047-178/D13-3047-178_detalhe1.jpg?resize=254:*' + + vm.htmlData.forms.forEach(function(curr, index, arr){ + curr.model = vm.formData[curr.name.toLowerCase()]; + }); + + } + + vm.resetForm = function(){ + vm.htmlData.forms.forEach(function(curr, index, arr){ + curr.model = ''; + }); + }; + + vm.submitForm = function(){ + + vm.htmlData.forms.forEach(function(curr, index, arr){ + vm.formData[curr.name.toLowerCase()] = curr.model; + }); + console.log(vm.formData); + crudService.post('produto', vm.formData) + .then(function(){ + console.log('Success!'); + $state.go('produto.table'); + }, function(err){ + console.log('err', err); + }); + }; + +} + +angular + .module('app') + .controller('produtoAddCtrl', produtoAddCtrl); diff --git a/pool/shard000/JavaScript/0004231_lb-services.js b/pool/shard000/JavaScript/0004231_lb-services.js new file mode 100644 index 0000000000000000000000000000000000000000..e93f980dc0993f18ae5e169f57585e30b5906153 --- /dev/null +++ b/pool/shard000/JavaScript/0004231_lb-services.js @@ -0,0 +1,1166 @@ +// CommonJS package manager support +if (typeof module !== 'undefined' && typeof exports !== 'undefined' && + module.exports === exports) { + // Export the *name* of this Angular module + // Sample usage: + // + // import lbServices from './lb-services'; + // angular.module('app', [lbServices]); + // + module.exports = "lbServices"; +} + +(function(window, angular, undefined) { + 'use strict'; + + var urlBase = "/api"; + var authHeader = 'authorization'; + + function getHost(url) { + var m = url.match(/^(?:https?:)?\/\/([^\/]+)/); + return m ? m[1] : null; + } + + var urlBaseHost = getHost(urlBase) || location.host; + +/** + * @ngdoc overview + * @name lbServices + * @module + * @description + * + * The `lbServices` module provides services for interacting with + * the models exposed by the LoopBack server via the REST API. + * + */ + var module = angular.module("lbServices", ['ngResource']); + +/** + * @ngdoc object + * @name lbServices.Coinmarketcap + * @header lbServices.Coinmarketcap + * @object + * + * @description + * + * A $resource object for interacting with the `Coinmarketcap` model. + * + * **Details** + * + * Coin Marketcap Service + * + * ## Example + * + * See + * {@link http://docs.angularjs.org/api/ngResource.$resource#example $resource} + * for an example of using this object. + * + */ + module.factory( + "Coinmarketcap", + [ + 'LoopBackResource', 'LoopBackAuth', '$injector', '$q', + function(LoopBackResource, LoopBackAuth, $injector, $q) { + var R = LoopBackResource( + urlBase + "/Coinmarketcaps/:id", + { 'id': '@id' }, + { + + /** + * @ngdoc method + * @name lbServices.Coinmarketcap#getTicker + * @methodOf lbServices.Coinmarketcap + * + * @description + * + * Get Ticker + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{number=}` - Market id + * + * - `limit` – `{number=}` - Market limit + * + * - `start` – `{number=}` - Market start + * + * - `convert` – `{string=}` - Market convert + * + * @param {function(Array.,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Array.} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Coinmarketcap` object.) + * + */ + "getTicker": { + isArray: true, + url: urlBase + "/Coinmarketcaps/getTicker", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Coinmarketcap#getGlobalData + * @methodOf lbServices.Coinmarketcap + * + * @description + * + * Get Global data + * + * @param {Object=} parameters Request parameters. + * + * - `convert` – `{string=}` - Market convert + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Coinmarketcap` object.) + * + */ + "getGlobalData": { + url: urlBase + "/Coinmarketcaps/getGlobalData", + method: "GET", + }, + } + ); + + + + + /** + * @ngdoc property + * @name lbServices.Coinmarketcap#modelName + * @propertyOf lbServices.Coinmarketcap + * @description + * The name of the model represented by this $resource, + * i.e. `Coinmarketcap`. + */ + R.modelName = "Coinmarketcap"; + + + + return R; + }]); + +/** + * @ngdoc object + * @name lbServices.Tick + * @header lbServices.Tick + * @object + * + * @description + * + * A $resource object for interacting with the `Tick` model. + * + * **Details** + * + * Tick Service + * + * ## Example + * + * See + * {@link http://docs.angularjs.org/api/ngResource.$resource#example $resource} + * for an example of using this object. + * + */ + module.factory( + "Tick", + [ + 'LoopBackResource', 'LoopBackAuth', '$injector', '$q', + function(LoopBackResource, LoopBackAuth, $injector, $q) { + var R = LoopBackResource( + urlBase + "/Ticks/:id", + { 'id': '@id' }, + { + + /** + * @ngdoc method + * @name lbServices.Tick#create + * @methodOf lbServices.Tick + * + * @description + * + * Create a new instance of the model and persist it into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "create": { + url: urlBase + "/Ticks", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#createMany + * @methodOf lbServices.Tick + * + * @description + * + * Create a new instance of the model and persist it into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Array.,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Array.} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "createMany": { + isArray: true, + url: urlBase + "/Ticks", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#upsert + * @methodOf lbServices.Tick + * + * @description + * + * Patch an existing model instance or insert a new one into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "upsert": { + url: urlBase + "/Ticks", + method: "PUT", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#replaceOrCreate + * @methodOf lbServices.Tick + * + * @description + * + * Replace an existing model instance or insert a new one into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "replaceOrCreate": { + url: urlBase + "/Ticks/replaceOrCreate", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#upsertWithWhere + * @methodOf lbServices.Tick + * + * @description + * + * Update an existing model instance or insert a new one into the data source based on the where criteria. + * + * @param {Object=} parameters Request parameters. + * + * - `where` – `{object=}` - Criteria to match model instances + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "upsertWithWhere": { + url: urlBase + "/Ticks/upsertWithWhere", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#exists + * @methodOf lbServices.Tick + * + * @description + * + * Check whether a model instance exists in the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * Data properties: + * + * - `exists` – `{boolean=}` - + */ + "exists": { + url: urlBase + "/Ticks/:id/exists", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#findById + * @methodOf lbServices.Tick + * + * @description + * + * Find a model instance by {{id}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * - `filter` – `{object=}` - Filter defining fields and include - must be a JSON-encoded string ({"something":"value"}) + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "findById": { + url: urlBase + "/Ticks/:id", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#replaceById + * @methodOf lbServices.Tick + * + * @description + * + * Replace attributes for a model instance and persist it into the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "replaceById": { + url: urlBase + "/Ticks/:id/replace", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#find + * @methodOf lbServices.Tick + * + * @description + * + * Find all instances of the model matched by filter from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `filter` – `{object=}` - Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({"something":"value"}) + * + * @param {function(Array.,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Array.} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "find": { + isArray: true, + url: urlBase + "/Ticks", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#findOne + * @methodOf lbServices.Tick + * + * @description + * + * Find first instance of the model matched by filter from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `filter` – `{object=}` - Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({"something":"value"}) + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "findOne": { + url: urlBase + "/Ticks/findOne", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#updateAll + * @methodOf lbServices.Tick + * + * @description + * + * Update instances of the model matched by {{where}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `where` – `{object=}` - Criteria to match model instances + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * Information related to the outcome of the operation + */ + "updateAll": { + url: urlBase + "/Ticks/update", + method: "POST", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#deleteById + * @methodOf lbServices.Tick + * + * @description + * + * Delete a model instance by {{id}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "deleteById": { + url: urlBase + "/Ticks/:id", + method: "DELETE", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#count + * @methodOf lbServices.Tick + * + * @description + * + * Count instances of the model matched by where from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `where` – `{object=}` - Criteria to match model instances + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * Data properties: + * + * - `count` – `{number=}` - + */ + "count": { + url: urlBase + "/Ticks/count", + method: "GET", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#prototype$updateAttributes + * @methodOf lbServices.Tick + * + * @description + * + * Patch attributes for a model instance and persist it into the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Tick id + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + "prototype$updateAttributes": { + url: urlBase + "/Ticks/:id", + method: "PUT", + }, + + /** + * @ngdoc method + * @name lbServices.Tick#createChangeStream + * @methodOf lbServices.Tick + * + * @description + * + * Create a change stream. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * - `options` – `{object=}` - + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * Data properties: + * + * - `changes` – `{ReadableStream=}` - + */ + "createChangeStream": { + url: urlBase + "/Ticks/change-stream", + method: "POST", + }, + } + ); + + + + /** + * @ngdoc method + * @name lbServices.Tick#patchOrCreate + * @methodOf lbServices.Tick + * + * @description + * + * Patch an existing model instance or insert a new one into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["patchOrCreate"] = R["upsert"]; + + /** + * @ngdoc method + * @name lbServices.Tick#updateOrCreate + * @methodOf lbServices.Tick + * + * @description + * + * Patch an existing model instance or insert a new one into the data source. + * + * @param {Object=} parameters Request parameters. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["updateOrCreate"] = R["upsert"]; + + /** + * @ngdoc method + * @name lbServices.Tick#patchOrCreateWithWhere + * @methodOf lbServices.Tick + * + * @description + * + * Update an existing model instance or insert a new one into the data source based on the where criteria. + * + * @param {Object=} parameters Request parameters. + * + * - `where` – `{object=}` - Criteria to match model instances + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["patchOrCreateWithWhere"] = R["upsertWithWhere"]; + + /** + * @ngdoc method + * @name lbServices.Tick#update + * @methodOf lbServices.Tick + * + * @description + * + * Update instances of the model matched by {{where}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `where` – `{object=}` - Criteria to match model instances + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * Information related to the outcome of the operation + */ + R["update"] = R["updateAll"]; + + /** + * @ngdoc method + * @name lbServices.Tick#destroyById + * @methodOf lbServices.Tick + * + * @description + * + * Delete a model instance by {{id}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["destroyById"] = R["deleteById"]; + + /** + * @ngdoc method + * @name lbServices.Tick#removeById + * @methodOf lbServices.Tick + * + * @description + * + * Delete a model instance by {{id}} from the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Model id + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["removeById"] = R["deleteById"]; + + /** + * @ngdoc method + * @name lbServices.Tick#patchAttributes + * @methodOf lbServices.Tick + * + * @description + * + * Patch attributes for a model instance and persist it into the data source. + * + * @param {Object=} parameters Request parameters. + * + * - `id` – `{*}` - Tick id + * + * @param {Object} postData Request data. + * + * This method expects a subset of model properties as request parameters. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `Tick` object.) + * + */ + R["patchAttributes"] = R["prototype$updateAttributes"]; + + + /** + * @ngdoc property + * @name lbServices.Tick#modelName + * @propertyOf lbServices.Tick + * @description + * The name of the model represented by this $resource, + * i.e. `Tick`. + */ + R.modelName = "Tick"; + + + + return R; + }]); + + + module + .factory('LoopBackAuth', function() { + var props = ['accessTokenId', 'currentUserId', 'rememberMe']; + var propsPrefix = '$LoopBack$'; + + function LoopBackAuth() { + var self = this; + props.forEach(function(name) { + self[name] = load(name); + }); + this.currentUserData = null; + } + + LoopBackAuth.prototype.save = function() { + var self = this; + var storage = this.rememberMe ? localStorage : sessionStorage; + props.forEach(function(name) { + save(storage, name, self[name]); + }); + }; + + LoopBackAuth.prototype.setUser = function(accessTokenId, userId, userData) { + this.accessTokenId = accessTokenId; + this.currentUserId = userId; + this.currentUserData = userData; + }; + + LoopBackAuth.prototype.clearUser = function() { + this.accessTokenId = null; + this.currentUserId = null; + this.currentUserData = null; + }; + + LoopBackAuth.prototype.clearStorage = function() { + props.forEach(function(name) { + save(sessionStorage, name, null); + save(localStorage, name, null); + }); + }; + + return new LoopBackAuth(); + + // Note: LocalStorage converts the value to string + // We are using empty string as a marker for null/undefined values. + function save(storage, name, value) { + try { + var key = propsPrefix + name; + if (value == null) value = ''; + storage[key] = value; + } catch (err) { + console.log('Cannot access local/session storage:', err); + } + } + + function load(name) { + var key = propsPrefix + name; + return localStorage[key] || sessionStorage[key] || null; + } + }) + .config(['$httpProvider', function($httpProvider) { + $httpProvider.interceptors.push('LoopBackAuthRequestInterceptor'); + }]) + .factory('LoopBackAuthRequestInterceptor', ['$q', 'LoopBackAuth', + function($q, LoopBackAuth) { + return { + 'request': function(config) { + // filter out external requests + var host = getHost(config.url); + if (host && host !== urlBaseHost) { + return config; + } + + if (LoopBackAuth.accessTokenId) { + config.headers[authHeader] = LoopBackAuth.accessTokenId; + } else if (config.__isGetCurrentUser__) { + // Return a stub 401 error for User.getCurrent() when + // there is no user logged in + var res = { + body: { error: { status: 401 }}, + status: 401, + config: config, + headers: function() { return undefined; }, + }; + return $q.reject(res); + } + return config || $q.when(config); + }, + }; + }]) + + /** + * @ngdoc object + * @name lbServices.LoopBackResourceProvider + * @header lbServices.LoopBackResourceProvider + * @description + * Use `LoopBackResourceProvider` to change the global configuration + * settings used by all models. Note that the provider is available + * to Configuration Blocks only, see + * {@link https://docs.angularjs.org/guide/module#module-loading-dependencies Module Loading & Dependencies} + * for more details. + * + * ## Example + * + * ```js + * angular.module('app') + * .config(function(LoopBackResourceProvider) { + * LoopBackResourceProvider.setAuthHeader('X-Access-Token'); + * }); + * ``` + */ + .provider('LoopBackResource', function LoopBackResourceProvider() { + /** + * @ngdoc method + * @name lbServices.LoopBackResourceProvider#setAuthHeader + * @methodOf lbServices.LoopBackResourceProvider + * @param {string} header The header name to use, e.g. `X-Access-Token` + * @description + * Configure the REST transport to use a different header for sending + * the authentication token. It is sent in the `Authorization` header + * by default. + */ + this.setAuthHeader = function(header) { + authHeader = header; + }; + + /** + * @ngdoc method + * @name lbServices.LoopBackResourceProvider#getAuthHeader + * @methodOf lbServices.LoopBackResourceProvider + * @description + * Get the header name that is used for sending the authentication token. + */ + this.getAuthHeader = function() { + return authHeader; + }; + + /** + * @ngdoc method + * @name lbServices.LoopBackResourceProvider#setUrlBase + * @methodOf lbServices.LoopBackResourceProvider + * @param {string} url The URL to use, e.g. `/api` or `//example.com/api`. + * @description + * Change the URL of the REST API server. By default, the URL provided + * to the code generator (`lb-ng` or `grunt-loopback-sdk-angular`) is used. + */ + this.setUrlBase = function(url) { + urlBase = url; + urlBaseHost = getHost(urlBase) || location.host; + }; + + /** + * @ngdoc method + * @name lbServices.LoopBackResourceProvider#getUrlBase + * @methodOf lbServices.LoopBackResourceProvider + * @description + * Get the URL of the REST API server. The URL provided + * to the code generator (`lb-ng` or `grunt-loopback-sdk-angular`) is used. + */ + this.getUrlBase = function() { + return urlBase; + }; + + this.$get = ['$resource', function($resource) { + var LoopBackResource = function(url, params, actions) { + var resource = $resource(url, params, actions); + + // Angular always calls POST on $save() + // This hack is based on + // http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/ + resource.prototype.$save = function(success, error) { + // Fortunately, LoopBack provides a convenient `upsert` method + // that exactly fits our needs. + var result = resource.upsert.call(this, {}, this, success, error); + return result.$promise || result; + }; + return resource; + }; + + LoopBackResource.getUrlBase = function() { + return urlBase; + }; + + LoopBackResource.getAuthHeader = function() { + return authHeader; + }; + + return LoopBackResource; + }]; + }); +})(window, window.angular); diff --git a/pool/shard000/JavaScript/0004232_fields-builder.js b/pool/shard000/JavaScript/0004232_fields-builder.js new file mode 100644 index 0000000000000000000000000000000000000000..6391dc554414cecb0c6f0c5170273c695c2666ea --- /dev/null +++ b/pool/shard000/JavaScript/0004232_fields-builder.js @@ -0,0 +1,109 @@ +module.exports = { + + template: require('./fields-builder.template.html'), + + props: [ + 'data', + 'config', + 'name', + 'fields', + 'fieldtypes', + 'root' + ], + + data: function() { + return { + selectedField: null + } + }, + + computed: { + + hasFields: function() { + return this.fields && this.fields.length; + }, + + selectedFieldConfig: function() { + if (this.selectedField === null) { + return []; + } + + var type = this.fields[this.selectedField].type; + var fieldtype = _.findWhere(this.fieldtypes, { name: type }); + return fieldtype.config; + } + + }, + + methods: { + + addField: function(fieldtype) { + var fieldsLength = this.fields.length || 0; + var count = fieldsLength + 1; + + var tmp = _.findWhere(this.fieldtypes, { name: fieldtype }); + var field = $.extend({}, tmp); + + field.type = field.name; + field.name = 'field_' + count; + field.display = 'Field ' + count; + field.instructions = null; + field.isNew = true; + delete field.config; + delete field.label; + delete field.canBeValidated; + delete field.canBeLocalized; + delete field.canHaveDefault; + + if (field.type === 'title') { + // Title field goes first with predefined values + field.display = translate('cp.title'); + field.name = 'title'; + this.fields.unshift(field); + this.selectedField = 0; + } else { + // Other fields go to the end. + this.fields.push(field); + this.selectedField = count - 1; + } + }, + + selectField: function(index) { + this.selectedField = index; + this.tab = 'edit'; + }, + + deleteField: function(index) { + this.selectedField = null; + this.fields.splice(index, 1); + }, + + sortFields: function(from, to) { + this.fields.splice(to, 0, this.fields.splice(from, 1)[0]); + this.ensureTitleIsFirst(); + }, + + ensureTitleIsFirst: function() { + var self = this; + var title = _.indexOf(self.fields, _.findWhere(self.fields, { name: 'title' })); + + // If there's no title, do nothing. + if (title === -1) { + return; + } + + // If title isn't first, make it so. + if (this.fields[0].name !== 'title') { + this.sortFields(title, 0); + } + } + + }, + + ready: function() { + this.fields = this.fields || []; + this.root = Boolean(this.root || false); + this.ensureTitleIsFirst(); + } + +}; diff --git a/pool/shard000/JavaScript/0004235_preferences.model.js b/pool/shard000/JavaScript/0004235_preferences.model.js new file mode 100644 index 0000000000000000000000000000000000000000..1c1b11fdbbc75c53c9098dc23eda1be7399034e0 --- /dev/null +++ b/pool/shard000/JavaScript/0004235_preferences.model.js @@ -0,0 +1,200 @@ +'use strict'; + +const _ = require('lodash'); +const Config = require('../../config'); +const Chalk = require('chalk'); +const Boom = require('boom'); +const Joi = require('joi'); +const authStrategy = Config.get('/restHapiConfig/authStrategy'); +const defaultPreference = Config.get('/preferences'); + +module.exports = function(mongoose) { + var modelName = "preferences"; + var Types = mongoose.Schema.Types; + var Schema = new mongoose.Schema({ + user: { + type: Types.ObjectId, + ref: "user", + unique: true + }, + preferences: { + type: Types.Mixed, + required: true + } + }, { collection: modelName }); + + Schema.statics = { + collectionName: modelName, + routeOptions: { + associations: { + user: { + type: "ONE_ONE", + model: "user" + } + }, + create: { + post: function(payload, request, Log) { + let query = { + _id: mongoose.Types.ObjectId(payload.user) + } + let update = { + preferences: payload._id + } + return mongoose.model('user').update(query, update) + .then(_ => payload) + .catch(error => { + Log.error(error); + throw 'Error while connecting user to preferences!'; + }); + } + }, + delete: { + pre: function(payload, request, Log) { + throw 'delete request is not allowed!'; + } + }, + extraEndpoints: [ + function(server, model, options, Log) { + Log = Log.bind(Chalk.magenta("User profile Preferences")); + + const HeadersValidation = Joi.object({ + 'authorization': Joi.string().required() + }).options({ allowUnknown: true }); + + const preferenceProfileHandler = function(request, reply) { + if (request.auth.credentials.user.preferences) { + mongoose.model('preferences').findOne({ _id: request.auth.credentials.user.preferences }) + .then(result => reply(result)) + .catch(error => { + return reply(Boom.internal('Error while access database.')); + }); + } else { + return reply({ + "_id": null, + "user": request.auth.credentials.user._id, + "preferences": defaultPreference, + "isDeleted": false + }) + } + }; + + server.route({ + method: 'GET', + path: '/preferences/profilepreferences', + config: { + handler: preferenceProfileHandler, + auth: authStrategy, + description: 'User profile preferences.', + tags: ['api', 'Profile', 'profile preferences'], + validate: { + headers: HeadersValidation + }, + plugins: { + 'hapi-swagger': { + responseMessages: [ + { code: 200, message: 'Success' }, + { code: 400, message: 'Bad Request' }, + { code: 404, message: 'Not Found' }, + { code: 500, message: 'Internal Server Error' } + ] + } + } + } + }); + }, + function(server, model, options, Log) { + Log = Log.bind(Chalk.magenta("User profile Preferences ")); + + const HeadersValidation = Joi.object({ + 'authorization': Joi.string().required() + }).options({ allowUnknown: true }); + + //check if preference is present in db then update else create new one + function checkAndUpdatePreference(preferenceId, user, preferences) { + + return new Promise((resolve, reject) => { + let query = { _id: mongoose.Types.ObjectId(preferenceId) }; + mongoose.model('preferences').findOne(query) + .then(result => { + if (result) { + result.preferences = preferences + return result.save() + } else { + let create = {}; + create.preferences = preferences; + create.user = user; + return mongoose.model('preferences').create(create) + } + }) + .then(result => { + resolve(result) + }) + .catch(error => reject(error)) + }); + } + + const preferenceProfileSaveHandler = function(request, reply) { + + mongoose.model('user').findOne({ _id: request.auth.credentials.user._id }, "preferences") + .then(result => result.preferences || null) + .then(preferencesId => { + if (preferencesId) { + return checkAndUpdatePreference(preferencesId, request.auth.credentials.user._id, request.payload.preferences) + } else { + let create = {}; + create.preferences = request.payload.preferences; + create.user = request.auth.credentials.user._id; + return mongoose.model('preferences').create(create) + } + }) + .then(result => { + if (result._id) { + let query = { _id: mongoose.Types.ObjectId(request.auth.credentials.user._id) }; + let update = { preferences: result._id } + return mongoose.model('user').update(query, { $set: update }) + } else { + return result; + } + }) + .then(result => { + return reply({ message: "success", error: 0 }) + }) + .catch(error => { + Log.error(error); + return reply(Boom.internal("Error while saving the preferences!")); + }) + }; + + server.route({ + method: 'PUT', + path: '/preferences/save', + config: { + handler: preferenceProfileSaveHandler, + auth: authStrategy, + description: 'Save User profile preferences.', + tags: ['api', 'Profile', 'profile preferences'], + validate: { + headers: HeadersValidation, + payload: { + preferences: Joi.object().required() + } + }, + plugins: { + 'hapi-swagger': { + responseMessages: [ + { code: 200, message: 'Success' }, + { code: 400, message: 'Bad Request' }, + { code: 404, message: 'Not Found' }, + { code: 500, message: 'Internal Server Error' } + ] + } + } + } + }); + } + ] + } + }; + + return Schema; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004236_index.test.js b/pool/shard000/JavaScript/0004236_index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..558840d8a5a07513e445bfc1c422ebd30fea8b12 --- /dev/null +++ b/pool/shard000/JavaScript/0004236_index.test.js @@ -0,0 +1,37 @@ +/** + * + * Tests for Review + * + * @see https://github.com/react-boilerplate/react-boilerplate/tree/master/docs/testing + * + */ + +import React from 'react'; +import { render } from 'react-testing-library'; +// import 'jest-dom/extend-expect'; // add some helpful assertions + +import Review from '../index'; + +describe('', () => { + it('Expect to not log errors in console', () => { + const spy = jest.spyOn(global.console, 'error'); + render(); + expect(spy).not.toHaveBeenCalled(); + }); + + it('Expect to have additional unit tests specified', () => { + expect(true).toEqual(false); + }); + + /** + * Unskip this test to use it + * + * @see {@link https://jestjs.io/docs/en/api#testskipname-fn} + */ + it.skip('Should render and match the snapshot', () => { + const { + container: { firstChild }, + } = render(); + expect(firstChild).toMatchSnapshot(); + }); +}); diff --git a/pool/shard000/JavaScript/0004239_searchDrawDeck.spec.js b/pool/shard000/JavaScript/0004239_searchDrawDeck.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d7b500d382a6a5b2bc51c26cc089434fe8926b93 --- /dev/null +++ b/pool/shard000/JavaScript/0004239_searchDrawDeck.spec.js @@ -0,0 +1,77 @@ +/*global describe, it, beforeEach, expect, jasmine*/ +/* eslint camelcase: 0 */ + +const _ = require('underscore'); +const Player = require('../../../server/game/player.js'); + +describe('the Player', () => { + var game = jasmine.createSpyObj('game', ['getOtherPlayer', 'playerDecked']); + + var player = new Player('1', 'Player 1', true, game); + var drawDeck = _([ + { name: 'foo' }, + { name: 'bar' }, + { name: 'baz' }, + { name: 'ball' } + ]); + + beforeEach(() => { + player.deck = drawDeck; + player.initialise(); + + player.drawDeck = drawDeck; + }); + + describe('the searchDrawDeck() function', () => { + describe('when no limit is passed', () => { + it('should search all cards in the deck', () => { + var cards = player.searchDrawDeck(() => { + return true; + }); + expect(cards.length).toBe(drawDeck.size()); + }); + + it('should filter the results using the predicate', () => { + var cards = player.searchDrawDeck((card) => { + return card.name === 'bar'; + }); + + expect(cards.length).toBe(1); + }); + }); + + describe('when a limit is passed but no predicate', () => { + describe('when the limit is positive', () => { + it('should return from the top of the deck', () => { + var cards = player.searchDrawDeck(2); + + expect(cards.length).toBe(2); + expect(cards[0].name).toBe('foo'); + expect(cards[1].name).toBe('bar'); + }); + }); + + describe('when the limit is negative', () => { + it('should return from the bottom of the deck', () => { + var cards = player.searchDrawDeck(-2); + + expect(cards.length).toBe(2); + expect(cards[0].name).toBe('baz'); + expect(cards[1].name).toBe('ball'); + }); + }); + }); + + describe('when both a limit and a predicate are passed', () => { + it('should limit and filter', () => { + var cards = player.searchDrawDeck(3, (card) => { + return card.name[0] === 'b'; + }); + + expect(cards.length).toBe(2); + expect(cards[0].name).toBe('bar'); + expect(cards[1].name).toBe('baz'); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004248_Home.test.js b/pool/shard000/JavaScript/0004248_Home.test.js new file mode 100644 index 0000000000000000000000000000000000000000..98ed69c88b55a87ea02e2ed31da396cc8d68be60 --- /dev/null +++ b/pool/shard000/JavaScript/0004248_Home.test.js @@ -0,0 +1,114 @@ +/* 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/. */ + +// @flow +import * as React from 'react'; +import { Provider } from 'react-redux'; + +import { render } from 'firefox-profiler/test/fixtures/testing-library'; +import { Home } from '../../components/app/Home'; +import createStore from '../../app-logic/create-store'; +import { mockWebChannel } from '../fixtures/mocks/web-channel'; +import { fireFullClick } from '../fixtures/utils'; + +// ListOfPublishedProfiles depends on IDB and renders asynchronously, so we'll +// just test we want to render it, but otherwise test it more fully in a +// separate test file. +jest.mock('../../components/app/ListOfPublishedProfiles', () => ({ + ListOfPublishedProfiles: 'list-of-published-profiles', +})); + +// Provide a mechanism to overwrite the navigator.userAgent, which can't be set. +const FIREFOX = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0'; +const SAFARI = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8'; +let userAgent; + +// Flow doesn't understand Object.defineProperty. Use the "any" type to use it anyway. +(Object.defineProperty: any)(window.navigator, 'userAgent', { + get: () => userAgent, +}); + +describe('app/Home', function () { + function setup(userAgentToConfigure: string) { + userAgent = userAgentToConfigure; + const renderResults = render( + + + + ); + + return { ...renderResults }; + } + + it('renders a button to enable the popup in Firefox', () => { + const { container } = setup(FIREFOX); + expect(container.firstChild).toMatchSnapshot(); + }); + + it('renders the information screen for other browsers', () => { + const { container } = setup(SAFARI); + expect(container.firstChild).toMatchSnapshot(); + }); + + // This test's assertions are that it can find elements through getByTestId. + // eslint-disable-next-line jest/expect-expect + it('will switch to recording instructions when enabling the popup', async () => { + const { triggerResponse, getLastRequestId } = mockWebChannel(); + const { findByTestId, getByText } = setup(FIREFOX); + + // Respond back from the browser that the menu button is not yet enabled. + triggerResponse({ + type: 'SUCCESS_RESPONSE', + requestId: getLastRequestId(), + response: { + menuButtonIsEnabled: false, + }, + }); + await findByTestId('home-enable-popup-instructions'); + + fireFullClick(getByText('Enable \u2068Firefox Profiler\u2069 Menu Button')); + + // Respond back from the browser that the menu button was enabled. + triggerResponse({ + type: 'SUCCESS_RESPONSE', + requestId: getLastRequestId(), + response: undefined, + }); + await findByTestId('home-record-instructions'); + }); + + it('renders an error if the WebChannel is not available', async () => { + // This simulates what happens if the profiler is run from a host which + // is not the configured profiler base-url, or in an old Firefox version (<76) + // which has WebChannels but no profiler WebChannel. + + const { listeners, triggerResponse } = mockWebChannel(); + + // No one has asked anything to the WebChannel. + expect(listeners).toHaveLength(0); + + const { findByText } = setup(FIREFOX); + + // There is an outstanding question to the WebChannel + expect(listeners.length).toBeGreaterThan(0); + + // Respond from the browser that the WebChannel does not exist. + jest.spyOn(console, 'error').mockImplementation(() => {}); + triggerResponse({ + errno: 2, // ERRNO_NO_SUCH_CHANNEL + error: 'No such channel', + }); + expect(console.error).toHaveBeenCalled(); + + // The UI should update to include a note about the WebChannel being unavailable, + // which is an async handler of the WebChannel message. + const webChannelUnavailableMessage = await findByText( + /This profiler instance was unable to connect to the WebChannel/ + ); + + expect(webChannelUnavailableMessage).toMatchSnapshot(); + }); +}); diff --git a/pool/shard000/JavaScript/0004249_ArticleDetailView.js b/pool/shard000/JavaScript/0004249_ArticleDetailView.js new file mode 100644 index 0000000000000000000000000000000000000000..df2a1353282482682993b0522ae5a8f0a7953f66 --- /dev/null +++ b/pool/shard000/JavaScript/0004249_ArticleDetailView.js @@ -0,0 +1,138 @@ +function ArticleDetailView(args) { + var self = Ti.UI.createWindow(args); + //need to pass articleID to to instantiate + var articleID = args.articleID; + + //socket business + var io = require('socket/socket.io-titanium'); + var socket = io.connect('http://10.1.212.94:8080'); + + var chat = socket.of('/chat'); + chat.emit('join', { + channelId: articleID + }); + chat.emit('post', 'some lolz matey!!', 'user' + Ti.App.uid); + + + var ChatPopover = require('ui/common/ChatPopover'); + var SharePopover = require('ui/common/SharePopover'); + + var chatPopover = new ChatPopover(); + var sharePopover = new SharePopover(); + + var button = Titanium.UI.createButton({ + title: 'Toggle Menu', + top: 10, + width: 100, + height: 50, + left: 10 + }); + button.addEventListener('click',function(e) + { + self.fireEvent('toggle'); + }); + + self.add(button); + + var chatButton = Titanium.UI.createButton({ + title: 'Chat', + top: 10, + width: 100, + height: 50, + left: 300 + }); + + self.add(chatButton); + + chatButton.addEventListener('click', function(e){ + chatPopover.show({view: chatButton}); + }); + + var shareButton = Titanium.UI.createButton({ + title: 'Share', + top: 10, + width: 100, + height: 50, + left: 450 + }); + + self.add(shareButton); + + shareButton.addEventListener('click', function(e){ + sharePopover.show({view: shareButton}); + }); + + var titleLabel = Titanium.UI.createLabel({ + color:'#000', + height:'auto', + width:'auto', + top:150, + left: 50, + text:'', + textAlign:'center', + font:{fontSize:20,fontWeight:'bold'}, + shadowColor:'#eee',shadowOffset:{x:0,y:1} + }); + + self.add(titleLabel); + + var mainImage = Ti.UI.createImageView({ + image:'http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif', + top: 200, + left: 80 + // width: auto, + // height:auto + }); + self.add(mainImage); + + var articleBody = Titanium.UI.createLabel({ + text:'', + top:700 + }); + self.add(articleBody); + + + self.updateLabel = function(txt) { + titleLabel.text = txt; + chat.emit('join', { + channelId: txt + }); + chat.emit('post', 'state name', 'user' + Ti.App.uid); + } + + self.updateImage = function(img){ + mainImage.image = img; + } + self.updateBody= function(htmlCode){ + var clean = htmlCode.replace( /<[^>]+>/g, '' ); + articleBody.text = clean; + + } + + var textField = Ti.UI.createTextField({ + borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED, + color: '#336699', + top: 700, left: 20, + width: 250, height: 60 + }); + + //self.add(textField); + + var sendChatButton = Titanium.UI.createButton({ + title: 'Send Chat', + top: 770, + width: 100, + height: 50, + left: 30 + }); + + //self.add(sendChatButton); + + sendChatButton.addEventListener('click', function(e){ + chat.emit('post', textField.value, 'user' + Ti.App.uid); + }); + + return self; +} + +module.exports = ArticleDetailView; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004250_plan.test.js b/pool/shard000/JavaScript/0004250_plan.test.js new file mode 100644 index 0000000000000000000000000000000000000000..befe7d785b711e069c7d091f18361e527d94859f --- /dev/null +++ b/pool/shard000/JavaScript/0004250_plan.test.js @@ -0,0 +1,60 @@ +import assert from 'assert'; +import { Recurly } from '../../lib/recurly'; +import { initRecurly, apiTest } from './support/helpers'; + +apiTest(function (requestMethod) { + describe('Recurly.plan (' + requestMethod + ')', function () { + const valid = 'basic'; + const invalid = 'invalid'; + + beforeEach(function () { + this.recurly = initRecurly({ cors: requestMethod === 'cors' }); + }); + + it('requires a callback', function () { + const { recurly } = this; + assert.throws(() => recurly.plan(valid), 'Missing callback'); + }); + + it('requires a plan code', function () { + const { recurly } = this; + assert.throws(() => recurly.plan(), 'Missing plan code'); + }); + + it('requires Recurly.configure', function () { + try { + const recurly = new Recurly(); + recurly.plan(valid, () => {}); + } catch (e) { + assert(~e.message.indexOf('configure')); + } + }); + + describe('when given an invalid plan', function () { + it('produces an error', function (done) { + const { recurly } = this; + recurly.plan(invalid, function (err, plan) { + assert(err); + assert(!plan); + done(); + }); + }); + }); + + describe('when given a valid plan', function () { + it('yields a plan', function (done) { + const { recurly } = this; + recurly.plan(valid, function (err, plan) { + assert(!err); + assert(plan); + assert(plan.code === 'basic'); + assert(plan.name === 'Basic'); + assert(plan.period); + assert(plan.price); + assert(typeof plan.tax_exempt === 'boolean'); + done(); + }); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004252_admin.js b/pool/shard000/JavaScript/0004252_admin.js new file mode 100644 index 0000000000000000000000000000000000000000..9bfb10661c67f2309cac61c828cd446a219ac095 --- /dev/null +++ b/pool/shard000/JavaScript/0004252_admin.js @@ -0,0 +1,251 @@ +/** + * Oprecx Object + * + * @type O @exp;window@pro;O + */ +var O = window.O || {}; + +///////////////////////////////////////////////// +// Oprecx simple message +(function(O, window){ + var msg = window.msg || {}; + O.t = function(defaultMsg, arg){ + var str = msg[defaultMsg] || defaultMsg; + + if (arg) { + return str.replace(/\{[^}]+\}/, function(m){ + return arg[m] || m; + }); + } + else { + return str; + } + + }; +})(O, window); + + + +///////////////////////////////////////////////// +// Oprecx simple Notification +(function(O, $) { + if (O.notify) return; + + var counter = 100; + var $container; + + function hideNotification(id) { + $('#' + id).fadeOut(); + } + + O.notify = function(type) { + var id = 'o-notification-' + counter++; + var className = 'alert alert-block o-notification-item'; + if (type) className += ' alert-' + type; + var $elm = $('
'); + + if (!$container) { + $container = $('#o-notification-container:first'); + if ($container.length < 1) { + $container = $('
'); + $('body').append($container); + $container.css ({ + position: 'absolute', + right: '30px', + top: '50px', + 'max-width': '400px' + }); + } + } + $elm.css({display: 'none'}); + $container.append($elm); + + var hideTimer = setTimeout(function(){hideNotification(id);}, 5000); + $elm.mousemove(function(){ + clearTimeout(hideTimer); + }); + + $elm.mouseout(function(){ + hideTimer = setTimeout(function(){hideNotification(id);}, 3000); + }); + + + return { + id: id, + hide: function(){ + hideNotification(id); + return this; + }, + setHtml: function(html) { + $elm.html('' + html); + return this; + }, + show: function(){ + $elm.fadeIn(); + return this; + } + }; + }; + + O.notify.hide = hideNotification; + +})(O, jQuery); + + + + + +///////////////////////////////////////////////// +// Oprecx simple Undo +(function(O){ + if (O.undo) return; + + var i = 0; + + /** + * @type {Function} + */ + var undo = O.undo = function(id, arg) { + undo[id](arg); + undo[id] = null; + }; + + undo.timeout = {}; + + /** + * @param func {Function} + * @param timeout {Number} + * @returns {string} + */ + undo.add = function(func, timeout) { + var name = 'f' + i++; + undo[name] = func; + if (timeout) { + undo.timeout[name] = timeout; + } + return name; + }; + +})(O); + + + + + +/////////////////////////////////////////////////////////////////////////// +///// handler for share dialog +jQuery(function($){ + var win = window; + $("#share-link-url").on('mouseenter', function() { + $(this).select(); + }); + $('#shareOrgLink .share-link').click(function(){ + var + w = 600, h = 350, + winW = win.outerWidth || win.innerWidth || win.screen.availWidth || w + 50, + winH = win.outerHeight || win.innerHeight || win.screen.availHeight || h + 20, + winX = win.screenX || win.screenLeft || win.screen.availLeft || 0, + winY = win.screenY || win.screenTop || win.screen.availLeft || 0, + + x = ((winW - w) >> 1) + winX, y = ((winH - h) >> 1) + winY, + arg = 'menubar=0,location=0,toolbar=0,fullscreen=0,left=' + x + ',top=' + y + ',width=' + w + ',height=' + h, + newWin = win.open('about:blank', null, arg); + + if (newWin){ + newWin.location.replace(this.href); + return false; + } + else return true; + }); +}); + + +/////////////////////////////////////////////////////////////////////////// +///// this is for sort-form + +jQuery(function($){ + var msg = window.msg || {}; + + var modifiedFormCount = 0, + modifiedIndex = [], + //modifiedMessage = msg['sort-form-mofied'] || 'List have been modified', + saveButtons = []; + + function setModified(i, modified){ + if (modifiedIndex[i] && !modified) { + modifiedFormCount--; + } + else if (!modifiedIndex[i] && modified) { + modifiedFormCount++; + } + saveButtons[i].attr('disabled', !modified); + modifiedIndex[i] = modified; + } + + window.onbeforeunload = function() { + //if (modifiedFormCount > 0) return modifiedMessage; + }; + $('.oprecx-sort-form').each(function(i, elm){ + var $elm = $(elm); + var $list = $elm.find('.oprecx-sort-list'); + saveButtons[i] = $elm.find('.save-button'); + elm.setModified = function(m) { + setModified(this.getAttribute('data-sort-id'), m); + }; + + $elm.attr('data-sort-id', i); + $elm.submit(function(){ + var elm_id = $(this).attr('data-sort-id'); + var saveButton = saveButtons[elm_id]; + + var saveText = saveButton.html(); + saveButton.attr('disabled', true); + saveButton.html('Loading...'); + $(this).ajaxSubmit({ + dataType : 'json', + success : function(data) { + saveButton.html(saveText); + setModified(i, false); + } + }); + + return false; + }); + + $list.attr('data-sort-id', i); + $list.sortable({ + handle: '.handler', + update: function(e, ui) { + setModified($(this).attr('data-sort-id'), true); + } + }); + + $elm.on('click', '.action-delete', function(e){ + //if (confirm('Are you sure?')) { + + var $target = $('#' + e.currentTarget.getAttribute('data-target-id')); + var $parent = $target.parent(); + + //$target.animate({overflow:'hidden', height:'1px', opacity:0}, 500); + //setTimeout(function(){$target.remove();}, 600); + $target.remove(); + var notification = O.notify(); + + elm.setModified(true); + //var $notifElm = $elm.find('.notifications:first'); + var undoId = O.undo.add(function(){ + $parent.append($target); + //$target.animate({height: '38px', opacity: 1}) + notification.hide(); + }); + + var msg = O.t('You just delete an item from the list, {undo}', { + '{undo}' : '' + O.t('Undo') + '' + }); + notification.setHtml(msg).show(); + + // dont follow link + return false; + }); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004255_app.js b/pool/shard000/JavaScript/0004255_app.js new file mode 100644 index 0000000000000000000000000000000000000000..3bfee99b107bee79f3030dcd04e627e482f3018f --- /dev/null +++ b/pool/shard000/JavaScript/0004255_app.js @@ -0,0 +1,11 @@ +var express = require('express'); +var app = express(); +app.use(express.static(__dirname)); +app.listen(process.env.PORT || 3000); +app.get('/', function(request, response) { + response.redirect('/app/views'); +}); + +app.get('/constants.js', function(request,response) { + response.send("angular.module('PoliticiansLibrary').constant('plConfig', {apiKey: '"+process.env.apiKey+"'});") +}) diff --git a/pool/shard000/JavaScript/0004259_transition.js b/pool/shard000/JavaScript/0004259_transition.js new file mode 100644 index 0000000000000000000000000000000000000000..bd68689641b46bd50c9c8c20ece569f16b8488f2 --- /dev/null +++ b/pool/shard000/JavaScript/0004259_transition.js @@ -0,0 +1,66 @@ +/* + * Copyright by Jörg Wrase - www.Computer-Und-Sound.de + * Hire me! coder@cusp.de + * + * LastModified: 2017.07.23 at 04:20 MESZ + */ + +/* ======================================================================== + * Bootstrap: transition.js v3.3.7 + * http://getbootstrap.com/javascript/#transitions + * ======================================================================== + * Copyright 2011-2016 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) + // ============================================================ + + function transitionEnd() { + var el = document.createElement('bootstrap') + + var transEndEventNames = { + WebkitTransition : 'webkitTransitionEnd', + MozTransition : 'transitionend', + OTransition : 'oTransitionEnd otransitionend', + transition : 'transitionend' + } + + for (var name in transEndEventNames) { + if (el.style[name] !== undefined) { + return { end: transEndEventNames[name] } + } + } + + return false // explicit for ie8 ( ._.) + } + + // http://blog.alexmaccaw.com/css-transitions + $.fn.emulateTransitionEnd = function (duration) { + var called = false + var $el = this + $(this).one('bsTransitionEnd', function () { called = true }) + var callback = function () { if (!called) $($el).trigger($.support.transition.end) } + setTimeout(callback, duration) + return this + } + + $(function () { + $.support.transition = transitionEnd() + + if (!$.support.transition) return + + $.event.special.bsTransitionEnd = { + bindType: $.support.transition.end, + delegateType: $.support.transition.end, + handle: function (e) { + if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) + } + } + }) + +}(jQuery); diff --git a/pool/shard000/JavaScript/0004260_CBGSliceSegment.js b/pool/shard000/JavaScript/0004260_CBGSliceSegment.js new file mode 100644 index 0000000000000000000000000000000000000000..4becc56eba1ff466e66305c9298cf13019b49262 --- /dev/null +++ b/pool/shard000/JavaScript/0004260_CBGSliceSegment.js @@ -0,0 +1,97 @@ +/* + * == BSD2 LICENSE == + * Copyright (c) 2017, Tidepool Project + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the associated License, which is identical to the BSD 2-Clause + * License as published by the Open Source Initiative at opensource.org. + * + * 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 License for more details. + * + * You should have received a copy of the License along with this program; if + * not, you can obtain one from Tidepool Project at tidepool.org. + * == BSD2 LICENSE == + */ + +import PropTypes from 'prop-types'; +import React, { PureComponent } from 'react'; + +export class CBGSliceSegment extends PureComponent { + static propTypes = { + classes: PropTypes.string.isRequired, + datum: PropTypes.shape({ + id: PropTypes.string.isRequired, + }), + focusSlice: PropTypes.func.isRequired, + interpolated: PropTypes.shape({ + key: PropTypes.string.isRequired, + style: PropTypes.object.isRequired, + }), + positionData: PropTypes.shape({ + left: PropTypes.number.isRequired, + tooltipLeft: PropTypes.bool.isRequired, + yPositions: PropTypes.shape({ + firstQuartile: PropTypes.number.isRequired, + max: PropTypes.number.isRequired, + median: PropTypes.number.isRequired, + min: PropTypes.number.isRequired, + ninetiethQuantile: PropTypes.number.isRequired, + tenthQuantile: PropTypes.number.isRequired, + thirdQuartile: PropTypes.number.isRequired, + topMargin: PropTypes.number.isRequired, + }).isRequired, + }), + segment: PropTypes.shape({ + height: PropTypes.string.isRequired, + heightKeys: PropTypes.arrayOf(PropTypes.string).isRequired, + y: PropTypes.string.isRequired, + }), + unfocusSlice: PropTypes.func.isRequired, + width: PropTypes.number.isRequired, + x: PropTypes.number.isRequired, + } + + constructor(props) { + super(props); + + this.handleMouseOut = this.handleMouseOut.bind(this); + this.handleMouseOver = this.handleMouseOver.bind(this); + } + + handleMouseOut(e) { + // we don't want to unfocus the slice if the user just rolled over a cbg inside it + if (e.relatedTarget && e.relatedTarget.id.search('cbgCircle') !== -1) { + return; + } + this.props.unfocusSlice(); + } + + handleMouseOver() { + const { + datum, focusSlice, positionData, segment: { heightKeys: focusedKeys }, + } = this.props; + focusSlice(datum, positionData, focusedKeys); + } + + render() { + const { classes, datum, interpolated: { key, style }, segment, width, x } = this.props; + return ( + + ); + } +} + +export default CBGSliceSegment; diff --git a/pool/shard000/JavaScript/0004262_sign.js b/pool/shard000/JavaScript/0004262_sign.js new file mode 100644 index 0000000000000000000000000000000000000000..75a6d0f598930bf11f95e0a33794496b502ee8e0 --- /dev/null +++ b/pool/shard000/JavaScript/0004262_sign.js @@ -0,0 +1,116 @@ +/* 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/. */ +"use strict"; + +var _ = require("lodash"); +var getID = require("jetpack-id"); +var tmp = require("tmp"); +var nodefn = require("when/node"); +var when = require("when"); + +var DefaultAMOClient = require("./amo-client").Client; +var cmd = require("./cmd"); +var utils = require("./utils"); +var logger = utils.console; +var xpi = require("./xpi"); + + +function sign (program, options, config) { + config = _.assign({ + createXPI: xpi, + getManifest: utils.getManifest, + systemProcess: process, + AMOClient: DefaultAMOClient, + }, config); + + return when.promise(function(resolve, reject) { + var missingOptions = []; + var toCheck = [ + {value: options.apiKey, flag: '--api-key'}, + {value: options.apiSecret, flag: '--api-secret'}, + ]; + toCheck.forEach(function(opt) { + if (!opt.value) { + missingOptions.push(opt.flag); + } + }); + if (missingOptions.length) { + console.error(); + missingOptions.forEach(function(flag) { + console.error(" error: missing required option `%s'", flag); + }); + console.error(); + return reject(); + } + cmd.validateProgram(program); + + resolve(config.getManifest({ + addonDir: program.addonDir, + xpiPath: options.xpi, + })); + + }).then(function (manifest) { + var xpiConfig = { + manifest: manifest, + }; + if (options.xpi) { + logger.log("Signing XPI: " + options.xpi); + return _.assign(xpiConfig, {xpiPath: options.xpi}); + } else { + var createTmpDir = nodefn.lift(tmp.dir); + return createTmpDir({ + prefix: 'tmp-unsigned-xpi-', + unsafeCleanup: true, + }) + .then(function(tmpResult) { + var tmpDir = tmpResult[0]; + var removeTmpDir = tmpResult[1]; + // Merge the program and sub-command options. + var xpiOptions = _.assign({}, program, options, { + xpiPath: tmpDir, + }); + return config.createXPI(manifest, xpiOptions) + .then(function(xpiPath) { + logger.log("Created XPI for signing: " + xpiPath); + return _.assign(xpiConfig, { + xpiPath: xpiPath, + cleanUp: removeTmpDir, + }); + }); + }); + } + }).then(function (xpiConfig) { + + var client = new config.AMOClient({ + apiKey: options.apiKey, + apiSecret: options.apiSecret, + apiUrlPrefix: options.apiUrlPrefix, + debugLogging: program.verbose, + }); + return client.sign({ + xpiPath: xpiConfig.xpiPath, + guid: getID(xpiConfig.manifest), + version: xpiConfig.manifest.version, + }).then(function(result) { + if (typeof xpiConfig.cleanUp !== 'undefined') { + client.debug('cleaning up XPI temp directory'); + xpiConfig.cleanUp(); + } + return result; + }); + + }).then(function(result) { + logger.log(result.success ? 'SUCCESS' : 'FAIL'); + config.systemProcess.exit(result.success ? 0 : 1); + }, function (err) { + logger.error('FAIL'); + if (err) { + console.error(err.stack); + } + config.systemProcess.exit(1); + }); +} + + +module.exports = sign; diff --git a/pool/shard000/JavaScript/0004263_RepositoryProvider.spec.js b/pool/shard000/JavaScript/0004263_RepositoryProvider.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7da80eb18d5c63ca676243c6767df84e679727f4 --- /dev/null +++ b/pool/shard000/JavaScript/0004263_RepositoryProvider.spec.js @@ -0,0 +1,75 @@ +(function() { + 'use strict'; + describe('RepositoryProvider', function() { + var RepositoryProvider; + var $httpBackend; + + beforeEach(module('JsonApi')); + + beforeEach(module(function($provide) { + $provide.service('JsonApiCache', function() { + this.addItem = function() { + }; + this.setResponsibility = function() { + }; + }); + $provide.service('ItemProvider', function() { + this.create = function(resource) { + return { + id: resource.id, + type: resource.type + }; + }; + }); + })); + + beforeEach(inject(function($injector, _RepositoryProvider_) { + RepositoryProvider = _RepositoryProvider_; + $httpBackend = $injector.get('$httpBackend'); + })); + + it('should fetch an resource and create an item', function() { + $httpBackend.when('GET', '/books/1') + .respond(function() { + return [200, { + data: { + id: '1', + type: 'book' + } + }]; + }); + var repository = RepositoryProvider.create('/books/1'); + repository.fetch().then(function(item) { + expect(item.id).toEqual('1'); + expect(item.type).toEqual('book'); + }); + $httpBackend.flush(); + }); + + it('should fetch an resource and create a collection', function() { + $httpBackend.when('GET', '/books') + .respond(function() { + return [200, { + data: [ + { + id: '1', + type: 'book' + }, { + id: '2', + type: 'book' + } + ] + }]; + }); + var repository = RepositoryProvider.create('/books'); + repository.fetch().then(function(collection) { + expect(collection.length).toEqual(2); + expect(collection[0].id).toEqual('1'); + expect(collection[0].type).toEqual('book'); + expect(collection[1].id).toEqual('2'); + expect(collection[1].type).toEqual('book'); + }); + $httpBackend.flush(); + }); + }); +}()); diff --git a/pool/shard000/JavaScript/0004264_text.js b/pool/shard000/JavaScript/0004264_text.js new file mode 100644 index 0000000000000000000000000000000000000000..c8c1c7058bbefc28e230a0843a982ce0caac8d33 --- /dev/null +++ b/pool/shard000/JavaScript/0004264_text.js @@ -0,0 +1,27 @@ +import { avalon, inBrowser } from '../seed/core' + + +avalon.directive('text', { + delay: true, + init: function () { + + var node = this.node + if (node.isVoidTag) { + avalon.error('自闭合元素不能使用ms-text') + } + var child = { nodeName: '#text', nodeValue: this.getValue() } + node.children.splice(0, node.children.length, child) + if(inBrowser){ + avalon.clearHTML(node.dom) + node.dom.appendChild( avalon.vdom(child,'toDOM')) + } + this.node = child + var type = 'expr' + this.type = this.name = type + var directive = avalon.directives[type] + var me = this + this.callback = function (value) { + directive.update.call(me, me.node, value) + } + } +}) diff --git a/pool/shard000/JavaScript/0004266_control.js b/pool/shard000/JavaScript/0004266_control.js new file mode 100644 index 0000000000000000000000000000000000000000..6ead95b8d20a369b43dd343a2c6caf8898d2543f --- /dev/null +++ b/pool/shard000/JavaScript/0004266_control.js @@ -0,0 +1,70 @@ +function dataURLtoBlob(dataurl) { + let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], + bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); + while (n--) { + u8arr[n] = bstr.charCodeAt(n); + } + return new Blob([u8arr], { type: mime }); +} + +$(document).ready(function() { + $.getJSON('./config.json', function (json) { + CONFIG = json; + let URL = CONFIG.BASE_URL + ':' + CONFIG.WEBSOCKET_PORT + '/control'; + + $('#drawing-color').val(CONFIG.COLOR_SELECT[0]); // set default brush color + $('#drawing-line-width').val(CONFIG.SIZE_SELECT[0]); // set default brush size + $('#line-info').html($('#drawing-line-width').val()); + canvas = this.__canvas = new fabric.StaticCanvas('c'); + resizeCanvas(); + $("#canvas-contain").css({ 'max-height': 960 * (CONFIG.CANVAS_WIDTH / CONFIG.CANVAS_HEIGHT)}); + + bindSpacebar(); + + socket = openSocket(URL); + + $('#clear-canvas').click(function() { + canvas.clear(); + socket.send(JSON.stringify('{"objects":[],"background":""}')); + }); + + $('#save-png').click(function () { + let tempCanvas = new fabric.Canvas(); + tempCanvas.setWidth(CONFIG.CANVAS_WIDTH); + tempCanvas.setHeight(CONFIG.CANVAS_HEIGHT); + tempCanvas.loadFromJSON(getNewCanvasJSON(CONFIG.CANVAS_WIDTH)); + + let blob = dataURLtoBlob( tempCanvas.toDataURL({ format: 'png' })); + saveAs(blob, 'canvas.png'); + }); + $('#save-json').click(function () { + let blob = new Blob([getNewCanvasJSON(CONFIG.CANVAS_WIDTH)], { type: 'application/json; charset=utf-8' }); + saveAs(blob, 'canvas.json'); + }); + + $('#load-json').click(function () { + if ($('#load-json-text').val().length < 1) { + return; + } + let abort = false; + let oldWidth = canvas.getWidth(); + let oldHeight = canvas.getHeight(); + canvas.setWidth(CONFIG.CANVAS_WIDTH); + canvas.setHeight(CONFIG.CANVAS_HEIGHT); + try { + canvas.loadFromJSON($('#load-json-text').val(), canvas.renderAll.bind(canvas)); + } catch (e) { + abort = true; + canvas.setWidth(oldWidth); + canvas.setHeight(oldHeight); + alert('Invalid JSON, loading aborted.'); + } finally { + $('#load-json-text').val(''); + if (!abort) { + resizeCanvas(); + sendCanvas(); + } + } + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004267_revisions.js b/pool/shard000/JavaScript/0004267_revisions.js new file mode 100644 index 0000000000000000000000000000000000000000..1a9e04f92f3c64fa1ceba819893bd050034bd852 --- /dev/null +++ b/pool/shard000/JavaScript/0004267_revisions.js @@ -0,0 +1,130 @@ +'use strict' + +/* application modules */ +const ImmutableCoreModel = require('../lib/immutable-core-model') +const initTestEnv = require('./helpers/init-test-env') + +describe('immutable-core-model - revisions', function () { + + var mysql, redis, reset, session + + before(async function () { + [mysql, redis, reset, session] = await initTestEnv() + }) + + beforeEach(async function () { + await reset(mysql, redis) + }) + + after(async function () { + await mysql.close() + }) + + // will be pouplated in before + var foo1, foo2, foo3, globalFooModel, fooModel + + beforeEach(async function () { + // create initial model + globalFooModel = new ImmutableCoreModel({ + mysql: mysql, + name: 'foo', + redis: redis, + }) + // create local model with session + fooModel = globalFooModel.session(session) + // sync with mysql + await globalFooModel.sync() + // insert first record + foo1 = await fooModel.create({foo: 'foo'}) + // create revision + foo2 = await foo1.update({foo: 'bar'}) + // create another revision + foo3 = await foo2.update({foo: 'bam'}) + }) + + it('should only return the current revision of an object by default', async function () { + // get all foos + var foos = await fooModel.query({ + all: true + }) + // there should only be one record returned + assert.strictEqual(foos.length, 1) + // record should be current revision + assert.deepEqual(foos[0].data, foo3.data) + }) + + it('should only return all revisions if option set', async function () { + // get all foos + var foos = await fooModel.query({ + all: true, + allRevisions: true, + order: ['createTime'], + }) + // there should only be one record returned + assert.strictEqual(foos.length, 3) + // record should be current revision + assert.deepEqual(foos[0].data, foo1.data) + assert.deepEqual(foos[1].data, foo2.data) + assert.deepEqual(foos[2].data, foo3.data) + }) + + it('should return exact revision specified by id', async function () { + // query for old revision + var foo = await fooModel.query({ + limit: 1, + where: { + id: foo1.id + }, + }) + // record should match + assert.deepEqual(foo.data, foo1.data) + }) + + it('should return current revision when selecting by id with current', async function () { + // query for old revision + var foo = await fooModel.query({ + current: true, + limit: 1, + where: { + id: foo1.id + }, + }) + // record should match + assert.deepEqual(foo.data, foo3.data) + }) + + it('should set isCurrent false on old revision with isCurrent:true', async function () { + // query for old revision + var foo = await fooModel.query({ + isCurrent: true, + limit: 1, + where: { + id: foo1.id + }, + }) + // foo should not be current + assert.isFalse(foo.isCurrent) + }) + + it('should have current method that returns current instance', async function () { + // query for old revision + var foo = await fooModel.query({ + limit: 1, + where: { + id: foo1.id + }, + }) + // query for current revision + foo = await foo.current() + // foo should be current + assert.strictEqual(foo.id, foo3.id) + }) + + it('should select current instance', async function () { + // select current with old id + var foo = await fooModel.select.current.by.id(foo1.id) + // foo should be current + assert.strictEqual(foo.id, foo3.id) + }) + +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004269_less.js b/pool/shard000/JavaScript/0004269_less.js new file mode 100644 index 0000000000000000000000000000000000000000..86b932b68db0710c4aa6b37cbc677d9d742ad24c --- /dev/null +++ b/pool/shard000/JavaScript/0004269_less.js @@ -0,0 +1,16 @@ +var gulp = require('gulp') +var path = require('path') +var less = require('gulp-less') +var concat = require('gulp-concat') + +gulp.task('editor-less', function () { + gulp.src(['./editor/css/editor.less']) + .pipe(less({ + generateSourceMap: false, // default true + paths: [path.join(__dirname, 'less', 'includes')] + })) + .pipe(concat('editor.css')) + .pipe(gulp.dest('./editor/css/')) +}) + +gulp.task('less', ['editor-less']) diff --git a/pool/shard000/JavaScript/0004270_dashboard.js b/pool/shard000/JavaScript/0004270_dashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..61be89bd9ae81e023509e1ae5434dd2a5cc64a56 --- /dev/null +++ b/pool/shard000/JavaScript/0004270_dashboard.js @@ -0,0 +1,153 @@ +import $ from 'jquery'; +import Api from './../Api'; +import utils from './../utils'; +import EditModal from './edit-modal'; + +export default { + components: {editModal: EditModal}, + + directives: utils.directives, + + filters: {emoji: utils.emojiFilter}, + + transitions: {fade: utils.fadeTransition}, + + data() { + return { + init: false, + comments: [], + page: 1, + status: 'all', + pageId: null, + fetchRoute: null, + pagination: {}, + statusCount: {}, + loading: true, + redirected: false, + bulkAction: 0, + markedAll: false, + editComment: null, + statuses: ['all', 'pending', 'approved', 'spam', 'trash'] + }; + }, + + compiled () { + this.init = true; + this.fetch(); + }, + + methods: { + fetch () { + this.loading = true; + + Api.get({ + page: this.page, + status: this.status, + pageId: this.pageId + }) + .done((data) => this._fetchDone(data)); + }, + + _fetchDone (data) { + if (!data.comments.length && this.page > 1) { + this.page = this.redirected ? 1 : this.page - 1; + this.redirected = true; + return this.fetch(); + } + + data.comments.forEach((comment) => comment.mark = false); + + this.loading = false; + this.comments = data.comments; + this.pageCount = data.page_count; + this.pagination = data.pagination; + this.statusCount = data.status_count; + + this.$nextTick(() => { + $(this.$el).find('[data-toggle="tooltip"]').tooltip(); + + const id = utils.param('edit'); + + if (id) { + Api.find(id).done((comment) => this.editComment = comment); + } + }); + }, + + onCloseEdit (updated) { + if (updated) { + this.fetch(); + } + + this.editComment = null; + + window.location.hash = ''; + }, + + markAll () { + this.comments.forEach(comment => comment.mark = this.markedAll); + }, + + mark () { + this.markedAll = this.comments.length === this.marked().length; + }, + + bulkUpdate (e) { + e.preventDefault(); + + const ids = this.marked().map(comment => comment.id); + + if (this.bulkAction && ids.length) { + Api.update('', { + ids: ids, + status: this.bulkAction + }) + .done(() => { + this.markedAll = false; + this.bulkAction = 0; + this.fetch(); + }); + } + }, + + marked () { + return this.comments.filter((comment) => comment.mark); + }, + + updateStatus (comment, status, e) { + this.highlight(e, status); + + Api.update(comment.id, {status: status}) + .done(() => this.fetch()); + }, + + destroy (comment, e) { + this.highlight(e, 'trash'); + + Api.destroy(comment.id) + .done(() => this.fetch()); + }, + + highlight (e, status) { + e.preventDefault(); + + const tr = $(e.target).closest('tr'); + + switch (status) { + case 'trash': + case 'spam': + return tr.addClass('danger'); + + case 'pending': + return tr.addClass('warning'); + + case 'approved': + return tr.removeClass('warning').addClass('success'); + } + }, + + highlighted (comment) { + return comment.status === 'pending' && this.status !== 'pending'; + } + } +} diff --git a/pool/shard000/JavaScript/0004272_dropLoader.js b/pool/shard000/JavaScript/0004272_dropLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..f0a5fd3d6547e41a7ce13a42ef45b0fd219543f7 --- /dev/null +++ b/pool/shard000/JavaScript/0004272_dropLoader.js @@ -0,0 +1,282 @@ +//@author liuchunhua +//date 20170314 +//注意事项,如果有改变元素高度的行为,必须调用calculationDomHeight方法 +//function upCallBack(){} +//new DropLoader({selectorId:'main',upCallback:upCallback,downLock:true,maxTranslateY:50,reduce:1,upNoticeId:'up-notice'}); +"use strict"; +var DropLoader = function(config) { + + //滑动的元素id + this.selectorId; + //滑动加载提示元素id + this.upNoticeId = 'up-loading'; + this.downNoticeId = 'down-loading'; + //窗口 id,默认可以不用配置 + this.windowSelectorId; + this.loadDataTranslate = 30; //加载数据阈值 + + //锁定不请求数据 + this.downLock = false; //下拉锁定 + this.upLock = false; //上拉锁定 + + + this.maxTranslateY = 400; //最大偏移值,实际要除以 this.reduce,此处作用是偏移时有迟缓感 + this.reduce = 8; + + //提示内容 + this.upNotice = { + touchmove: '上拉加载', + touchend: '松开立即加载', + loading: '加载中...', + noMore: '加载完成' + }; + this.downNotice = { + touchmove: '上拉加载', + touchend: '松开立即加载', + loading: '加载中...', + noMore: '加载完成' + }; + + //上拉回调函数 + this.upCallback; + //下拉回调函数 + this.downCallback; + + + //偏移值 + var translateX = 0; + var translateY = 0; + //窗口高度 + var windowHeight = 0; + //被滑动的元素高度 + var domHeight = 0; + //滑动的元素 + var dom; + + //起始触摸点 + var startX; + var startY; + + //滚动条初始位置 + var startScrollTop = 0; + + //滑动方向 + var isUp = false; + var isDown = false; + + //当前实例 + var instance; + + + //禁止默认滚动 + document.addEventListener('touchmove', function(e) { + e.preventDefault(); + }, { + passive: false + }); + + this.getWindowHeight = function() { + return windowHeight; + }; + + this.getDomHeight = function() { + return domHeight; + }; + + //计算dom高度 + this.calculationDomHeight = function() { + domHeight = dom.offsetHeight; + }; + /** + * 滚动条上下移动,多出来部分用于设置translate + */ + var moveScrollY = function(y) { + + var maxMove = domHeight - windowHeight < 0 ? 0 : domHeight - windowHeight; + var realMove = startScrollTop + startY - y; + + if (startY - y > 0) { + isUp = true; + isDown = false; + } else if (startY - y < 0) { + isDown = true; + isUp = false; + } + + + if (realMove > maxMove) { + realMove = maxMove; + } + //滚动条在顶部为0, 在底部为maxMove + if (realMove >= 0 && realMove <= maxMove) { + document.body.scrollTop = realMove; + } + + + if (isDown && realMove <= 0 && Math.abs(translateY) < instance.maxTranslateY) { + translateY += 1; + } else if (isUp && realMove >= maxMove && Math.abs(translateY) < instance.maxTranslateY) { + translateY--; + } + }; + + //设置 translate + var setTranslate = function(x, y) { + y > instance.maxTranslateY ? y = instance.maxTranslateY : ''; + var move = true; + y = y / instance.reduce; + if (instance.upLock == true && y < 0) { + //上拉锁定 + move = false; + } else if (instance.downLock == true && y > 0) { + //下拉锁定 + move = false; + } + if (move) { + dom.style.transform = "translate(" + x + "px," + y + "px)"; + } + }; + + var setLoadingText = function(id, notice) { + + var loadingDom = document.getElementById(id); + if (loadingDom !== null) { + loadingDom.innerHTML = notice; + } + }; + + /** + * 初始化 + * 列表最大高度 + * 页面最大高度 + */ + var init = function() { + for (var i in config) { + instance[i] = config[i]; + } + + dom = document.getElementById(instance.selectorId); + if (dom === null) { + throw '错误的selector id!'; + } + instance.calculationDomHeight(); + + if (instance.windowSelectorId !== undefined) { + var win = document.getElementById(instance.windowSelectorId); + + if (win === null) { + throw '错误的 window selector id'; + } + + windowHeight = win.offsetHeight; + } else { + windowHeight = window.screen.height; + } + + //触摸开始 + dom.addEventListener('touchstart', function(evt) { + try { + // evt.preventDefault(); + var touch = evt.touches[0]; //获取第一个触点 + var x = Number(touch.clientX); //页面触点X坐标 + var y = Number(touch.clientY); //页面触点Y坐标 + + startScrollTop = document.body.scrollTop; + //记录触点初始位置 + startX = x; + startY = y; + } catch (e) { + console.log(e.message); + } + }, false); + //移动 + dom.addEventListener('touchmove', function(evt) { + try { + // evt.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等 + var touch = evt.touches[0]; //获取第一个触点 + var x = parseInt(touch.clientX); //页面触点X坐标 + var y = parseInt(touch.clientY); //页面触点Y坐标 + //计算滚动条移动数据,并且移动滚动条 + moveScrollY(y); + + if (isTimeToCallback()) { + if (isDown) { + setLoadingText(instance.downNoticeId, instance.downNotice.touchend); + } else { + setLoadingText(instance.upNoticeId, instance.upNotice.touchend); + } + } else { + if (isDown) { + setLoadingText(instance.downNoticeId, instance.downNotice.touchmove); + } else { + setLoadingText(instance.upNoticeId, instance.upNotice.touchmove); + } + } + setTranslate(0, translateY); + } catch (e) { + console.log(e.message); + } + }, false); + //移动结束 + dom.addEventListener('touchend', function(evt) { + try { + + setTimeout(function(){ + down(); + up(); + translateX = translateY = 0; + setTranslate(translateX, translateY); + },500); + } catch (e) { + console.log(e.message); + } + }, false); + }; + + var down = function() { + if (translateY <= 0) { + return false; + } + + if (typeof instance.downCallback !== 'function') { + return false; + } + + if (!isTimeToCallback()) { + return false; + } + setLoadingText(instance.downNoticeId, instance.downNotice.loading, 'touchend'); + + if (!instance.downLock) { + instance.downCallback(); + return true; + } + return false; + }; + + var up = function() { + if (translateY >= 0) { + return false; + } + if (typeof instance.upCallback !== 'function') { + return false; + } + + if (!isTimeToCallback()) { + return false; + } + setLoadingText(instance.upNoticeId, instance.upNotice.loading, 'touchend'); + if (isTimeToCallback() && !instance.upLock) { + instance.upCallback(); + return true; + } + return false; + }; + + var isTimeToCallback = function() { + return Math.abs(translateY / instance.reduce) >= instance.loadDataTranslate; + }; + + instance = this; + init(); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004273_tasks.js b/pool/shard000/JavaScript/0004273_tasks.js new file mode 100644 index 0000000000000000000000000000000000000000..ea10292f608ab8f1d56d4887f73bfeb24efa2907 --- /dev/null +++ b/pool/shard000/JavaScript/0004273_tasks.js @@ -0,0 +1,48 @@ +function getRatioPercent(ratio) { + return (ratio * 100).toFixed(1) + "%"; +} + +function _initTasks_sub(li, tasks) { + if (tasks) { + var ul = $('
    '); + for (const [key, task] of Object.entries(tasks)) { + var liTask = $('
  • ').text(getRatioPercent(task.ratio) + " " + key); + _initTasks_sub(liTask, task.tasks); + ul.append(liTask); + } + li.append(ul); + } +} + +function _getTasks_div(root, title) { + var taskDiv = $('
    '); + var taskDivHeading = $('

    ').text(title); + taskDiv.append(taskDivHeading); + var ulClasses = $('
      '); + for (const [key, clazz] of Object.entries(root)) { + var liClass = $('
    • ').text(getRatioPercent(clazz.ratio) + " " + key); + _initTasks_sub(liClass, clazz.tasks) + ulClasses.append(liClass); + } + taskDiv.append(ulClasses); + return taskDiv +} + +function _renderTasks(data) { + var tasks = $('#tasks .tasks'); + tasks.empty(); + tasks.append(_getTasks_div(data.per_class, 'Ratio per User class')); + tasks.append(_getTasks_div(data.total, 'Total ratio')); +} + +function fillTasksFromObj() { + var tasks = $('#tasks .tasks') + var data = tasks.data('tasks'); + _renderTasks(data) +} + +function fillTasksFromRequest() { + $.get('/tasks', function (data) { + _renderTasks(data) + }); +} diff --git a/pool/shard000/JavaScript/0004275_initiator.js b/pool/shard000/JavaScript/0004275_initiator.js new file mode 100644 index 0000000000000000000000000000000000000000..fcb27092227bf34cfe2eb106510789ca79248ef1 --- /dev/null +++ b/pool/shard000/JavaScript/0004275_initiator.js @@ -0,0 +1,270 @@ +/* + * Initiator v1.1 - (c) Tarun Sharma + * + * 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 2 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 + * + * + * Initiator is a JavaScript plugin that helps you define CSS and JavaScript + * to target any browser & its versions, device (phone, tablet, desktop), + * and platform (iPhone, Android, iPad). + * + */ + +(function() { + + var usrAgent, isTab, isPhone, isDesktop, isInt, browser, device, vendorize, vendorizeIE, addPrefix, initiator, vendorPrefix; + + usrAgent = navigator.userAgent; + + // Object to create browser dependend API + browser = { + + name : false, + version: false, + + // Method to set properties for browser + setProperties: function(version, name) { + this.version = version; + this.name = name; + }, + + // Method to initialize browser API + initialize: function() { + + // If browser is Internet Explorer + if (/MSIE (\d+\.\d+);/.test(usrAgent)) { + this.setProperties(Number(RegExp.$1), vendorPrefix.ie); + vendorize(vendorPrefix.ie, this.version, true); + } + + // If browser is Mozila Firefox + else if (/Firefox[\/\s](\d+\.\d+)/.test(usrAgent)) { + this.setProperties(Number(RegExp.$1), vendorPrefix.mozila); + vendorize(vendorPrefix.mozila, this.version); + } + + //IF browser is Safari + else if(/Safari/.test(usrAgent) && (/Version[\/\s](\d+\.\d+)/.test(usrAgent))) { + this.setProperties(Number(RegExp.$1), vendorPrefix.safari); + vendorize(vendorPrefix.safari, this.version); + } + + // If browser is Chrome + else if(/Chrome[\/\s](\d+\.\d+)/.test(usrAgent)) { + this.setProperties(Number(RegExp.$1), vendorPrefix.chrome); + vendorize(vendorPrefix.chrome, this.version); + } + + // If browser is Opera + else if (/Opera[\/\s](\d+\.\d+)/.test(usrAgent)) { + this.setProperties(Number(RegExp.$1), vendorPrefix.opera); + vendorize(vendorPrefix.opera, this.version); + } + } + }; + + // Object to create device dependend API + device = { + + name: false, + type: false, + + // Method to set properties for device + setProperties: function(name, type) { + this.name = name; + this.type = type; + addPrefix(name + ' ' + type); + + // If device is phone + if(type == vendorPrefix.phone) { + isPhone = true; + } + + // If device is tablet + else if (type == vendorPrefix.tablet) { + isTab = true; + } + + // If device is desktop or laptop + else { + isDesktop = true; + } + }, + + // Method to initialize device API + initialize: function() { + + // If device is iPod + if (/iPod/i.test(usrAgent)) { + this.setProperties(vendorPrefix.iPod, vendorPrefix.phone); + } + + // If device is iPhone + else if (/iPhone/i.test(usrAgent)) { + this.setProperties(vendorPrefix.iPhone, vendorPrefix.phone); + } + + // If device is iPad + else if(/iPad/i.test(usrAgent)) { + this.setProperties(vendorPrefix.iPad, vendorPrefix.tablet); + } + + // If device is Android + else if(/Android/i.test(usrAgent)) { + + // If device is Mobile + if(/Mobile/i.test(usrAgent)) { + this.setProperties(vendorPrefix.android, vendorPrefix.phone); + } + + else { + this.setProperties(vendorPrefix.android, vendorPrefix.tablet); + } + } + + // If device is BlackBerry + else if(/BlackBerry/i.test(usrAgent) || (/BB1/i.test(usrAgent) && (/Mobile/i.test(usrAgent)))) { + this.setProperties(vendorPrefix.blackBerry, vendorPrefix.phone); + } + + // If device is PlayBook + else if(/PlayBook/i.test(usrAgent)) { + this.setProperties(vendorPrefix.playBook, vendorPrefix.tablet); + } + + // If device is Windows Phone + else if(/IEMobile/i.test(usrAgent)) { + this.setProperties(vendorPrefix.winOS, vendorPrefix.phone); + } + + // If device is Windows's Desktop or Laptop + else if(/Windows NT/i.test(usrAgent)) { + this.setProperties(vendorPrefix.windows, vendorPrefix.desktop); + } + + // If device is Mac's Desktop or Laptop + else if(/Mac OS/i.test(usrAgent)) { + this.setProperties(vendorPrefix.mac, vendorPrefix.desktop); + } + + // If device is Linux's Desktop or Laptop + else if(/Linux/i.test(usrAgent)) { + this.setProperties(vendorPrefix.linux, vendorPrefix.desktop); + } + } + } + + // Function to initialize vendor prefix in HTML + vendorize = function(browser, version, internetExplorer) { + + // If browser version is integer + if(isInt(version * 1)) { + + // If browser is Internet Explorer + if(internetExplorer) { + addPrefix(browser + ' ' + vendorizeIE(version)) + } + + else { + addPrefix(browser + ' ' + browser + (version)); + } + } + + // If browser version is floating value + else { + /(\d+).(\d+)/.exec(version); + var decimal = RegExp.$2 + addPrefix(browser + ' ' + browser + parseInt(version) + '-' + decimal); + } + } + + // Function to initialize Internet Explorer prefix + vendorizeIE = function(version) { + version = parseInt(version); + + switch(version) { + case 6: + return vendorPrefix.ie6; + break; + + case 7: + return vendorPrefix.ie7; + break; + + case 8: + return vendorPrefix.ie8; + break; + + case 9: + return vendorPrefix.ie9; + break; + + case 10: + return vendorPrefix.ie10; + break; + + default: + return false; + } + } + + // Function to check number is an integer or not + isInt = function(number) { + return typeof number === 'number' && number % 1 == 0; + } + + // Function to add prefix + addPrefix = function(targetClass) { + var element = document.documentElement; + element.className = element.className == '' ? targetClass : element.className + ' ' + targetClass; + } + + // Object to create collection of vendor prefixes + vendorPrefix = { + ie : 'ie', + ie6 : 'ie6 lt-ie10 lt-ie9 lt-ie8 lt-ie7', + ie7 : 'gt-ie6 ie7 lt-ie10 lt-ie9 lt-ie8', + ie8 : 'gt-ie6 gt-ie7 ie8 lt-ie10 lt-ie9', + ie9 : 'gt-ie6 gt-ie7 gt-ie8 ie9 lt-ie10', + ie10 : 'gt-ie6 gt-ie7 gt-ie8 gt-ie9 ie10', + mozila : 'moz', + chrome : 'chrome', + safari : 'safari', + opera : 'opera', + iPod : 'iPod', + iPhone : 'iPhone', + iPad : 'iPad', + android : 'android', + blackBerry: 'blackBerry', + playBook : 'playBook', + winOS : 'winOS', + mac : 'macOS', + windows : 'windows', + linux : 'linux', + tablet : 'tab', + phone : 'phone', + desktop : 'desktop' + + } + + // Object to initialize initiator + initiator = function() { + browser.initialize(); + device.initialize(); + this.browser = browser; + this.device = device; + } + + return initiator(); +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004279_PerformanceMetricsStore.js b/pool/shard000/JavaScript/0004279_PerformanceMetricsStore.js new file mode 100644 index 0000000000000000000000000000000000000000..f18d67b586ca293f6c516bdb1d6d3a6539fb68b1 --- /dev/null +++ b/pool/shard000/JavaScript/0004279_PerformanceMetricsStore.js @@ -0,0 +1,118 @@ +import { EventEmitter } from 'events'; +import PerformanceMetricsDispatcher from '../dispatcher/PerformanceMetricsDispatcher' +import { PerformanceMetricsConstants } from '../constants/PerformanceMetricsConstants' + +const CHANGE_EVENT = 'change'; + +/** +* Performance metrics Store default data +**/ +let _performanceMetricsStore = { + data:[ + {id:"metric1", title:"Memory", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric2", title:"CPU", summary:"32%", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric3", title:"Network", summary:"1,242 kb/s", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric4", title:"Disk I/O", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric5", title:"Projected Cost Per Month", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric6", title:"Projected Cost Per Month", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric7", title:"Projected Cost Per Month", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]}, + {id:"metric8", title:"Projected Cost Per Month", summary:"124", graph:[2, 2, 2, 2, 2.5, 2, 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2]} + ], + searchFilters: [ + {id:"keyword_search",name:"Keyword Search",type:"input",default:""}, + {id:"target_namespace",name:"Target Namespace",type:"input",default:"acmeair"}, + {id:"target_pod",name:"Target Pod",type:"select",default:"web-rc"}, + {id:"target_container",name:"Target Container",type:"select",default:"web"}, + {id:"measurement_type",name:"Measurement Type",type:"select",default:"Memory"}, + {id:"function_type",name:"Function Type",type:"select",default:"max"} + ], + searchItems:[ + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"}, + {namespace:"acmeair/web-rc/web",name:"mem_total_inactive_file_max"} + ], + expandedData: [], + expandedView: false, + editing: false +} + +// Define the public event listeners and getters that +// the views will use to listen for changes and retrieve +// the store +class PerformanceMetricsStoreClass extends EventEmitter { + + addChangeListener(cb) { + this.on(CHANGE_EVENT, cb); + } + + removeChangeListener(cb) { + this.removeListener(CHANGE_EVENT, cb); + } + + getPerformanceMetricsData() { + return _performanceMetricsStore; + } + +} + +// Initialize the singleton to register with the +// dispatcher and export for React components +const PerformanceMetricsStore = new PerformanceMetricsStoreClass(); + + +// Register each of the actions with the dispatcher +// by changing the store's data and emitting a +// change +PerformanceMetricsDispatcher.register((payload) => { + const action = payload.action; + + switch(action.actionType) { + case PerformanceMetricsConstants.FINISH_EDIT: + _performanceMetricsStore.editing = false; + PerformanceMetricsStore.emit(CHANGE_EVENT); + break; + case PerformanceMetricsConstants.EDIT_METRIC: + _performanceMetricsStore.editing = true; + PerformanceMetricsStore.emit(CHANGE_EVENT); + break; + case PerformanceMetricsConstants.SAVE_METRIC: + _performanceMetricsStore.data.push(action.item); + PerformanceMetricsStore.emit(CHANGE_EVENT); + break; + case PerformanceMetricsConstants.REMOVE_METRIC: + _performanceMetricsStore.data = _performanceMetricsStore.data.filter((item,index) => { + return index !== action.index; + }); + PerformanceMetricsStore.emit(CHANGE_EVENT); + break; + case PerformanceMetricsConstants.EXPANDED_VIEW: + _performanceMetricsStore.expandedData = action.data + _performanceMetricsStore.expandedView = action.type + PerformanceMetricsStore.emit(CHANGE_EVENT); + break; + default: + return true; + } + +}) + +export default PerformanceMetricsStore; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004289_response-types.js b/pool/shard000/JavaScript/0004289_response-types.js new file mode 100644 index 0000000000000000000000000000000000000000..6be4fb82a5f04b294cb30288aa8d2d2265b91038 --- /dev/null +++ b/pool/shard000/JavaScript/0004289_response-types.js @@ -0,0 +1,84 @@ +const request = require('request-promise-native'); +const Discord = require('discord.js'); +const Url = require('urijs'); + +const manamoji = require('./middleware/manamoji'); +const utm = require('./middleware/utm'); + + +class TextResponse { + constructor(client, cardName) { + this.client = client; + this.cardName = cardName; + } + + makeQuerystring() { + return { + fuzzy: this.cardName, + format: 'text' + }; + } + + makeUrl() { + return Url(this.url).query(this.makeQuerystring()).toString(); + } + + makeRequest() { + return new Promise((resolve, reject) => { + request({ + method: 'GET', + resolveWithFullResponse: true, + uri: this.makeUrl() + }).then(response => { + resolve(response); + }).catch(err => { + resolve(err.response); + }); + }); + } + + makeEmbed(response) { + let parts = response.body.split('\n'); + const embedTitle = parts.shift(); + return { + title: `${embedTitle}`, + description: parts.join('\n'), + url: response.headers['x-scryfall-card'], + thumbnail: { + url: response.headers['x-scryfall-card-image'] + } + }; + } + + embed() { + return new Promise((resolve, reject) => { + this.makeRequest().then(response => { + let embed = this.makeEmbed(response); + this.middleware.length > 0 && this.middleware.forEach(mw => { + embed = mw(this.client, embed); + }); + resolve(embed); + }); + }); + } +} + +TextResponse.prototype.middleware = [ manamoji, utm ]; +TextResponse.prototype.url = 'https://api.scryfall.com/cards/named'; + + +class ImageResponse extends TextResponse { + makeEmbed(response) { + let parts = response.body.split('\n'); + return { + title: parts[0].match(/^([^{]+)/)[0].trim(), + url: response.headers['x-scryfall-card'], + image: { + url: response.headers['x-scryfall-card-image'] + } + }; + } +} + + +module.exports = { TextResponse, ImageResponse }; diff --git a/pool/shard000/JavaScript/0004291_languages.js b/pool/shard000/JavaScript/0004291_languages.js new file mode 100644 index 0000000000000000000000000000000000000000..b7d3e58a83a785d1f97418494777dd060aa9a2b6 --- /dev/null +++ b/pool/shard000/JavaScript/0004291_languages.js @@ -0,0 +1,29 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var url = "api/languages"; + + var OctoPrintLanguagesClient = function(base) { + this.base = base; + }; + + OctoPrintLanguagesClient.prototype.list = function(opts) { + return this.base.get(url, opts); + }; + + OctoPrintLanguagesClient.prototype.upload = function(file) { + return this.base.upload(url, file); + }; + + OctoPrintLanguagesClient.prototype.delete = function(locale, pack, opts) { + var packUrl = url + "/" + locale + "/" + pack; + return this.base.delete(packUrl, opts); + }; + + OctoPrintClient.registerComponent("languages", OctoPrintLanguagesClient); + return OctoPrintLanguagesClient; +}); diff --git a/pool/shard000/JavaScript/0004293_IndVars.js b/pool/shard000/JavaScript/0004293_IndVars.js new file mode 100644 index 0000000000000000000000000000000000000000..6cb6d6e92748b71960ad74cbdf37245c2b648642 --- /dev/null +++ b/pool/shard000/JavaScript/0004293_IndVars.js @@ -0,0 +1,41 @@ +var Immutable = require('immutable'); +const initialState = new Immutable.Map(); + +module.exports = function(state = initialState, action) { + if (action.type === 'SET_IND_VARS') { + return Immutable.fromJS(action.indVars); + } + if (action.type === 'CREATE_IND_VAR') { + return state.set(action.indVarId, new Immutable.Map({ + options: new Immutable.List() + })); + } + if (action.type === 'SET_INDVAR_NAME') { + return state.setIn([action.indVarId, 'name'], action.name); + } + if (action.type === 'SET_INDVAR_ACTIONS_PER_TRIAL') { + return state.setIn([action.indVarId, 'actionsPerTrial'], action.actionsPerTrial); + } + if (action.type === 'SET_INDVAR_NUM_TRIALS') { + return state.setIn([action.indVarId, 'numTrials'], action.numTrials); + } + if (action.type === 'SET_INDVAR_RANDOMIZED') { + return state.setIn([action.indVarId, 'randomized'], action.randomized); + } + if (action.type === 'ADD_INDVAR_OPTION') { + return state.updateIn([action.indVarId, 'options'], function(list) { + return list.push(action.option); + }); + } + if (action.type === 'REMOVE_INDVAR_OPTION') { + var newOptions = state.get(action.indVarId).get('options'); + // Find index of item + var optionIndex = newOptions.indexOf(action.option); + // Remove if in list + if (optionIndex >= 0) { + newOptions = newOptions.splice(optionIndex, 1); + } + return state.setIn([action.indVarId, 'options'], newOptions); + } + return state; +}; diff --git a/pool/shard000/JavaScript/0004302_serviceworker.js b/pool/shard000/JavaScript/0004302_serviceworker.js new file mode 100644 index 0000000000000000000000000000000000000000..91fc7015427f9089d2f17d4f40e5b5a741ff7923 --- /dev/null +++ b/pool/shard000/JavaScript/0004302_serviceworker.js @@ -0,0 +1,40 @@ +var CACHE_NAME = 'gih-cache'; +var CACHED_URLS = [ + 'offline.html', + 'css/styles.css', + 'css/materialize.css', + 'img/logont.png', + 'img/logont-200.png', + 'img/logont-350.png', + 'img/logont-450.png', + 'fonts/roboto/MaterialIcons-Regular.eot', + 'fonts/roboto/MaterialIcons-Regular.woff', + 'fonts/roboto/MaterialIcons-Regular.woff2', + 'fonts/roboto/MaterialIcons-Regular.ttf', + 'fonts/roboto/Roboto-Regular.eot', + 'fonts/roboto/Roboto-Regular.woff', + 'fonts/roboto/Roboto-Regular.woff2', + 'fonts/roboto/Roboto-Regular.ttf' +]; + +self.addEventListener('install', function(event) { + event.waitUntil( + caches.open(CACHE_NAME).then(function(cache) { + return cache.addAll(CACHED_URLS); + }) + ); +}); + +self.addEventListener('fetch', function(event) { + event.respondWith( + fetch(event.request).catch(function() { + return caches.match(event.request).then(function(response) { + if (response) { + return response; + } else if (event.request.headers.get('accept').includes('text/html')) { + return caches.match('offline.html'); + } + }); + }) + ); +}); diff --git a/pool/shard000/JavaScript/0004305_search_tweets.test.js b/pool/shard000/JavaScript/0004305_search_tweets.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2956b62ea8491e2d3d5d5ecf53216ff37d44cba7 --- /dev/null +++ b/pool/shard000/JavaScript/0004305_search_tweets.test.js @@ -0,0 +1,59 @@ +const test = require('ava') +const _ = require('lodash') + +const searchTweets = require('../../../src/actions/twitter/search_tweets') +const resultMocked = require('../../mock/search_mock') + +test('Should execute a search and return result', t => { + const queryString = { + q: '#nodebots', + result_type: 'recent', + count: 100 + } + + const twit = { + get: (path, query, cb) => { + t.true(_.isString(path)) + t.true(_.isObject(query)) + t.is(query, queryString) + t.true(_.isFunction(cb)) + + cb(null, resultMocked) + } + } + + return searchTweets(twit, queryString) + .then(result => { + t.deepEqual(result, resultMocked) + }) + .catch(() => { + t.fail() + }) +}) + +test('Should execute a search and return a error', t => { + const queryString = { + q: '#nodebots', + result_type: 'recent', + count: 100 + } + + const erroMocked = { + 'status': 'error', + 'message': 'Unable to communicate with Twitter' + } + + const twit = { + get: (path, query, cb) => { + cb(erroMocked, null) + } + } + + return searchTweets(twit, queryString) + .then(result => { + t.fail() + }) + .catch(err => { + t.deepEqual(err, erroMocked) + }) +}) diff --git a/pool/shard000/JavaScript/0004306_EthiopicDate.js b/pool/shard000/JavaScript/0004306_EthiopicDate.js new file mode 100644 index 0000000000000000000000000000000000000000..237f7358b4ea9b26dae04170c8b1c3e0297c47c9 --- /dev/null +++ b/pool/shard000/JavaScript/0004306_EthiopicDate.js @@ -0,0 +1,308 @@ +/* + * EthiopicDate.js - Represent a date in the Ethiopic calendar + * + * Copyright © 2015, 2018, 2021 JEDLSoft + * + * 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 ilib = require("../index.js"); +var MathUtils = require("./MathUtils.js"); + +var EthiopicRataDie = require("./EthiopicRataDie.js"); +var Locale = require("./Locale.js"); +var LocaleInfo = require("./LocaleInfo.js"); +var IDate = require("./IDate.js"); +var TimeZone = require("./TimeZone.js"); +var EthiopicCal = require("./EthiopicCal.js"); + +/** + * @class + * Construct a new date object for the Ethiopic Calendar. The constructor can be called + * with a parameter object that contains any of the following properties: + * + *
        + *
      • unixtime - sets the time of this instance according to the given + * unix time. Unix time is the number of milliseconds since midnight on Jan 1, 1970 (Gregorian). + *
      • julianday - the Julian Day to set into this date + *
      • year - any integer + *
      • month - 1 to 13, where 1 means Maskaram, 2 means Teqemt, etc., and 13 means Paguemen + *
      • day - 1 to 30 + *
      • hour - 0 to 23. A formatter is used to display 12 hour clocks, but this representation + * is always done with an unambiguous 24 hour representation + *
      • minute - 0 to 59 + *
      • second - 0 to 59 + *
      • millisecond - 0 to 999 + *
      • locale - the TimeZone instance or time zone name as a string + * of this ethiopic date. The date/time is kept in the local time. The time zone + * is used later if this date is formatted according to a different time zone and + * the difference has to be calculated, or when the date format has a time zone + * component in it. + *
      • timezone - the time zone of this instance. If the time zone is not + * given, it can be inferred from this locale. For locales that span multiple + * time zones, the one with the largest population is chosen as the one that + * represents the locale. + * + *
      • date - use the given intrinsic Javascript date to initialize this one. + *
      + * + * If called with another Ethiopic date argument, the date components of the given + * date are copied into the current one.

      + * + * If the constructor is called with no arguments at all or if none of the + * properties listed above + * from unixtime through millisecond are present, then the date + * components are + * filled in with the current date at the time of instantiation. Note that if + * you do not give the time zone when defaulting to the current time and the + * time zone for all of ilib was not set with ilib.setTimeZone(), then the + * time zone will default to UTC ("Universal Time, Coordinated" or "Greenwich + * Mean Time").

      + * + * + * @constructor + * @extends IDate + * @param {Object=} params parameters that govern the settings and behaviour of this Ethiopic date + */ +var EthiopicDate = function(params) { + this.cal = new EthiopicCal(); + + params = params || {}; + + if (typeof(params.noinstance) === 'boolean' && params.noinstance) { + // for doing inheritance, so don't need to fill in the data. The inheriting class only wants the methods. + return; + } + if (params.timezone) { + this.timezone = params.timezone; + } + if (params.locale) { + this.locale = (typeof(params.locale) === 'string') ? new Locale(params.locale) : params.locale; + } + + if (!this.timezone) { + if (this.locale) { + new LocaleInfo(this.locale, { + sync: params.sync, + loadParams: params.loadParams, + onLoad: ilib.bind(this, function(li) { + this.li = li; + this.timezone = li.getTimeZone(); + this._init(params); + }) + }); + } else { + this.timezone = "local"; + this._init(params); + } + } else { + this._init(params); + } +}; + +EthiopicDate.prototype = new IDate({ noinstance: true }); +EthiopicDate.prototype.parent = IDate; +EthiopicDate.prototype.constructor = EthiopicDate; + +/** + * Initialize this instance + * @private + */ +EthiopicDate.prototype._init = function (params) { + new TimeZone({ + id: this.timezone, + sync: params.sync, + loadParams: params.loadParams, + onLoad: ilib.bind(this, function(tz) { + this.tz = tz; + + if (params.year || params.month || params.day || params.hour || + params.minute || params.second || params.millisecond ) { + /** + * Year in the Ethiopic calendar. + * @type number + */ + this.year = parseInt(params.year, 10) || 0; + /** + * The month number, ranging from 1 (Maskaram) to 13 (Paguemen). + * @type number + */ + this.month = parseInt(params.month, 10) || 1; + /** + * The day of the month. This ranges from 1 to 30. + * @type number + */ + this.day = parseInt(params.day, 10) || 1; + /** + * The hour of the day. This can be a number from 0 to 23, as times are + * stored unambiguously in the 24-hour clock. + * @type number + */ + this.hour = parseInt(params.hour, 10) || 0; + /** + * The minute of the hours. Ranges from 0 to 59. + * @type number + */ + this.minute = parseInt(params.minute, 10) || 0; + /** + * The second of the minute. Ranges from 0 to 59. + * @type number + */ + this.second = parseInt(params.second, 10) || 0; + /** + * The millisecond of the second. Ranges from 0 to 999. + * @type number + */ + this.millisecond = parseInt(params.millisecond, 10) || 0; + + /** + * The day of the year. Ranges from 1 to 366. + * @type number + */ + this.dayOfYear = parseInt(params.dayOfYear, 10); + + if (typeof(params.dst) === 'boolean') { + this.dst = params.dst; + } + + this.rd = this.newRd(this); + + // add the time zone offset to the rd to convert to UTC + // getOffsetMillis requires that this.year, this.rd, and this.dst + // are set in order to figure out which time zone rules apply and + // what the offset is at that point in the year + this.offset = this.tz._getOffsetMillisWallTime(this) / 86400000; + if (this.offset !== 0) { + this.rd = this.newRd({ + rd: this.rd.getRataDie() - this.offset + }); + } + } + + if (!this.rd) { + this.rd = this.newRd(params); + this._calcDateComponents(); + } + + if (typeof(params.onLoad) === "function") { + params.onLoad(this); + } + }) + }); +}; + +/** + * Return a new RD for this date type using the given params. + * @protected + * @param {Object=} params the parameters used to create this rata die instance + * @returns {RataDie} the new RD instance for the given params + */ +EthiopicDate.prototype.newRd = function (params) { + return new EthiopicRataDie(params); +}; + +/** + * Return the year for the given RD + * @protected + * @param {number} rd RD to calculate from + * @returns {number} the year for the RD + */ +EthiopicDate.prototype._calcYear = function(rd) { + var year = Math.floor((4*(Math.floor(rd)-1) + 1463)/1461); + + return year; +}; + +/** + * Calculate date components for the given RD date. + * @protected + */ +EthiopicDate.prototype._calcDateComponents = function () { + var remainder, + rd = this.rd.getRataDie(); + + this.year = this._calcYear(rd); + + if (typeof(this.offset) === "undefined") { + this.year = this._calcYear(rd); + + // now offset the RD by the time zone, then recalculate in case we were + // near the year boundary + if (!this.tz) { + this.tz = new TimeZone({id: this.timezone}); + } + this.offset = this.tz.getOffsetMillis(this) / 86400000; + } + + if (this.offset !== 0) { + rd += this.offset; + this.year = this._calcYear(rd); + } + + var jan1 = this.newRd({ + year: this.year, + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }); + remainder = rd + 1 - jan1.getRataDie(); + + this.month = Math.floor((remainder-1)/30) + 1; + remainder = remainder - (this.month-1) * 30; + + this.day = Math.floor(remainder); + remainder -= this.day; + + // now convert to milliseconds for the rest of the calculation + remainder = Math.round(remainder * 86400000); + + this.hour = Math.floor(remainder/3600000); + remainder -= this.hour * 3600000; + + this.minute = Math.floor(remainder/60000); + remainder -= this.minute * 60000; + + this.second = Math.floor(remainder/1000); + remainder -= this.second * 1000; + + this.millisecond = remainder; +}; + +/** + * Return the day of the week of this date. The day of the week is encoded + * as number from 0 to 6, with 0=Sunday, 1=Monday, etc., until 6=Saturday. + * + * @return {number} the day of the week + */ +EthiopicDate.prototype.getDayOfWeek = function() { + var rd = Math.floor(this.rd.getRataDie() + (this.offset || 0)); + return MathUtils.mod(rd-5, 7); +}; + +/** + * Return the name of the calendar that governs this date. + * + * @return {string} a string giving the name of the calendar + */ +EthiopicDate.prototype.getCalendar = function() { + return "ethiopic"; +}; + +//register with the factory method +IDate._constructors["ethiopic"] = EthiopicDate; + +module.exports = EthiopicDate; diff --git a/pool/shard000/JavaScript/0004308_sync.js b/pool/shard000/JavaScript/0004308_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..9a9e35b38c194c179439c49a345b81734224a471 --- /dev/null +++ b/pool/shard000/JavaScript/0004308_sync.js @@ -0,0 +1,177 @@ +'use strict'; +var utils = require('./utils'); +var replication = require('./replicate'); +var replicate = replication.replicate; +var EE = require('events').EventEmitter; + +utils.inherits(Sync, EE); +module.exports = sync; +function sync(src, target, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof opts === 'undefined') { + opts = {}; + } + opts = utils.clone(opts); + /*jshint validthis:true */ + opts.PouchConstructor = opts.PouchConstructor || this; + src = replication.toPouch(src, opts); + target = replication.toPouch(target, opts); + return new Sync(src, target, opts, callback); +} +function Sync(src, target, opts, callback) { + var self = this; + this.canceled = false; + + var onChange, complete; + if ('onChange' in opts) { + onChange = opts.onChange; + delete opts.onChange; + } + if (typeof callback === 'function' && !opts.complete) { + complete = callback; + } else if ('complete' in opts) { + complete = opts.complete; + delete opts.complete; + } + + this.push = replicate(src, target, opts); + + this.pull = replicate(target, src, opts); + var emittedCancel = false; + function onCancel(data) { + if (!emittedCancel) { + emittedCancel = true; + self.emit('cancel', data); + } + } + + function pullChange(change) { + self.emit('change', { + direction: 'pull', + change: change + }); + } + function pushChange(change) { + self.emit('change', { + direction: 'push', + change: change + }); + } + function pushDenied(doc) { + self.emit('denied', { + direction: 'push', + doc: doc + }); + } + function pullDenied(doc) { + self.emit('denied', { + direction: 'pull', + doc: doc + }); + } + var listeners = {}; + + var removed = {}; + function removeAll(type) { // type is 'push' or 'pull' + return function (event, func) { + var isChange = event === 'change' && + (func === pullChange || func === pushChange); + var isCancel = event === 'cancel' && func === onCancel; + var isOtherEvent = event in listeners && func === listeners[event]; + + if (isChange || isCancel || isOtherEvent) { + if (!(event in removed)) { + removed[event] = {}; + } + removed[event][type] = true; + if (Object.keys(removed[event]).length === 2) { + // both push and pull have asked to be removed + self.removeAllListeners(event); + } + } + }; + } + + this.on('newListener', function (event) { + if (event === 'change') { + self.pull.on('change', pullChange); + self.push.on('change', pushChange); + } else if (event === 'denied') { + self.pull.on('denied', pullDenied); + self.push.on('denied', pushDenied); + } else if (event === 'cancel') { + self.pull.on('cancel', onCancel); + self.push.on('cancel', onCancel); + } else if (event !== 'error' && + event !== 'removeListener' && + event !== 'complete' && !(event in listeners)) { + listeners[event] = function (e) { + self.emit(event, e); + }; + self.pull.on(event, listeners[event]); + self.push.on(event, listeners[event]); + } + }); + + this.on('removeListener', function (event) { + if (event === 'change') { + self.pull.removeListener('change', pullChange); + self.push.removeListener('change', pushChange); + } else if (event === 'cancel') { + self.pull.removeListener('cancel', onCancel); + self.push.removeListener('cancel', onCancel); + } else if (event in listeners) { + if (typeof listeners[event] === 'function') { + self.pull.removeListener(event, listeners[event]); + self.push.removeListener(event, listeners[event]); + delete listeners[event]; + } + } + }); + + this.pull.on('removeListener', removeAll('pull')); + this.push.on('removeListener', removeAll('push')); + + var promise = utils.Promise.all([ + this.push, + this.pull + ]).then(function (resp) { + var out = { + push: resp[0], + pull: resp[1] + }; + self.emit('complete', out); + if (complete) { + complete(null, out); + } + self.removeAllListeners(); + return out; + }, function (err) { + self.cancel(); + self.emit('error', err); + if (complete) { + complete(err); + } + self.removeAllListeners(); + throw err; + }); + + this.then = function (success, err) { + return promise.then(success, err); + }; + + this.catch = function (err) { + return promise.catch(err); + }; +} + +Sync.prototype.cancel = function () { + if (!this.canceled) { + this.canceled = true; + this.push.cancel(); + this.pull.cancel(); + } +}; diff --git a/pool/shard000/JavaScript/0004310_GameProfile.js b/pool/shard000/JavaScript/0004310_GameProfile.js new file mode 100644 index 0000000000000000000000000000000000000000..7a2c532ce5b1d5fe96a324c1eed6ad67034680eb --- /dev/null +++ b/pool/shard000/JavaScript/0004310_GameProfile.js @@ -0,0 +1,73 @@ +import React, { Component } from 'react'; +import { PageHeader, Image, Col, Thumbnail, + Button, ButtonGroup, Panel, ListGroup, ListGroupItem } from 'react-bootstrap'; + +import AddButton from '../element/AddButton.js' +import { GetGame } from '../Client'; + +class GameProfile extends Component { + componentDidMount() { + if (this.props.location.state) { + this.setState({game: this.props.location.state.game}); + } else { + console.log(this); + GetGame(this.props.match.params.id).then((data) => { + this.setState({ game: data }); + }); + } + } + + render() { + let attr = {}; + let gameId = -1; + if (this.state && this.state.game) { + attr = this.state.game.data.attributes; + gameId = this.state.game.data.id; + } + const { name, developer, publisher, console, + exclusive, releaseDate, genres, image } = attr; + + return ( + <> + +   + {name} {developer} + + + + + Game Details + + + + + + Release Date: {releaseDate} + Console: {console} + Developer: {developer} + Publisher: {publisher} + Console Exclusive: {exclusive ? 'Yes' : 'No'} + Genres: {genres} + + + + + + + Actions + + + + + + + + + + + + ) + } +} + +export default GameProfile; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004312_Array.prototype.single.spec.js b/pool/shard000/JavaScript/0004312_Array.prototype.single.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b9a542464e1dbd93dd50e1df4d8a0043d3cb17f2 --- /dev/null +++ b/pool/shard000/JavaScript/0004312_Array.prototype.single.spec.js @@ -0,0 +1,63 @@ +import './index'; + +describe('Array.prototype.single', function () { + describe('when doesn\'t have a condition', function () { + describe('and array has one item', function () { + it('should return the item', function () { + let array = [1]; + let result = array.single(); + expect(result).toBe(1); + }); + }); + + describe('and array has more than one item', function () { + it('should throw an error', function () { + let array = [1, 2, 3]; + expect(function () { + let result = array.single(); + }).toThrow('More than one element found.'); + }); + }); + + describe('and array has no items', function () { + it('should throw an error', function () { + let array = []; + expect(function () { + let result = array.single(); + }).toThrow('No elements in the iterable'); + }); + }); + }); + + describe('when does have a condition', function () { + let array; + + beforeEach(function () { + array = [1, 2, 3, 4, 5]; + }); + + describe('and filtered array has one item', function () { + it('should return the item', function () { + let result = array.single(i => i % 3 === 0); + expect(result).toBe(3); + }); + }); + + describe('and array has more than one item', function () { + it('should throw an error', function () { + expect(function () { + let result = array.single(i => i % 2 === 0); + }).toThrow('More than one element found.'); + }); + }); + + describe('and array has no items', function () { + it('should throw an error', function () { + let array = []; + expect(function () { + let result = array.single(i => i > 5); + }).toThrow('No elements in the iterable'); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004313_PlaybackController.js b/pool/shard000/JavaScript/0004313_PlaybackController.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c7cc37423b59f4da94ffabc6411128a084ccdb --- /dev/null +++ b/pool/shard000/JavaScript/0004313_PlaybackController.js @@ -0,0 +1,142 @@ +function PlaybackController(player) { + this.player = player; + this.current_stream = ""; + this.current_track = undefined; + this.current = undefined; + this.is_playing = false; + this.volume = this.player.storage["volume"] || 100; + this.scrobble_time = 320000; + this.repeat_state = 0;//this.player.storage["repeat"] || 0; // 0 - repeat all, 1 - repeat one, 2 - no repeat +} + +PlaybackController.prototype.playTrack = function(track) { + this.current_track = track; + gui.activateControls(track); + gui.list_gui.highlightTrackById(track.id); + gui.ui_slider.show(); + + if (this.is_playing) { + this.pause(); + } + + this.is_playing = true; + this.current_stream = track.url; + + var _this = this; + soundManager.destroySound("current"); + this.current = soundManager.createSound({ + id: 'current', + url: _this.current_stream, + autoLoad: true, + autoPlay: true, + volume: _this.volume, + onconnect: function () { + _this.player.fireEvent("TrackPlay"); + gui.ui_playbutton.removeClass("playbutton-play").addClass("playbutton-pause"); + }, + onload: function() { + gui.ui_bar.css("width", "0"); + //gui.ui_smallinfo.fadeOut("slow"); + + // Время скробблинга (либо половина, либо 320 секунд) + _this.scrobble_time = Math.floor(Math.min(this.duration / 2, 320000)); + }, + whileloading: function () { + //gui.ui_smallinfo.html("загружено: " + parseInt(this.bytesLoaded / 1024) + " из " + parseInt(this.bytesTotal / 1024) + " кБ"); + gui.ui_bar.css("width", parseInt(this.bytesLoaded / this.bytesTotal * 100) + "%"); + }, + whileplaying: function () { + gui.ui_slider.slider("value", _this.current.position / 10); + gui.ui_positionlabel.html(timeFormat(_this.current.position)); + + if (_this.scrobble_time && _this.current.position > _this.scrobble_time && _this.current.position < _this.scrobble_time + 5000) { + _this.player.fireEvent("TrackJustBeforeFinish"); + _this.scrobble_time = null; // больше не скробблить этот трек + } + }, + onfinish: function () { + _this.playNextTrack(); + } + }); +}; + +PlaybackController.prototype.play = function() { + // Играем текущий установленный трек + // Установить можно через setCurrent + if (this.current) { + gui.ui_playbutton.removeClass("playbutton-play").addClass("playbutton-pause"); + this.is_playing = true; + soundManager.play('current'); + this.player.fireEvent("TrackPlay"); + } +}; + +PlaybackController.prototype.pause = function() { + // Приостановка текущего трека + if (this.current && this.is_playing) { + soundManager.pause('current'); + gui.pauseControls(); + this.is_playing = false; + this.player.fireEvent("TrackPause"); + } +}; + +PlaybackController.prototype.playPreviousTrack = function() { + // Получить предыдущий трек текущего списка и начать играть + this.pause(); + var track = this.player.listController.getPreviousTrack(); + if (!track) { + // TODO: тут можно возвращать последний + track = this.player.listController.getFirstTrack(); + } + this.playTrack(track); + this.player.fireEvent("PreviousTrackPlay"); +}; + +PlaybackController.prototype.playNextTrack = function() { + // Получить следующий трек текущего списка и начать играть + this.pause(); + switch (parseInt(this.repeat_state)) { + case 0: + // next track or first + var track = this.player.listController.getNextTrack(); + if (!track) { + track = this.player.listController.getFirstTrack(); + } + this.playTrack(track); + break; + case 1: + // repeat one + this.playTrack(this.current_track); + break; + case 2: + // next track or stop + var track = this.player.listController.getNextTrack(); + if (track) { + this.playTrack(track); + } + break; + } + this.player.fireEvent("NextTrackPlay"); +}; + +PlaybackController.prototype.seekPosition = function(position) { + position = parseInt(position) * 10; + this.current.setPosition(position); +}; + +PlaybackController.prototype.seekVolume = function(volume) { + this.volume = volume; + if (this.current) this.current.setVolume(this.volume); + this.player.storage["volume"] = this.volume; +}; + +PlaybackController.prototype.toggleRepeat = function() { + this.repeat_state = (this.repeat_state + 1) % 3; + this.player.storage["repeat"] = this.repeat_state; + return this.repeat_state; +}; + +PlaybackController.prototype.shuffle = function() { + this.player.listController.shuffle(); +}; diff --git a/pool/shard000/JavaScript/0004314_worker-ready.js b/pool/shard000/JavaScript/0004314_worker-ready.js new file mode 100644 index 0000000000000000000000000000000000000000..b725bd192cde9c7df2e9753b7c32b8fc1e987f38 --- /dev/null +++ b/pool/shard000/JavaScript/0004314_worker-ready.js @@ -0,0 +1,64 @@ +var cservice = require("../cluster-service"), + cluster = require("cluster"), + util = require("util"), + messageBus = require("./message-bus"), + onWorkerStop = null; + +module.exports = exports = workerReady; + +function workerReady(options, forceIsWorker) { + if (cluster.isMaster === true && forceIsWorker !== true) { + return; // ignore if coming from master + } + + if (cservice.locals.workerReady === true) { + return; // ignore dup calls + } + + if (options === false) { + cservice.locals.workerReady = false; + + return; // do not continue + } + + cservice.locals.workerReady = true; + + options = options || {}; + + if (options.servers) { + require("./net-servers").add(options.servers); + } + + onWorkerStop = options.onWorkerStop; + + process.on("message", onMessageFromMaster); + + // allow worker to inform the master when ready to speed up initialization + cservice.processSafeSend(process, + messageBus.createMessage("workerReady", { + onStop: (typeof options.onWorkerStop === "function") + }) + ); +} + +function onMessageFromMaster(msg) { + if (!messageBus.isValidMessage(msg) || + cservice.msgBus.processMessage(msg)) { + return; + } + + switch (msg.cservice.cmd) { + case "onWorkerStop": + cservice.netServers.close(function() { + if (typeof onWorkerStop === "function") { + // if custom handler is provided rely on that to + // cleanup and exit process + onWorkerStop(); + } else { + // otherwise we can exit now that net servers have exited gracefully + process.exit(); + } + }); + break; + } +} diff --git a/pool/shard000/JavaScript/0004315_accounts.js b/pool/shard000/JavaScript/0004315_accounts.js new file mode 100644 index 0000000000000000000000000000000000000000..6258dfe9b690bc170cf7cf270fbf467e0172c2e0 --- /dev/null +++ b/pool/shard000/JavaScript/0004315_accounts.js @@ -0,0 +1,69 @@ +// Copyright 2016 Gavin Wood + +import React, { Component, PropTypes } from 'react'; +import { Chip } from 'material-ui'; + +import IdentityIcon from '../IdentityIcon'; + +import styles from './accounts.css'; + +export default class Accounts extends Component { + static contextTypes = { + api: PropTypes.object.isRequired, + instance: PropTypes.object.isRequired + } + + static propTypes = { + accounts: PropTypes.array + } + + render () { + const has = this._hasAccounts(); + + return ( +

      + { has ? this.renderAccounts() : this.renderEmpty() } +
      + ); + } + + renderEmpty () { + return ( +
      + You currently do not have any GAVcoin in any of your addresses, buy some +
      + ); + } + + renderAccounts () { + const { accounts } = this.props; + + return accounts + .filter((account) => account.hasGav) + .map((account) => { + return ( + + + + { account.name } + + + { account.gavBalance } + + + ); + }); + } + + _hasAccounts () { + const { accounts } = this.props; + + if (!accounts || !accounts.length) { + return false; + } + + return accounts.filter((account) => account.hasGav).length !== 0; + } +} diff --git a/pool/shard000/JavaScript/0004316_collision.js b/pool/shard000/JavaScript/0004316_collision.js new file mode 100644 index 0000000000000000000000000000000000000000..595fb5e4cfcfb6a32f3b5c1e23e226da07d8895e --- /dev/null +++ b/pool/shard000/JavaScript/0004316_collision.js @@ -0,0 +1,158 @@ +import RepeatGroup from './repeat_group'; +import log from '../utils/log'; + +var Collision; + +export default Collision = { + + tiles: {}, + link_id: 0, + + nextLinkId() { + return this.link_id++; + }, + + startTile (tile) { + let state = this.tiles[tile] = { + bboxes: { // current set of placed bounding boxes + aabb: [], + obb: [] + }, + objects: {}, // objects to collide, grouped by priority, then by style + keep: {}, // objects that were kept after collision, grouped by style + styles: new Set() // styles contributing collision objects + }; + + // Promise resolved when all registered styles have added objects + state.complete = new Promise((resolve, reject) => { + state.resolve = resolve; + state.reject = reject; + }); + }, + + resetTile (tile) { + delete this.tiles[tile]; + }, + + // Add a style to the pending set, collision will block on all styles submitting to collision set + addStyle (style, tile) { + this.tiles[tile].styles.add(style); + }, + + // Add collision objects for a style + collide (objects, style, tile) { + let state = this.tiles[tile]; + if (!state) { + log('trace', 'Collision.collide() called with null tile', tile, this.tiles, style, objects); + return Promise.resolve([]); + } + + // Group by priority and style + let tile_objects = state.objects; + for (let i=0; i < objects.length; i++) { + let obj = objects[i]; + let priority = obj.label.layout.priority; + tile_objects[priority] = tile_objects[priority] || {}; + tile_objects[priority][style] = tile_objects[priority][style] || []; + tile_objects[priority][style].push(obj); + } + + // Remove from pending style set, if no more styles, do collision & finish tile + state.styles.delete(style); + if (state.styles.size === 0) { + this.endTile(tile); + } + + // Wait for objects to be added from all styles + return state.complete.then(() => { + return state.keep[style] || []; + }); + }, + + // Test labels for collisions, higher to lower priority + // When two collide, discard the lower-priority label + endTile (tile) { + let state = this.tiles[tile]; + let keep = state.keep; + + RepeatGroup.clear(tile); + + // Process labels by priority, then by style + let priorities = Object.keys(state.objects).sort((a, b) => a - b); + for (let priority of priorities) { + let style_objects = state.objects[priority]; + if (!style_objects) { // no labels at this priority, skip to next + continue; + } + + // For each style + for (let style in style_objects) { + let objects = style_objects[style]; + keep[style] = keep[style] || []; + + for (let i = 0; i < objects.length; i++) { + let object = objects[i]; + if (this.canBePlaced(object, tile, object.linked)) { + // Keep object if it isn't dependent on a parent object + if (!object.linked) { + keep[style].push(object); + this.place(object, tile); + } + // If object is dependent on a parent, only keep if both can be placed + else if (this.canBePlaced(object.linked, tile, object)) { + keep[style].push(object); + this.place(object, tile); + this.place(object.linked, tile); + } + } + } + } + } + + delete this.tiles[tile]; + state.resolve(); + }, + + // Run collision and repeat check to see if label can currently be placed + canBePlaced (object, tile, exclude = null) { + let label = object.label; + let layout = object.label.layout; + + // Skip if already processed (e.g. by parent object) + if (label.placed != null) { + return label.placed; + } + + // Test the label for intersections with other labels in the tile + let bboxes = this.tiles[tile].bboxes; + if (!layout.collide || !label.discard(bboxes, exclude && exclude.label)) { + // check for repeats + let repeat = RepeatGroup.check(label, layout, tile); + if (repeat) { + // log('trace', `discard label '${label.text}', (one_per_group: ${repeat.one_per_group}), dist ${Math.sqrt(repeat.dist_sq)/layout.units_per_pixel} < ${Math.sqrt(repeat.repeat_dist_sq)/layout.units_per_pixel}`); + label.placed = false; + } + else { + return true; + } + } + else if (layout.collide) { + // log('trace', `discard label '${label.text}' due to collision`); + label.placed = false; + } + return label.placed; + }, + + // Place label + place ({ label }, tile) { + // Skip if already processed (e.g. by parent object) + if (label.placed != null) { + return; + } + + // Register as placed for future collision and repeat culling + RepeatGroup.add(label, label.layout, tile); + label.add(this.tiles[tile].bboxes); + } + +}; diff --git a/pool/shard000/JavaScript/0004321_AddFrameToOrderCtrl.js b/pool/shard000/JavaScript/0004321_AddFrameToOrderCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..9b67e3c0b6fb1a840e4f54f0c2b904b720c2a5fd --- /dev/null +++ b/pool/shard000/JavaScript/0004321_AddFrameToOrderCtrl.js @@ -0,0 +1,28 @@ +angular.module('app.controllers') + .controller('AddFrameToOrderCtrl', ['$scope', '$http', '$location', '$modalInstance', function ($scope, $http, $location, $modalInstance) { + + var split = $location.path().split("/"); + var personId = split.length > 2 ? split[2] : null; + + $http.get('/frame/' + personId + '.json'). + then(function ({ data }) { + if (!data.length) { + alert("There are no existing frames tied to this person"); + return; + } + + $scope.existingFrames = data; + }). + catch(function ({ data }) { + $window.alert(data); + Rollbar.error('/frame/' + personId + '.json', data); + }); + + $scope.selectFrame = function(frame) { + $modalInstance.close(frame); + }; + + $scope.cancel = function () { + $modalInstance.dismiss('cancel'); + }; + }]); diff --git a/pool/shard000/JavaScript/0004326_baseSortedIndex.js b/pool/shard000/JavaScript/0004326_baseSortedIndex.js new file mode 100644 index 0000000000000000000000000000000000000000..c192505913e5dd956028ea18b9c6a6d350b0e59e --- /dev/null +++ b/pool/shard000/JavaScript/0004326_baseSortedIndex.js @@ -0,0 +1,42 @@ +import baseSortedIndexBy from './_baseSortedIndexBy.js'; +import identity from './identity.js'; +import isSymbol from './isSymbol.js'; + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + +/** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); +} + +export default baseSortedIndex; diff --git a/pool/shard000/JavaScript/0004328_answer_questions.js b/pool/shard000/JavaScript/0004328_answer_questions.js new file mode 100644 index 0000000000000000000000000000000000000000..0260c996e651c229d863dc525a0410d824ffd0d3 --- /dev/null +++ b/pool/shard000/JavaScript/0004328_answer_questions.js @@ -0,0 +1,122 @@ +$(document).ready(function(){ + $(".question-list").each(function(){ + + // adds an answer submit button appended to each question
        + var questionId = $(this).attr("id").split('-').pop(); + $(this).append($("")); + + // adds a listener attached to each of these buttons + $(this).children("input[type=submit]").click(function(event){ + event.preventDefault(); + var questionId = $(event.target).attr("id").split('-').pop(); + var answerOptionId = $("#question-" + questionId + " input[type=radio]:checked").val(); + sendAnswer(questionId, answerOptionId); + }); + }); + + // queries results of possible previous answers and populates the answer selections + // and result texts accordingly + getPreviousResults(); +}); + +function getPreviousResults(){ + var questionSeriesId = $("#questionSeriesId").val(); + $.ajax({ + url: "/vastaukset/topic/" + questionSeriesId + "/aiemmat", + dataType: "json", + contentType: "application/json; charset=utf-8", + type: "get", + success: function(result){ + populatePreviousResults(result) + } + }); +} + +function populatePreviousResults(result){ + $.each(result[0], function(key, answerResult){ + var answerOptionId = answerResult.AnswerOptionId; + var questionId = answerResult.QuestionId; + if(answerResult.ResultText != 'ei vastattu'){ + $("input:radio[value=" + answerOptionId + "]").prop("checked", true); + populateResultText(questionId, answerResult.ResultText, answerResult.Comment); + } + }); + var achievementHtml = ""; + if(result[1]){ + $.each(result[1], function(key, achievement){ + achievementHtml += "
      • " + achievement.name + "
      • "; + }); + } + + $("#achievement-list").html(achievementHtml); +} + +function sendAnswer(questionId, answerOptionId){ + // if nothing had been selected, just sets the message for user + if(!answerOptionId){ + setResultText(questionId, { successvalue: 2, comment: '' }); + return; + } + + var payload = JSON.stringify({ + answerOptionId: answerOptionId, + questionId: questionId + }); + + $.ajax({ + url: "/vastaukset", + dataType: 'json', + contentType: 'application/json; charset=utf-8', + type: 'post', + data: payload, + success: function(result){ + setResultText(questionId, result); + } + }); +} + +function setResultText(questionId, results){ + var resultMessage; + if(results[0].successValue == 0){ + resultMessage = "Väärin..."; + } else if (results[0].successValue == 1) { + resultMessage = "Oikein!"; + } else if (results[0].successValue == 2) { + resultMessage = "Valitse ensin vastaus."; + } + populateResultText(questionId, resultMessage, results[0].comment); + + var achievementHtml = ""; + if(results[1]){ + $.each(results[1], function(key, achievement){ + achievementHtml += "
      • " + achievement.Name + "
      • "; + }); + } + + $("#achievement-list").html(achievementHtml); +} + +function populateResultText(questionId, resultMessage, comment){ + var msgPart = "

        " + resultMessage + "

        "; + var commentPart = "

        " + comment + "

        "; + $("#question-result-" + questionId).children().remove(); + $("#question-result-" + questionId) + .append(msgPart) + .append(commentPart); +} + +/* + * Disabled for now because of the meta tag in the template for some not working + * with the tests (despite working otherwise). + * + * The error is as follows: + * org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "_csrf.token" (answer_questions:13) + +// sets a CSRF token for ajax calls +var token = $("meta[name='_csrf']").attr("content"); +var header = $("meta[name='_csrf_header']").attr("content"); +$(document).ajaxSend(function (e, xhr, options) { + xhr.setRequestHeader(header, token); +}); + +*/ \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004330_articles.client.controller.js b/pool/shard000/JavaScript/0004330_articles.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..4a373baddc7fb6186d3fee65bdbfe10488f1ab14 --- /dev/null +++ b/pool/shard000/JavaScript/0004330_articles.client.controller.js @@ -0,0 +1,106 @@ +'use strict'; + +angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', 'Users', '$http', 'Emodules', + function($scope, $stateParams, $location, Authentication, Articles, Users, $http, Emodules) { + + $scope.authentication = Authentication; + $scope.user = Authentication.user; + + $scope.myUser = new Users($scope.user); + $scope.myUser.userArticles = $scope.user.userArticles; + + $scope.emodules = Emodules.query(); + $scope.belongsToModule = []; + + $scope.create = function() { + var article = new Articles({ + title: this.title, + content: this.content, + arType: this.arType, + skills: this.skills, + resource: this.resource, + status: this.status, + belongsToModule: this.belongsToModule + }); + article.$save(function(response) { + $location.path('articles/' + response._id); + }, function(errorResponse) { + $scope.error = errorResponse.data.message; + }); + + this.title = ''; + this.content = ''; + this.arType = ''; + this.skills = ''; + this.resource = ''; + this.status = ''; + this.belongsToModule = ''; + }; + + $scope.remove = function(article) { + if (article) { + article.$remove(); + + for (var i in $scope.articles) { + if ($scope.articles[i] === article) { + $scope.articles.splice(i, 1); + } + } + } else { + $scope.article.$remove(function() { + $location.path('articles'); + }); + } + }; + + $scope.update = function() { + var article = $scope.article; + + article.$update(function() { + $location.path('articles/' + article._id); + }, function(errorResponse) { + $scope.error = errorResponse.data.message; + }); + }; + + $scope.find = function() { + $scope.articles = Articles.query(); + }; + + $scope.findOne = function() { + $scope.article = Articles.get({ + articleId: $stateParams.articleId + }); + }; + + $scope.filterAlreadyAdded = function(item) { + // console.log("Filtrando " + item._id); + return ($scope.myUser.userArticles.indexOf(item._id) == -1); + }; + + $scope.selectionsChanged = function(elementId) { + + + $scope.belongsToModule = [] + $scope.belongsToModule.push(elementId); + console.log("belongsToModule : " + $scope.belongsToModule); + // if (!inArray(elementId, $scope.belongsToModule)) { + // $scope.belongsToModule.push(elementId); + + // console.log("Agregada a belongsToModule : " + $scope.belongsToModule); + // // $scope.belongsToModule.push(elementId); + // } else { + // $scope.belongsToModule.slice(elementId); + // } + + }; + + function inArray(x, arr) { + for (var i = 0; i < arr.length; i++) { + if (x === arr[i]) return true; + } + return false; + } + + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004332_index.js b/pool/shard000/JavaScript/0004332_index.js new file mode 100644 index 0000000000000000000000000000000000000000..0641667045de9144bcebc50db56db3dc597346a6 --- /dev/null +++ b/pool/shard000/JavaScript/0004332_index.js @@ -0,0 +1,61 @@ +var fs = require('fs'); +var path = require('path'); +var url = require('url'); +var util = require('util'); + +var _ = require('lodash'); +var async = require('async'); +var multer = require('multer'); +var log = require('debug')('pet-api:csv-importer'); + +var config = require('../config'); +var csvReader = require('./reader'); + +function CSVImporter() { + this.reader = csvReader; + this.log = log; +} + +CSVImporter.prototype = { + + /** + * + * @returns {Promise.} + */ + run: function () { + + var self = this; + return this.reader.parseSpeciesProps({ + readPath: [ + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Model - Cats.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Model - Dogs.csv') + ], + cache: true + }) + .then(function () { + self.log('species props parsed'); + return self.reader.parseOptions({ + cache: true, + readPath: [ + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Small Animals.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Rabbits.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Reptiles.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Birds.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Dogs.csv'), + path.resolve(process.cwd(), 'tmp/CfO_Animal_Adoption_DB_Options - Cats.csv') + ] + }) + + }) + .then(function () { + self.log('options parsed'); + return self.reader.parseDataset({cache: true}); + }) + .then(function (petCollection) { + self.log('done parsing csv data'); + return petCollection + }); + } +}; + +module.exports = CSVImporter; diff --git a/pool/shard000/JavaScript/0004333_cas.js b/pool/shard000/JavaScript/0004333_cas.js new file mode 100644 index 0000000000000000000000000000000000000000..09ac98207d8c83efdc6558e1ba532dd1ac4a4de7 --- /dev/null +++ b/pool/shard000/JavaScript/0004333_cas.js @@ -0,0 +1,46 @@ +"use strict"; + +import config from "config"; +import session from "express-session"; +import CASAuthentication from "cas-authentication"; + +/* Instantiate MemStore */ +const MemoryStore = require("memorystore")(session); +let cas = null; + +/** + * Return Singleton Instance of CAS + * @returns {*} + */ +module.exports.getCAS = () => { + return cas; +}; + +/** + * Instantiate CAS Services + * @param express + */ +module.exports.instantiate = (express) => { + + /* Utilize Express Sessions */ + /* TODO: Fix Persistent Store */ + /* TODO: Fix Configuration Values */ + express.use(session({ + secret: config.get("authentication.sessions.secret"), + resave: config.get("authentication.sessions.resave"), + saveUninitialized: config.get("authentication.sessions.saveUninitialized"), + store: new MemoryStore({ + checkPeriod: 86400000 // Prune expired entries every 24 hours + }), + })); + + /* Instantiate CAS */ + cas = new CASAuthentication({ + cas_url: config.get("authentication.cas.cas_url"), + service_url: config.get("authentication.cas.service_url"), + cas_version: config.get("authentication.cas.cas_version"), + is_dev_mode: config.get("authentication.cas.is_dev_mode"), + dev_mode_user: config.get("authentication.cas.dev_mode_user") + }); + +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004335_intersection-observer-polyfill.js b/pool/shard000/JavaScript/0004335_intersection-observer-polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..117fe6adc00e68f2f40aec49f9acb2629e820c4b --- /dev/null +++ b/pool/shard000/JavaScript/0004335_intersection-observer-polyfill.js @@ -0,0 +1,461 @@ +/** + * Copyright 2016 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS-IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {SubscriptionApi} from './iframe-helper'; +import {dev} from './log'; +import {dict} from './utils/object'; +import {isArray, isFiniteNumber} from './types'; +import {layoutRectLtwh, moveLayoutRect, rectIntersection} from './layout-rect'; + +/** + * The structure that defines the rectangle used in intersection observers. + * + * @typedef {{ + * top: number, + * bottom: number, + * left: number, + * right: number, + * width: number, + * height: number, + * x: number, + * y: number, + * }} + */ +export let DOMRect; + +export const DEFAULT_THRESHOLD = + [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, + 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1]; + +/** @typedef {{ + * element: !Element, + * currentThresholdSlot: number, + * }} + */ +let ElementIntersectionStateDef; + +/** @const @private */ +const TAG = 'INTERSECTION-OBSERVER'; + +/** @const @private */ +const INIT_TIME = Date.now(); + +/** + * A function to get the element's current IntersectionObserverEntry + * regardless of the intersetion ratio. Only available when element is not + * nested in a container iframe. + * TODO: support opt_iframe if there's valid use cases. + * @param {!./layout-rect.LayoutRectDef} element element's rect + * @param {?./layout-rect.LayoutRectDef} owner element's owner rect + * @param {!./layout-rect.LayoutRectDef} hostViewport hostViewport's rect + * @return {!IntersectionObserverEntry} A change entry. + */ +export function getIntersectionChangeEntry( + element, owner, hostViewport) { + const intersection = rectIntersection(element, owner, hostViewport) || + layoutRectLtwh(0, 0, 0, 0); + const ratio = intersectionRatio(intersection, element); + return calculateChangeEntry( + element, hostViewport, intersection, ratio); +} + +/** + * @param {!Window} win + * @return {boolean} + */ +export function nativeIntersectionObserverSupported(win) { + return 'IntersectionObserver' in win && + 'IntersectionObserverEntry' in win && + 'intersectionRatio' in win.IntersectionObserverEntry.prototype; +} + +/** + * A class to help amp-iframe and amp-ad nested iframe listen to intersection + * change. + */ +export class IntersectionObserverApi { + /** + * @param {!AMP.BaseElement} baseElement + * @param {!Element} iframe + * @param {boolean=} opt_is3p + */ + constructor(baseElement, iframe, opt_is3p) { + /** @private @const {!AMP.BaseElement} */ + this.baseElement_ = baseElement; + + /** @private {?IntersectionObserverPolyfill} */ + this.intersectionObserver_ = null; + + /** @private {boolean} */ + this.shouldObserve_ = false; + + /** @private {boolean} */ + this.isInViewport_ = false; + + /** @private {?function()} */ + this.unlistenOnDestroy_ = null; + + /** @private @const {!./service/viewport/viewport-impl.Viewport} */ + this.viewport_ = baseElement.getViewport(); + + /** @private {?SubscriptionApi} */ + this.subscriptionApi_ = new SubscriptionApi( + iframe, 'send-intersections', opt_is3p || false, () => { + this.startSendingIntersection_(); + }); + + this.intersectionObserver_ = new IntersectionObserverPolyfill(entries => { + // Remove target info from cross origin iframe. + for (let i = 0; i < entries.length; i++) { + delete entries[i]['target']; + } + this.subscriptionApi_.send('intersection', dict({'changes': entries})); + }, {threshold: DEFAULT_THRESHOLD}); + this.intersectionObserver_.tick(this.viewport_.getRect()); + + /** @const {function()} */ + this.fire = () => { + if (!this.shouldObserve_ || !this.isInViewport_) { + return; + } + this.intersectionObserver_.tick(this.viewport_.getRect()); + }; + } + + /** + * Function to start listening to viewport event. and observer intersection + * change on the element. + */ + startSendingIntersection_() { + this.shouldObserve_ = true; + this.intersectionObserver_.observe(this.baseElement_.element); + this.baseElement_.getVsync().measure(() => { + this.isInViewport_ = this.baseElement_.isInViewport(); + this.fire(); + }); + + const unlistenViewportScroll = this.viewport_.onScroll(this.fire); + const unlistenViewportChange = this.viewport_.onChanged(this.fire); + this.unlistenOnDestroy_ = () => { + unlistenViewportScroll(); + unlistenViewportChange(); + }; + } + + /** + * Enable to the PositionObserver to listen to viewport events + * @param {boolean} inViewport + */ + onViewportCallback(inViewport) { + this.isInViewport_ = inViewport; + } + + /** + * Clean all listenrs + */ + destroy() { + this.shouldObserve_ = false; + this.intersectionObserver_ = null; + if (this.unlistenOnDestroy_) { + this.unlistenOnDestroy_(); + this.unlistenOnDestroy_ = null; + } + this.subscriptionApi_.destroy(); + this.subscriptionApi_ = null; + } +} + + +/** + * The IntersectionObserverPolyfill class lets any element receive its + * intersection data with the viewport. It acts like native browser supported + * IntersectionObserver. + * The IntersectionObserver receives a callback function and an optional option + * as params. Whenever the element intersection ratio cross a threshold value, + * IntersectionObserverPolyfill will call the provided callback function with + * the change entry. + * @visibleForTesting + */ +export class IntersectionObserverPolyfill { + /** + * @param {function(!Array)} callback + * @param {Object=} opt_option + */ + constructor(callback, opt_option) { + /** @private @const {function(!Array)} */ + this.callback_ = callback; + + // The input threshold can be a number or an array of numbers. + let threshold = opt_option && opt_option.threshold; + if (threshold) { + threshold = isArray(threshold) ? + threshold : [threshold]; + } else { + threshold = [0]; + } + + for (let i = 0; i < threshold.length; i++) { + dev().assert(isFiniteNumber(threshold[i]), 'Threshold should be a ' + + 'finite number or an array of finite numbers'); + } + + /** + * A list of threshold, sorted in increasing numeric order + * @private @const {!Array} + */ + this.threshold_ = threshold.sort(); + dev().assert(this.threshold_[0] >= 0 && + this.threshold_[this.threshold_.length - 1] <= 1, + 'Threshold should be in the range from "[0, 1]"'); + + /** @private {?./layout-rect.LayoutRectDef} */ + this.lastViewportRect_ = null; + + /** @private {./layout-rect.LayoutRectDef|undefined} */ + this.lastIframeRect_ = undefined; + + /** + * Store a list of observed elements and their current threshold slot which + * their intersection ratio fills, range from [0, this.threshold_.length] + * @private {Array} + */ + this.observeEntries_ = []; + } + + /** + */ + disconnect() { + this.observeEntries_.length = 0; + } + + /** + * Provide a way to observe the intersection change for a specific element + * Please note IntersectionObserverPolyfill only support AMP element now + * TODO: Support non AMP element + * @param {!Element} element + */ + observe(element) { + // Check the element is an AMP element. + dev().assert(element.getLayoutBox); + + // If the element already exists in current observeEntries, do nothing + for (let i = 0; i < this.observeEntries_.length; i++) { + if (this.observeEntries_[i].element === element) { + dev().warn(TAG, 'should observe same element once'); + return; + } + } + + const newState = { + element, + currentThresholdSlot: 0, + }; + + // Get the new observed element's first changeEntry based on last viewport + if (this.lastViewportRect_) { + const change = this.getValidIntersectionChangeEntry_( + newState, this.lastViewportRect_, this.lastIframeRect_); + if (change) { + this.callback_([change]); + } + } + + // push new observed element + this.observeEntries_.push(newState); + } + + /** + * Provide a way to unobserve intersection change for a specified element + * @param {!Element} element + */ + unobserve(element) { + // find the unobserved element in observeEntries + for (let i = 0; i < this.observeEntries_.length; i++) { + if (this.observeEntries_[i].element === element) { + this.observeEntries_.splice(i, 1); + return; + } + } + dev().warn(TAG, 'unobserve non-observed element'); + } + + /** + * Tick function that update the DOMRect of the root of observed elements. + * Caller needs to make sure to pass in the correct container. + * Note: the opt_iframe param is the iframe position relative to the host doc, + * The iframe must be a non-scrollable iframe. + * @param {!./layout-rect.LayoutRectDef} hostViewport + * @param {./layout-rect.LayoutRectDef=} opt_iframe + */ + tick(hostViewport, opt_iframe) { + + if (opt_iframe) { + // If element inside an iframe. Adjust origin to the iframe.left/top. + hostViewport = + moveLayoutRect(hostViewport, -opt_iframe.left, -opt_iframe.top); + opt_iframe = + moveLayoutRect(opt_iframe, -opt_iframe.left, -opt_iframe.top); + } + + this.lastViewportRect_ = hostViewport; + this.lastIframeRect_ = opt_iframe; + + const changes = []; + + for (let i = 0; i < this.observeEntries_.length; i++) { + const change = this.getValidIntersectionChangeEntry_( + this.observeEntries_[i], hostViewport, opt_iframe); + if (change) { + changes.push(change); + } + } + + if (changes.length) { + this.callback_(changes); + } + } + + /** + * Return a change entry for one element that should be compatible with + * IntersectionObserverEntry if it's valid with current config. + * When the new intersection ratio doesn't cross one of a threshold value, + * the function will return null. + * + * @param {!ElementIntersectionStateDef} state + * @param {!./layout-rect.LayoutRectDef} hostViewport hostViewport's rect + * @param {./layout-rect.LayoutRectDef=} opt_iframe iframe container rect + * @return {?IntersectionObserverEntry} A valid change entry or null if ratio + * @private + */ + getValidIntersectionChangeEntry_(state, hostViewport, opt_iframe) { + const {element} = state; + + // Normalize container LayoutRect to be relative to page + let ownerRect = null; + + // If opt_iframe is provided, all LayoutRect has position relative to + // the iframe. + // If opt_iframe is not provided, all LayoutRect has position relative to + // the host document. + const elementRect = element.getLayoutBox(); + const owner = element.getOwner(); + ownerRect = owner && owner.getLayoutBox(); + + // calculate intersectionRect. that the element intersects with hostViewport + // and intersects with owner element and container iframe if exists. + const intersectionRect = + rectIntersection(elementRect, ownerRect, hostViewport, opt_iframe) || + layoutRectLtwh(0, 0, 0, 0); + // calculate ratio, call callback based on new ratio value. + const ratio = intersectionRatio(intersectionRect, elementRect); + const newThresholdSlot = getThresholdSlot(this.threshold_, ratio); + + if (newThresholdSlot == state.currentThresholdSlot) { + return null; + } + state.currentThresholdSlot = newThresholdSlot; + + // To get same behavior as native IntersectionObserver set hostViewport null + // if inside an iframe + const changeEntry = calculateChangeEntry(elementRect, + (opt_iframe ? null : hostViewport), intersectionRect, ratio); + changeEntry.target = element; + return changeEntry; + } +} + +/** + * Returns the ratio of the smaller box's area to the larger box's area. + * @param {!./layout-rect.LayoutRectDef} smaller + * @param {!./layout-rect.LayoutRectDef} larger + * @return {number} + */ +function intersectionRatio(smaller, larger) { + return (smaller.width * smaller.height) / (larger.width * larger.height); +} + +/** + * Returns the slot number that the current ratio fills in. + * @param {!Array} sortedThreshold valid sorted IoB threshold + * @param {number} ratio Range from [0, 1] + * @return {number} Range from [0, threshold.length] + * @visibleForTesting + */ +export function getThresholdSlot(sortedThreshold, ratio) { + let startIdx = 0; + let endIdx = sortedThreshold.length; + // 0 is a special case that does not fit into [small, large) range + if (ratio == 0) { + return 0; + } + let mid = ((startIdx + endIdx) / 2) | 0; + while (startIdx < mid) { + const midValue = sortedThreshold[mid]; + // In the range of [small, large) + if (ratio < midValue) { + endIdx = mid; + } else { + startIdx = mid; + } + mid = ((startIdx + endIdx) / 2) | 0; + } + return endIdx; +} + +/** + * Helper function to calculate the IntersectionObserver change entry. + * @param {!./layout-rect.LayoutRectDef} element element's rect + * @param {?./layout-rect.LayoutRectDef} hostViewport hostViewport's rect + * @param {!./layout-rect.LayoutRectDef} intersection + * @param {number} ratio + * @return {!IntersectionObserverEntry}} + */ +function calculateChangeEntry( + element, hostViewport, intersection, ratio) { + // If element not in an iframe. + // adjust all LayoutRect to hostViewport Origin. + let boundingClientRect = element; + let rootBounds = hostViewport; + // If no hostViewport is provided, element is inside an non-scrollable iframe. + // Every Layoutrect has already adjust their origin according to iframe + // rect origin. LayoutRect position is relative to iframe origin, + // thus relative to iframe's viewport origin because the viewport is at the + // iframe origin. No need to adjust position here. + + if (hostViewport) { + // If element not in an iframe. + // adjust all LayoutRect to hostViewport Origin. + rootBounds = /** @type {!./layout-rect.LayoutRectDef} */ (rootBounds); + intersection = moveLayoutRect(intersection, -hostViewport.left, + -hostViewport.top); + // The element is relative to (0, 0), while the viewport moves. So, we must + // adjust. + boundingClientRect = moveLayoutRect(boundingClientRect, + -hostViewport.left, -hostViewport.top); + // Now, move the viewport to (0, 0) + rootBounds = moveLayoutRect(rootBounds, + -hostViewport.left, -hostViewport.top); + } + + return /** @type {!IntersectionObserverEntry} */ ({ + time: (typeof performance !== 'undefined' && performance.now) ? + performance.now() : Date.now() - INIT_TIME, + rootBounds, + boundingClientRect, + intersectionRect: intersection, + intersectionRatio: ratio, + }); +} diff --git a/pool/shard000/JavaScript/0004338_race.js b/pool/shard000/JavaScript/0004338_race.js new file mode 100644 index 0000000000000000000000000000000000000000..3f99b6c16e8bad2f9af4b5b459f8599003038cde --- /dev/null +++ b/pool/shard000/JavaScript/0004338_race.js @@ -0,0 +1,28 @@ +var level = require('level'); +var db = level('/tmp/race.db', { valueEncoding: 'json' }); +var lock = require('../'); + +var name = process.argv[2]; +var data = { bio: 'beep boop' }; + +for (var i = 0; i < 3; i++) (function (i) { + create(name, data, function (err) { + console.error(i + ' create: ' + (err || 'ok')); + }); +})(i); + +function create (name, data, cb) { + var key = 'users!' + name; + + var unlock = lock(db, key, 'w'); + if (!unlock) return cb(new Error('locked')); + + db.get(key, function (err, value) { + if (value) return cb(new Error('that username already exists')); + + db.put('users!substack', data, function (err) { + unlock(); + cb(err); + }); + }); +} diff --git a/pool/shard000/JavaScript/0004340_analytics-view.js b/pool/shard000/JavaScript/0004340_analytics-view.js new file mode 100644 index 0000000000000000000000000000000000000000..29416c5afe5acee9772c8c22db5203a5dc5f13e4 --- /dev/null +++ b/pool/shard000/JavaScript/0004340_analytics-view.js @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +function onRequest(context) { + var log = new Log("stats.js"); + var carbonServer = require("carbon").server; + var device = context.unit.params.device; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var constants = require("/app/modules/constants.js"); + var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss"); + var jwtService = carbonServer.osgiService( + 'org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService'); + var jwtClient = jwtService.getJWTClient(); + var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]); + var token = ""; + var user = session.get(constants.USER_SESSION_KEY); + if (!user) { + log.error("User object was not found in the session"); + throw constants.ERRORS.USER_NOT_FOUND; + } + if (encodedClientKeys) { + var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; + var resp = tokenUtil.decode(encodedClientKeys).split(":"); + + if (user.domain == "carbon.super") { + var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {}); + if (tokenPair) { + token = tokenPair.accessToken; + } + websocketEndpoint = websocketEndpoint + "/secured-websocket/iot.per.device.stream.raspberrypi.temperature/1.0.0?" + + "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token; + } else { + var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username + "@" + user.domain + , "default", {}); + if (tokenPair) { + token = tokenPair.accessToken; + } + websocketEndpoint = websocketEndpoint + "/secured-websocket/t/" + user.domain + "/iot.per.device.stream.raspberrypi.temperature/1.0.0?" + + "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token; + } + + } + return {"device": device, "websocketEndpoint": websocketEndpoint}; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004346_createStore.js b/pool/shard000/JavaScript/0004346_createStore.js new file mode 100644 index 0000000000000000000000000000000000000000..d1ea766c9c5c469b93f1e941da17bd9b5fd5c4d4 --- /dev/null +++ b/pool/shard000/JavaScript/0004346_createStore.js @@ -0,0 +1,44 @@ +import {applyMiddleware, compose, createStore as rawCreateStore} from 'redux'; +import {persistStore, autoRehydrate} from 'redux-persist'; +import createSagaMiddleware from 'redux-saga'; +import createRootReducer from './createRootReducer'; +import rootSaga from './rootSaga'; +import {APP_NAME} from '../modules/common/constants'; + +/** + * @returns {function} + */ +export const createStore = () => + new Promise((resolve) => { + const rootReducer = createRootReducer(); + const sagaMiddleware = createSagaMiddleware(); + const middlewares = []; + + middlewares.push(sagaMiddleware); + + const enhancer = compose( + applyMiddleware(...middlewares), + autoRehydrate(), + window.devToolsExtension ? window.devToolsExtension() : (f) => f + ); + + const store = rawCreateStore(rootReducer, enhancer); + + // The promise returned by "createStore" will be resolved once we have re-hydrated the state. + persistStore(store, { + whitelist: ['language', 'map'], + blacklist: [], + keyPrefix: `${APP_NAME}:`, + }, () => resolve(store)); + + sagaMiddleware.run(rootSaga); + + if (__DEV__ && module.hot) { + module.hot.accept('./createRootReducer', () => { + const newRootReducer = require('./createRootReducer').default(); + store.replaceReducer(newRootReducer); + }); + } + }); + +export default createStore; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004348_index.js b/pool/shard000/JavaScript/0004348_index.js new file mode 100644 index 0000000000000000000000000000000000000000..697bb54bfe9ff76257b9af551c60b4b86fcdcd7b --- /dev/null +++ b/pool/shard000/JavaScript/0004348_index.js @@ -0,0 +1,24 @@ +var parser = require('./parser'), + request = require('request'); + +module.exports = { + + Parser: function() + { + return new parser(); + }, + + Request: function(opts) + { + if (!opts.headers) opts.headers = {}; + if (!opts.headers.Accept) opts.headers.Accept = 'application/kml,text/kml'; + return request(opts); + }, + + transform: [ + {to: 'properties', type: 'Object'}, + {to: 'type', type: 'String'}, + {to: 'geometry', type: 'Object'}, + ] + +}; diff --git a/pool/shard000/JavaScript/0004349_fetchStatusActions.js b/pool/shard000/JavaScript/0004349_fetchStatusActions.js new file mode 100644 index 0000000000000000000000000000000000000000..89b27a5eb017d484092c24dd38b3d27aa1b95186 --- /dev/null +++ b/pool/shard000/JavaScript/0004349_fetchStatusActions.js @@ -0,0 +1,129 @@ +/* fetchStatusActions.js - fetch status actions */ +import fetch from 'isomorphic-fetch' + +export const PRE_FETCH = 'PRE_FETCH' +export const FETCH_START = 'FETCH_START' +export const FETCH_SUCCESS = 'FETCH_SUCCESS' +export const FETCH_ERROR = 'FETCH_ERROR' +export const SET_MESSAGE = 'SET_MESSAGE' +export const TRANSITION_TO = 'TRANSITION_TO' + +// export const MSG_INVALID_CREDENTIALS = 'INVALID_CREDENTIALS' +// export const MSG_UNKNOWN_SERVER_ERROR = 'UNKNOWN_SERVER_ERROR' +// export const MSG_OTHER_FETCH_ERROR = 'OTHER_FETCH_ERROR = ' +import { defineMessages } from 'react-intl' + +export const componentText = defineMessages({ + invalidCredentials: { id: 'fetchStatus.InvalidCredentials', defaultMessage: 'Invalid Credentials - please log in with a valid username and password' }, + unknownServerError: { id: 'fetchStatus.UnknownServerError', defaultMessage: 'Unknown Server Error - please log out and refresh application' }, + invalidRequest: { id: 'fetchStatus.InvalidRequest', defaultMessage: 'Erroneous API use, server validation failed' }, + otherFetchError: { id: 'fetchStatus.OtherFetchError', defaultMessage: 'Error fetching information from server - please refresh application' } +}) + +// Function to set the status message manually where needed +export function setMessage (message, messageType = 'status') { + return { type: SET_MESSAGE, messageType, message } +} + +// Function to set a next path if needed +export function setNewPath (newPath) { + return { type: TRANSITION_TO, newPath } +} + +/* Handle the mechanics of asynchronous fetching, including error checking, + using the contents of the payload structure. This structure must include the + following members: + - apiUrl => The (relative) url path to call + - method => String indicating HTTP method to use (GET, POST, PUT, DELETE) + - type => type of action + - sendData => Data associated with the action to fetch, sent to server +*/ + +export function fetchReduxAction (payload, username = undefined, password = undefined, successPath = undefined) { + return (dispatch, getState) => { + /* If we didn't get a username and password, it is because we're supposed to get that from state */ + if (username === undefined) { + username = getState().getIn(['user', 'token']) + password = 'unused' + } + dispatch(fetchStart(payload.type, payload.sendData)) + let headers + switch (payload.method) { + /* GET does not have payloads */ + case 'GET': + headers = getApiHeaders(payload.method, username, password) + break + /* PUT, POST, and DELETE all have payloads */ + case 'DELETE': + case 'PUT': + case 'POST': + headers = getApiHeaders(payload.method, username, password, JSON.stringify(payload.sendData)) + break + default: + throw new Error('fetchReduxAction: Invalid or mssing method in payload') + } + return fetch(process.env.API_ROOT + payload.apiUrl, headers) + .then(response => checkResponse(payload.method, response)) + .then(json => dispatch(fetchSuccess(payload.type, payload.sendData, json, successPath))) + .catch(error => dispatch(fetchError(payload.type, payload.sendData, error))) + } +} + +/* Check the response code and throw appropriate & consistent errors that + can be localized in the UI if desired */ +function checkResponse (httpVerb, response) { + if (response.ok) { + // The HTTP protocol doesn't allow payload for DELETE verb, so there will be no JSON + if (httpVerb !== 'DELETE') { + return response.json() + } else { + return undefined + } + } else if (response.status === 400) { + throw componentText.invalidRequest + } else if (response.status === 401) { + throw componentText.invalidCredentials + } else if (response.status === 500) { + throw componentText.unknownServerError + } else { + throw componentText.otherFetchError + } +} + +/* Redux action for all fetch starts */ +function fetchStart (type, sendData) { + return { type, status: FETCH_START, sendData } +} + +/* Redux action for all fetch errors */ +function fetchError (type, sendData, message) { + return { type, status: FETCH_ERROR, sendData, message } +} + +/* Redux action for all fetch successes */ +function fetchSuccess (type, sendData, receivedData, nextPath) { + return { type, status: FETCH_SUCCESS, sendData, receivedData, nextPath } +} + +/* Construct an HTTP basic authentication header given a username and password */ +function getAuthstring (username, password) { + return 'Basic ' + + new Buffer(unescape(encodeURIComponent(username)) + ':' + + unescape(encodeURIComponent(password))).toString('base64') +} + +/* Construct the payload argument to fetch given the HTTP method, + authentication information, and optional body */ +function getApiHeaders (httpMethod, username, password, body = undefined) { + const result = { + 'method': httpMethod, + 'headers': { + 'Authorization': getAuthstring(username, password), + 'Content-Type': 'application/json' + } + } + if (body !== undefined) { + result['body'] = body + } + return result +} diff --git a/pool/shard000/JavaScript/0004350_app.js b/pool/shard000/JavaScript/0004350_app.js new file mode 100644 index 0000000000000000000000000000000000000000..406da1d45df8c516f3ca0434861a8b41ed689b44 --- /dev/null +++ b/pool/shard000/JavaScript/0004350_app.js @@ -0,0 +1,145 @@ +'use strict'; + +var platform = require('./platform'), + isArray = require('lodash.isarray'), + isPlainObject = require('lodash.isplainobject'), + async = require('async'), + producer, opt = {}; + +let sendData = (data) => { + data = JSON.stringify(data); + if (opt.version === '0.8.x and up') { + + var payloads = [{ topic: opt.topic, messages: data, partition: opt.partition }]; + + producer.send(payloads, function (err, ackData) { + if (!err) { + platform.log(JSON.stringify({ + title: 'Data Successfully sent to Kafka.', + data: data + })); + } else { + console.error('Error sending data to Kafka', err); + platform.handleException(err); + } + }); + + } else { + try { + producer.send(data); + platform.log(JSON.stringify({ + title: 'Data Successfully sent to Kafka.', + data: data + })); + } catch (e) { + console.error('Error sending data to Kafka', e); + platform.handleException(e); + } + } +}; + +platform.on('data', function (data) { + if(isPlainObject(data)){ + sendData(data); + } + else if(isArray(data)){ + async.each(data, (datum) => { + sendData(datum); + }); + } + else + platform.handleException(new Error(`Invalid data received. Data must be a valid Array/JSON Object or a collection of objects. Data: ${data}`)); +}); + +platform.once('close', function () { + var domain = require('domain'); + var d = domain.create(); + + d.once('error', function(error) { + console.error(error); + platform.handleException(error); + platform.notifyClose(); + d.exit(); + }); + + d.run(function() { + // TODO: Release all resources and close connections etc. + if (producer) producer.close(); + platform.notifyClose(); // Notify the platform that resources have been released. + d.exit(); + }); +}); + +platform.once('ready', function (options) { + + options.port = ((options.port) ? options.port : 9092); + opt = { + topic : options.topic, + partition : options.partition, + version : options.version + }; + + if (options.version === '0.8.x and up') { + var clientOpt = {}, + url = options.host + ':' + options.port + '/'; + + clientOpt.sessionTimeout = ((options.sessionTimeout) ? options.sessionTimeout : 30000); + clientOpt.spinDelay = ((options.spinDelay) ? options.spinDelay : 1000); + clientOpt.retries = ((options.retries) ? options.retries : 0); + + options.requireAcks = ((options.requireAcks) ? options.requireAcks : 1); + options.ackTimeoutMs = ((options.ackTimeoutMs) ? options.ackTimeoutMs : 100); + options.partition = ((options.partition) ? options.partition : 0); + + options.clientId = ((options.clientId) ? options.clientId : 'reekoh-client'); + + var kafka8 = require('kafka-node'), + HighLevelProducer = kafka8.HighLevelProducer, + isConnected = false, + client = new kafka8.Client(url, options.clientId, clientOpt); + + producer = new HighLevelProducer(client, {requireAcks: options.requireAcks, ackTimeoutMs: options.ackTimeoutMs}); + + setTimeout(function() { + if (!isConnected) { + platform.handleException('Cannot connect to Kafka. Host: ' + options.host + ' Port: ' + options.port ); + process.exit(1); + } + }, 5000); + + producer.on('ready', function () { + isConnected = true; + platform.log('Kafka producer ready version: ' + options.version); + platform.notifyReady(); + }); + + + producer.on('error', function (prodErr) { + console.error('Error connecting in Kafka broker.', prodErr); + platform.handleException(prodErr); + }); + + } else { + var kafka7 = require('kafka'); + + producer = new kafka7.Producer({ + host: options.host, + port: options.port, + topic: opt.topic, + partition: opt.partition + }); + + producer.connect(); + + producer.on('connect', function(err) { + platform.log('Kafka producer ready version: ' + options.version); + platform.notifyReady(); + }); + + producer.on('error', function(prodErr) { + console.error('Error connecting in Kafka broker.', prodErr); + platform.handleException(prodErr); + }); + } + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004352_app.js b/pool/shard000/JavaScript/0004352_app.js new file mode 100644 index 0000000000000000000000000000000000000000..d7850e8ce0cf4ff1f453739b3cdf1bbf482c66da --- /dev/null +++ b/pool/shard000/JavaScript/0004352_app.js @@ -0,0 +1,57 @@ +var remote = require('remote'); +var app = remote.require('app'); + +var $result = $('#result'); + +$('#app-info-button').click(function () { + + var appMethods = [ + 'getVersion', + 'getName', + 'getAppPath' + ]; + + var $table = $(''); + var $row; + + $table.addClass('table table-striped'); + + $row = $(''); + $row.append(''); + $table.append($row); + + appMethods.forEach(function (method) { + $row = $(''); + $row.append(''); + $table.append($row); + }); + + var pathArgs = [ + 'home', + 'appData', + 'userData', + 'cache', + 'userCache', + 'temp', + 'userDesktop', + 'exe', + 'module' + ]; + + pathArgs.forEach(function (arg) { + $row = $(''); + $row.append(''); + $table.append($row); + }); + + $result.html(''); + $result.append($table); + +}); + +$('#close-button').click(function () { + var quit = confirm('Are you sure you want to close this application?'); + if (quit) { + app.quit(); + } +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004353_resource.js b/pool/shard000/JavaScript/0004353_resource.js new file mode 100644 index 0000000000000000000000000000000000000000..0ec95d83a83ec9c054a72b3eab5382eb3b5be524 --- /dev/null +++ b/pool/shard000/JavaScript/0004353_resource.js @@ -0,0 +1,139 @@ +var _ = require('lodash'); + +module.exports = function(ddb) { + var resourceRouter = require('express').Router(); + var resourceName = process.env.GENERIC_RESOURCE_NAME; + var resourceIDName = process.env.GENERIC_RESOURCE_ID_NAME; + var resourceIDType = process.env.GENERIC_RESOURCE_ID_TYPE; + var resourceIDRegex = process.env.GENERIC_RESOURCE_ID_REGEX; + // var producer = require('./producer'); + + var mergeResource = function(original, updated) { + var result = original; + for (var key in updated) { + if (updated.hasOwnProperty(key)) { + result[key] = updated[key]; + } + } + return result; + }; + + function toInternal(obj) { + obj = JSON.parse(JSON.stringify(obj)); + for (key in obj) { + if (obj.hasOwnProperty(key)) { + obj[key] = JSON.stringify(obj[key]); + } + } + return obj; + } + + function toExternal(obj) { + obj = JSON.parse(JSON.stringify(obj)); + for (key in obj) { + if (obj.hasOwnProperty(key)) { + obj[key] = JSON.parse(obj[key]); + } + } + return obj; + } + + resourceRouter.post('/', function(req, res, next) { + require('./validator')(ddb, function(validator) { + validResource = validator.validate(req.body); + if (!validResource) { + return res.status(400).send('Message body contains an invalid resource.'); + } + var resource = {}; + for (key in req.body) { + if (req.body.hasOwnProperty(key)) { + resource[key] = req.body[key]; + } + } + ddb.putItem('resource', toInternal(resource), {}, function(err, r) { + if (err) { return res.status(500).json(err); } + // producer.send({ + // "resource": resourceName, + // "action": "added", + // "id": resource[resourceIDName], + // "object": resource + // }); + return res.status(200).json(resource); + }); + }); + }); + + resourceRouter.put('/:id', function(req, res, next) { + require('./validator')(ddb, function(validator) { + ddb.getItem('resource', req.params.id, null, {}, function(err, unmodified) { + if (err) return res.status(500).json(err); + if (!unmodified) { return res.status(404).send('field does not exist.'); } + + unmodified = toExternal(unmodified); + var merged = JSON.parse(JSON.stringify(unmodified)); + for (var key in req.body) { + if (req.body.hasOwnProperty(key)) { + merged[key] = req.body[key]; + } + } + if (!validator.validate(merged)) { + return res.status(400).send('Message body contains an invalid resource.'); + } + + ddb.deleteItem('resource', req.params.id, null, {}, function(err, dr) { + if (err) return res.status(500).json(err); + ddb.putItem('resource', toInternal(merged), {}, function(err, pr) { + if (err) return res.status(500).json(err); + // producer.send({ + // "resource": resourceName, + // "action": "modified", + // "id": merged[resourceIDName], + // "old_object": unmodified, + // "new_object": merged + // }); + return res.status(200).json(merged); + }); + }); + }); + }); + }); + + resourceRouter.get('/', function(req, res, next) { + ddb.scan('resource', {}, function(err, resources) { + if (err) { return res.status(500).json(err); } + if (resources.items) { + return res.status(200).json(resources.items.map(toExternal)); + } else { + return res.status(200).json(resources); + } + }); + }); + + resourceRouter.get('/:id', function(req, res, next) { + ddb.getItem('resource', req.params.id, null, {}, function(err, resource) { + if (!resource) { return res.status(404).send('field does not exist.') } + if (err) { return res.status(500).json(err); } + return res.status(200).json(toExternal(resource)); + }); + }); + + resourceRouter.delete('/:id', function(req, res, next) { + ddb.getItem('resource', req.params.id, null, {}, function(err, resource) { + if (!resource) { return res.status(404).send('resource does not exist.') } + if (err) { return res.status(500).json(err); } + ddb.deleteItem('resource', req.params.id, null, {}, function(err, r) { + if (err) { return res.status(500).json(err); } + // producer.send({ + // "resource": resourceName, + // "action": "removed", + // "id": resource[resourceIDName] + // }); + return res.status(200).send('resource deleted.'); + }); + }); + }); + + return { + router: resourceRouter + }; +}; diff --git a/pool/shard000/JavaScript/0004354_gulpfile.js b/pool/shard000/JavaScript/0004354_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b06ed36bc54b45628d6027f61daef8e75dc46e4b --- /dev/null +++ b/pool/shard000/JavaScript/0004354_gulpfile.js @@ -0,0 +1,216 @@ +/*eslint-env node*/ +const fs = require('fs'); +const gulp = require('gulp'); +const util = require('gulp-util'); +const eslint = require('gulp-eslint'); +const rename = require('gulp-rename'); +const sourcemaps = require('gulp-sourcemaps'); +const uglify = require('gulp-uglify'); +const bump = require('gulp-bump'); +const inquirer = require('inquirer'); +const source = require('vinyl-source-stream'); +const rollup = require('rollup-stream'); +const buble = require('rollup-plugin-buble'); +const del = require('del'); +const sequence = require('run-sequence'); +const semver = require('semver'); +const es = require('event-stream'); +const shell = require('shelljs'); + +const pkg = JSON.parse(fs.readFileSync('package.json')); +const paths = { + src: 'src', + dist: 'dist', + main: pkg['main'], + esmain: pkg['jsnext:main'] +}; + +function bundle(format) { + const banner = `/*! ${pkg.name} v${pkg.version} | ${pkg.license} License | ${pkg.homepage} */\n`; + const moduleName = 'ngXhrPromisify'; + + return rollup({ + input: `${paths.src}/index.js`, + plugins: [ buble() ], + external: [ 'angular' ], + globals: { 'angular': 'angular' }, + name: moduleName, + banner: banner, + sourcemap: false, + format: format || 'umd' + }); +} + +gulp.task('bundle:es', () => { + return bundle('es') + .pipe(source(paths.esmain)) + .pipe(gulp.dest('.')); +}); + +gulp.task('bundle:umd', () => { + return bundle('umd') + .pipe(source(paths.main)) + .pipe(gulp.dest('.')); +}); + +gulp.task('minify:umd', () => { + gulp.src(paths.main) + .pipe(sourcemaps.init()) + .pipe(uglify({ preserveComments: 'license' })) + .pipe(rename({ suffix: '.min' })) + .pipe(sourcemaps.write('.', { + includeContent: false, + mapFile: name => name.replace(/\.js\.map$/, '.map') + })) + .pipe(gulp.dest(paths.dist)); +}); + +gulp.task('lint', () => { + return gulp.src(`${paths.src}/**/*.js`) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + +gulp.task('clean', () => { + return del(paths.dist); +}); + +gulp.task('build', (callback) => { + sequence('lint', 'clean', ['bundle:es', 'bundle:umd'], 'minify:umd', callback); +}); + +gulp.task('release:check', (callback) => { + const branch = shell.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).stdout.trim(); + if (branch !== 'master') { + const red = util.colors.red; + console.log(red('Switch to'), red.bold('master'), red('branch before continuing.')); + process.exit(1); + } + + const changes = shell.exec('git status --untracked-files=no --porcelain', { silent: true }).stdout.trim(); + if (changes) { + console.log(util.colors.red('You have unstaged or uncommitted changes. Commit or stash before continuing.')); + process.exit(1); + } + + callback(); +}); + +function bumpPackage(version) { + return gulp.src('package.json') + .pipe(bump({ version: version })) + .pipe(gulp.dest('.')) + .on('end', () => pkg.version = version); +} + +function bumpChangeLog(version, previous) { + const date = new Date().toISOString().slice(0, 10); + const repo = pkg.repository.url.replace(/\.git$/, ''); + const entry = `## [${version}] \\(${date}\\)\n- TODO`; + const link = `[${version}]: ${repo}/compare/v${previous}...v${version}`; + + return gulp.src('CHANGELOG.md') + .pipe(es.map((file, callback) => { + const changelog = file.contents.toString() + .replace('# Change Log', `$&\n\n${entry}`) + .concat(`${link}\n`); + + file.contents = new Buffer(changelog); + callback(null, file); + })) + .pipe(gulp.dest('.')); +} + +gulp.task('release:bump', () => { + const choices = ['patch', 'minor', 'major'].map(type => { + const version = semver.inc(pkg.version, type); + return { name: `${type} (${version})`, value: version, short: type }; + }); + + return inquirer.prompt({ + type: 'list', + name: 'bump', + message: 'Release type', + choices: choices + }).then(choice => { + return new Promise((resolve, reject) => { + es.merge( + bumpPackage(choice.bump), + bumpChangeLog(choice.bump, pkg.version) + ).on('end', resolve); + }); + }); +}); + +gulp.task('release:changelog', () => { + return inquirer.prompt({ + type: 'list', + name: 'changelog', + message: 'Edit CHANGELOG.md before continuing', + choices: [{ name: `Release ${pkg.version}`, value: null, short: ' ' }] + }); +}); + +gulp.task('release:commit', (callback) => { + const commands = [ + 'git add -f package.json CHANGELOG.md', + `git commit -m '${pkg.version}'`, + 'git checkout --detach', + `git add -f ${paths.dist}`, + `git commit -m '${pkg.version}'`, + `git tag -f v${pkg.version}`, + 'git checkout master' + ]; + + commands.forEach(cmd => { + const result = shell.exec(cmd, { silent: true }); + if (result.code !== 0) { + console.log(util.colors.red(result.stderr.trim())); + process.exit(1); + } + }); + + callback(); +}); + +gulp.task('release:publish', (callback) => { + const commands = [ + `git push origin master v${pkg.version}`, + `git checkout v${pkg.version}`, + 'npm publish', + `git checkout master` + ]; + + inquirer.prompt({ + type: 'confirm', + name: 'publish', + message: `Publish ${pkg.version}`, + default: false + }).then(choice => { + if(choice.publish) { + commands.forEach(cmd => { + const result = shell.exec(cmd, { silent: true }); + if (result.code !== 0) { + console.log(util.colors.red(result.stderr.trim())); + process.exit(1); + } + }); + } + callback(); + }); +}); + +gulp.task('release', (callback) => { + sequence( + 'release:check', + 'release:bump', + 'build', + 'release:changelog', + 'release:commit', + 'release:publish', + callback + ); +}); + +gulp.task('default', ['build']); diff --git a/pool/shard000/JavaScript/0004356_logDownload.js b/pool/shard000/JavaScript/0004356_logDownload.js new file mode 100644 index 0000000000000000000000000000000000000000..23ff47034ff8a342fb7680497751e3401a0499db --- /dev/null +++ b/pool/shard000/JavaScript/0004356_logDownload.js @@ -0,0 +1,49 @@ +/** + * 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.LogDownloadController = Ember.ObjectController.extend(App.FileHandler,{ + buttons: [ + { + title: Em.I18n.t('common.close'), + action: "cancel", + classBindings:[':btn',':btn-default'] + } + ], + jobLogsLoader:function (output) { + var jobId = this.get('content.id'); + var url = ['jobs',jobId, 'results','stderr'].join('/'); + + return this.fileProxy(url); + }.property('content'), + + suggestedFilename: function() { + return this.get("content.jobId").toLowerCase().replace(/\W+/g, "_") + '_logs.txt'; + }.property("content.jobId"), + + jobLogs:function () { + return this.get('jobLogsLoader.content.fileContent'); + }.property("content","jobLogsLoader.isPending"), + + actions:{ + download:function () { + return this.downloadFile(this.get("jobLogs"), this.get("suggestedFilename")); + } + } +}); diff --git a/pool/shard000/JavaScript/0004357_WhileSeriesTests.js b/pool/shard000/JavaScript/0004357_WhileSeriesTests.js new file mode 100644 index 0000000000000000000000000000000000000000..94a428f1d47c943ba54070dd078d81cb566e2ebc --- /dev/null +++ b/pool/shard000/JavaScript/0004357_WhileSeriesTests.js @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2016 airbug Inc. http://airbug.com + * + * bugcore may be freely distributed under the MIT license. + */ + + +//------------------------------------------------------------------------------- +// Annotations +//------------------------------------------------------------------------------- + +//@TestFile + +//@Require('Class') +//@Require('Flows') +//@Require('Throwables') +//@Require('bugmeta.BugMeta') +//@Require('bugunit.TestTag') + + +//------------------------------------------------------------------------------- +// Context +//------------------------------------------------------------------------------- + +require('bugpack').context("*", function(bugpack) { + + //------------------------------------------------------------------------------- + // BugPack + //------------------------------------------------------------------------------- + + var Class = bugpack.require('Class'); + var Flows = bugpack.require('Flows'); + var Throwables = bugpack.require('Throwables'); + var BugMeta = bugpack.require('bugmeta.BugMeta'); + var TestTag = bugpack.require('bugunit.TestTag'); + + + //------------------------------------------------------------------------------- + // Simplify References + //------------------------------------------------------------------------------- + + var bugmeta = BugMeta.context(); + var test = TestTag.test; + + + //------------------------------------------------------------------------------- + // Declare Tests + //------------------------------------------------------------------------------- + + /** + * This tests.. + * 1) That the while series completes + */ + var bugflowExecuteWhileSeriesTest = { + + async: true, + + + // Setup Test + //------------------------------------------------------------------------------- + + setup: function(test) { + var _this = this; + this.numberAssertionsStarted = 0; + this.numberTasksCompleted = 0; + this.numberTasksStarted = 0; + this.testAssertionMethod = function(flow) { + _this.numberAssertionsStarted++; + return (_this.numberAssertionsStarted <= 2); + }; + this.testTask = Flows.$task(function(flow) { + _this.numberTasksStarted++; + test.assertEqual(_this.numberTasksStarted, _this.numberAssertionsStarted, + "Assert tasks are executed in series with assertions"); + test.assertEqual(_this.numberTasksCompleted, _this.numberTasksStarted - 1, + "Assert tasks are executed in series"); + setTimeout(function() { + _this.numberTasksCompleted++; + flow.complete(); + }, 0); + }); + this.whileSeries = Flows.$whileSeries(this.testAssertionMethod, this.testTask); + test.completeSetup(); + }, + + + // Run Test + //------------------------------------------------------------------------------- + + test: function(test) { + var _this = this; + var executeCallbackFired = false; + this.whileSeries.execute(function(throwable) { + test.assertFalse(executeCallbackFired, + "Assert that the execute callback has not already fired"); + executeCallbackFired = true; + if (!throwable) { + test.assertEqual(_this.numberTasksStarted, 2, + "Assert testTask was started twice"); + test.assertEqual(_this.numberTasksCompleted, 2, + "Assert testTask was completed twice"); + test.assertEqual(_this.numberAssertionsStarted, 3, + "Assert that the ForEachParallel iterated twice and ended on the third"); + } else { + test.error(throwable); + } + test.completeTest(); + }); + } + }; + + + /** + * This tests.. + * 1) That the while series does not execute another assertion until the previous assertion completes + */ + var bugflowExecuteWhileSeriesWithAsyncAssertionTest = { + + async: true, + + + // Setup Test + //------------------------------------------------------------------------------- + + setup: function(test) { + var _this = this; + this.numberAssertionsCompleted = 0; + this.numberAssertionsStarted = 0; + this.numberTasksCompleted = 0; + this.numberTasksStarted = 0; + this.testAsyncAssertionMethod = function(flow) { + test.assertEqual(_this.numberAssertionsStarted, _this.numberTasksCompleted, + "Assert that assertions are running in series with tasks"); + _this.numberAssertionsStarted++; + if (_this.numberAssertionsStarted > 3) { + throw new Throwables.exception("TestException", {}, "Test assertions are running infinitely"); + } + setTimeout(function() { + _this.numberAssertionsCompleted++; + test.assertEqual(_this.numberAssertionsCompleted, _this.numberAssertionsStarted, + "Assert that previous assertion completed before the next one started"); + flow.assert(_this.numberAssertionsStarted < 3); + }, 0); + }; + this.testWhileTask = Flows.$task(function(flow) { + _this.numberTasksStarted++; + setTimeout(function() { + _this.numberTasksCompleted++; + flow.complete(); + }, 0); + }); + this.whileSeries = Flows.$whileSeries(this.testAsyncAssertionMethod, this.testWhileTask); + test.completeSetup(); + }, + + + // Run Test + //------------------------------------------------------------------------------- + + test: function(test) { + var _this = this; + var executeCallbackFired = false; + this.whileSeries.execute(function(throwable) { + test.assertFalse(executeCallbackFired, + "Assert that the execute callback has not already fired"); + executeCallbackFired = true; + if (!throwable) { + test.assertEqual(_this.numberAssertionsStarted, 3, + "Assert three assertions started"); + test.assertEqual(_this.numberAssertionsCompleted, 3, + "Assert three assertions completed"); + test.assertEqual(_this.numberTasksStarted, 2, + "Assert that the ForEachParallel started 2 tasks"); + test.assertEqual(_this.numberTasksCompleted, 2, + "Assert that the ForEachParallel completed 2 tasks"); + } else { + test.error(throwable); + } + test.completeTest(); + }); + } + }; + + + //------------------------------------------------------------------------------- + // BugMeta + //------------------------------------------------------------------------------- + + bugmeta.tag(bugflowExecuteWhileSeriesTest).with( + test().name("Flows WhileSeries - execute test") + ); + bugmeta.tag(bugflowExecuteWhileSeriesWithAsyncAssertionTest).with( + test().name("Flows WhileSeries - execute with async assertion test") + ); +}); diff --git a/pool/shard000/JavaScript/0004358_common.js b/pool/shard000/JavaScript/0004358_common.js new file mode 100644 index 0000000000000000000000000000000000000000..41bf6929f7c97c5c08409810efa88b6fd6e015ab --- /dev/null +++ b/pool/shard000/JavaScript/0004358_common.js @@ -0,0 +1,50 @@ +// Meteor Components +import { Template } from 'meteor/templating'; +import * as _ from 'lodash'; + + +/** + * + */ +export const FormatPipes = { + + /** + * + * @param {string|*} errorValue + * @returns {string|*} + */ + asFriendlyErrorMsg(errorValue) { + // Get Error Message + let err = errorValue; + if (_.has(err, 'reason')) { err = err.reason; } + if (_.has(err, 'message')) { err = err.message; } + + // Strip error codes from beginning or end of message; + // - [400] sample error + // - sample error [400] + err = err.replace(/^\[[\d]+]\s?|\s?\[[\d]+]$/g, ''); + + // Prevent exposing specific auth errors + const defaultAuthError = 'Invalid credentials'; + err = /user not found/i.test(err) ? defaultAuthError : err; + err = /incorrect password/i.test(err) ? defaultAuthError : err; + + // Return Friendly Error Message + return err; + } + +}; +export default FormatPipes; + + +// +// Template Formatting Pipes +// + +/** + * + * @param {string|*} errorValue + */ +Template.registerHelper('asFriendlyErrorMsg', (errorValue) => + FormatPipes.asFriendlyErrorMsg(errorValue) +); diff --git a/pool/shard000/JavaScript/0004359_imageicon.js b/pool/shard000/JavaScript/0004359_imageicon.js new file mode 100644 index 0000000000000000000000000000000000000000..a3646078bdec0ab2094feab6b5ff41e7d3816a73 --- /dev/null +++ b/pool/shard000/JavaScript/0004359_imageicon.js @@ -0,0 +1,25 @@ +import React from 'react' +require("sass/logoicon.sass") + +function logo(name){ + if (!name) + return '' + let ns=name.split(' ') + if (ns.length>=2){ + return ns.map((n) => n[0]).join('').slice(0,2).toUpperCase() + } + return name.slice(0,2).toUpperCase() +} + +let count=0 + +function ImageIcon(props){ + return ( +
        + + {logo(props.name)} +
        + ) +} + +export default ImageIcon diff --git a/pool/shard000/JavaScript/0004360_nuke.js b/pool/shard000/JavaScript/0004360_nuke.js new file mode 100644 index 0000000000000000000000000000000000000000..b95291efdb8fc9a65e20057b92f0266d18aafcf1 --- /dev/null +++ b/pool/shard000/JavaScript/0004360_nuke.js @@ -0,0 +1,97 @@ +const async = require('async'); +const AWS = require('aws-sdk'); +const http = require('http'); + +// configurable params +const BUCKET = 'foo'; +const LISTING_LIMIT = 300; +const ACCESSKEY = 'accessKey1'; +const SECRETKEY = 'verySecretKey1'; +const ENDPOINT = 'http://127.0.0.1:8000'; +const QUIET_MODE = true; + +AWS.config.update({ + accessKeyId: ACCESSKEY, + secretAccessKey: SECRETKEY, + region: "us-west-1", + sslEnabled: false, + endpoint: ENDPOINT, + s3ForcePathStyle: true, + apiVersions: { s3: '2006-03-01' }, + signatureVersion: 'v4', + signatureCache: false, +}); + +const s3 = new AWS.S3({ + httpOptions: { + maxRetries: 0, + timeout: 0, + agent: new http.Agent({ keepAlive: true }), + }, +}); + +// list object versions +function _listObjectVersions(VersionIdMarker, KeyMarker, cb) { + s3.listObjectVersions({ Bucket: BUCKET, MaxKeys: LISTING_LIMIT, VersionIdMarker, KeyMarker }, cb); +} + +// return object with key and version_id +function _getKeys(keys) { + return keys.map((v) => ({ + Key: v.Key, + VersionId: v.VersionId, + })); +} + +// delete all versions of an object +function _deleteVersions(objectsToDelete, cb) { + // multi object delete can delete max 1000 objects + function _batchDelete(Objects, done) { + s3.deleteObjects({ Bucket: BUCKET, Delete: { Objects, Quiet: QUIET_MODE } }, (err, res) => { + if (err) { + console.log('batch delete err', err); + return done(err); + } + Objects.forEach(v => console.log('deleted key: ' + v.Key)); + return done(); + }); + } + const fns = []; + while(Object.keys(objectsToDelete).length > 0) { + const Objects = objectsToDelete.splice(0, 999); + fns.push(done => _batchDelete(Objects, done)); + } + async.parallel(fns, cb); + +} + +function nukeObjects(cb) { + let VersionIdMarker = null; + let KeyMarker = null; + async.doWhilst( + done => _listObjectVersions(VersionIdMarker, KeyMarker, (err, data) => { + if (err) { + return done(err); + } + VersionIdMarker = data.NextVersionIdMarker; + KeyMarker = data.NextKeyMarker; + const keysToDelete = _getKeys(data.Versions); + const markersToDelete = _getKeys(data.DeleteMarkers); + _deleteVersions(keysToDelete.concat(markersToDelete), done); + }), + () => { + if (VersionIdMarker || KeyMarker) { + return true; + } + return false; + }, + cb + ); +} + +nukeObjects((err, res) => { + if (err) { + return console.log('error occured deleting objects', err); + } + return console.log('completed deletion'); +}); diff --git a/pool/shard000/JavaScript/0004362_pbliteserializer.js b/pool/shard000/JavaScript/0004362_pbliteserializer.js new file mode 100644 index 0000000000000000000000000000000000000000..665108552843ac18fab272aa97b2909172117769 --- /dev/null +++ b/pool/shard000/JavaScript/0004362_pbliteserializer.js @@ -0,0 +1,196 @@ +// Copyright 2008 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 Protocol Buffer 2 Serializer which serializes messages + * into PB-Lite ("JsPbLite") format. + * + * PB-Lite format is an array where each index corresponds to the associated tag + * number. For example, a message like so: + * + * message Foo { + * optional int bar = 1; + * optional int baz = 2; + * optional int bop = 4; + * } + * + * would be represented as such: + * + * [, (bar data), (baz data), (nothing), (bop data)] + * + * Note that since the array index is used to represent the tag number, sparsely + * populated messages with tag numbers that are not continuous (and/or are very + * large) will have many (empty) spots and thus, are inefficient. + * + * + */ + +goog.provide('goog.proto2.PbLiteSerializer'); + +goog.require('goog.asserts'); +goog.require('goog.proto2.FieldDescriptor'); +goog.require('goog.proto2.LazyDeserializer'); +goog.require('goog.proto2.Serializer'); + + + +/** + * PB-Lite serializer. + * + * @constructor + * @extends {goog.proto2.LazyDeserializer} + */ +goog.proto2.PbLiteSerializer = function() {}; +goog.inherits(goog.proto2.PbLiteSerializer, goog.proto2.LazyDeserializer); + + +/** + * If true, fields will be serialized with 0-indexed tags (i.e., the proto + * field with tag id 1 will have index 0 in the array). + * @type {boolean} + * @private + */ +goog.proto2.PbLiteSerializer.prototype.zeroIndexing_ = false; + + +/** + * By default, the proto tag with id 1 will have index 1 in the serialized + * array. + * + * If the serializer is set to use zero-indexing, the tag with id 1 will have + * index 0. + * + * @param {boolean} zeroIndexing Whether this serializer should deal with + * 0-indexed protos. + */ +goog.proto2.PbLiteSerializer.prototype.setZeroIndexed = function(zeroIndexing) { + this.zeroIndexing_ = zeroIndexing; +}; + + +/** + * Serializes a message to a PB-Lite object. + * + * @param {goog.proto2.Message} message The message to be serialized. + * @return {!Array} The serialized form of the message. + * @override + */ +goog.proto2.PbLiteSerializer.prototype.serialize = function(message) { + var descriptor = message.getDescriptor(); + var fields = descriptor.getFields(); + + var serialized = []; + var zeroIndexing = this.zeroIndexing_; + + // Add the known fields. + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + + if (!message.has(field)) { + continue; + } + + var tag = field.getTag(); + var index = zeroIndexing ? tag - 1 : tag; + + if (field.isRepeated()) { + serialized[index] = []; + + for (var j = 0; j < message.countOf(field); j++) { + serialized[index][j] = + this.getSerializedValue(field, message.get(field, j)); + } + } else { + serialized[index] = this.getSerializedValue(field, message.get(field)); + } + } + + // Add any unknown fields. + message.forEachUnknown(function(tag, value) { + var index = zeroIndexing ? tag - 1 : tag; + serialized[index] = value; + }); + + return serialized; +}; + + +/** @override */ +goog.proto2.PbLiteSerializer.prototype.deserializeField = + function(message, field, value) { + + if (value == null) { + // Since value double-equals null, it may be either null or undefined. + // Ensure we return the same one, since they have different meanings. + return value; + } + + if (field.isRepeated()) { + var data = []; + + goog.asserts.assert(goog.isArray(value)); + + for (var i = 0; i < value.length; i++) { + data[i] = this.getDeserializedValue(field, value[i]); + } + + return data; + } else { + return this.getDeserializedValue(field, value); + } +}; + + +/** @override */ +goog.proto2.PbLiteSerializer.prototype.getSerializedValue = + function(field, value) { + if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL) { + // Booleans are serialized in numeric form. + return value ? 1 : 0; + } + + return goog.proto2.Serializer.prototype.getSerializedValue.apply(this, + arguments); +}; + + +/** @override */ +goog.proto2.PbLiteSerializer.prototype.getDeserializedValue = + function(field, value) { + + if (field.getFieldType() == goog.proto2.FieldDescriptor.FieldType.BOOL) { + goog.asserts.assert(goog.isNumber(value) || goog.isBoolean(value), + 'Value is expected to be a number or boolean'); + return !!value; + } + + return goog.proto2.Serializer.prototype.getDeserializedValue.apply(this, + arguments); +}; + + +/** @override */ +goog.proto2.PbLiteSerializer.prototype.deserialize = + function(descriptor, data) { + var toConvert = data; + if (this.zeroIndexing_) { + // Make the data align with tag-IDs (1-indexed) by shifting everything + // up one. + toConvert = []; + for (var key in data) { + toConvert[parseInt(key, 10) + 1] = data[key]; + } + } + return goog.base(this, 'deserialize', descriptor, toConvert); +}; diff --git a/pool/shard000/JavaScript/0004363_PenStrokeRight.js b/pool/shard000/JavaScript/0004363_PenStrokeRight.js new file mode 100644 index 0000000000000000000000000000000000000000..13238073f15b2defc372908e20290cdf61aa0c3b --- /dev/null +++ b/pool/shard000/JavaScript/0004363_PenStrokeRight.js @@ -0,0 +1,23 @@ +define([ + './_PenStrokeCenterChild' +], function( + Parent +) { + "use strict"; + function PenStrokeRight() { + Parent.call(this); + } + var _p = PenStrokeRight.prototype = Object.create(Parent.prototype); + _p.constructor = PenStrokeRight; + + Object.defineProperty(_p, 'MOMType', { + value: 'MOM PenStrokeRight' + }); + + Object.defineProperty(_p, 'type', { + /* this is used for CPS selectors */ + value: 'right' + }); + + return PenStrokeRight; +}); diff --git a/pool/shard000/JavaScript/0004364_time_converter.js b/pool/shard000/JavaScript/0004364_time_converter.js new file mode 100644 index 0000000000000000000000000000000000000000..01383002f817cb799c542dbd97ce67c3f878030f --- /dev/null +++ b/pool/shard000/JavaScript/0004364_time_converter.js @@ -0,0 +1,32 @@ +/*************************GO-LICENSE-START********************************* + * Copyright 2014 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. + *************************GO-LICENSE-END**********************************/ + +var CruiseTimeConverter = Class.create({ + fromSecondsToHHMMSS: function(seconds){ + var hour = Math.floor(seconds / 3600); + seconds = seconds - hour * 3600; + var minite = Math.floor(seconds / 60); + seconds = seconds - minite * 60; + + return this._time_to_text(hour) + ':' + + this._time_to_text(minite) + ':' + + this._time_to_text(seconds); + }, + _time_to_text: function(number) { + return ((number > 9)?"":"0") + number; + } +}); +var cruiseTimeConverter = new CruiseTimeConverter(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004366_config.js b/pool/shard000/JavaScript/0004366_config.js new file mode 100644 index 0000000000000000000000000000000000000000..d02b7fe66440759f933b9efd0f4ced81802fb3f2 --- /dev/null +++ b/pool/shard000/JavaScript/0004366_config.js @@ -0,0 +1,25 @@ +'use strict'; + +const VERSION = require('../../package.json').version; +const API_BASE = 'https://api.chartmogul.com'; + +class Config { + constructor (apiKey, apiBase) { + this.apiKey = apiKey; + this.apiBase = apiBase || API_BASE; + } + + getApiKey () { + return this.apiKey; + } + + get VERSION () { + return VERSION; + } + + get API_BASE () { + return this.apiBase; + } +} + +module.exports = Config; diff --git a/pool/shard000/JavaScript/0004367_alarm-watcher.js b/pool/shard000/JavaScript/0004367_alarm-watcher.js new file mode 100644 index 0000000000000000000000000000000000000000..1bfa3d2f709dc70a1ce1f7872ba12190da0993ad --- /dev/null +++ b/pool/shard000/JavaScript/0004367_alarm-watcher.js @@ -0,0 +1,22 @@ +/** + Create by Huy: codocmm@gmail.com ~ nqhuy2k6@gmail.com + 07/31/2015 + */ +define(["backbone", "knockout", "moment", "jquery", "underscore"], function (Backbone, ko, Moment, $, _) { + return Backbone.Model.extend({ + url: "api/AlarmWatchers/", + defaults: {}, + acknowledge: function () { + var that = this; + var params = { + timeout: 30000, + type: "POST", + dataType: "json", + //data: JSON.stringify({id: }), + url: that.url + that.get("id") + "/acknowledge?access_token=" + localStorage.getItem('swagger_accessToken'), + processData: false + }; + return $.ajax(params); + } + }); +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004369_SugarFieldFile.js b/pool/shard000/JavaScript/0004369_SugarFieldFile.js new file mode 100644 index 0000000000000000000000000000000000000000..693e7bfb541242defdda0ff90a6bfaa2fc3e647f --- /dev/null +++ b/pool/shard000/JavaScript/0004369_SugarFieldFile.js @@ -0,0 +1,204 @@ +/********************************************************************************* + * The contents of this file are subject to the SugarCRM Master Subscription + * Agreement ("License") which can be viewed at + * http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf + * By installing or using this file, You have unconditionally agreed to the + * terms and conditions of the License, and You may not use this file except in + * compliance with the License. Under the terms of the license, You shall not, + * among other things: 1) sublicense, resell, rent, lease, redistribute, assign + * or otherwise transfer Your rights to the Software, and 2) use the Software + * for timesharing or service bureau purposes such as hosting the Software for + * commercial gain and/or for the benefit of a third party. Use of the Software + * may be subject to applicable fees and any use of the Software without first + * paying applicable fees is strictly prohibited. You do not have the right to + * remove SugarCRM copyrights from the source code or user interface. + * + * All copies of the Covered Code must include on each user interface screen: + * (i) the "Powered by SugarCRM" logo and + * (ii) the SugarCRM copyright notice + * in the same form as they appear in the distribution. See full license for + * requirements. + * + * Your Warranty, Limitations of liability and Indemnity are expressly stated + * in the License. Please refer to the License for the specific language + * governing these rights and limitations under the License. Portions created + * by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved. + ********************************************************************************/ + + +if ( typeof(SUGAR.field) == 'undefined' ) { + SUGAR.field = new Object(); +} + +if ( typeof(SUGAR.field.file) == 'undefined' ) { + SUGAR.field.file = { + deleteAttachment: function(elemBaseName,docTypeName,elem) { + ajaxStatus.showStatus(SUGAR.language.get("Notes", "LBL_REMOVING_ATTACHMENT")); + elem.form.deleteAttachment.value=1; + elem.form.action.value="EditView"; + SUGAR.dashlets.postForm(elem.form, SUGAR.field.file.deleteAttachmentCallbackGen(elemBaseName,docTypeName)); + elem.form.deleteAttachment.value=0; + elem.form.action.value=""; + }, + deleteAttachmentCallbackGen: function(elemBaseName,docTypeName) { + return function(text) { + if(text == 'true') { + document.getElementById(elemBaseName+'_new').style.display = ''; + ajaxStatus.hideStatus(); + document.getElementById(elemBaseName+'_old').innerHTML = ''; + document.getElementById(docTypeName).disabled = false; + document.getElementById(elemBaseName).value = ''; + } else { + document.getElementById(elemBaseName+'_new').style.display = 'none'; + ajaxStatus.flashStatus(SUGAR.language.get('Notes', 'ERR_REMOVING_ATTACHMENT'), 2000); + } + } + }, + checkEapiLogin: function(res) { + var failedLogins = JSON.parse(res.responseText); + if ( failedLogins.length == 0 ) { return; } + + for ( var idx in failedLogins ) { + if(confirm(failedLogins[idx].label)) { + window.open(failedLogins[idx].checkURL,'EAPM_CHECK_'+idx); + } else { + document.getElementById(res.argument.docTypeName).value = 'Sugar'; + document.getElementById(res.argument.docTypeName).onchange(); + } + } + }, + setupEapiShowHide: function(elemBaseName,docTypeName,formName) { + var externalSearchToggle = function() { + var moreElem = document.getElementById(elemBaseName + "_more"); + var hideMore = (moreElem.style.display == 'none'); + if ( hideMore ) { + // We're hiding the "more" element, so we clicked on the "less" element and want to hide stuff + moreElem.style.display = ''; + document.getElementById(elemBaseName + '_less').style.display = 'none'; + document.getElementById(elemBaseName + '_remoteNameSpan').style.display = 'none'; + document.getElementById(elemBaseName + '_file').disabled = false; + } else { + // We're not hiding the "more" element, so we clicked on the "more" element and want to show stuff + moreElem.style.display = 'none'; + document.getElementById(elemBaseName + '_less').style.display = ''; + document.getElementById(elemBaseName + '_remoteNameSpan').style.display = ''; + document.getElementById(elemBaseName + '_file').disabled = true; + } + } + + var showHideFunc = function() { + var docShowHideElem = document.getElementById(elemBaseName + "_externalApiSelector"); + + var dropdownValue = document.getElementById(docTypeName).value; + if ( typeof(SUGAR.eapm) != 'undefined' + && typeof(SUGAR.eapm[dropdownValue]) != 'undefined' + && typeof(SUGAR.eapm[dropdownValue].docSearch) != 'undefined' + && SUGAR.eapm[dropdownValue].docSearch ) { + docShowHideElem.style.display = ''; + + + // Double check to make sure their login is valid + YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=EAPM&action=CheckLogins&to_pdf=1&api='+dropdownValue,{success:SUGAR.field.file.checkEapiLogin,argument:{'elemBaseName':elemBaseName,'docTypeName':docTypeName}}); + + // Start a refresh of the document cache in the background. Thanks AJAX! + YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=EAPM&action=flushFileCache&to_pdf=1&api='+dropdownValue,{}); + } else { + docShowHideElem.style.display = 'none'; + document.getElementById(elemBaseName + '_file').disabled = false; + } + // Update the quick search + sqs_objects[formName+"_"+elemBaseName+"_remoteName"].api = dropdownValue; + + + // Now time to see if we can select security options + var secLevelBoxElem = document.getElementById(elemBaseName + '_securityLevelBox'); + var secLevelElem = document.getElementById(elemBaseName + '_securityLevel'); + + secLevelElem.options.length = 0; + + if ( SUGAR.eapm[dropdownValue] && SUGAR.eapm[dropdownValue].sharingOptions ) { + var opts = SUGAR.eapm[dropdownValue].sharingOptions; + var i = 0; + + for ( idx in opts ) { + secLevelElem.options[i] = new Option(SUGAR.language.get('app_strings',opts[idx]),idx,false,false); + i++; + } + + secLevelBoxElem.style.display=''; + } else { + secLevelBoxElem.style.display='none'; + } + + } + document.getElementById(docTypeName).onchange = showHideFunc; + + document.getElementById(elemBaseName + '_externalApiLabel').onclick = externalSearchToggle; + showHideFunc(); + }, + +// Select button / popup related functions + openPopup: function(elemBaseName) { + window.open('index.php?module=Documents&action=extdoc&isPopup=1&elemBaseName='+elemBaseName+'&apiName='+document.getElementById('doc_type').value,'sugarPopup','width=600,height=400,menubar=no,toolbar=no,status=no,resizeable=yes,scrollbars=yes'); + }, + + clearRemote: function(elemBaseName) { + document.getElementById('doc_id').value = ''; + document.getElementById(elemBaseName).value = ''; + document.getElementById(elemBaseName + '_remoteName').value = ''; + document.getElementById('doc_url').value = ''; + }, + + populateFromPopup: function(elemBaseName, docId, docName, docUrl, docDirectUrl) { + document.getElementById('doc_id').value = docId; + document.getElementById(elemBaseName).value = docId; + document.getElementById(elemBaseName + '_remoteName').value = docName; + document.getElementById('doc_url').value = docUrl; + }, + + getFileExtension:function(fileName) { + var lastindex = fileName.lastIndexOf("."); + if(lastindex == -1) + return ''; + else + return fileName.substr(++lastindex); + }, + isFileExtensionValid: function(fileName) { + var docType = document.getElementById('doc_type').value; + var fileExtension = this.getFileExtension(fileName); + + if( typeof(SUGAR.eapm[docType]) == 'undefined' || ! SUGAR.eapm[docType].restrictUploadsByExtension ){ + return true; + } + var whiteSuffixlist = SUGAR.eapm[docType]['restrictUploadsByExtension']; + if(whiteSuffixlist.constructor == Array){ + var results = false; + for(var i=0;i 0) { + return 1; + } + return 0; + }, + color: function (data, index) { + return data.color || globals_1.default.COLORS[index].hex(); + } +}; +exports.default = utils; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004387_Exporter.js b/pool/shard000/JavaScript/0004387_Exporter.js new file mode 100644 index 0000000000000000000000000000000000000000..872fda81888b7f85fa2b03dab5b7942134d35566 --- /dev/null +++ b/pool/shard000/JavaScript/0004387_Exporter.js @@ -0,0 +1,42 @@ +export default class Exporter { + constructor(editor) { + this.editor = editor; + } + + getData() { + var tweenTime = this.editor.tweenTime; + var domain = this.editor.timeline.x.domain(); + var domain_start = domain[0]; + var domain_end = domain[1]; + return { + settings: { + time: tweenTime.timer.getCurrentTime(), + duration: tweenTime.timer.getDuration(), + domain: [domain_start.getTime(), domain_end.getTime()] + }, + data: tweenTime.data + }; + } + + getJSON() { + var options = this.editor.options; + var json_replacer = function(key, val) { + // Disable all private properies from TweenMax/TimelineMax + if (key.indexOf('_') === 0) { + return undefined; + } + if (options.json_replacer !== undefined) { + return options.json_replacer(key, val); + } + return val; + }; + + var data = this.getData(); + // Give the possibility to add your own data in the export. + // ex: new Editor({getJSON: function(data) {data.test = 42; return data;} }) + if (typeof this.editor.options.getJSON !== 'undefined') { + data = this.editor.options.getJSON(data); + } + return JSON.stringify(data, json_replacer, 2); + } +} diff --git a/pool/shard000/JavaScript/0004388_index.js b/pool/shard000/JavaScript/0004388_index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce5d48b56a059cf065ee956f3402b216bdf106b6 --- /dev/null +++ b/pool/shard000/JavaScript/0004388_index.js @@ -0,0 +1,57 @@ +var express = require('express') + , fetcher = require('./lib/fetcher') + , writer = require('./lib/writer') + , buildStaticSite = require('./lib/smithy') + , dataServiceInitializer = require('./lib/data') + , config = require('./lib/config') + , app = express() + ; + +// Fail fast. +if (! process.env.REDIS_URL) { + throw new Error('Missing environment variable REDIS_URL.'); +} + +console.log(config); + +// We initialize the redis writer first. +writer.initialize(function(connectionError) { + if (connectionError) { + console.log(connectionError); + process.exit(-1); + } + // The callback sent to the fetcher will be called every minute with new data + // that needs to be stored in redis by the writer initialized above. + fetcher(function(fetchError, data) { + if (fetchError) { + console.error('Error fetching new traffic data:'); + console.error(fetchError); + } else { + // Writes new traffic data to redis. + writer.write(data, function(writeError) { + if (writeError) { + console.error('Error writing new traffic data:'); + console.error(writeError); + } else { + console.log('Write completed at %s', new Date().toString()); + } + }); + } + }); +}); + +// The data service exposes HTTP endpoints so users can query the traffic data +// stored in redis by the fetcher and writer above. +dataServiceInitializer(function(connectionError, requestHandler) { + if (connectionError) { + console.log(connectionError); + process.exit(-1); + } + buildStaticSite(); + app.use(express.static('build')); + app.use('/:trafficRoute*', requestHandler); + app.listen(config.port, function(error) { + if (error) return console.error(error); + console.log('%s:%s', config.host, config.port); + }); +}); diff --git a/pool/shard000/JavaScript/0004393_mocha-runner.js b/pool/shard000/JavaScript/0004393_mocha-runner.js new file mode 100644 index 0000000000000000000000000000000000000000..92e16d817e1d99ad55cbbdbd7c76272392c4ef47 --- /dev/null +++ b/pool/shard000/JavaScript/0004393_mocha-runner.js @@ -0,0 +1,16 @@ +/** + * Run test specs in mocha environment + */ + +var should = require('should'); + +describe('mocha demo', function(){ + it('should return a number', function(){ + var a = 4; + a.should.be.a.Number; + }); + it('should return a string', function(){ + var num = '4'; + num.should.be.a.String; + }); +}); diff --git a/pool/shard000/JavaScript/0004395_index.js b/pool/shard000/JavaScript/0004395_index.js new file mode 100644 index 0000000000000000000000000000000000000000..ca3e4578bbab423a140468ce110eb365f67af4bf --- /dev/null +++ b/pool/shard000/JavaScript/0004395_index.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = function (_ref) { + var types = _ref.types; + return { + visitor: { + Program: { + exit: function exit(path) { + if (path.BABEL_PLUGIN_EXPORT_DEFAULT_MODULE_EXPORTS) { + return; + } + + var hasExportDefault = false; + var hasExportNamed = false; + + path.get('body').forEach(function (path) { + if (path.isExportDefaultDeclaration()) { + hasExportDefault = true; + return; + } + + if (path.isExportNamedDeclaration()) { + if (path.node.specifiers.length === 1 && path.node.specifiers[0].exported.name === 'default') { + hasExportDefault = true; + } else { + hasExportNamed = true; + } + return; + } + }); + + if (!hasExportDefault && hasExportNamed) { + var moduleExports = types.memberExpression(types.identifier('module'), types.identifier('exports')); + path.pushContainer('body', [types.expressionStatement(types.assignmentExpression('=', types.memberExpression(types.identifier('exports'), types.stringLiteral('default'), true), types.memberExpression(types.identifier('module'), types.identifier('exports')))), types.exportDefaultDeclaration(moduleExports)]); + } + + path.BABEL_PLUGIN_EXPORT_DEFAULT_MODULE_EXPORTS = true; + } + } + } + }; +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004400_import.js b/pool/shard000/JavaScript/0004400_import.js new file mode 100644 index 0000000000000000000000000000000000000000..9a49446d528a49647cac9f8305c654f3fe46091e --- /dev/null +++ b/pool/shard000/JavaScript/0004400_import.js @@ -0,0 +1,329 @@ +/*jshint globalstrict:false, strict:false */ +/*global assertEqual */ + +//////////////////////////////////////////////////////////////////////////////// +/// @brief tests for import +/// +/// @file +/// +/// DISCLAIMER +/// +/// Copyright 2010-2012 triagens GmbH, Cologne, Germany +/// +/// 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. +/// +/// Copyright holder is triAGENS GmbH, Cologne, Germany +/// +/// @author Jan Steemann +/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany +//////////////////////////////////////////////////////////////////////////////// + +var internal = require("internal"); +var jsunity = require("jsunity"); +var ArangoError = require("@arangodb").ArangoError; + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test suite +//////////////////////////////////////////////////////////////////////////////// + +function importTestSuite () { + 'use strict'; + var errors = internal.errors; + +//////////////////////////////////////////////////////////////////////////////// +/// @brief return the error code from a result +//////////////////////////////////////////////////////////////////////////////// + + function getErrorCode (fn) { + try { + fn(); + } + catch (e) { + return e.errorNum; + } + } + +//////////////////////////////////////////////////////////////////////////////// +/// @brief execute a given query +//////////////////////////////////////////////////////////////////////////////// + + function executeQuery (query) { + var statement = internal.db._createStatement({"query": query}); + if (statement instanceof ArangoError) { + return statement; + } + + var cursor = statement.execute(); + return cursor; + } + +//////////////////////////////////////////////////////////////////////////////// +/// @brief execute a given query and return the results as an array +//////////////////////////////////////////////////////////////////////////////// + + function getQueryResults (query) { + var result = executeQuery(query); + var results = [ ]; + + while (result.hasNext()) { + var keys = [ ]; + var row = result.next(); + var k; + for (k in row) { + if (row.hasOwnProperty(k) && k !== '_id' && k !== '_rev' && k !== '_key') { + keys.push(k); + } + } + + keys.sort(); + var resultRow = { }; + for (k in keys) { + if (keys.hasOwnProperty(k)) { + resultRow[keys[k]] = row[keys[k]]; + } + } + + results.push(resultRow); + } + + return results; + } + + return { + +//////////////////////////////////////////////////////////////////////////////// +/// @brief set up +//////////////////////////////////////////////////////////////////////////////// + + setUp : function () { + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief tear down +//////////////////////////////////////////////////////////////////////////////// + + tearDown : function () { + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json import +//////////////////////////////////////////////////////////////////////////////// + + testJsonImport1 : function () { + var expected = [ { "id": 1, + "one": 1, + "three": 3, + "two": 2 }, + { "a": 1234, + "b": "the quick fox", + "id": 2, + "jumped": + "over the fox", + "null": null }, + { "id": 3, + "not": "important", + "spacing": "is" }, + { " c ": "h\"'ihi", + "a": true, + "b": false, + "d": "", + "id": 4 }, + { "id": 5 } ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportJson1 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json import +//////////////////////////////////////////////////////////////////////////////// + + testJsonImport2 : function () { + var expected = [ { "id": 1, "value": -445.4 }, { "id": 2, "value": 34000 }, { "id": 3, "value": null } ]; + var actual = getQueryResults("FOR i IN UnitTestsImportJson2 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json import +//////////////////////////////////////////////////////////////////////////////// + + testJsonImport3 : function () { + var expected = [ + { "id": 1, "one": 1, "three": 3, "two": 2 }, + { "a": 1234, "b": "the quick fox", "id": 2, "jumped": "over the fox", "null": null }, + { "id": 3, "not": "important", "spacing": "is" }, + { " c ": "h\"'ihi", "a": true, "b": false, "d": "", "id": 4 }, + { "id": 5 } + ]; + var actual = getQueryResults("FOR i IN UnitTestsImportJson3 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json import +//////////////////////////////////////////////////////////////////////////////// + + testJsonImport4 : function () { + var expected = [ ]; + for (var i = 0; i < 1000; ++i) { + expected.push({ "active": true, "id": i, "value": "somerandomstuff" + i }); + } + var actual = getQueryResults("FOR i IN UnitTestsImportJson4 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json import +//////////////////////////////////////////////////////////////////////////////// + + testJsonImport5 : function () { + var expected = [ + { "active": true, "id": 0, "value": "something" }, + { "id": 1, "value": "foobar" }, + { "id": 2, "data": 99.5, "true": "a\t\r\nb c " } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportJson5 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test csv import +//////////////////////////////////////////////////////////////////////////////// + + testCsvImport1 : function () { + var expected = [ + { "a": "1", "b": 1, "c": "1.3", "e": -5, "id": 1 }, + { "b": "", "c": 3.1, "d": -2.5, "e": "ddd \" ' ffd", "id": 2 }, + { "a": "9999999999999999999999999999999999", "b": "test", "c" : -99999999, "d": true, "e": -888.4434, "id": 5 }, + { "a": 10e4, "b": 20.5, "c": -42, "d": " null ", "e": false, "id": 6 }, + { "a": -1.05e2, "b": 1.05e-2, "c": true, "d": false, "id": 7 } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportCsv1 SORT i.id RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test csv import +//////////////////////////////////////////////////////////////////////////////// + + testCsvImport2 : function () { + assertEqual(errors.ERROR_ARANGO_COLLECTION_NOT_FOUND.code, + getErrorCode(function() { executeQuery("FOR i IN UnitTestsImportCsv2 SORT i.id RETURN i"); } )); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test csv import +//////////////////////////////////////////////////////////////////////////////// + + testCsvImport3 : function () { + var expected = [ + { name: "Bar", password: "wow!\nthis is a\nmultiline password!" }, + { name: "Bartholomew \"Bart\" Simpson", password: "Milhouse" }, + { name: "Foo", password: "r4\\nd\\\\om\"123!" } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportCsv3 SORT i.name RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test csv import +//////////////////////////////////////////////////////////////////////////////// + + testCsvImport4 : function () { + var expected = [ + { name: "Bar", password: "wow!\nthis is a\nmultiline password!" }, + { name: "Bartholomew \"Bart\" Simpson", password: "Milhouse" }, + { name: "Foo", password: "r4\\nd\\\\om\"123!" } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportCsv4 SORT i.name RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test csv import +//////////////////////////////////////////////////////////////////////////////// + + testCsvImport5 : function () { + var expected = [ + { name: "bar", password: "foo" }, + { name: "foo\t", password: "wow \t \r\nthis is \t\ra multiline password!" } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportCsv5 SORT i.name RETURN i"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test tsv import +//////////////////////////////////////////////////////////////////////////////// + + testTsvImport1 : function () { + var expected = [ { "ab": "g", "cd": "h", "ef": "i" }, { "ab" : "j", "cd" : "k", "ef" : "l" } ]; + var actual = getQueryResults("FOR i IN UnitTestsImportTsv1 SORT i.ab RETURN i"); + + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test tsv import +//////////////////////////////////////////////////////////////////////////////// + + testTsvImport2 : function () { + var expected = [ { " fox" : "dog", + "brown " : " the lazy", + "the quick": " jumped over" }, + { " fox" : " end", + "brown " : "\"\"\"", + "the quick" : "\"'.,;" } ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportTsv2 SORT i.` fox` DESC RETURN i"); + + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test json edge import +//////////////////////////////////////////////////////////////////////////////// + + testJsonEdgesImport : function () { + var expected = [ + { _from : "UnitTestsImportVertex/v1", _to: "UnitTestsImportVertex/v2", id: 1, what: "v1->v2" }, + { _from : "UnitTestsImportVertex/v2", _to: "UnitTestsImportVertex/v3", id: 2, what: "v2->v3" }, + { _from : "UnitTestsImportVertex/v9", _to: "UnitTestsImportVertex/v4", extra: "foo", id: 3, what: "v9->v4" }, + { _from : "UnitTestsImportVertex/v12", _to: "UnitTestsImportVertex/what", id: 4 } + ]; + + var actual = getQueryResults("FOR i IN UnitTestsImportEdge SORT i.id RETURN i"); + assertEqual(expected, actual); + } + + }; +} + +//////////////////////////////////////////////////////////////////////////////// +/// @brief executes the test suite +//////////////////////////////////////////////////////////////////////////////// + +jsunity.run(importTestSuite); + +return jsunity.done(); + +// Local Variables: +// mode: outline-minor +// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)" +// End: diff --git a/pool/shard000/JavaScript/0004401_index.js b/pool/shard000/JavaScript/0004401_index.js new file mode 100644 index 0000000000000000000000000000000000000000..cf0cb2def80a09bdcd6c69cbc11d6af54dc0f2a5 --- /dev/null +++ b/pool/shard000/JavaScript/0004401_index.js @@ -0,0 +1,27 @@ +/** + * Node.js stats module + * + * @see: https://github.com/watson/talks/tree/master/2016/06%20NodeConf%20Oslo/example-app/stats/ + */ +'use strict' + +var agent = module.exports = {}; + +require('./async-hook')(agent); // Hook into nextTick, timers and Promise in Node core +require('./async-wrap')(agent); // Use AsyncWrap + +require('./tracers')(agent); // Custom traces + +var util = require('util'); +var Transaction = require('./transaction'); + +agent.newTransaction = function newTransaction(ae, req, res, tags) { + agent.currentTransaction = new Transaction(ae, req, res, tags); + agent.currentTransaction.req = req; + return agent.currentTransaction; +} + +agent.newTrace = function newTrace(name) { + if (!agent.currentTransaction) return; + return agent.currentTransaction.newTrace(name); +} diff --git a/pool/shard000/JavaScript/0004402_request.js b/pool/shard000/JavaScript/0004402_request.js new file mode 100644 index 0000000000000000000000000000000000000000..c8d4473b20d327e5c7e140b585aff9348494bd91 --- /dev/null +++ b/pool/shard000/JavaScript/0004402_request.js @@ -0,0 +1,84 @@ +/** + * Request.js is heavily based off the work done by TJ Holowaychuk + * and all the other contributers to Express.js + * + * https://github.com/visionmedia/express/blob/master/lib/request.js + */ + + +var http = require('http'), + utils = require('./utils'), + mime = require('mime'); + +/** + * Request prototype. + */ + +var req = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * @param {String} name + * @return {String} + */ + +req.get = req.header = function(name) { + name = name.toLowerCase(); + + switch (name) { + case 'referer': + return this.headers.referrer || this.headers.referer; + case 'referrer': + return this.headers.referrer || this.headers.referer; + default: + return this.headers[name]; + } +}; + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * @param {String|Array} type(s) + * @return {String} + */ + +req.accepts = function(type){ + return utils.accepts(type, this.get('Accept')); +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * @param {String} type + * @return {Boolean} + */ + +req.is = function(type){ + var ct = this.get('Content-Type'); + if (!ct) return false; + ct = ct.split(';')[0]; + if (!~type.indexOf('/')) type = mime.lookup(type); + if (~type.indexOf('*')) { + type = type.split('/'); + ct = ct.split('/'); + if ('*' == type[0] && type[1] == ct[1]) return true; + if ('*' == type[1] && type[0] == ct[0]) return true; + return false; + } + return !! ~ct.indexOf(type); +}; diff --git a/pool/shard000/JavaScript/0004408_StrenNGen.js b/pool/shard000/JavaScript/0004408_StrenNGen.js new file mode 100644 index 0000000000000000000000000000000000000000..f3e9f2f82f17c5c732b09d8e60d04ffc4edb355f --- /dev/null +++ b/pool/shard000/JavaScript/0004408_StrenNGen.js @@ -0,0 +1,231 @@ +/*! + * strength.js + * Original author: @aaronlumsden + * Further changes, comments: @aaronlumsden + * Licensed under the MIT license + */ +;(function ( $, window, document, undefined ) { + + var pluginName = "strenNgen", + defaults = { + confirmPassword: '', + strengthMeterBar: '', + generatePassword: '', + progressBar: '.progress-bar', + strengthMeterLabel: '', + minStrengthValid: 6, + minPasswordLength: 8 + }; + + // $('').appendTo('head'); + + function Plugin( element, options ) { + this.element = element; + this.$elem = $(this.element); + this.options = $.extend( {}, defaults, options ); + this._defaults = defaults; + this._name = pluginName; + this.init(); + } + + + + Plugin.prototype = { + + init: function() { + + var confirmPassword = this.options.confirmPassword, + strengthMeterBar = this.options.strengthMeterBar, + generatePassword = this.options.generatePassword, + progressBar = this.options.progressBar, + strengthMeterLabel = this.options.strengthMeterLabel, + minStrengthValid = this.options.minStrengthValid, + minPasswordLength = this.options.minPasswordLength, + me = this.$elem; + + var strengthMeterBar = $( strengthMeterBar ), + progressBar = strengthMeterBar.children( progressBar ); + + + progressBar.text( strengthMeterLabel ); + + var forbiddenSequences = [ + '0123456789', + 'abcdefghijklmnopqrstuvwxyz', + 'qwertyuiop', + 'asdfghjkl', + 'zxcvbnm', + '!@#$%^&*()_+' + ]; + + var scoreChars = 0; + var scoreUppercase = 0; + var scoreLowercase = 0; + var scoreOneNumber = 0; + var scoreThreeNumbers = 0; + var scoreOneSpecialChar = 0; + var scoreTwoSpecialChar = 0; + var scoreRepetitions = 0; + + var wordLowercase = new RegExp( '[a-z]' ); + var wordUppercase = new RegExp( '[A-Z]' ); + var wordOneNumber = new RegExp( '[0-9]' ); + var wordThreeNumbers = new RegExp( '(.*[0-9].*[0-9].*[0-9])' ); + var wordOneSpecialChar = new RegExp( '([!,%,&,@,#,$,^,*,?,_,~])' ); + var wordTwoSpecialChar = new RegExp( '(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])' ); + + function GetPercentage( a, b ) { + return ( ( b / a ) * 100 ); + } + + function calc_strength( thisval ){ + + if( thisval.length >= minPasswordLength ){ + scoreChars = 1; + }else{ + scoreChars = -1; + } + if( thisval.match( wordLowercase ) ){ + scoreLowercase = 1; + }else{ + scoreLowercase = 0; + } + if( thisval.match( wordUppercase ) ){ + scoreUppercase = 1; + }else{ + scoreUppercase = 0; + } + if( thisval.match( wordOneNumber ) ){ + scoreOneNumber = 1; + }else{ + scoreOneNumber = 0; + } + if( thisval.match( wordThreeNumbers ) ){ + scoreThreeNumbers = 1; + }else{ + scoreThreeNumbers = 0; + } + if( thisval.match( wordOneSpecialChar ) ){ + scoreOneSpecialChar = 1; + }else{ + scoreOneSpecialChar = 0; + } + if( thisval.match( wordTwoSpecialChar ) ){ + scoreTwoSpecialChar = 1; + }else{ + scoreTwoSpecialChar = 0; + } + + + var total = scoreChars + scoreUppercase + scoreLowercase + scoreOneNumber + scoreThreeNumbers + scoreOneSpecialChar + scoreTwoSpecialChar; + var totalpercent = GetPercentage( 7, total ).toFixed(0); + + if( !thisval.length ){ + total = -1; + } + + write_strength( total, totalpercent ); + + } + + function write_strength( total, totalpercent ){ + + progressBar.animate( { width: totalpercent + '%' }, 10 ); + + if( total == -1 ){ + strengthMeterBar.removeClass().children( progressBar ).text( strengthMeterLabel ); + }else{ + + if( total == 2 || total == 3 ){ + strengthClass = 'weak'; + strengthMessage = 'Weak'; + } + else if( total == 4 ){ + strengthClass = 'medium'; + strengthMessage = 'Medium'; + } + else if( total == 5 | total == 6 ){ + strengthClass = 'strong'; + strengthMessage = 'Strong'; + } + else if( total >= 7 ){ + strengthClass = 'verystrong'; + strengthMessage = 'Very strong'; + } + else{ + strengthClass = 'tooweak'; + strengthMessage = 'Too weak'; + } + + strengthMeterBar.attr( 'class', strengthClass ).children( progressBar ).text( strengthMessage ); + + } + + if( total >= minStrengthValid ){ + me.removeClass( 'invalid-password' ); + }else{ + me.addClass( 'invalid-password' ); + } + + } + + + + $( me ).bind( 'keyup keydown', function( e ) { + calc_strength( $( this ).val() ); + }); + + $( document ).ready(function() { //Quick dirty + calc_strength( $( me ).val() ); + }) + + $( generatePassword ).bind( 'click', function( e ) { + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz', + numbs = '01234567890', + spesh = '!@#$%^_~*?', + randomstring = ''; + + for ( var i = 0; i < minPasswordLength; i++ ) { + if( i == 4 || i == 9 || i == 14 ){ + targ = spesh; + }else if( i == 2 || i == 6 ){ + targ = numbs; + }else{ + targ = chars; + } + var rnum = Math.floor( Math.random() * targ.length ); + randomstring += targ.substring( rnum, rnum +1 ); + } + + $( me ).val( randomstring ); + if( confirmPassword != '' ){ + $( confirmPassword ).val( randomstring ); + } + calc_strength( $( me ).val() ); + + }); + + + + + + + + }, + + + }; + + + $.fn[pluginName] = function ( options ) { + return this.each(function () { + if (!$.data(this, "plugin_" + pluginName)) { + $.data(this, "plugin_" + pluginName, new Plugin( this, options )); + } + }); + }; + +})( jQuery, window, document ); + + diff --git a/pool/shard000/JavaScript/0004409_chart.js b/pool/shard000/JavaScript/0004409_chart.js new file mode 100644 index 0000000000000000000000000000000000000000..725c5eb28b2574270af6c2a44de8943a7d62c05d --- /dev/null +++ b/pool/shard000/JavaScript/0004409_chart.js @@ -0,0 +1,191 @@ +/* +This file implements the chart view for the environment. The chart view is made +up of the chart widget, a sidebar, an exporter and other things. + +If you're looking for the chart widget which is embedded in this view, check out +`chart/chart.js`. +*/ +import {html, forward, Effects, Task, thunk} from 'reflex'; +import {merge, tagged, tag, batch} from '../common/prelude'; +import {cursor} from '../common/cursor'; +import {update as updateUnknown} from '../common/unknown'; +import {compose} from '../lang/functional'; +import {findRunningRecipe, findAirTemperature} from './doc'; + +// Import Chart d3 widget +import * as Chart from './chart/chart'; +import * as Sidebar from './chart/sidebar'; + +// Import shared environment widgets +import * as Toolbox from '../environment/toolbox'; +import * as Exporter from '../environment/exporter'; + +// Action and tagging functions + +const RequestOpenRecipes = { + type: 'RequestOpenRecipes' +}; + +const TagExporter = tag('Exporter'); +const OpenExporter = TagExporter(Exporter.Open); +export const Configure = compose(TagExporter, Exporter.Configure); + +export const AddData = value => ({ + type: 'AddData', + value +}); + +const TagSidebar = action => + action.type === 'RequestOpenRecipes' ? + RequestOpenRecipes : + action.type === 'DropMarker' ? + DropMarker : + tagged('Sidebar', action); + +export const SetRecipe = compose(TagSidebar, Sidebar.SetRecipe); +const SetAirTemperature = compose(TagSidebar, Sidebar.SetAirTemperature); + +const TagToolbox = action => + action.type === 'OpenExporter' ? + OpenExporter : + tagged('Toolbox', action); + +const TagChart = action => + tagged('Chart', action); + +const AddChartData = compose(TagChart, Chart.AddData); + +const ChartLoading = compose(TagChart, Chart.Loading); +// Drop a marker (in the chart) +const DropMarker = TagChart(Chart.DropMarker); + +// Init and Update + +export const init = (id) => { + const [chart, chartFx] = Chart.init(); + const [exporter, exporterFx] = Exporter.init(); + const [sidebar, sidebarFx] = Sidebar.init(); + + return [ + { + id, + chart, + exporter, + sidebar, + isLoading: true + }, + Effects.batch([ + chartFx.map(TagChart), + exporterFx.map(TagExporter), + sidebarFx.map(TagSidebar) + ]) + ]; +} + +export const update = (model, action) => + action.type === 'Exporter' ? + updateExporter(model, action.source) : + action.type === 'Chart' ? + updateChart(model, action.source) : + action.type === 'Sidebar' ? + updateSidebar(model, action.source) : + action.type === 'AddData' ? + addData(model, action.value) : + updateUnknown(model, action); + +const updateSidebar = cursor({ + get: model => model.sidebar, + set: (model, sidebar) => merge(model, {sidebar}), + update: Sidebar.update, + tag: TagSidebar +}); + +const updateExporter = cursor({ + get: model => model.exporter, + set: (model, exporter) => merge(model, {exporter}), + update: Exporter.update, + tag: TagExporter +}); + +const updateChart = cursor({ + get: model => model.chart, + set: (model, chart) => merge(model, {chart}), + update: Chart.update, + tag: TagChart +}); + +const addData = (model, data) => { + const next = merge(model, { + // We've received data, so we're no longer in loading state. + isLoading: false + }); + + const actions = [ + AddChartData(data) + ]; + + // find air temperature + const airTemperature = findAirTemperature(data); + if (airTemperature) { + actions.push(SetAirTemperature(airTemperature)); + } + + const recipeStart = findRunningRecipe(data); + if (recipeStart) { + const id = recipeStart._id; + const name = readRecipeName(recipeStart); + actions.push(SetRecipe(id, name)); + } + + return batch(update, next, actions); +} + +// View + +export const view = (model, address) => + (model.id && !model.isLoading) ? + viewReady(model, address) : + viewUnready(model, address); + +const viewReady = (model, address) => + html.div({ + className: 'chart-view split-view' + }, [ + thunk( + 'chart', + Chart.view, + model.chart, + forward(address, TagChart) + ), + thunk( + 'sidebar', + Sidebar.view, + model.sidebar, + forward(address, TagSidebar) + ), + thunk('chart-toolbox', Toolbox.view, model, forward(address, TagToolbox)), + thunk( + 'chart-export', + Exporter.view, + model.exporter, + forward(address, TagExporter), + model.id + ) + ]); + +const viewUnready = (model, address) => + html.div({ + className: 'chart-view split-view' + }, [ + thunk( + 'sidebar', + Sidebar.view, + model.sidebar, + forward(address, TagSidebar) + ), + html.div({ + className: 'chart-view-content chart-view-content--loading split-view-content' + }) + ]); + +const readRecipeName = recipe => (recipe.name ? recipe.name : recipe.value); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004411_repository.service.js b/pool/shard000/JavaScript/0004411_repository.service.js new file mode 100644 index 0000000000000000000000000000000000000000..b6a5312f3895d5155910738d317d2d01856685a3 --- /dev/null +++ b/pool/shard000/JavaScript/0004411_repository.service.js @@ -0,0 +1,209 @@ +/*! + * Copyright 2019 Hitachi Vantara. 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. + */ + +/** + * The Repository Service + * + * The Repository Service, a collection of endpoints used by the application + * + * @module services/data.service + * @property {String} name The name of the module. + */ +define( + [ + "../../components/utils", + "../data.service" + ], + function (utils) { + "use strict"; + + var factoryArray = ["helperService", "dataService", "$http", "$q", factory]; + var module = { + name: "repositoryService", + factory: factoryArray + }; + + return module; + + /** + * The dataService factory + * + * @param {Object} $http - The $http angular helper service + * + * @return {Object} The dataService api + */ + function factory(helperService, dt, $http, $q) { + var baseUrl = "/cxf/browser-new"; + return { + provider: "repository", + order: 1, + matchPath: matchPath, + selectFolder: selectFolder, + getTreePath: getTreePath, + getFilePath: getFilePath, + createFolder: createFolder, + addFolder: addFolder, + deleteFiles: deleteFiles, + renameFile: renameFile, + isCopy: isCopy, + open: open, + save: save, + resolvePath: resolvePath, + getBreadcrumbPath: getBreadcrumbPath, + getPath: getPath + }; + + function getPath(file) { + return file.root ? _getTreePath(file) : file.path; + } + + function getBreadcrumbPath(file) { + var path = { + type: "repository", + fileType: file.type ? file.type : "folder", + prefix: null, + uri: _getFilePath(file), + path: _getTreePath(file) + }; + return path; + } + + function _getTreePath(folder) { + if (!folder.path) { + return folder.root ? folder.root + "/" + folder.name : folder.name; + } + return folder.root + folder.path; + } + + function _getFilePath(file) { + return file.path ? file.path : null; + } + + function resolvePath(path, properties) { + return $q(function (resolve, reject) { + resolve("Pentaho Repository" + path); + }); + } + + function matchPath(path) { + return path && path.indexOf("/") === 0; + } + + function selectFolder(folder, filters, useCache) { + return $q(function (resolve, reject) { + if (folder.path && !folder.loaded) { + getFiles(folder, filters, useCache).then(function (response) { + folder.children = response.data; + folder.loaded = true; + for (var i = 0; i < folder.children.length; i++) { + folder.children[i].provider = folder.provider; + } + resolve(); + }); + } else { + resolve(); + } + }); + } + + function getTreePath(folder) { + return folder.root + folder.path; + } + + function getFilePath(file) { + return file.path; + } + + + function createFolder(node, name) { + return $q(function (resolve, reject) { + getFiles(node).then(function (response) { + node.loaded = true; + resolve(response.data); + }); + }); + } + + /** + * Gets the directory tree for the currently connected repository + * + * @return {Promise} - a promise resolved once data is returned + */ + function getFiles(folder, filters, useCache) { + var parameters = { + "filters": filters, + "useCache": useCache + }; + return helperService.httpPost([baseUrl, "getFiles"].join("/") + utils.buildParameters(parameters), folder); + } + + function deleteFiles(files) { + return helperService.httpPost([baseUrl, "delete"].join("/"), files); + } + + function addFolder(folder) { + return $q(function (resolve, reject) { + return helperService.httpPut([baseUrl, "add"].join("/"), folder).then(function (response) { + folder.objectId = response.data.data; + resolve(response); + }); + }); + } + + function renameFile(file, newPath) { + return $q(function (resolve, reject) { + return helperService.httpPost([baseUrl, "rename"].join("/") + "?newPath=" + newPath, file).then(function (response) { + file.objectId = response.data.data; + if (file.type === "transformation") { + file.path = newPath + ".ktr"; + } + if (file.type === "job") { + file.path = newPath + ".kjb"; + } + resolve(response); + }); + }); + } + + function isCopy(from, to) { + return from.provider !== to.provider; + } + + function open(file) { + select(file.objectId, file.name, file.path, file.parent,null, file.provider, file.type); + } + + function save(filename, folder, currentFilename, override) { + return $q(function(resolve, reject) { + dt.checkForSecurityOrDupeIssues(folder.path, filename, currentFilename, override ? override : false).then(function(response) { + if (response.status === 200) { + select(null, filename, null, folder.path, null, folder.provider, null); + resolve(); + } else { + reject(); + } + }, function() { + reject(); + }); + }); + } + + function _getName(path) { + var newPath = path.substr(path.lastIndexOf("/") + 1, path.length); + return newPath.substr(0, newPath.lastIndexOf(".")); + } + } + }); diff --git a/pool/shard000/JavaScript/0004414_FacilityServiceTest.js b/pool/shard000/JavaScript/0004414_FacilityServiceTest.js new file mode 100644 index 0000000000000000000000000000000000000000..70404c2d0636ce625b2709767a0b8cddde97b519 --- /dev/null +++ b/pool/shard000/JavaScript/0004414_FacilityServiceTest.js @@ -0,0 +1,37 @@ +/* jslint node: true */ +/* eslint-env mocha */ + +const chai = require('chai'); +const chaiAsPromised = require("chai-as-promised"); +chai.use(chaiAsPromised); +const expect = chai.expect; + +const FacilityLoaderMock = require('./FacilityLoaderMock.js'); +const FacilityService = require('./../../Facility/FacilityService.js'); + + +describe('FacilityService', () => { + var facilityLoaderMock = new FacilityLoaderMock(); + let facilityServcie = new FacilityService(facilityLoaderMock) + + beforeEach(function() { + facilityLoaderMock = new FacilityLoaderMock(); + facilityServcie = new FacilityService(facilityLoaderMock); + }); + + it('stationByEvaId should return valid station', () => { + facilityLoaderMock.result = require('./FacilitiesMockResults'); + let promise = facilityServcie.facilitiesForStationNumber(1).then(facilities => facilities[0]); + + return Promise.all([ + expect(promise).to.eventually.have.property("equipmentNumber", 10355942), + expect(promise).to.eventually.have.property("type", "ELEVATOR"), + expect(promise).to.eventually.have.property("description", "zu Gleis 6/7"), + expect(promise).to.eventually.have.property("state", "ACTIVE"), + expect(promise).to.eventually.have.deep.property("location", {latitude: 50.767629, longitude: 6.09134}) + + ]); + }); + + +}); diff --git a/pool/shard000/JavaScript/0004415_notification.js b/pool/shard000/JavaScript/0004415_notification.js new file mode 100644 index 0000000000000000000000000000000000000000..b21c2c7cc2f783f56a3ab3066aedfbffe2cba89e --- /dev/null +++ b/pool/shard000/JavaScript/0004415_notification.js @@ -0,0 +1,21 @@ +var client = require('twilio')( + process.env.TWILIO_ACCOUNT_SID || 'AC2f96ac34eac1c6979002dd71c97b54aa', + process.env.TWILIO_AUTH_TOKEN || 'b734790d50e19c27b1c08ee0d3736662' +); + + +const smsToUser = function(receiver,msg,callback) { + client.messages.create({ + from: process.env.TWILIO_PHONE_NUMBER || '+14152125199' , + to: receiver, + body: msg + }, function(err, message) { + err ? callback(err) : callback(null,message) + }); + +} + + +module.exports = { + smsToUser:smsToUser +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004419_skeleton_assembler_colors.js b/pool/shard000/JavaScript/0004419_skeleton_assembler_colors.js new file mode 100644 index 0000000000000000000000000000000000000000..4bc3bc356892641b10a9b63c8fdcbcb9d73fcd4f --- /dev/null +++ b/pool/shard000/JavaScript/0004419_skeleton_assembler_colors.js @@ -0,0 +1,60 @@ +/* + * grunt-skeleton-assembler-colors + * https://github.com/ginetta/grunt-skeleton-assembler-colors + * + * Copyright (c) 2015 Ginetta + * Licensed under the MIT license. + */ + +"use strict"; + +var _ = require("lodash"); +var theo = require("theo"); + + + +var THEO_ADAPTED_TMP_PATH = ".tmp/theo/adapters/"; +var THEO_GENERATED_TMP_PATH = ".tmp/theo/generated/"; +var CUSTOM_THEO_TEMPLATES_PATH = __dirname + "/custom-theo-templates"; + +module.exports = function(grunt) { + + function generateAdaptedColorsSpec (options) { + var colorsSpec = grunt.file.readJSON(options.src); + var adapted = []; + _.each(colorsSpec, function (colors, palette) { + _.each(colors, function (color, name) { + adapted.push({ palette: palette, name: name, value: color, category: "color", comment: "" }); + }); + + }); + + var finalAdapted = { theme: { properties: adapted } }; + + grunt.file.write(THEO_ADAPTED_TMP_PATH + options.destName + ".json", JSON.stringify(finalAdapted, undefined, 2)); + } + + function generateSass (options) { + theo.convert( THEO_ADAPTED_TMP_PATH + options.destName + ".json", THEO_GENERATED_TMP_PATH, + { + templates: ["scss"], + templatesDirectory: CUSTOM_THEO_TEMPLATES_PATH + } + ); + var sassContents = grunt.file.read(THEO_GENERATED_TMP_PATH + options.destName + ".scss"); + grunt.file.write(options.destFolder + options.destName + ".scss", sassContents); + } + + grunt.registerTask("skeleton_assembler_colors", "Grunt task that converts skeleton colors definition file into sass variables.", function() { + // Merge task-specific and/or target-specific options with these defaults. + var options = this.options({ + src: "", + destFolder: "", + destName: "" + }); + + generateAdaptedColorsSpec(options); + generateSass(options); + }); + +}; diff --git a/pool/shard000/JavaScript/0004421_rightclick.js b/pool/shard000/JavaScript/0004421_rightclick.js new file mode 100644 index 0000000000000000000000000000000000000000..ef07d2b428c9ef95f0d73edfe224ff8cad9eec92 --- /dev/null +++ b/pool/shard000/JavaScript/0004421_rightclick.js @@ -0,0 +1,20 @@ +'use strict'; + +describe('Directive: rightclick', function () { + + // load the directive's module + beforeEach(module('fdappApp')); + + var element, + scope; + + beforeEach(inject(function ($rootScope) { + scope = $rootScope.$new(); + })); + + it('should make hidden element visible', inject(function ($compile) { + element = angular.element(''); + element = $compile(element)(scope); + expect(element.text()).toBe('this is the rightclick directive'); + })); +}); diff --git a/pool/shard000/JavaScript/0004425_header.js b/pool/shard000/JavaScript/0004425_header.js new file mode 100644 index 0000000000000000000000000000000000000000..c2fe2cade517cae0644b1db5b3e80a3e95c783e6 --- /dev/null +++ b/pool/shard000/JavaScript/0004425_header.js @@ -0,0 +1,48 @@ +import React, { Component } from 'react'; +import AddForm from './add_form'; + +class Header extends Component { + constructor(props) { + super(props); + + this.state = { showAddForm: false }; + + this.toggleForm = this.toggleForm.bind(this); + } + + addListing(listing) { + Meteor.call('listings.insert', listing); + } + + toggleForm() { + this.setState({ showAddForm: !this.state.showAddForm }); + } + + render() { + return ( +
        +
        +
        +

        Leaderboard

        +
        +
        + +
        +
        + {(this.state.showAddForm) ? ( + + ) : null} +
        + ); + } +} + +export default Header; diff --git a/pool/shard000/JavaScript/0004431_simple-login-github-popup.spec.js b/pool/shard000/JavaScript/0004431_simple-login-github-popup.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..012f25c041b8bd60e29582a65d5e330305bdff3a --- /dev/null +++ b/pool/shard000/JavaScript/0004431_simple-login-github-popup.spec.js @@ -0,0 +1,74 @@ +if (typeof casper === 'undefined') { + var casper = require('casper').create({ + verbose: true, + logLevel: 'error' + }); +} + +phantom.clearCookies(); + +casper.on('remote.message', function(msg) { + this.log('> ' + msg, 'debug'); +}); + +var TEST_URL = 'http://localhost:9090/js/test/casper/', + TEST_FIREBASE = 'https://demos.firebaseio.com'; + +casper.test.begin('GitHub OAuth Popup Flow', 6, function suite(test) { + var result; + casper.start(TEST_URL, function() { + this.log('GitHub 01: Instantiating FirebaseSimpleLogin...', 'info'); + this.evaluate(function(TEST_FIREBASE) { + window.result = { error: null, user: null }; + Firebase.enableLogging(true); + var ref = new Firebase(TEST_FIREBASE); + var authClient = new FirebaseSimpleLogin(ref, function(error, user) { + if (user) { + window.result.user = user; + window.result.error = error; + } + }); + authClient.logout(); + authClient.login('github'); + }, TEST_FIREBASE); + this.log('GitHub 02: Waiting for popup...', 'info'); + }); + + casper.waitForPopup(/github\.com/g, function() { + this.log('GitHub 03: Found popup!', 'info'); + }); + + casper.withPopup(/github\.com/g, function() { + this.log('GitHub 04: Submitting login form...', 'info'); + this.fill('div#login > form', { + 'login' : 'FirebaseTestuser', + 'password' : 'firebasetest0' + }, true); + }); + + casper.waitFor(function check() { + result = this.evaluate(function() { + return window.result; + }); + return result.error || result.user; + + }, function then() { + this.echo('GitHub 05: Received authentication callback...'); + test.assertFalsy(result.error, 'error is falsy'); + test.assert(result.user && result.user.provider === 'github', 'user.provider === "github"'); + test.assert(result.user.id === '4391301', 'user.id matches registered account value'); + test.assert(result.user.username === 'FirebaseTestuser', 'user.username matches registered account value'); + test.assert(result.user.displayName === 'Firebase Testuser', 'user.displayName matches registered account value'); + test.assert(typeof result.user.firebaseAuthToken === 'string', 'typeof user.firebaseAuthToken === "string"'); + }, function timeout() { + test.fail('GitHub : failed to receive authentication callback'); + }); + + casper.then(function() { + this.log('GitHub 06: Finished....', 'info'); + }); + + casper.run(function() { + test.done(); + }); +}); diff --git a/pool/shard000/JavaScript/0004435_identifier.js b/pool/shard000/JavaScript/0004435_identifier.js new file mode 100644 index 0000000000000000000000000000000000000000..9aee1029205ab5fad49d8156311d2f71ee7db278 --- /dev/null +++ b/pool/shard000/JavaScript/0004435_identifier.js @@ -0,0 +1,191 @@ +"use strict"; + +/** + * ObjectIdentifier object which helps with the location of files and building identifiers + * + * @class ObjectIdentifier + * @since 28 March 2014 + * @param {String} identifier Identifier to convert to an object. + * @constructor + */ +function ObjectIdentifier(identifier) { + /** + * Rewrite of the existing identifier package. + * + * It will now become url like: :/// + */ + if(identifier.indexOf(':') === -1) { + throw new RaddishError(500, 'Malformed identifier'); + } + + // We will parse our own identifiers. + var parts = identifier.split(':'); + var _type = parts[0]; + + parts = parts[1].replace('//', '').split('/'); + + if(parts.length === 1) { + var _application = ''; + var _path = parts[0].replace('/', '').split('.'); + } else { + var _application = parts[0]; + var _path = parts[1].replace('/', '').split('.'); + } + + var _package = _path.shift(); + var _name = _path.pop(); + + /** + * Return a new instance of the current identifier. + * + * @method clone + * @returns {BaseIdentifier} A cloned identifier. + */ + this.clone = function() { + return new ObjectIdentifier(this.toString()); + }; + + /** + * Recreate the identifier given to the Object. + * + * @method toString + * @returns {string} The recreated identifier string given to the current object. + */ + this.toString = function() { + var string = ''; + + if(_type) { + string += _type + '://'; + } + + if(_application) { + string += _application + '/'; + } + + if(_package) { + string += _package + '.'; + } + + if(_path) { + string += _path.join('.') + '.'; + } + + if(_name) { + string += _name; + } + + return string; + }; + + /** + * Return the current type + * + * @method getType + * @returns {String} Type of the current identifier. + */ + this.getType = function() { + return _type; + }; + + /** + * Return the current application + * + * @method getApplication + * @returns {String} Application name of the current identifier. + */ + this.getApplication = function() { + return _application; + }; + + /** + * Return the current component + * + * @method getComponent + * @returns {String} Component name of the current identifier. + */ + this.getPackage = function() { + return _package; + }; + + /** + * Return the current path + * + * @method getPath + * @returns {Array} path of the current identifier. + */ + this.getPath = function() { + return _path; + }; + + /** + * Return the current name + * + * @method getName + * @returns {String} Name of the current identifier. + */ + this.getName = function() { + return _name; + }; + + /** + * Set the type of the current identifier + * + * @method setApplication + * @param {String} newApplication The application name for the current identifier. + */ + this.setType = function(newType) { + _type = newType; + + return this; + }; + + /** + * Set the application of the current identifier + * + * @method setApplication + * @param {String} newApplication The application name for the current identifier. + */ + this.setApplication = function(newApplication) { + _application = newApplication; + + return this; + }; + + /** + * Set the component of the current identifier + * + * @method setComponent + * @param {String} component The component name for the current identifier. + */ + this.setPackage = function(newPackage) { + _package = newPackage; + + return this; + }; + + /** + * Set the path of the current identifier + * + * @method setPath + * @param {Array} path The path for the current identifier. + */ + this.setPath = function(newPath) { + _path = newPath; + + return this; + }; + + /** + * Set the name for the current identifier + * + * @method setName + * @param {String} name The name for the current identifier. + */ + this.setName = function(newName) { + _name = newName; + + return this; + }; +} + +module.exports = ObjectIdentifier; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004436_CodeBank.EditForm.js b/pool/shard000/JavaScript/0004436_CodeBank.EditForm.js new file mode 100644 index 0000000000000000000000000000000000000000..860fdd283f422203469ba388c1b2b86a1ba71eeb --- /dev/null +++ b/pool/shard000/JavaScript/0004436_CodeBank.EditForm.js @@ -0,0 +1,64 @@ +(function($) { + $.entwine('ss', function($) { + $('.CodeBankAddSnippet #Form_AddForm_Text, .CodeBankEditSnippet #Form_EditForm_Text').entwine({ + onkeydown: function(e) { + if(e.keyCode===9) { // tab was pressed + var domElm=$(this).get(0); + + // get caret position/selection + var start=domElm.selectionStart; + var end=domElm.selectionEnd; + console.log(start, end); + + // set textarea value to: text before caret + tab + text after caret + $(this).val($(this).val().substring(0, start)+"\t"+$(this).val().substring(end)); + + // put caret at right position again + domElm.selectionStart=domElm.selectionEnd=start+1; + + // prevent the focus lose + return false; + } + } + }); + + + //Cancel Button + $('.CodeBankEditSnippet #Form_EditForm_action_doCancel').entwine({ + onclick: function(e) { + $('.cms-container').loadPanel('admin/codeBank/show/'+$('#Form_EditForm_ID').val()); + } + }); + + + $('.CodeBankEditSnippet input[name=Title]').entwine({ + onchange: function() { + this.updatedRelatedFields(); + }, + + /** + * Same as the onchange handler but callable as a method + */ + updatedRelatedFields: function() { + var menuTitle = this.val(); + this.updateTreeLabel(menuTitle); + }, + + /** + * Function: updatePanelLabels + * + * Update the tree + * (String) title + */ + updateTreeLabel: function(title) { + var pageID = $('.cms-edit-form input[name=ID]').val(); + + // only update immediate text element, we don't want to update all the nested ones + var treeItem = $('.item:first', $('.cms-tree').find("[data-id='" + pageID + "']")); + if (title && title != "") { + treeItem.text(title); + } + } + }); + }); +})(jQuery); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004440_15.2.3.6-3-243.js b/pool/shard000/JavaScript/0004440_15.2.3.6-3-243.js new file mode 100644 index 0000000000000000000000000000000000000000..353dabfd982925381a64f3d620127acd03be4cfd --- /dev/null +++ b/pool/shard000/JavaScript/0004440_15.2.3.6-3-243.js @@ -0,0 +1,36 @@ +/// Copyright (c) 2012 Ecma International. All rights reserved. +/** + * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-243.js + * @description Object.defineProperty - 'set' property in 'Attributes' is own accessor property that overrides an inherited data property (8.10.5 step 8.a) + */ + + +function testcase() { + var obj = {}; + var data1 = "data"; + var data2 = "data"; + + var proto = { + set: function (value) { + data1 = value; + } + }; + + var ConstructFun = function () { }; + ConstructFun.prototype = proto; + + var child = new ConstructFun(); + Object.defineProperty(child, "set", { + get: function () { + return function (value) { + data2 = value; + }; + } + }); + + Object.defineProperty(obj, "property", child); + obj.property = "ownAccessorProperty"; + + return obj.hasOwnProperty("property") && data1 === "data" && data2 === "ownAccessorProperty"; + } +runTestCase(testcase); diff --git a/pool/shard000/JavaScript/0004443_pipeline.js b/pool/shard000/JavaScript/0004443_pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..99d360f0cf449d60a1128848b701b2409e46cae3 --- /dev/null +++ b/pool/shard000/JavaScript/0004443_pipeline.js @@ -0,0 +1,80 @@ +/* global utils,PVector */ +(function (exports) { + var Pipeline = function (x, velocity, paper) { + this.height = 150; + this.width = 80; + this.top = utils.random(200, paper.height - 200); + this.bottom = this.top + this.height; + + this.x = x; + this.velocity = velocity; + this.paper = paper; + this._initBody(); + this.passed = false; + }; + + Pipeline.prototype._initBody = function () { + this.paper.setStart(); + + this.topBody = this.paper.rect(0, 0, this.width, this.top); + this.bottomBody = this.paper.rect(0, this.bottom, + this.width, this.paper.height - this.bottom); + this.body = this.paper.setFinish(); + this.body.attr({ fill: '#0e0', 'stroke': '#050' }); + + this.move(); + }; + + Pipeline.prototype.update = function () { + this.x -= this.velocity; + return this; + }; + + Pipeline.prototype.move = function () { + this.body.transform('t' + this.x + ' 0'); + return this; + }; + + Pipeline.prototype.isDead = function () { + return this.x < -100; + }; + + Pipeline.prototype.checkTouch = function (bird) { + var p = bird.location; + var r = bird.r; + if (p.x < this.x) { + var leftTop = new PVector(this.x, this.top); + var leftBottom = new PVector(this.x, this.bottom); + if (PVector.dist(p, leftTop) < r || PVector.dist(p, leftBottom < r)) { + return true; + } + } else if (p.x > this.x + this.width) { + var rightTop = new PVector(this.x + this.width, this.top); + var rightBottom = new PVector(this.x + this.width, this.bottom); + if (PVector.dist(p, rightTop) < r || PVector.dist(p, rightBottom < r)) { + return true; + } + } else { + if (p.y + r > this.bottom || p.y - r < this.top) { + return true; + } + } + return false; + }; + + Pipeline.prototype.checkPass = function (bird) { + var pass = bird.location.x > this.x + this.width / 2; + this.passed = pass; + return pass; + }; + + Pipeline.prototype.destroy = function () { + this.topBody.remove(); + this.bottomBody.remove(); + this.body.clear(); + return this; + }; + + exports.Pipeline = Pipeline; + +})(this); diff --git a/pool/shard000/JavaScript/0004444_main.js b/pool/shard000/JavaScript/0004444_main.js new file mode 100644 index 0000000000000000000000000000000000000000..b5c4c1191c6a023f0fc5c8d51fd16063e8cc3e78 --- /dev/null +++ b/pool/shard000/JavaScript/0004444_main.js @@ -0,0 +1,60 @@ +'use strict'; + +const electron = require('electron'); +// Module to control application life. +const app = electron.app; +// Module to create native browser window. +const BrowserWindow = electron.BrowserWindow; + +// Keep a global reference of the window object, if you don't, the window will +// be closed automatically when the JavaScript object is garbage collected. +let mainWindow; + +function createWindow () { + // Create the browser window. + // var appIcon = new Tray('res/monitoricon.png'); + mainWindow = new BrowserWindow({width: 600, height: 800, title: "Administrator's Friend", icon: __dirname + '/res/monitoricon.png', alwaysOnTop: false}); + // 1100 x 900 + + // and load the index.html of the app. + mainWindow.loadURL('file://' + __dirname + '/index.html'); + + // Open the DevTools. + mainWindow.webContents.openDevTools(); + + // Testing + // var child_process = require('child_process'); + // var output = child_process.execSync('cmd.exe /c "ping dt-0166"'); + // const dialog = electron.dialog; + // dialog.showMessageBox(mainWindow, {type:'info', buttons:['Sounds good', 'Wait a minute...'], defaultId:1, title:'Tittel', message:'message box!', detail:output.toString()}); + // dialog.showErrorBox('childprocess', 'test'); + + // Emitted when the window is closed. + mainWindow.on('closed', function() { + // Dereference the window object, usually you would store windows + // in an array if your app supports multi windows, this is the time + // when you should delete the corresponding element. + mainWindow = null; + }); +} + +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +app.on('ready', createWindow); + +// Quit when all windows are closed. +app.on('window-all-closed', function () { + // On OS X it is common for applications and their menu bar + // to stay active until the user quits explicitly with Cmd + Q + if (process.platform !== 'darwin') { + app.quit(); + } +}); + +app.on('activate', function () { + // On OS X it's common to re-create a window in the app when the + // dock icon is clicked and there are no other windows open. + if (mainWindow === null) { + createWindow(); + } +}); diff --git a/pool/shard000/JavaScript/0004451_Overlay_Helper.js b/pool/shard000/JavaScript/0004451_Overlay_Helper.js new file mode 100644 index 0000000000000000000000000000000000000000..13feff40827c8a8b96e85e1248499bb183efb208 --- /dev/null +++ b/pool/shard000/JavaScript/0004451_Overlay_Helper.js @@ -0,0 +1,31 @@ +/*! + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +var Overlay_Helper = { + + /** Encode the iframe url to put it behind the hash in sidebar mode */ + encodeFrameUrl: function (url) { + // url encode + replace % with $ to make sure that browsers don't break the encoding + return encodeURIComponent(url).replace(/%/g, '$') + }, + + /** Decode the url after reading it from the hash */ + decodeFrameUrl: function (url) { + // reverse encodeFrameUrl() + return decodeURIComponent(url.replace(/\$/g, '%')); + }, + + /** Get the url to launch overlay */ + getOverlayLink: function (idSite, period, date, link) { + var url = 'index.php?module=Overlay&period=' + encodeURIComponent(period) + '&date=' + encodeURIComponent(date) + '&idSite=' + encodeURIComponent(idSite); + if (link) { + url += '#l=' + Overlay_Helper.encodeFrameUrl(link); + } + return url; + } + +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004452_testEnv.js b/pool/shard000/JavaScript/0004452_testEnv.js new file mode 100644 index 0000000000000000000000000000000000000000..1c33965dbacb6ea418ebd3e82c8eec7235322a6a --- /dev/null +++ b/pool/shard000/JavaScript/0004452_testEnv.js @@ -0,0 +1,67 @@ +/** @license MIT License (c) copyright 2010-2015 original author or authors */ +/** @author Brian Cavalier */ +/** @author John Hann */ + +import { newScheduler, newTimeline, currentTime, delay } from '@most/scheduler' +import { propagateEventTask, propagateEndTask } from '../../src/scheduler/PropagateTask' +import VirtualTimer from './VirtualTimer' +import { runEffects } from '../../src/runEffects' +import { tap } from '../../src/combinator/transform' +import { disposeWith, disposeNone } from '@most/disposable' + +export function newEnv () { + const timer = new VirtualTimer() + return { tick: n => timer.tick(n), scheduler: newScheduler(timer, newTimeline()) } +} + +export function ticks (dt) { + const { tick, scheduler } = newEnv() + tick(dt) + return scheduler +} + +export function collectEvents (stream, scheduler) { + const into = [] + const s = tap(x => into.push({ time: currentTime(scheduler), value: x }), stream) + return runEffects(s, scheduler).then(() => into) +} + +export const collectEventsFor = (nticks, stream) => + collectEvents(stream, ticks(nticks)) + +export const makeEventsFromArray = (dt, a) => + atTimes(a.map((value, i) => ({ time: i * dt, value }))) + +export const makeEvents = (dt, n) => + makeEventsFromArray(dt, Array.from(Array(n), (_, i) => i)) + +export const atTime = (time, value) => atTimes([{ time, value }]) + +export const atTimes = array => new AtTimes(array) + +class AtTimes { + constructor (array) { + this.events = array + } + + run (sink, scheduler) { + return this.events.length === 0 + ? disposeNone() + : runEvents(this.events, sink, scheduler) + } +} + +const runEvents = (events, sink, scheduler) => { + const s = events.reduce(appendEvent(sink, scheduler), { tasks: [], time: 0 }) + const end = delay(s.time, propagateEndTask(sink), scheduler) + return disposeWith(cancelAll, s.tasks.concat(end)) +} + +const appendEvent = (sink, scheduler) => (s, event) => { + const task = delay(event.time, propagateEventTask(event.value, sink), scheduler) + return { tasks: s.tasks.concat(task), time: Math.max(s.time, event.time) } +} + +const cancelAll = tasks => Promise.all(tasks.map(cancelOne)) + +const cancelOne = task => task.dispose() diff --git a/pool/shard000/JavaScript/0004453_index.js b/pool/shard000/JavaScript/0004453_index.js new file mode 100644 index 0000000000000000000000000000000000000000..013d8d6dbcd4ba3dc06cddfb1774fd95f6a70e62 --- /dev/null +++ b/pool/shard000/JavaScript/0004453_index.js @@ -0,0 +1,52 @@ +const fs = require("fs"); +const COMMON_MAX = 1 << 30; + +function test(file) { + console.log("Testing '" + file + "' ...\n"); + + const exports = new WebAssembly.Instance(new WebAssembly.Module(fs.readFileSync(__dirname + "/" + file)), { + env: { + abort(msg, file, line, column) { + throw Error("Assertion failed: " + (msg ? "'" + getString(msg) + "' " : "") + "at " + getString(file) + ":" + line + ":" + column); + }, + log(ptr) { console.log(getString(ptr)); }, + logi(i) { console.log(i); }, + trace(...args) { console.log("trace", args); } + } + }).exports; + + function getString(ptr) { + if (!ptr) return "null"; + var U32 = new Uint32Array(exports.memory.buffer); + var U16 = new Uint16Array(exports.memory.buffer); + var length = U32[(ptr - 4) >>> 2] >>> 1; + var offset = ptr >>> 1; + return String.fromCharCode.apply(String, U16.subarray(offset, offset + length)); + } + + require("./runner")(exports, 20, 20000); + + console.log("mem final: " + exports.memory.buffer.byteLength); + console.log(); + + const alloc = exports["__alloc"]; + var overflow = false; + try { + alloc(COMMON_MAX + 1, 0); // unreachable + overflow = true; + } catch (e) { /* nop */ } + if (overflow) throw Error("allocation can overflow COMMON_MAX + 1"); + try { + alloc(0xffffffff, 0); // unreachable + overflow = true; + } catch (e) { /* nop */ } + if (overflow) throw Error("allocation can overflow 0xffffffff"); +} + +if (process.argv.length > 2) { + test(process.argv[2] + "/untouched.wasm"); + test(process.argv[2] + "/optimized.wasm"); +} else { + console.error("Usage: npm test "); + process.exit(1); +} diff --git a/pool/shard000/JavaScript/0004455_companyService.js b/pool/shard000/JavaScript/0004455_companyService.js new file mode 100644 index 0000000000000000000000000000000000000000..affd558d2413ca6dd3783da0813ce3d69a9156cd --- /dev/null +++ b/pool/shard000/JavaScript/0004455_companyService.js @@ -0,0 +1,31 @@ +// +// File: CompanyService.js +// Author: Kris Thomsen 2013 +// + +angular.module('companyModule').factory('companyService', function () { + + "use strict"; + + var urlBase = "/api"; + var companyService = {}; + + companyService.getCompanies = function () { + return $http.get(urlBase); + }; + + companyService.getCompany = function (id) { + return $http.get(urlBase + '/' + id); + }; + + companyService.createCompany = function (company) { + return $http.post(urlBase, company); + }; + + companyService.updateCompany = function (company) { + return $http.put(urlBase + '/' + company.ID, company); + }; + + return companyService; +}); + diff --git a/pool/shard000/JavaScript/0004456_UserListContainer.js b/pool/shard000/JavaScript/0004456_UserListContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..2d9c27fc92923bc10c21a4c392a2395d13fea522 --- /dev/null +++ b/pool/shard000/JavaScript/0004456_UserListContainer.js @@ -0,0 +1,56 @@ +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; +import {connect} from 'react-redux'; +import {push} from 'react-router-redux'; +import UserList from '../../views/user/UserList'; +import {list} from '../../../apis/UserApi'; +import {getStore} from '../../../store'; +import {listUsersSuccess} from '../../../actions/user'; + +class UserListContainer extends Component { + constructor(props) { + super(props); + } + + componentDidMount() { + list((users) => getStore().dispatch(listUsersSuccess(users))); + } + + render() { + return ( // +
        + +
        + ); + } +} + +UserListContainer.propTypes = { + users: PropTypes.any, + isNew: PropTypes.bool, + list: PropTypes.func.isRequired, + edit: PropTypes.func.isRequired, + create: PropTypes.func.isRequired +}; + +const mapStateToProps = (state) => { + return { + users: state.userReducer.get('users') + }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + list: (page, sort) => { + list((users) => dispatch(listUsersSuccess(users)), page, sort); + }, + edit: (id) => { + dispatch(push('/user/edit/' + id)); + }, + create: () => { + dispatch(push('/user/new')); + } + }; +}; + +export default connect(mapStateToProps, mapDispatchToProps)(UserListContainer); diff --git a/pool/shard000/JavaScript/0004457_settings.js b/pool/shard000/JavaScript/0004457_settings.js new file mode 100644 index 0000000000000000000000000000000000000000..64a760e4c3db5f27f222257a6b4caad50cdf46dc --- /dev/null +++ b/pool/shard000/JavaScript/0004457_settings.js @@ -0,0 +1,77 @@ +/** + * Created by horacio on 07/09/2016. + */ + +define(['storage/defaultsettings', 'storage/storage'], function (DefaultSettings, Storage) { + class Settings { + constructor() { + this.storage = new Storage(); + var defaultSettings = this._getDefaultData(); + this._settings = this.storage.getItem('settings', defaultSettings); + } + + _getDefaultData() { + return $.extend(true, {}, DefaultSettings); + } + + getDefaultKeys() { + return this._getDefaultData().keys; + } + + getKeys() { + return this._settings.keys; + } + + getSoundMuted() { + return this._settings.audio.soundMuted; + } + + getMusicMuted() { + return this._settings.audio.musicMuted; + } + + getSoundVolume() { + return this._settings.audio.soundVolume; + } + + getMusicVolume() { + return this._settings.audio.musicVolume; + } + + setSoundMuted(muted) { + this._settings.audio.soundMuted = muted; + this.save(); + } + + setMusicMuted(muted) { + this._settings.audio.musicMuted = muted; + this.save(); + } + + setSoundVolume(vol) { + this._settings.audio.soundVolume = vol; + this.save(); + } + + setMusicVolume(vol) { + this._settings.audio.musicVolume = vol; + this.save(); + } + + setKeys(keys) { + this._settings.keys = keys; + this.save(); + } + + save() { + this.storage.setItem('settings', this._settings); + } + + clear() { + this.storage.removeItem('settings'); + } + + } + + return Settings; +}); diff --git a/pool/shard000/JavaScript/0004460_login_buttons_session.js b/pool/shard000/JavaScript/0004460_login_buttons_session.js new file mode 100644 index 0000000000000000000000000000000000000000..7654bd8531c3010e6608921d50afbb628268bcc6 --- /dev/null +++ b/pool/shard000/JavaScript/0004460_login_buttons_session.js @@ -0,0 +1,103 @@ +var VALID_KEYS = [ + 'dropdownVisible', + + // XXX consider replacing these with one key that has an enum for values. + 'inSignupFlow', + 'inForgotPasswordFlow', + 'inChangePasswordFlow', + 'inMessageOnlyFlow', + + 'errorMessage', + 'infoMessage', + + // dialogs with messages (info and error) + 'resetPasswordToken', + 'enrollAccountToken', + 'justVerifiedEmail', + + 'configureLoginServiceDialogVisible', + 'configureLoginServiceDialogServiceName', + 'configureLoginServiceDialogSaveDisabled' +]; + +var validateKey = function (key) { + if (!_.contains(VALID_KEYS, key)) + throw new Error("Invalid key in loginButtonsSession: " + key); +}; + +var KEY_PREFIX = "Meteor.loginButtons."; + +// XXX This should probably be package scope rather than exported +// (there was even a comment to that effect here from before we had +// namespacing) but accounts-ui-viewer uses it, so leave it as is for +// now +Accounts._loginButtonsSession = { + set: function(key, value) { + validateKey(key); + if (_.contains(['errorMessage', 'infoMessage'], key)) + throw new Error("Don't set errorMessage or infoMessage directly. Instead, use errorMessage() or infoMessage()."); + + this._set(key, value); + }, + + _set: function(key, value) { + Session.set(KEY_PREFIX + key, value); + }, + + get: function(key) { + validateKey(key); + return Session.get(KEY_PREFIX + key); + }, + + closeDropdown: function () { + this.set('inSignupFlow', false); + this.set('inForgotPasswordFlow', false); + this.set('inChangePasswordFlow', false); + this.set('inMessageOnlyFlow', false); + this.set('dropdownVisible', false); + this.resetMessages(); + }, + + infoMessage: function(message) { + this._set("errorMessage", null); + this._set("infoMessage", message); + this.ensureMessageVisible(); + }, + + errorMessage: function(message) { + this._set("errorMessage", message); + this._set("infoMessage", null); + this.ensureMessageVisible(); + }, + + // is there a visible dialog that shows messages (info and error) + isMessageDialogVisible: function () { + return this.get('resetPasswordToken') || + this.get('enrollAccountToken') || + this.get('justVerifiedEmail'); + }, + + // ensure that somethings displaying a message (info or error) is + // visible. if a dialog with messages is open, do nothing; + // otherwise open the dropdown. + // + // notably this doesn't matter when only displaying a single login + // button since then we have an explicit message dialog + // (_loginButtonsMessageDialog), and dropdownVisible is ignored in + // this case. + ensureMessageVisible: function () { + if (!this.isMessageDialogVisible()) + this.set("dropdownVisible", true); + }, + + resetMessages: function () { + this._set("errorMessage", null); + this._set("infoMessage", null); + }, + + configureService: function (name) { + this.set('configureLoginServiceDialogVisible', true); + this.set('configureLoginServiceDialogServiceName', name); + this.set('configureLoginServiceDialogSaveDisabled', true); + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004462_controllers.js b/pool/shard000/JavaScript/0004462_controllers.js new file mode 100644 index 0000000000000000000000000000000000000000..d80c11cb3b7d64704b57456439ee40d58073b7e6 --- /dev/null +++ b/pool/shard000/JavaScript/0004462_controllers.js @@ -0,0 +1,32 @@ +'use strict'; + +/* Controllers */ + +var experimentControllers = angular.module('experimentControllers', []) + +.factory('experimentFactory', function() { + var factory = {}; + var customers = [ + { name: 'Dave Jones', city: 'Phoenix' }, + { name: 'Jamie Riley', city: 'Atlanta' }, + { name: 'Heedy Wahlin', city: 'Chandler' }, + { name: 'Thomas Winters', city: 'Seattle' }, + ]; + factory.getCustomers = function() { + return customers; + }; + return factory; +}) + +.controller('ExperimentController', ['$scope', 'experimentFactory', + function($scope, experimentFactory) { + $scope.customers = experimentFactory.getCustomers(); + + $scope.addCustomer = function () { + $scope.customers.push({ + name: $scope.newCustomer.name, + city: $scope.newCustomer.city, + }); + }; + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004464_api.js b/pool/shard000/JavaScript/0004464_api.js new file mode 100644 index 0000000000000000000000000000000000000000..826000d193bf1d9cb452904a06cae5018167dab5 --- /dev/null +++ b/pool/shard000/JavaScript/0004464_api.js @@ -0,0 +1,128 @@ +const credentials = { credentials: 'same-origin' } + +class API { + + static currentUser() { return API.jsonCall('/api/user') } + static server(snowflake) { return API.jsonCall(`/api/server/${snowflake}`) } + static logs() { return API.jsonCall('/logs/top') } + static userLogs(snowflake) { return API.jsonCall(`/logs/user/${snowflake}`) } + static giveawayInfo() { return API.jsonCall('/giveaways/user') } + static twitterOAuthToken() { return API.jsonCall('/twitter/oauth_token') } + static twitterStatus() { return API.jsonCall('/twitter/status') } + static twitterDisconnect() { + return API.jsonCall('/twitter/disconnect', { method: 'POST' }) + } + static attachments(snowflake) { return API.jsonCall(`/logs/attachments/${snowflake}`) } + static twitchStatus() { return API.jsonCall('/twitch/status') } + static twitchOAuthUrl() { return API.path('/twitch/oauth')} + static twitchDisconnect() { + return API.jsonCall('/twitch/disconnect', { method: 'POST' }) + } + static twitchFollowed() { return API.jsonCall('/twitch/followed') } + static twitchMention(channelName, on) { + let form = new FormData + + form.append('channel', channelName) + form.append('state', on) + + return API.jsonCall('/twitch/mention', { body: form, method: 'POST' }) + } + static twitchWhisper(channelName, on) { + let form = new FormData + + form.append('channel', channelName) + form.append('state', on) + + return API.jsonCall('/twitch/whisper', { body: form, method: 'POST' }) + } + + static gameStats() { return API.jsonCall('/stats/games/top') } + static gameStatsGame(gameName) { + return API.jsonCall(`/stats/games/game?name=${encodeURIComponent(gameName)}`) + } + static gameStatsUser(userId) { return API.jsonCall(`/stats/games/user/${userId}`) } + + static giveawayStart(serverId, title, content) { + let form = new FormData + + form.append('server_id', serverId) + form.append('title', title) + form.append('content', content) + + return API.jsonCall('/giveaways/start', { body: form, method: 'POST' }) + } + + static voiceInfo() { + return API.jsonCall('/voice') + } + + static voiceAction(data) { + let form = new FormData + + for (var key in data) + form.append(key, data[key]) + + return API.jsonCall('/voice', { body: form, method: 'POST' }) + } + + static joinVoice(serverId, channelId) { + return API.voiceAction({ + action_type: 'join', + channel_id: channelId, + server_id: serverId + }) + } + + static leaveVoice(serverId) { + return API.voiceAction({ + action_type: 'leave', + server_id: serverId + }) + } + + static tts(serverId, content) { + return API.voiceAction({ + action_type: 'tts', + server_id: serverId, + content: content + }) + } + + static queueSong(serverId, song) { + return API.voiceAction({ + action_type: 'queue', + server_id: serverId, + song: song + }) + } + + static logsWebSocket() { + return new WebSocket(`wss://${document.domain}/ws/logs`) + } + + static voiceWebSocket() { + return new WebSocket(`wss://${document.domain}/ws/voice`) + } + + static jsonCall(route, extra={}) { + let init = Object.assign(extra, credentials) + + let promise = + fetch(API.path(route), init) + .then(response => { + if (response.ok) + return response.json() + else + throw new Error(response.status) + }) + + return promise + } + + static path(suffix) { + return '/bot' + suffix + } + +} + +module.exports = API diff --git a/pool/shard000/JavaScript/0004465_expander.js b/pool/shard000/JavaScript/0004465_expander.js new file mode 100644 index 0000000000000000000000000000000000000000..6708ff9d5c4b497d9bf9e7f64947ef7182f1ba7a --- /dev/null +++ b/pool/shard000/JavaScript/0004465_expander.js @@ -0,0 +1,68 @@ +/* + * Author: Ralph B. Magnus + * Date: 07.2010 + * + */ + +function baseUrl() { + var href = window.location.href.split('/'); + return href[0]+'//'+href[2]+'/'; +} + +function setBackground(elems, background){ + elems.css('background-image','url("' + baseUrl() + '/images/' + background + '")'); +} + +var openZIMExpander = { + + init: function() { + $(".msg_content").hide(); + if ( ! $.cookies.test() ){ + $(".msg_content:first").slideToggle(600,callback); + }else{ + $(".msg_content").each(function(){ + var pos = $(".msg_content").index(this); + var key = location.pathname+'/'+ pos; + var display = $.cookies.get(key); + if ( display == null ){ + if ( pos == 0 ){ + $(this).slideToggle(600,function(){ + setBackground($(this).parent().children('.msg_head'), 'div_opened.png'); + $.cookies.set(key, $(this).css('display')); + }); + } else { + setBackground($(this).parent().children('.msg_head'), 'div_closed.png'); + $.cookies.set(key, $(this).css('display')); + } + }else{ + if ( display != 'none' ) { + setBackground($(this).parent().children('.msg_head'), 'div_opened.png'); + $(this).show(); + } else { + setBackground($(this).parent().children('.msg_head'), 'div_closed.png'); + } + } + }); + } + }, + + setup: function() { + + $(document).on('click', ".msg_head", function() { + var state = $(this).next(".msg_content").css('display'); + if( state == 'none' ) { + setBackground($(this), 'div_opened.png'); + } else { + setBackground($(this), 'div_closed.png'); + } + $(this).next(".msg_content").slideToggle(600,function(){ + $.cookies.set(location.pathname + '/'+$(".msg_content").index(this), $(this).css('display')); + }); + }); + this.init(); + } +} + +$(document).ready(function(){ + openZIMExpander.setup(); +}); diff --git a/pool/shard000/JavaScript/0004468_mood_smiley_face.js b/pool/shard000/JavaScript/0004468_mood_smiley_face.js new file mode 100644 index 0000000000000000000000000000000000000000..877891dab0ae7c9eb11ae6c19db85113eac18976 --- /dev/null +++ b/pool/shard000/JavaScript/0004468_mood_smiley_face.js @@ -0,0 +1,150 @@ +/** + * Location: /php/apps/mood/mood_smiley_face.php + * Description: The displayed smiley face +**/ +var mood_smiley_face = 'mood-smiley-face'; + +/** + * Location: /php/apps/mood/mood_smiley_face.php + * Description: The displayed smile on the smiley face +**/ +var mood_smiley_face_smile = 'mood-smiley-face-smile'; + +/** + * Location: /php/apps/mood/mood_smiley_face.php + * Description: The first eye of the smiley face +**/ +var mood_smiley_face_eye_one = 'mood-smiley-face-eye-one'; + +/** + * Location: /php/apps/mood/mood_smiley_face.php + * Description: The second eye of the smiley face +**/ +var mood_smiley_face_eye_two = 'mood-smiley-face-eye-two'; + + + + +var mood_smiley_face_starting_percent = 75; +var mood_smiley_face_width = 220; +var mood_smiley_face_height = 220; + +var mood_smiley_face_eye_color = '#000'; + + +/** + * Initialize the css for mood_smiley_face +**/ +function mood_smiley_face_run_css() { + + /** + * #mood-smiley-face css + **/ + var e_mood_smiley_face = document.getElementById(mood_smiley_face); + + e_mood_smiley_face .style .zIndex = 40; + e_mood_smiley_face .style .background = 'rgba(238, 196, 29, 1)'; + e_mood_smiley_face .style .display = 'inline'; + e_mood_smiley_face .style .position = 'absolute'; + e_mood_smiley_face .style .width = mood_smiley_face_width + 'px' + e_mood_smiley_face .style .height = mood_smiley_face_height + 'px' + e_mood_smiley_face .style .top = 70+'px' + e_mood_smiley_face .style .right = 50+'px' + e_mood_smiley_face .style .borderRadius = (mood_smiley_face_width/2) + 'px'; + + + /** + * #mood-smiley-face-eye-one css + **/ + var e_mood_smiley_face_eye_one = document.getElementById(mood_smiley_face_eye_one); + + e_mood_smiley_face_eye_one .style .zIndex = 45; + e_mood_smiley_face_eye_one .style .background = mood_smiley_face_eye_color; + e_mood_smiley_face_eye_one .style .display = 'inline'; + e_mood_smiley_face_eye_one .style .position = 'absolute'; + e_mood_smiley_face_eye_one .style .width = 50 + 'px'; + e_mood_smiley_face_eye_one .style .height = 50 + 'px'; + e_mood_smiley_face_eye_one .style .top = 50 + 'px'; + e_mood_smiley_face_eye_one .style .right = 130 + 'px'; + e_mood_smiley_face_eye_one .style .borderRadius = 25 + 'px'; + + + /** + * #mood-smiley-face-eye-two css + **/ + var e_mood_smiley_face_eye_two = document.getElementById(mood_smiley_face_eye_two); + + e_mood_smiley_face_eye_two .style .zIndex = 45; + e_mood_smiley_face_eye_two .style .background = mood_smiley_face_eye_color; + e_mood_smiley_face_eye_two .style .display = 'inline'; + e_mood_smiley_face_eye_two .style .position = 'absolute'; + e_mood_smiley_face_eye_two .style .width = 50 + 'px'; + e_mood_smiley_face_eye_two .style .height = 50 + 'px'; + e_mood_smiley_face_eye_two .style .top = 50 + 'px'; + e_mood_smiley_face_eye_two .style .right = 40 + 'px'; + e_mood_smiley_face_eye_two .style .borderRadius = 25 + 'px'; +} + + +/** + * mood_smiley_face init +**/ +function mood_smiley_face_init() { + mood_smiley_face_run_css(); + window.onload = mood_smiley_face_draw( + (mood_smiley_face_height/1.69230), + (mood_smiley_face_height/1.29411), + (mood_smiley_face_width/4.88888), + (mood_smiley_face_width/1.25714), + mood_smiley_face_starting_percent); +} + + +function mood_smiley_face_draw(top, bottom, left, right, percent) { + + var element = document.getElementById(mood_smiley_face_smile); + while (element.firstChild) { + element.removeChild(element.firstChild); + } + var parent = document.getElementById(mood_smiley_face); + var red = ( 39 + ( 209 * ( percent/100.0 ) ) ); + var blue = ( 248 - ( 209 * ( percent/100.0 ) ) ); + parent.style.background = + 'rgba( ' + Math.round(red) + + ', 206, ' + Math.round(blue) + + ', 1)'; + + var height = Math.abs(top-bottom); + var width = Math.abs(left-right); + var dimension = Math.min(width, height); + var count = 0; + + var smile_height = ((width/2)/(width/12)) * ((width/2)/(width/12)); + var norm_const = height/smile_height; + + if (percent > 50) { + norm_const = norm_const * ( (percent-50) / ( -50 ) ); + } else { + norm_const = norm_const * ( (50-percent) / 50 ); + } + var startTop = top-( height*(percent/ (-100) ) ); + + + for (var i = left; i < right-(5-1); i+=5) { + count+=5; + + var div = document.createElement('div'); + div.style.width = (dimension/2) + 'px'; + div.style.height = (dimension/2) + 'px'; + div.style.borderRadius = (dimension/4) + 'px'; + div.style.background = '#000'; + div.style.position = 'absolute'; + div.style.zIndex = 41; + + div.style.left = (left+count-(dimension/4)) + 'px'; + + var x_var = (count-(width/2))/(width/12); + div.style.top = ( startTop + ( x_var * x_var * norm_const) ) + 'px'; + element.appendChild(div); + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004471_index.js b/pool/shard000/JavaScript/0004471_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f43be65f7d52aa1e34a50c040a96240f4b44f901 --- /dev/null +++ b/pool/shard000/JavaScript/0004471_index.js @@ -0,0 +1,41 @@ +const LessPassFingerprint = require("lesspass-fingerprint"); +const LessPassEntropy = require("lesspass-entropy"); +const LessPassRenderPassword = require("lesspass-render-password"); + +function generatePassword(site, login, masterPassword, passwordProfile) { + return LessPassEntropy.calcEntropy( + { + site, + login, + options: { + counter: passwordProfile.counter + } + }, + masterPassword + ).then(entropy => { + const options = { + length: passwordProfile.length, + lowercase: passwordProfile.lowercase, + uppercase: passwordProfile.uppercase, + digits: passwordProfile.numbers, + symbols: passwordProfile.symbols + }; + const generatedPassword = LessPassRenderPassword.renderPassword( + entropy, + options + ); + return Promise.resolve(generatedPassword); + }); +} + +function createFingerprint(string) { + return LessPassFingerprint.createHmac("sha256", string).then(hmac => { + const fingerprint = LessPassFingerprint.createFingerprint(hmac); + return Promise.resolve(fingerprint); + }); +} + +module.exports = { + generatePassword, + createFingerprint +}; diff --git a/pool/shard000/JavaScript/0004472_fuzzify.js b/pool/shard000/JavaScript/0004472_fuzzify.js new file mode 100644 index 0000000000000000000000000000000000000000..bbeee4e551e0a6647bae507fb29c4c45425d92e1 --- /dev/null +++ b/pool/shard000/JavaScript/0004472_fuzzify.js @@ -0,0 +1,23 @@ +/* Copyright 2017 Ronny Reichmann */ +/* FUZZIFY Adjectify value ranges for later use in pattern matching */ + +function composeCheckFn (compareFn, adjective) { + return nextCheckFn => { + return value => { + if (compareFn(value)) return adjective + else return nextCheckFn(value) + } + } +} + +function fuzzify (config) { + const initializers = Object.keys(config) + .map(adjective => { + const compareFn = config[adjective] + return composeCheckFn(compareFn, adjective) + }) + initializers.reverse() + return initializers.reduce((acc, initCheckFn) => initCheckFn(acc), v => v) +} + +module.exports = fuzzify diff --git a/pool/shard000/JavaScript/0004474_prettydate.js b/pool/shard000/JavaScript/0004474_prettydate.js new file mode 100644 index 0000000000000000000000000000000000000000..16fcb1d3803ee10ce9064dd654fc169746c6feaf --- /dev/null +++ b/pool/shard000/JavaScript/0004474_prettydate.js @@ -0,0 +1,108 @@ +/* + * Javascript Humane Dates + * Copyright (c) 2008 Dean Landolt (deanlandolt.com) + * Re-write by Zach Leatherman (zachleat.com) + * + * Adopted from the John Resig's pretty.js + * at http://ejohn.org/blog/javascript-pretty-date + * and henrah's proposed modification + * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458 + * + * Licensed under the MIT license. + */ + +function humaneDate(date, compareTo){ + + if(!date) { + return; + } + + var lang = { + ago: 'Ago', + from: '', + now: 'Just Now', + minute: 'Minute', + minutes: 'Minutes', + hour: 'Hour', + hours: 'Hours', + day: 'Day', + days: 'Days', + week: 'Week', + weeks: 'Weeks', + month: 'Month', + months: 'Months', + year: 'Year', + years: 'Years' + }, + formats = [ + [60, lang.now], + [3600, lang.minute, lang.minutes, 60], // 60 minutes, 1 minute + [86400, lang.hour, lang.hours, 3600], // 24 hours, 1 hour + [604800, lang.day, lang.days, 86400], // 7 days, 1 day + [2628000, lang.week, lang.weeks, 604800], // ~1 month, 1 week + [31536000, lang.month, lang.months, 2628000], // 1 year, ~1 month + [Infinity, lang.year, lang.years, 31536000] // Infinity, 1 year + ], + isString = typeof date == 'string', + date = isString ? + new Date(('' + date).replace(/-/g,"/").replace(/[TZ]/g," ")) : + date, + compareTo = compareTo || new Date, + seconds = (compareTo - date + + (compareTo.getTimezoneOffset() - + // if we received a GMT time from a string, doesn't include time zone bias + // if we got a date object, the time zone is built in, we need to remove it. + (isString ? 0 : date.getTimezoneOffset()) + ) * 60000 + ) / 1000, + token; + + if(seconds < 0) { + seconds = Math.abs(seconds); + token = lang.from ? ' ' + lang.from : ''; + } else { + token = lang.ago ? ' ' + lang.ago : ''; + } + + /* + * 0 seconds && < 60 seconds Now + * 60 seconds 1 Minute + * > 60 seconds && < 60 minutes X Minutes + * 60 minutes 1 Hour + * > 60 minutes && < 24 hours X Hours + * 24 hours 1 Day + * > 24 hours && < 7 days X Days + * 7 days 1 Week + * > 7 days && < ~ 1 Month X Weeks + * ~ 1 Month 1 Month + * > ~ 1 Month && < 1 Year X Months + * 1 Year 1 Year + * > 1 Year X Years + * + * Single units are +10%. 1 Year shows first at 1 Year + 10% + */ + + function normalize(val, single) + { + var margin = 0.1; + if(val >= single && val <= single * (1+margin)) { + return single; + } + return val; + } + + for(var i = 0, format = formats[0]; formats[i]; format = formats[++i]) { + if(seconds < format[0]) { + if(i === 0) { + // Now + return format[1]; + } + + var val = Math.ceil(normalize(seconds, format[3]) / (format[3])); + return val + + ' ' + + (val != 1 ? format[2] : format[1]) + + (i > 0 ? token : ''); + } + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004475_map.js b/pool/shard000/JavaScript/0004475_map.js new file mode 100644 index 0000000000000000000000000000000000000000..dcde6bb14a2dc637d79bb6aafbd8811c104cc27b --- /dev/null +++ b/pool/shard000/JavaScript/0004475_map.js @@ -0,0 +1,14 @@ +var map; +var myLatLng = {lat: 57.048654, lng: 9.920159}; + +function initMap() { + map = new google.maps.Map(document.getElementById('map'), { + center: myLatLng, + scrollwheel: false, + zoom: 18 + }); + var marker = new google.maps.Marker({ + position: myLatLng, + map: map + }); +} diff --git a/pool/shard000/JavaScript/0004477_angular-loader.js b/pool/shard000/JavaScript/0004477_angular-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..2662e0d3d606446158643b8553a2db64518aea24 --- /dev/null +++ b/pool/shard000/JavaScript/0004477_angular-loader.js @@ -0,0 +1,484 @@ +/** + * @license AngularJS v1.5.0 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ + +(function() {//'use strict'; + function isFunction(value) {return typeof value === 'function';}; + +/* global: toDebugString: true */ + +function serializeObject(obj) { + var seen = []; + + return JSON.stringify(obj, function(key, val) { + val = toJsonReplacer(key, val); + if (isObject(val)) { + + if (seen.indexOf(val) >= 0) return '...'; + + seen.push(val); + } + return val; + }); +} + +function toDebugString(obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(obj)) { + return 'undefined'; + } else if (typeof obj !== 'string') { + return serializeObject(obj); + } + return obj; +} + +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning + * error from returned function, for cases when a particular type of error is useful. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ + +function minErr(module, ErrorConstructor) { + ErrorConstructor = ErrorConstructor || Error; + return function() { + var SKIP_INDEXES = 2; + + var templateArgs = arguments, + code = templateArgs[0], + message = '[' + (module ? module + ':' : '') + code + '] ', + template = templateArgs[1], + paramPrefix, i; + + message += template.replace(/\{\d+\}/g, function(match) { + var index = +match.slice(1, -1), + shiftedIndex = index + SKIP_INDEXES; + + if (shiftedIndex < templateArgs.length) { + return toDebugString(templateArgs[shiftedIndex]); + } + + return match; + }); + + message += '\nhttp://errors.angularjs.org/1.5.0/' + + (module ? module + '/' : '') + code; + + for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { + message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' + + encodeURIComponent(toDebugString(templateArgs[i])); + } + + return new ErrorConstructor(message); + }; +} + +/** + * @ngdoc type + * @name angular.Module + * @module ng + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ + +function setupModuleLoader(window) { + + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @module ng + * @description + * + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be + * registered using this mechanism. + * + * Passing one argument retrieves an existing {@link angular.Module}, + * whereas passing more than one argument creates a new {@link angular.Module} + * + * + * # Module + * + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. + * + * ```js + * // Create a new module + * var myModule = angular.module('myModule', []); + * + * // register a new service + * myModule.value('appName', 'MyCoolApp'); + * + * // configure existing services inside initialization blocks. + * myModule.config(['$locationProvider', function($locationProvider) { + * // Configure existing providers + * $locationProvider.hashPrefix('!'); + * }]); + * ``` + * + * Then you can create an injector and load your modules like this: + * + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` + * + * However it's more likely that you'll just use + * {@link ng.directive:ngApp ngApp} or + * {@link angular.bootstrap} to simplify this process for you. + * + * @param {!string} name The name of the module to create or retrieve. + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as + * {@link angular.Module#config Module#config()}. + * @returns {angular.Module} new module with the {@link angular.Module} api. + */ + return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; + + assertNotHasOwnProperty(name, 'module'); + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); + } + + /** @type {!Array.>} */ + var invokeQueue = []; + + /** @type {!Array.} */ + var configBlocks = []; + + /** @type {!Array.} */ + var runBlocks = []; + + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); + + /** @type {angular.Module} */ + var moduleInstance = { + // Private state + _invokeQueue: invokeQueue, + _configBlocks: configBlocks, + _runBlocks: runBlocks, + + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, + + /** + * @ngdoc property + * @name angular.Module#name + * @module ng + * + * @description + * Name of the module. + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @module ng + * @param {string} name service name + * @param {Function} providerType Construction function for creating new instance of the + * service. + * @description + * See {@link auto.$provide#provider $provide.provider()}. + */ + provider: invokeLaterAndSetModuleName('$provide', 'provider'), + + /** + * @ngdoc method + * @name angular.Module#factory + * @module ng + * @param {string} name service name + * @param {Function} providerFunction Function for creating new instance of the service. + * @description + * See {@link auto.$provide#factory $provide.factory()}. + */ + factory: invokeLaterAndSetModuleName('$provide', 'factory'), + + /** + * @ngdoc method + * @name angular.Module#service + * @module ng + * @param {string} name service name + * @param {Function} constructor A constructor function that will be instantiated. + * @description + * See {@link auto.$provide#service $provide.service()}. + */ + service: invokeLaterAndSetModuleName('$provide', 'service'), + + /** + * @ngdoc method + * @name angular.Module#value + * @module ng + * @param {string} name service name + * @param {*} object Service instance object. + * @description + * See {@link auto.$provide#value $provide.value()}. + */ + value: invokeLater('$provide', 'value'), + + /** + * @ngdoc method + * @name angular.Module#constant + * @module ng + * @param {string} name constant name + * @param {*} object Constant value. + * @description + * Because the constants are fixed, they get applied before other provide methods. + * See {@link auto.$provide#constant $provide.constant()}. + */ + constant: invokeLater('$provide', 'constant', 'unshift'), + + /** + * @ngdoc method + * @name angular.Module#decorator + * @module ng + * @param {string} The name of the service to decorate. + * @param {Function} This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. + * @description + * See {@link auto.$provide#decorator $provide.decorator()}. + */ + decorator: invokeLaterAndSetModuleName('$provide', 'decorator'), + + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link $animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ng.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#filter + * @module ng + * @param {string} name Filter name - this must be a valid angular expression identifier + * @param {Function} filterFactory Factory function for creating new instance of filter. + * @description + * See {@link ng.$filterProvider#register $filterProvider.register()}. + * + *
        + * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
        + */ + filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#controller + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. + * @param {Function} directiveFactory Factory function for creating new instance of + * directives. + * @description + * See {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#component + * @module ng + * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp) + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}) + * + * @description + * See {@link ng.$compileProvider#component $compileProvider.component()}. + */ + component: invokeLaterAndSetModuleName('$compileProvider', 'component'), + + /** + * @ngdoc method + * @name angular.Module#config + * @module ng + * @param {Function} configFn Execute this function on module load. Useful for service + * configuration. + * @description + * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#provider-recipe Provider Recipe}. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @module ng + * @param {Function} initializationFn Execute this function after injector creation. + * Useful for application initialization. + * @description + * Use this method to register work which should be performed when the injector is done + * loading all modules. + */ + run: function(block) { + runBlocks.push(block); + return this; + } + }; + + if (configFn) { + config(configFn); + } + + return moduleInstance; + + /** + * @param {string} provider + * @param {string} method + * @param {String=} insertMethod + * @returns {angular.Module} + */ + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; + return function() { + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + + /** + * @param {string} provider + * @param {string} method + * @returns {angular.Module} + */ + function invokeLaterAndSetModuleName(provider, method) { + return function(recipeName, factoryFunction) { + if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; + invokeQueue.push([provider, method, arguments]); + return moduleInstance; + }; + } + }); + }; + }); + +} + +setupModuleLoader(window); +})(window); + +/** + * Closure compiler type information + * + * @typedef { { + * requires: !Array., + * invokeQueue: !Array.>, + * + * service: function(string, Function):angular.Module, + * factory: function(string, Function):angular.Module, + * value: function(string, *):angular.Module, + * + * filter: function(string, Function):angular.Module, + * + * init: function(Function):angular.Module + * } } + */ +angular.Module; + diff --git a/pool/shard000/JavaScript/0004479_db.js b/pool/shard000/JavaScript/0004479_db.js new file mode 100644 index 0000000000000000000000000000000000000000..8a31e2e988ed22271f3fe0208aff36133b2802d8 --- /dev/null +++ b/pool/shard000/JavaScript/0004479_db.js @@ -0,0 +1,98 @@ + +/** + * This object manage the application database + */ +function Db(){ + this.name = ""; + this.version = "1.0"; + this.description = ""; + this.size = 5 * 1024 * 1024; + + return 0; +} + + +/** + * initialize the db and fill the instance attribute + * @return {integer} always 0 + */ +Db.prototype.init = function(){ + + var deferred = $.Deferred(); + + deferred.resolve(this.createTables()); + + return deferred.promise(); +} + + +/** + * Create a db instance or simply open it + * @return {jquery promise} the deffered's promise + */ +Db.prototype.openDb = function(){ + + var deferred = $.Deferred(); + deferred.resolve(openDatabase(this.name, this.version, this.description, this.size)); + + return deferred.promise(); +} + + +/** + * Create all application's required tables in the database + * @return {integer} always 0 + */ +Db.prototype.createTables = function(){ + + this.openDb().done(function(dbInstance){ + + dbInstance.transaction(function (tx) { + //tx.executeSql("CREATE TABLE IF NOT EXISTS ..."); + }, function(error){ + new Tools().test('error during creation tables '+error.message); + }); + + }).fail(function(error){ + new Tools().test('error while opening db '+error.message); + }); + + + return 0; +} + +/** + * executes a query upon the database and sends back a promise about the query result execution + * @param {string} queryString the query to execute + * @return {deferred.promise} the deferred promise + */ +Db.prototype.goQuery = function(queryString){ + +//new Tools().test('query '+queryString); + + var deferred = $.Deferred(); + + var success = function(tx, results){ + deferred.resolve(results); + } + + var fail = function(tx, error){ + deferred.reject(error); + } + + this.openDb().done(function(dbInstance){ + + dbInstance.transaction(function (tx) { + tx.executeSql(queryString, [], success, fail); + }); + + }).fail(function(){ + new Tools().test('error while opening db'); + }); + + return deferred.promise(); +} + + +//*/ + diff --git a/pool/shard000/JavaScript/0004480_logged_gaji.js b/pool/shard000/JavaScript/0004480_logged_gaji.js new file mode 100644 index 0000000000000000000000000000000000000000..28b19e7bcc4778d8e5fd7e42bc11feada59a5e6c --- /dev/null +++ b/pool/shard000/JavaScript/0004480_logged_gaji.js @@ -0,0 +1,40 @@ +$( document ).ready(function() { + $('#confirm-delete').on('show.bs.modal', function(e) { + $(this).find('.danger').attr('href', $(e.relatedTarget).data('href')); + }); + + //hanya bisa masukin angka + $('#inputgaji').keypress(function (data) { + if (data.which!=46 && data.which!=44 && data.which!=8 && data.which!=0 && + (data.which<48 || data.which>57)) + return false; + }); + $('#inputgaji').keyup(function(event) { + $(this).val(function(index, value) { + return value + .replace(/[^,\d]/g, "") + .replace(/\B(?=(\d{3})+(?!\d))/g, ".") + .replace(/[,]\d{3}/g, ",00") + ; + }); + }); + //validasi simpan +$("#btn").click(function(event){ + event.preventDefault(); + var base_url = $('#base_url').val(); + $.ajax({ + type: "POST", + url: base_url + "logged?menu=gaji&action=auth", + data: $("#form").serialize(), + success:function(data) { + if(data=="sukses"){ + $('#tampil').html("
        Data berhasil disimpan
        "); + window.location = base_url + "logged?menu=gaji"; + } + else{ + $('#tampil').html(data); + } + }, + }); + }); + }); diff --git a/pool/shard000/JavaScript/0004481_BlurYTintFilter.js b/pool/shard000/JavaScript/0004481_BlurYTintFilter.js new file mode 100644 index 0000000000000000000000000000000000000000..ae646984c93f7d914bd6c2a2dddb799605081468 --- /dev/null +++ b/pool/shard000/JavaScript/0004481_BlurYTintFilter.js @@ -0,0 +1,89 @@ +var core = require('../../core'); + +// @see https://github.com/substack/brfs/issues/25 +var fs = require('fs'); + +/** + * The BlurYTintFilter applies a vertical Gaussian blur to an object. + * + * @class + * @extends AbstractFilter + * @memberof PIXI.filters + */ +function BlurYTintFilter() +{ + core.AbstractFilter.call(this, + // vertex shader + fs.readFileSync(__dirname + '/blurYTint.vert', 'utf8'), + // fragment shader + fs.readFileSync(__dirname + '/blurYTint.frag', 'utf8'), + // set the uniforms + { + blur: { type: '1f', value: 1 / 512 }, + color: { type: 'c', value: [0,0,0]}, + alpha: { type: '1f', value: 0.7 }, + offset: { type: '2f', value:[5, 5]}, + strength: { type: '1f', value:1} + } + ); + + this.passes = 1; + this.strength = 4; +} + +BlurYTintFilter.prototype = Object.create(core.AbstractFilter.prototype); +BlurYTintFilter.prototype.constructor = BlurYTintFilter; +module.exports = BlurYTintFilter; + +BlurYTintFilter.prototype.applyFilter = function (renderer, input, output, clear) +{ + var shader = this.getShader(renderer); + + this.uniforms.strength.value = this.strength / 4 / this.passes * (input.frame.height / input.size.height); + + if(this.passes === 1) + { + renderer.filterManager.applyFilter(shader, input, output, clear); + } + else + { + var renderTarget = renderer.filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for(var i = 0; i < this.passes-1; i++) + { + renderer.filterManager.applyFilter(shader, flip, flop, clear); + + var temp = flop; + flop = flip; + flip = temp; + } + + renderer.filterManager.applyFilter(shader, flip, output, clear); + + renderer.filterManager.returnRenderTarget(renderTarget); + } +}; + + +Object.defineProperties(BlurYTintFilter.prototype, { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof BlurYFilter# + * @default 2 + */ + blur: { + get: function () + { + return this.strength; + }, + set: function (value) + { + this.padding = value * 0.5; + this.strength = value; + } + }, +}); diff --git a/pool/shard000/JavaScript/0004482_shared.js b/pool/shard000/JavaScript/0004482_shared.js new file mode 100644 index 0000000000000000000000000000000000000000..23336572ff1f949277d8d975badb6fcabc6d9af7 --- /dev/null +++ b/pool/shard000/JavaScript/0004482_shared.js @@ -0,0 +1,62 @@ +// Note: You must restart bin/webpack-dev-server for changes to take effect + +/* eslint global-require: 0 */ +/* eslint import/no-dynamic-require: 0 */ + +const webpack = require('webpack') +const { basename, dirname, join, relative, resolve } = require('path') +const { sync } = require('glob') +const ExtractTextPlugin = require('extract-text-webpack-plugin') +const ManifestPlugin = require('webpack-manifest-plugin') +const extname = require('path-complete-extname') +const { env, settings, output, loadersDir } = require('./configuration.js') + +const extensionGlob = `**/*{${settings.extensions.join(',')}}*` +const entryPath = join(settings.source_path, settings.source_entry_path) +const packPaths = sync(join(entryPath, extensionGlob)) + +module.exports = { + entry: packPaths.reduce( + (map, entry) => { + const localMap = map + const namespace = relative(join(entryPath), dirname(entry)) + localMap[join(namespace, basename(entry, extname(entry)))] = resolve(entry) + return localMap + }, {} + ), + + output: { + filename: '[name].js', + path: output.path, + publicPath: output.publicPath + }, + + module: { + rules: sync(join(loadersDir, '*.js')).map(loader => require(loader)) + }, + + plugins: [ + new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))), + new ExtractTextPlugin(env.NODE_ENV === 'production' ? '[name]-[hash].css' : '[name].css'), + new ManifestPlugin({ + publicPath: output.publicPath, + writeToFileEmit: true + }), + new webpack.optimize.CommonsChunkPlugin({ + name: "common", + minChunks: Infinity, + }) + ], + + resolve: { + extensions: settings.extensions, + modules: [ + resolve(settings.source_path), + 'node_modules' + ] + }, + + resolveLoader: { + modules: ['node_modules'] + } +} diff --git a/pool/shard000/JavaScript/0004483_main.js b/pool/shard000/JavaScript/0004483_main.js new file mode 100644 index 0000000000000000000000000000000000000000..53375129a4376dee0af05ae4bdedf52e20aa6f6c --- /dev/null +++ b/pool/shard000/JavaScript/0004483_main.js @@ -0,0 +1,260 @@ +SlideTab = function(container, options) { + + if (arguments.length === 0) { + throw new Error('缺少参数, 容器的类名是必须要传的'); + } + + this.container = document.querySelector(container); + + if (!this.container) { + throw new Error('找不到class或id为' + container + '的元素'); + } + + //直接子元素的个数 + this.childCount = this.container.children.length; + + //一个窗格的宽度 + this.panelSize = this.container.offsetWidth / this.childCount; + + //保存每一个窗格的高度,当滑动到某一个窗格的时候需要改变窗格的高度 + this.paneHeight = []; + + //每一页是否还需要加载数据 + this.tabEnds = []; + + //当前的窗格 + this.currentIndex = 0; + + //上一个窗格,主要是slidechange事件中判断窗格是否发生了变化 + this.preIndex = 0; + + this.hammer = new Hammer.Manager(this.container, { + touchAction: 'auto' + }); + + this.hammer.add(new Hammer.Pan({ + threshold: 10 + })); + + this.hammer.on("panleft panright", Hammer.bindFn(this.onPan, this)); + this.hammer.on("panstart", Hammer.bindFn(this.onPanStart, this)); + this.hammer.on("panend pancancel", Hammer.bindFn(this.onPanEnd, this)); + + + //是否允许左右滑动 + this.canLeftRightslide = true; + + //是否第一次滑动 + this.globalFirstslide = true; + + this.init(options); +} + +SlideTab.prototype = { + + /** + * 初始化 + * @param options + */ + init: function(options) { + this.opts = { + initialPane: 0 + }; + Hammer.extend(this.opts, options || {}); + + this.currentIndex = this.opts.initialPane; + this.preIndex = this.currentIndex; + + this.show(this.currentIndex, 0, false); + + }, + + onPanStart: function(event) { + ////如果最开始手势是左右滑动,那就不允许上下滑动 + if (event.additionalEvent === 'panleft' || event.additionalEvent == 'panright') { + //document.addEventListener('touchmove', this.preventDefault, false); + this.canLeftRightslide = true; + } + + //如果最开始手势是上下滑动,那么就不允许左右滑动 + if (event.additionalEvent === 'pandown' || event.additionalEvent == 'panup') { + this.canLeftRightslide = false; + } + + this.slideStart(); + }, + onPan: function(event) { + + if (!this.canLeftRightslide) { + return false; + } + + var delta = event.deltaX, + percent = (delta / this.panelSize) * 100, + animate = false; + + this.preIndex = this.currentIndex; + + this.show(this.currentIndex, percent, animate); + + }, + onPanEnd: function(event) { + var delta = event.deltaX, + percent = (delta / this.panelSize) * 100; + + //当滑动的距离大于窗格的25%的时候才会滑动到下一个 + if (Math.abs(percent) > 20 && event.type == 'panend') { + this.currentIndex += (percent < 0) ? 1 : -1; + } + + this.show(this.currentIndex, 0, true); + + document.removeEventListener('touchmove', this.preventDefault, false); + this.slideEnd(); + }, + + /** + * 显示第几个窗口 + * @param showIndex + * @param percent + * @param animate 是否需要动画 + */ + show: function(showIndex, percent, animate) { + + //显示第几个 + showIndex = Math.max(0, Math.min(showIndex, this.childCount - 1)); + + percent = percent || 0; + + this.currentIndex = showIndex; + + var container = this.container, + classList = container.classList; + + if (animate) { + classList.add('animate'); + } else { + classList.remove('animate'); + } + + //需要滑动到的位置 + var pos; + if (percent == 0) { + + pos = -this.panelSize * showIndex; + + //更新container的高度 + // this.container.style.height = this.paneHeight[showIndex] || 0; + + //只要不是初次滑动都需要调用 + if (this.globalFirstslide) { + this.globalFirstslide = false; + } else { + this.handleLoad(); + } + + } else { + pos = -this.preIndex * this.panelSize + this.panelSize * percent / 100; + } + + var translate = 'translate3d(' + (pos) + 'px, 0, 0)'; + // this.container.style.transform = translate; + // this.container.style.webkitTransform = translate; + // this.container.style.mozTransform = translate; + // this.container.style.msTransform = translate; + + }, + /** + * 滑动到第几个 + */ + slideTo: function(index) { + this.show(index, 0, true); + }, + /** + * 当窗格发生变化完成后触发 + */ + slideChanged: function() { + this.opts.slideChanged && this.opts.slideChanged.call(this, this.currentIndex); + }, + /** + * 开始滑动 + */ + slideStart: function() { + this.opts.slideStart && this.opts.slideStart.call(this); + + }, + /** + * 当窗格发生变化完成后触发 + */ + slideEnd: function() { + if (this.currentIndex !== this.preIndex) { + this.slideChanged(); + } + this.opts.slideEnd && this.opts.slideEnd.call(this); + this.resetHeight(); + }, + /** + * 阻止默认事件 + * @param event + */ + preventDefault: function(event) { + event.preventDefault(); + }, + /** + * 重置容器的高度 + */ + resetHeight: function() { + console.log("resetHeight"); + // if (this.dropload) { + // this.dropload.resetload(); + // } + + // var style = this.container.style; + // style.height = this.container.children[this.currentIndex].offsetHeight + 'px'; + + // style.height = ($("body").height() - $(".fixed-title").height() - $(".nav").height() - $(".bar").height()) + "px";//$(this.container.children[this.currentIndex])[0].scrollHeight + "px"; + // console.log(this.container.children[this.currentIndex].height); + // console.log($(this.container.children[this.currentIndex])); + // console.log(this.container.children[this.currentIndex].offsetHeight); + // console.log($(this.container.children[this.currentIndex])[1].scrollHeight); + // console.log($("body").height() - $(".fixed-title").height()); + // console.log($("body").height() - $(".fixed-title").height() - $(".nav").height()); + // console.log($("body").height() - $(".fixed-title").height() - $(".nav").height() - $(".bar").height()); + // console.log($("body").height()-$(".fixed-title").height()-$(".nav").height()-$(".bar").height()); + // this.paneHeight[this.currentIndex] = style.height; + // this.dropload.resetload(); + }, + + /** + * 窗格切换的时候处理dropload是否需要加载数据 + */ + handleLoad: function() { + if (this.dropload) { + var dropload = this.dropload; + if (this.tabEnds[this.currentIndex]) { + dropload.noData(); + dropload.lock(); + } else { + // 解锁 + dropload.unlock(); + dropload.noData(false); + } + dropload.resetload(); + } + }, + + /** + * 锁定窗格加载数据 + */ + lock: function() { + if (this.dropload) { + var dropload = this.dropload; + dropload.lock(); + dropload.noData(); + } + this.tabEnds[this.currentIndex] = true; + } +}; + + +window.SlideTab = SlideTab; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004484_post.js b/pool/shard000/JavaScript/0004484_post.js new file mode 100644 index 0000000000000000000000000000000000000000..6c96eea6e701180bc63123c30e321515c729eab2 --- /dev/null +++ b/pool/shard000/JavaScript/0004484_post.js @@ -0,0 +1,93 @@ +var Dialog = require('./../../components/dialog/dialog'), + Loading = require('./../../components/loading/loading'); + +function Login() { + this.init(); +} + +Login.prototype = { + init: function() { + this.initPage(); + this.initDOM(); + this.bindEvent(); + }, + + initPage: function() { + this.dialog = new Dialog(); + this.loading = new Loading(); + }, + + initDOM: function() { + this.$title = $('#_j_title'); + this.$tab = $('#_j_tab'); + this.$content = $('#_j_content'); + this.$preview = $('#_j_preview'); + this.$publish = $('#_j_publish'); + }, + + bindEvent: function() { + this.$publish.on('click', this.submit.bind(this)); + }, + + checkForm: function() { + if ( this.$title.val() === '' ) { + this.dialog.alert('文章标题不能为空'); + return false; + } + + if ( this.$tab.val() === '' ) { + this.dialog.alert('文章标签不能为空'); + return false; + } + + if ( this.$content.val() === '' ) { + this.dialog.alert('文章内容不能为空'); + return false; + } + + return true; + }, + + getForm: function() { + return { + type : 'blog', + title : this.$title.val(), + tab : this.$tab.val(), + content : this.$content.val(), + }; + }, + + submitForm: function(data, callback) { + $.ajax({ + url : "/article/create", + type: "POST", + data: data, + success: function(data) { + callback && callback(data); + } + }); + }, + + submit: function() { + var that = this; + var check = this.checkForm(); + + if ( !check ) + return; + + this.submitForm(that.getForm.call(that), function(data) { + if ( data.errcode !== 0 ) { + that.dialog.alert(data.message || '发布出错'); + } + + else + that.loading.showTips('发布成功', { + confirmOp: function() { + // window.location.href = "/admin/index"; + } + }); + }); + } +} + +var login = new Login(); diff --git a/pool/shard000/JavaScript/0004485_autocompleteinput.js b/pool/shard000/JavaScript/0004485_autocompleteinput.js new file mode 100644 index 0000000000000000000000000000000000000000..d4f8179f8aca3f8d5a869579495795582ed85a87 --- /dev/null +++ b/pool/shard000/JavaScript/0004485_autocompleteinput.js @@ -0,0 +1,20 @@ +'use strict'; + +describe('Directive: autocompleteInput', function () { + + // load the directive's module + beforeEach(module('autocompleteApp')); + + var element, + scope; + + beforeEach(inject(function ($rootScope) { + scope = $rootScope.$new(); + })); + + it('should make hidden element visible', inject(function ($compile) { + element = angular.element(''); + element = $compile(element)(scope); + expect(element.text()).toBe('this is the autocompleteInput directive'); + })); +}); diff --git a/pool/shard000/JavaScript/0004486_request.js b/pool/shard000/JavaScript/0004486_request.js new file mode 100644 index 0000000000000000000000000000000000000000..313c7c6f62fc858c55d189391039acffdecff829 --- /dev/null +++ b/pool/shard000/JavaScript/0004486_request.js @@ -0,0 +1,503 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ +// +// req.get = +// req.header = function header(name) { +// if (!name) { +// throw new TypeError('name argument is required to req.get'); +// } +// +// if (typeof name !== 'string') { +// throw new TypeError('name must be a string to req.get'); +// } +// +// var lc = name.toLowerCase(); +// +// switch (lc) { +// case 'referer': +// case 'referrer': +// return this.headers.referrer +// || this.headers.referer; +// default: +// return this.headers[lc]; +// } +// }; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +// defineGetter(req, 'protocol', function protocol(){ +// var proto = this.connection.encrypted +// ? 'https' +// : 'http'; +// var trust = this.get('trust proxy fn'); +// +// if (!trust(this.connection.remoteAddress, 0)) { +// return proto; +// } +// +// // Note: X-Forwarded-Proto is normally only ever a +// // single value, but this is to be safe. +// proto = this.get('X-Forwarded-Proto') || proto; +// return proto.split(/\s*,\s*/)[0]; +// }); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +// defineGetter(req, 'secure', function secure(){ +// return this.protocol === 'https'; +// }); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +// defineGetter(req, 'ip', function ip(){ +// var trust = this.get('trust proxy fn'); +// return proxyaddr(this, trust); +// }); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +// defineGetter(req, 'ips', function ips() { +// var trust = this.get('trust proxy fn'); +// var addrs = proxyaddr.all(this, trust); +// return addrs.slice(1).reverse(); +// }); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +// defineGetter(req, 'subdomains', function subdomains() { +// var hostname = this.hostname; +// +// if (!hostname) return []; +// +// var offset = this.get('subdomain offset'); +// var subdomains = !isIP(hostname) +// ? hostname.split('.').reverse() +// : [hostname]; +// +// return subdomains.slice(offset); +// }); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ +// +// defineGetter(req, 'path', function path() { +// return parse(this).pathname; +// }); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +// defineGetter(req, 'hostname', function hostname(){ +// var trust = this.get('trust proxy fn'); +// var host = this.get('X-Forwarded-Host'); +// +// if (!host || !trust(this.connection.remoteAddress, 0)) { +// host = this.get('Host'); +// } +// +// if (!host) return; +// +// // IPv6 literal support +// var offset = host[0] === '[' +// ? host.indexOf(']') + 1 +// : 0; +// var index = host.indexOf(':', offset); +// +// return index !== -1 +// ? host.substring(0, index) +// : host; +// }); + +// TODO: change req.host to return host in next major +// +// defineGetter(req, 'host', deprecate.function(function host(){ +// return this.hostname; +// }, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +// defineGetter(req, 'fresh', function(){ +// var method = this.method; +// var s = this.res.statusCode; +// +// // GET or HEAD for weak freshness validation only +// if ('GET' !== method && 'HEAD' !== method) return false; +// +// // 2xx or 304 as per rfc2616 14.26 +// if ((s >= 200 && s < 300) || 304 === s) { +// return fresh(this.headers, (this.res._headers || {})); +// } +// +// return false; +// }); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +// defineGetter(req, 'stale', function stale(){ +// return !this.fresh; +// }); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +// defineGetter(req, 'xhr', function xhr(){ +// var val = this.get('X-Requested-With') || ''; +// return val.toLowerCase() === 'xmlhttprequest'; +// }); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/pool/shard000/JavaScript/0004487_file.js b/pool/shard000/JavaScript/0004487_file.js new file mode 100644 index 0000000000000000000000000000000000000000..d8541807dec14592762fe3af5d57219241f0888d --- /dev/null +++ b/pool/shard000/JavaScript/0004487_file.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (sequelize, DataTypes) { + var File = sequelize.define('File', { + 'name': DataTypes.STRING, + 'size': DataTypes.INTEGER, + 'type': DataTypes.STRING + }, { + 'classMethods': { + 'associate': function associate(models) { + File.belongsTo(models.Contact); + } + } + }); + return File; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004491_common.js b/pool/shard000/JavaScript/0004491_common.js new file mode 100644 index 0000000000000000000000000000000000000000..f08406285b815e5838d05fbd74df9890ef64110a --- /dev/null +++ b/pool/shard000/JavaScript/0004491_common.js @@ -0,0 +1,205 @@ +jQuery(document).ready(function(){ + +// FIXED MENU SHOW AND HIDE + + jQuery(".fixed-nav").hide(); + + jQuery(function () { + jQuery(window).scroll(function () { + if (jQuery(this).scrollTop() > 150) { + jQuery('.fixed-nav').fadeIn(); + } else { + jQuery('.fixed-nav').fadeOut(); + } + }); + }); + + + +jQuery('.one-page').waypoint(function(event, direction) { + jQuery('.navul li a').removeClass('active'); + getid = jQuery(this).attr('class').split(' ')[1]; + jQuery('.navul li .'+getid).addClass('active'); +}, { + offset: '0' +}); + + + + + + // HOVER-IMAGES + + + jQuery('.header-links ul li a').hover(function(){ + jQuery('div',this).stop().animate({top: '-16px'},300); + },function(){ + jQuery('div',this).stop().animate({top: '0'},300); + }); + + jQuery("a.anchorLink").anchorAnimate() + + + jQuery(function() { + + jQuery("").appendTo(".fixed-nav-center"); + + // Create default option "Go to..." + jQuery("
        APIResult
        ' + method + '' + app[method]() + '
        getPath(\'' + arg + '\')' + app.getPath(arg) + '
        "; + l+=""; + b=1; + idpregunta = 0; + pregunta =""; + flaresponde = 0; + for(var x in data.preguntas ){ + idpregunta= data.preguntas[x].idpregunta; + pregunta= data.preguntas[x].pregunta; + flaresponde = 0; + for (var z in data.respuestas){ + + idpreguntacliente = data.respuestas[z].idpregunta; + respuestacliente = data.respuestas[z].respuesta; + e = 0; + if(idpregunta == idpreguntacliente ){ + + if (respuestacliente == "yes") { + + l+=""; + l+=""; + }else{ + l+=""; + l+=""; + } + + + flaresponde = 1; + } + + } + /**/ + if (flaresponde == 0 ){ + l+=""; + l+=""; + } + b++; + } + + l+="
        #cuestionario SI NO
        "+b+""+pregunta+"
        "+b+""+pregunta+"
        "+b+""+pregunta+"
      "; + llenaelementoHTML("#cuestionario" , l); + + + + $(".trueresponse").click(trueresponseaction); + $(".falseresponse").click(falseresponseaction); + + }).fail(function(){ + alert("Falló algo reportar "); + + }); + +} + + +/********************************************************************************************/ +function trueresponseaction(e){ + + pregunta = e.target.id; + idcostomer = $("#idcostomer").val(); + + url = now + "index.php/api/creditorest/updaterespuestacliente/format/json"; + $.post(url , {"pregunta" : pregunta , "idcostomer" : idcostomer , "respuesta" : "yes"}) + .done(function(data){ + + + }).fail(function(){ + alert("Fallo actualización"); + }); + loadsurvey(); +} + + +/********************************************************************************************/ +function falseresponseaction(e){ + + pregunta = e.target.id; + idcostomer = $("#idcostomer").val(); + + + url = now + "index.php/api/creditorest/updaterespuestacliente/format/json"; + $.post(url , {"pregunta" : pregunta , "idcostomer" : idcostomer , "respuesta" : "not"}) + .done(function(data){ + + + }).fail(function(){ + alert("Fallo actualización"); + }); + loadsurvey(); + +} + + +/********************************************************************************************/ + + +function loadinfodocumentosolicitado(){ + + documento = $("#documento").val(); + nombredocumento =""; + notadocumento = ""; + url = now + "index.php/api/creditorest/getinfodocument/format/json"; + $.get(url , {"documento" : documento}) + .done(function(data){ + + + for (var x in data) { + + nombredocumento = data[x].nombredocumento; + notadocumento = data[x].notadocumento; + } + llenaelementoHTML("#documentosolicitado" , nombredocumento); + llenaelementoHTML("#especificaciones" , notadocumento); + + }).fail(function(){ + alert("Fallo actualización"); + }); +} + + diff --git a/pool/shard000/JavaScript/0004629_Offset.js b/pool/shard000/JavaScript/0004629_Offset.js new file mode 100644 index 0000000000000000000000000000000000000000..57b954134932382a75164047f125b8ad6276c22c --- /dev/null +++ b/pool/shard000/JavaScript/0004629_Offset.js @@ -0,0 +1,52 @@ +/** + * + */ +Ext.define('Ext.util.Offset', { + statics: { + fromObject: function(obj) { + return new this(obj.x, obj.y); + } + }, + + constructor: function(x, y) { + this.x = (x != null && !isNaN(x)) ? x : 0; + this.y = (y != null && !isNaN(y)) ? y : 0; + + return this; + }, + + copy: function() { + return new Ext.util.Offset(this.x, this.y); + }, + + copyFrom: function(p) { + this.x = p.x; + this.y = p.y; + }, + + toString: function() { + return "Offset[" + this.x + "," + this.y + "]"; + }, + + equals: function(offset) { + if(!(offset instanceof Ext.util.Offset)) + throw new Error('offset must be an instance of Ext.util.Offset'); + + return (this.x == offset.x && this.y == offset.y); + }, + + round: function(to) { + if (!isNaN(to)) { + var factor = Math.pow(10, to); + this.x = Math.round(this.x * factor) / factor; + this.y = Math.round(this.y * factor) / factor; + } else { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + } + }, + + isZero: function() { + return this.x == 0 && this.y == 0; + } +}); diff --git a/pool/shard000/JavaScript/0004631_curriculumPost_element.js b/pool/shard000/JavaScript/0004631_curriculumPost_element.js new file mode 100644 index 0000000000000000000000000000000000000000..f4ae2041cfffa9da28c8a4e986a8a0507e37c8d2 --- /dev/null +++ b/pool/shard000/JavaScript/0004631_curriculumPost_element.js @@ -0,0 +1,129 @@ +exports.definition = { + config: { + columns: { + "id": "INTEGER", + "post_id" : "INTEGER", + "type": "TEXT", + "element": "TEXT", + "caption": "TEXT", + "position" : "TEXT" + }, + adapter: { + type: "sql", + collection_name: "curriculumPost_element" + } + }, + extendModel: function(Model) { + _.extend(Model.prototype, { + // extended functions and properties go here + }); + + return Model; + }, + extendCollection: function(Collection) { + _.extend(Collection.prototype, { + // extended functions and properties go here + getRecordsById: function(id){ + var collection = this; + var sql = "SELECT * FROM " + collection.config.adapter.collection_name +" WHERE id ="+id; + + db = Ti.Database.open(collection.config.adapter.db_name); + if(Ti.Platform.osname != "android"){ + db.file.setRemoteBackup(false); + } + var res = db.execute(sql); + var arr = []; + + if (res.isValidRow()){ + arr = { + id: res.fieldByName('id'), + post_id: res.fieldByName('post_id'), + element: res.fieldByName('element'), + caption: res.fieldByName('caption'), + type: res.fieldByName('type'), + position: res.fieldByName('position') + }; + + } + res.close(); + db.close(); + collection.trigger('sync'); + return arr; + }, + getListByPost: function(post_id){ + var collection = this; + var sql = "SELECT * FROM " + collection.config.adapter.collection_name +" WHERE post_id ='"+post_id+"' ORDER by position ASC"; + + db = Ti.Database.open(collection.config.adapter.db_name); + if(Ti.Platform.osname != "android"){ + db.file.setRemoteBackup(false); + } + var res = db.execute(sql); + var listArr = []; + var count = 0; + while (res.isValidRow()){ + listArr[count] = { + id: res.fieldByName('id'), + post_id: res.fieldByName('post_id'), + element: res.fieldByName('element'), + caption: res.fieldByName('caption'), + type: res.fieldByName('type'), + position: res.fieldByName('position') + }; + + res.next(); + count++; + } + + res.close(); + db.close(); + collection.trigger('sync'); + return listArr; + }, + addElement : function(arr) { + var collection = this; + db = Ti.Database.open(collection.config.adapter.db_name); + + //db.execute("BEGIN"); + arr.forEach(function(entry) { + + var ele_arr = entry.element; + //remove the previous records + var delete_sql = "DELETE FROM " + collection.config.adapter.collection_name + " WHERE post_id="+entry.id; + + // console.log(delete_sql); + db.execute(delete_sql); + ele_arr.forEach(function(ele) { + + //add new 1 + var element = ele.element; + element = element.replace(/["']/g, """); + + var caption = ele.caption; + if(caption != "" && caption != null){ + caption = caption.replace(/["']/g, """); + } + + sql_query = "INSERT INTO "+ collection.config.adapter.collection_name + "(id, post_id, element,caption, type,position) VALUES ("+ele.id+", '"+ele.p_id+"', '"+element+"', '"+caption+"', '"+ele.type+"' , '"+ele.position+"')"; + + db.execute(sql_query); + }); + }); + + //db.execute("COMMIT"); + db.close(); + collection.trigger('sync'); + }, + resetPostElement : function(){ + var collection = this; + var sql = "DELETE FROM " + collection.config.adapter.collection_name; + db = Ti.Database.open(collection.config.adapter.db_name); + db.execute(sql); + db.close(); + collection.trigger('sync'); + }, + }); + + return Collection; + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004632_this-val-not-object.js b/pool/shard000/JavaScript/0004632_this-val-not-object.js new file mode 100644 index 0000000000000000000000000000000000000000..9b8ef05e68caa78572637ec037e201f149ba0612 --- /dev/null +++ b/pool/shard000/JavaScript/0004632_this-val-not-object.js @@ -0,0 +1,99 @@ +// Copyright 2018 Valerie Young. All rights reserved. +// This code is governed by the BSD license found in the LICENSE file. +/*--- +esid: sec-asyncgenerator-prototype-return +description: return rejects promise when `this` value not an object +info: | + AsyncGenerator.prototype.return ( value ) + 1. Let generator be the this value. + 2. Let completion be Completion{[[Type]]: return, [[Value]]: value, + [[Target]]: empty}. + 3. Return ! AsyncGeneratorEnqueue(generator, completion). + + AsyncGeneratorEnqueue ( generator, completion ) + ... + 3. If Type(generator) is not Object, or if generator does not have an + [[AsyncGeneratorState]] internal slot, then + a. Let badGeneratorError be a newly created TypeError object. + b. Perform ! Call(promiseCapability.[[Reject]], undefined, « badGeneratorError »). + c. Return promiseCapability.[[Promise]]. + +flags: [async] +features: [async-iteration] +---*/ + +async function* g() {} +var AsyncGeneratorPrototype = Object.getPrototypeOf(g).prototype; + +var symbol = Symbol(); + +var testPromises = [ + AsyncGeneratorPrototype.return.call(undefined).then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value `undefined`"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(undefined) expected TypeError but got " + e); + } + } + ), + AsyncGeneratorPrototype.return.call(1).then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value is a Number"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(Number) expected TypeError but got " + e); + } + } + ), + AsyncGeneratorPrototype.return.call("string").then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value is a String"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(String) expected TypeError but got " + e); + } + } + ), + AsyncGeneratorPrototype.return.call(null).then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value `null`"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(null) expected TypeError but got " + e); + } + } + ), + AsyncGeneratorPrototype.return.call(true).then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value is a Boolean"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(Boolean) expected TypeError but got " + e); + } + } + ), + AsyncGeneratorPrototype.return.call(symbol).then( + function () { + throw new Test262Error("AsyncGeneratorPrototype.return should reject promise" + + " when `this` value is a Symbol"); + }, + function (e) { + if (!(e instanceof TypeError)) { + throw new Test262Error("(Symbol) expected TypeError but got " + e); + } + } + ) +] + +Promise.all(testPromises).then(() => {}).then($DONE, $DONE) diff --git a/pool/shard000/JavaScript/0004634_console.js b/pool/shard000/JavaScript/0004634_console.js new file mode 100644 index 0000000000000000000000000000000000000000..03ba47be95605426f6f7dfa76f80a8fadde31529 --- /dev/null +++ b/pool/shard000/JavaScript/0004634_console.js @@ -0,0 +1,32 @@ +/** + * Copy and paste this into the console + */ + +var passwordCount = 60; + +// dinopass has jquery in the page +var input = $('#password-input'); +var newBtn = $('#simple-button'); + +var passwords = []; + +var interval; + +var getNewPassword = function () { + password = input.val(); + + if (passwords.indexOf(password) < 0) { + passwords.push(password); + } + + if (passwords.length >= passwordCount) { + window.clearInterval(interval); + console.log(passwords); + } + + newBtn.click(); +}; + +interval = window.setInterval(getNewPassword, 500); + +// Copy and paste the array out of the console and format it how you like in a text editor. diff --git a/pool/shard000/JavaScript/0004635_EditCardContent.js b/pool/shard000/JavaScript/0004635_EditCardContent.js new file mode 100644 index 0000000000000000000000000000000000000000..5440b05b8962f8fc76227f3f8b32fff8b480afd6 --- /dev/null +++ b/pool/shard000/JavaScript/0004635_EditCardContent.js @@ -0,0 +1,192 @@ +import React, { Component } from "react"; +import css from "./CreateCardContent.css"; +import FrontCard from "../flashcards/FlashcardFrontPreview"; +import BackCard from "../flashcards/FlashcardBackPreview"; +import { getTranslation } from "../sub-components/translate"; +import LangaugeScroll from "../sub-components/languageScroll"; + +/** + * Renders a page where the user can make changes to a card that they have + * previously made. Upon submission of the form on the page, + * the respective card would be updated in datastore. + */ +class EditCardContent extends Component { + constructor(props) { + super(props); + this.state = { + imgSrc: this.props.imageBlobKey, + text: this.props.rawText, + translation: this.props.textTranslated, + fromLang: "none", + toLang: "none", + uploadUrlFetched: false, + imageUploadUrl: "", + }; + this.translateText = this.translateText.bind(this); + this.fromLangSelected = this.fromLangSelected.bind(this); + this.toLangSelected = this.toLangSelected.bind(this); + this.imageSelected = this.imageSelected.bind(this); + this.textChanged = this.textChanged.bind(this); + } + + /** + * When the user has finished typing, the Google Translate + * API is called to fetch the translated version of the text input. + */ + translateText(event) { + const text = event.target.value; + if (this.state.fromLang !== "none" && this.state.toLang !== "none") { + (async () => { + const toLang = this.state.toLang; + const translated = await getTranslation( + text, + this.state.fromLang, + this.state.toLang + ); + this.setState((prevState) => { + if (prevState.toLang != toLang || prevState.text != text) { + return; + } + return { translation: translated.translation, text }; + }); + })(); + } + } + + async componentDidMount() { + try { + const uploadResponse = await fetch("/editcardupload"); + const uploadUrl = await uploadResponse.text(); + if (!uploadResponse.ok) { + throw Error(uploadUrl.statusText); + } + this.setState({ imageUploadUrl: uploadUrl, uploadUrlFetched: true }); + } catch (error) { + alert("Refresh page to create a card"); + } + } + + /* + * Updates the selected language code for future calls to the translateText function + */ + fromLangSelected(domEvent) { + const selectedValue = domEvent.target[domEvent.target.selectedIndex].value; + this.setState({ fromLang: selectedValue }); + } + + toLangSelected(domEvent) { + const selectedValue = domEvent.target[domEvent.target.selectedIndex].value; + this.setState({ toLang: selectedValue }); + } + + imageSelected(event) { + this.setState({ imgSrc: URL.createObjectURL(event.target.files[0]) }); + } + + textChanged(event) { + this.setState({ text: event.target.value }); + } + + render() { + if (!this.state.uploadUrlFetched) { + return

      Loading

      ; + } + return ( +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
        +
        +
      • + + + + + + + + +
      • +
      • + + +
      • +
      • + + +
      • +
      • + + + + +
      • + + +
      • + +
      • +
        +
      +
      +
      +
      + ); + } +} + +export default EditCardContent; diff --git a/pool/shard000/JavaScript/0004636_accounts.js b/pool/shard000/JavaScript/0004636_accounts.js new file mode 100644 index 0000000000000000000000000000000000000000..15611542a34d18f49bd10494d808d63f0a9581b2 --- /dev/null +++ b/pool/shard000/JavaScript/0004636_accounts.js @@ -0,0 +1,183 @@ +// Account Model + +dc.model.Account = Backbone.Model.extend({ + + DISABLED : 0, + ADMINISTRATOR : 1, + CONTRIBUTOR : 2, + REVIEWER : 3, + FREELANCER : 4, + + ROLE_NAMES : ['disabled', 'administrator', 'contributor', 'reviewer', 'freelancer'], // NB: Indexed by role number. + + GRAVATAR_BASE : location.protocol + (location.protocol == 'https:' ? '//secure.' : '//www.') + 'gravatar.com/avatar/', + + DEFAULT_AVATAR : location.protocol + '//' + location.host + '/images/embed/icons/user_blue_32.png', + + defaults : { first_name : '', last_name : '', email : '', role : 2 }, + + initialize: function(options) { + this.organizations = new dc.model.OrganizationSet(); + if (this.get('organizations')) { this.organizations.reset(this.get('organizations')); } + }, + + constructor : function(attrs, options) { + Backbone.Model.call(this, attrs, options); + this.organizations = new dc.model.OrganizationSet(); + }, + + current_organization: function(){ + return this.organization(); + }, + + organization : function() { + return this.organizations.first(); + }, + + addOrganization: function( organization_data ){ + var organization = new dc.model.Organization( organization_data ); + this.organizations.add( organization ); + Organizations.add( organization ); + return organization; + }, + + openDocuments : function(options) { + options || (options = {}); + var suffix = options.published ? ' filter: published' : ''; + dc.app.searcher.search('account: ' + this.get('slug') + suffix); + }, + + openOrganizationDocuments : function() { + dc.app.searcher.search('group: ' + dc.account.organization().get('slug')); + }, + + allowedToEdit: function(model) { + return this.ownsOrOrganization(model) || this.collaborates(model); + }, + + ownsOrOrganization: function(model) { + return (model.get('account_id') == this.id) || + (model.get('organization_id') == this.get('organization_id') && + (this.isAdmin() || this.isContributor()) && + _.contains([ + dc.access.PUBLIC, dc.access.EXCLUSIVE, dc.access.ORGANIZATION, + 'public', 'exclusive', 'organization' + ], model.get('access'))); + }, + + collaborates: function(model) { + var docId = model.get('document_id') || model.id; + var projectIds = model.get('project_ids'); + + for (var i = 0, l = Projects.length; i < l; i++) { + var project = Projects.models[i]; + if (_.contains(projectIds, project.get('id')) && !project.get('hidden')) { + for (var j = 0, k = project.collaborators.length; j < k; j++) { + var collab = project.collaborators.models[j]; + if (collab.ownsOrOrganization(model)) return true; + } + } + } + + return false; + }, + + fullName : function(nonbreaking) { + var name = this.get('first_name') + ' ' + this.get('last_name'); + return nonbreaking ? name.replace(/\s/g, ' ') : name; + }, + + documentsTitle : function() { + return dc.inflector.possessivize(this.fullName()) + ' Documents'; + }, + + isAdmin : function() { + return this.attributes.role == this.ADMINISTRATOR; + }, + + isContributor : function() { + return this.attributes.role == this.CONTRIBUTOR; + }, + + isReviewer : function() { + return this.attributes.role == this.REVIEWER; + }, + + isReal : function() { + var role = this.attributes.role; + return role == this.ADMINISTRATOR || role == this.CONTRIBUTOR || role == this.FREELANCER; + }, + + isPending : function() { + return !!this.get('pending'); + }, + + searchUrl : function() { + return "/#search/" + encodeURIComponent("account: " + this.get('slug')); + }, + + gravatarUrl : function(size) { + var hash = this.get('hashed_email'); + var fallback = encodeURIComponent(this.DEFAULT_AVATAR); + return this.GRAVATAR_BASE + hash + '.jpg?s=' + size + '&d=' + fallback; + }, + + resendWelcomeEmail: function(options) { + var url = '/accounts/' + this.id + '/resend_welcome'; + $.ajax(_.extend(options || {}, {type : 'POST', dataType : 'json', url : url})); + } + +}); + +// Account Set +dc.model.AccountSet = Backbone.Collection.extend({ + + model : dc.model.Account, + url : '/accounts', + + comparator : function(account) { + return (account.get('last_name') || '').toLowerCase() + ' ' + (account.get('first_name') || '').toLowerCase(); + }, + + getBySlug : function(slug) { + return this.detect(function(account) { + return account.get('slug') === slug; + }); + }, + + getByEmail: function(email) { + return this.detect(function(account){ + return account.get('email') === email; + }); + }, + + getValidByEmail: function(email) { + return this.detect(function(account){ + return !account.invalid && account.get('email') === email; + }); + }, + + // Fetch the account of the logged-in journalist. + current : function() { + if (!dc.account) return null; + return this.get(dc.account.id); + }, + + // All accounts other than yours. + others : function() { + return this.filter(function(account) { + return account.id !== dc.account.id; + }); + }, + + // If the contributor has logged-out of the workspace in a different tab, + // force the logout here. + forceLogout : function() { + dc.ui.Dialog.alert('You are no longer logged in to DocumentCloud.', {onClose : function() { + window.location = '/logout'; + }}); + } + +}); + +window.Accounts = new dc.model.AccountSet(); diff --git a/pool/shard000/JavaScript/0004637_WsEasyRtcAdapter.js b/pool/shard000/JavaScript/0004637_WsEasyRtcAdapter.js new file mode 100644 index 0000000000000000000000000000000000000000..c4bfdd9ca20a5a16d329780d1b727eb0c8614c7e --- /dev/null +++ b/pool/shard000/JavaScript/0004637_WsEasyRtcAdapter.js @@ -0,0 +1,148 @@ +/* global NAF */ +const NoOpAdapter = require('./NoOpAdapter'); + +class WsEasyRtcInterface extends NoOpAdapter { + + constructor(easyrtc) { + super(); + + this.easyrtc = easyrtc || window.easyrtc; + this.app = 'default'; + this.room = 'default'; + + this.connectedClients = []; + + this.serverTimeRequests = 0; + this.timeOffsets = []; + this.avgTimeOffset = 0; + } + + setServerUrl(url) { + this.serverUrl = url; + this.easyrtc.setSocketUrl(url); + } + + setApp(appName) { + this.app = appName; + } + + setRoom(roomName) { + this.room = roomName; + this.easyrtc.joinRoom(roomName, null); + } + + setWebRtcOptions(options) { + // No webrtc support + } + + setServerConnectListeners(successListener, failureListener) { + this.connectSuccess = successListener; + this.connectFailure = failureListener; + } + + setRoomOccupantListener(occupantListener){ + this.easyrtc.setRoomOccupantListener(function(roomName, occupants, primary) { + occupantListener(occupants); + }); + } + + setDataChannelListeners(openListener, closedListener, messageListener) { + this.openListener = openListener; + this.closedListener = closedListener; + this.easyrtc.setPeerListener(messageListener); + } + + updateTimeOffset() { + const clientSentTime = Date.now() + this.avgTimeOffset; + + return fetch(document.location.href, { method: "HEAD", cache: "no-cache" }) + .then(res => { + var precision = 1000; + var serverReceivedTime = new Date(res.headers.get("Date")).getTime() + (precision / 2); + var clientReceivedTime = Date.now(); + var serverTime = serverReceivedTime + ((clientReceivedTime - clientSentTime) / 2); + var timeOffset = serverTime - clientReceivedTime; + + this.serverTimeRequests++; + + if (this.serverTimeRequests <= 10) { + this.timeOffsets.push(timeOffset); + } else { + this.timeOffsets[this.serverTimeRequests % 10] = timeOffset; + } + + this.avgTimeOffset = this.timeOffsets.reduce((acc, offset) => acc += offset, 0) / this.timeOffsets.length; + + if (this.serverTimeRequests > 10) { + setTimeout(() => this.updateTimeOffset(), 5 * 60 * 1000); // Sync clock every 5 minutes. + } else { + this.updateTimeOffset(); + } + }); + } + + connect() { + Promise.all([ + this.updateTimeOffset(), + new Promise((resolve, reject) => { + this.easyrtc.connect(this.app, resolve, reject); + }) + ]).then(([_, clientId]) => { + this.connectSuccess(clientId); + }).catch(this.connectFailure); + } + + shouldStartConnectionTo(clientId) { + return true; + } + + startStreamConnection(clientId) { + this.connectedClients.push(clientId); + this.openListener(clientId); + } + + closeStreamConnection(clientId) { + var index = this.connectedClients.indexOf(clientId); + if (index > -1) { + this.connectedClients.splice(index, 1); + } + this.closedListener(clientId); + } + + sendData(clientId, dataType, data) { + this.easyrtc.sendDataWS(clientId, dataType, data); + } + + sendDataGuaranteed(clientId, dataType, data) { + this.sendData(clientId, dataType, data); + } + + broadcastData(dataType, data) { + var destination = {targetRoom: this.room}; + this.easyrtc.sendDataWS(destination, dataType, data); + } + + broadcastDataGuaranteed(dataType, data) { + this.broadcastData(dataType, data); + } + + getConnectStatus(clientId) { + var connected = this.connectedClients.indexOf(clientId) != -1; + + if (connected) { + return NAF.adapters.IS_CONNECTED; + } else { + return NAF.adapters.NOT_CONNECTED; + } + } + + getServerTime() { + return Date.now() + this.avgTimeOffset; + } + + disconnect() { + this.easyrtc.disconnect(); + } +} + +module.exports = WsEasyRtcInterface; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004638_scaffoldTenantUsersView.js b/pool/shard000/JavaScript/0004638_scaffoldTenantUsersView.js new file mode 100644 index 0000000000000000000000000000000000000000..4a7555b1f2ad770fb4df99a31bba3a7e9f291cf9 --- /dev/null +++ b/pool/shard000/JavaScript/0004638_scaffoldTenantUsersView.js @@ -0,0 +1,63 @@ +// LICENCE https://github.com/adaptlearning/adapt_authoring/blob/master/LICENSE +define(function(require) { + + var Backbone = require('backbone'); + var BackboneForms = require('backbone-forms'); + var Origin = require('core/origin'); + var Helpers = require('core/helpers'); + var UserCollection = require('modules/userManagement/collections/userCollection'); + + var ScaffoldTenantUsersView = Backbone.Form.editors.Select.extend({ + + initialize: function(options) { + options.schema.options = new UserCollection(); + Backbone.Form.editors.Select.prototype.initialize.call(this, options); + }, + + /** + * Sets the options that populate the +* +* Optionally, you can use a jQuery selector to specify a field that can +* be updated with the element id whenever you find a matching value +* +* Example: +* +*/ + +$(document).ready(function(){ + $('input[data-autocomplete]').railsAutocomplete(); +}); + +(function(jQuery) +{ + var self = null; + jQuery.fn.railsAutocomplete = function() { + return this.live('focus',function() { + if (!this.railsAutoCompleter) { + this.railsAutoCompleter = new jQuery.railsAutocomplete(this); + } + }); + }; + + jQuery.railsAutocomplete = function (e) { + _e = e; + this.init(_e); + }; + + jQuery.railsAutocomplete.fn = jQuery.railsAutocomplete.prototype = { + railsAutocomplete: '0.0.1' + }; + + jQuery.railsAutocomplete.fn.extend = jQuery.railsAutocomplete.extend = jQuery.extend; + jQuery.railsAutocomplete.fn.extend({ + init: function(e) { + e.delimiter = $(e).attr('data-delimiter') || null; + function split( val ) { + return val.split( e.delimiter ); + } + function extractLast( term ) { + return split( term ).pop().replace(/^\s+/,""); + } + + $(e).autocomplete({ + source: function( request, response ) { + $.getJSON( $(e).attr('data-autocomplete'), { + term: extractLast( request.term ) + }, function() { + $(arguments[0]).each(function(i, el) { + var obj = {}; + obj[el.id] = el; + $(e).data(obj); + }); + response.apply(null, arguments); + }); + }, + search: function() { + // custom minLength + var term = extractLast( this.value ); + if ( term.length < 2 ) { + return false; + } + }, + focus: function() { + // prevent value inserted on focus + return false; + }, + select: function( event, ui ) { + var terms = split( this.value ); + // remove the current input + terms.pop(); + // add the selected item + terms.push( ui.item.value ); + // add placeholder to get the comma-and-space at the end + if (e.delimiter != null) { + terms.push( "" ); + this.value = terms.join( e.delimiter ); + } else { + this.value = terms.join(""); + if ($(this).attr('data-id-element')) { + $($(this).attr('data-id-element')).val(ui.item.id); + } + if ($(this).attr('data-update-elements')) { + var data = $(this).data(ui.item.id.toString()); + var update_elements = $.parseJSON($(this).attr("data-update-elements")); + for (var key in update_elements) { + $(update_elements[key]).val(data[key]); + } + } + } + var remember_string = this.value; + $(this).bind('keyup.clearId', function(){ + if($(this).val().trim() != remember_string.trim()){ + $($(this).attr('data-id-element')).val(""); + $(this).unbind('keyup.clearId'); + } + }); + $(this).trigger('railsAutocomplete.select', ui); + + return false; + } + }); + } + }); +})(jQuery); diff --git a/pool/shard000/JavaScript/0004641_directives.test.js b/pool/shard000/JavaScript/0004641_directives.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3a10999aaea8efe3a82084e61aaa8878a01b744e --- /dev/null +++ b/pool/shard000/JavaScript/0004641_directives.test.js @@ -0,0 +1,30 @@ +'use strict' + +const webpack = require('../helpers/compiler') + +describe('Options', () => { + describe('directives', () => { + test('{Array}', () => { + const config = { + loader: { + test: /\.html$/, + options: { + directives: [{ + name: '?php', + start: '<', + end: '>' + }] + } + } + } + + return webpack('options/directives/fixture.js', config) + .then((stats) => { + const [module] = stats.toJson().modules + + expect(module.source).toMatchSnapshot() + }) + .catch((err) => err) + }) + }) +}) diff --git a/pool/shard000/JavaScript/0004642_cache_offline.js b/pool/shard000/JavaScript/0004642_cache_offline.js new file mode 100644 index 0000000000000000000000000000000000000000..280a5e704001c008eb3b387c39135ad0bc392078 --- /dev/null +++ b/pool/shard000/JavaScript/0004642_cache_offline.js @@ -0,0 +1,42 @@ +var cacheStatusValues = []; +cacheStatusValues[0] = 'uncached'; +cacheStatusValues[1] = 'idle'; +cacheStatusValues[2] = 'checking'; +cacheStatusValues[3] = 'downloading'; +cacheStatusValues[4] = 'updateready'; +cacheStatusValues[5] = 'obsolete'; + +var cache = window.applicationCache; +cache.addEventListener('cached', logEvent, false); +cache.addEventListener('checking', logEvent, false); +cache.addEventListener('downloading', logEvent, false); +cache.addEventListener('error', logEvent, false); +cache.addEventListener('noupdate', logEvent, false); +cache.addEventListener('obsolete', logEvent, false); +cache.addEventListener('progress', logEvent, false); +cache.addEventListener('updateready', logEvent, false); + +function logEvent(e) { + var online, status, type, message; + online = (navigator.onLine) ? 'yes' : 'no'; + status = cacheStatusValues[cache.status]; + type = e.type; + message = 'online: ' + online; + message+= ', event: ' + type; + message+= ', status: ' + status; + if (type == 'error' && navigator.onLine) { + message+= ' (prolly a syntax error in manifest)'; + } + console.log(message); +} + +window.applicationCache.addEventListener( + 'updateready', + function(){ + window.applicationCache.swapCache(); + console.log('swap cache has been called'); + }, + false +); + +setInterval(function(){cache.update()}, 20000); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004645_string.js b/pool/shard000/JavaScript/0004645_string.js new file mode 100644 index 0000000000000000000000000000000000000000..aad64f4b692f753aa5e982db297492b304d438f9 --- /dev/null +++ b/pool/shard000/JavaScript/0004645_string.js @@ -0,0 +1,167 @@ + + +import {isString} from './is' +import {regex} from "./regex"; + +/** + * 字符串两端剪切 + * + * @param {string} string + * @param {string} fe f or e or fe + * @param {string} char + * + * @example + * ```javascript + * trim(' abc ')//=>'abc' + * trim(' abc ','f')//=>'abc ' + * trim(' abc ','e')//=>' abc' + * trim('**abc**','*')//=>'abc' + * ``` + * + * @returns {string} + */ +export function trim(string,fe='fe',char='\\s' ){ + if(isString(string)&&isString(char)&&isString(fe)){ + if(!/^(fe)|([fe])$/.test(fe)){char=fe;fe='fe';} + let FRegex=new RegExp(`^[${char}]*`),ERegex=new RegExp(`[${char}]*$`); + switch (fe){ + case 'f': + return string.replace(FRegex,''); + case 'e': + return string.replace(ERegex,''); + default: + return string.replace(FRegex,'').replace(ERegex,'') + } + } + throw new Error('Parameter type error') +} + +/** + * + * 字符转unicode + * @param {string} str 需要转码的字符串 + * @example + * ```javascript + * encodeToUnicode('啊abc123.') + * //=>"\u554a\u0061\u0062\u0063\u0031\u0032\u0033\u002e" + * + * ``` + * + * @returns {string} + */ + +export function encodeToUnicode(str) { + if(!isString(str)){ + throw new Error(`${str} is not string`) + } + let temp = "", rs = ""; + for (let i = 0, len = str.length; i < len; i++) { + temp = str.charCodeAt(i).toString(16); + rs += "\\u" + new Array(5 - temp.length).join("0") + temp; + } + return rs; +} + +/** + * + * unicode字符串解码 + * @param {string} str 需要解码的字符串 + * @example + * ```javascript + * decodeUnicode('\u554a\u0061\u0062\u0063\u0031\u0032\u0033\u002e') + * //=>"啊abc123." + * + * ``` + * + * @returns {string} + */ + + +export function decodeUnicode(str) { + if(!isString(str)){ + throw new Error(`${str} is not string`) + } + return str.replace(/(\\u)(\w{4}|\w{2})/gi, function ($0, $1, $2) { + return String.fromCharCode(parseInt($2, 16)); + }); +} + + +/** + * + * Capitalize the first letter + * @param {string} string + * @example + * ```javascript + * firstUpperCase('abc')//=>'Abc' + * + * + * ``` + * + * @returns {string} + */ +export function firstUpperCase (string){ + return string[0].toUpperCase()+string.slice(1) +} + +/** + * + * Lowercase first letter + * @param {string} string + * @example + * ```javascript + * firstLowerCase('Abc')//=>'abc' + * + * + * ``` + * + * @returns {string} + */ +export function firstLowerCase(string) { + return string[0].toLowerCase()+string.slice(1) +} + + +/** + * + * split number with unit + * @param {string} value + * @param {boolean} relative + * @example + * ```javascript + * splitUnit('123px')//=>{value:123,unit:'px'} + * splitUnit('123%')//=>{value:123,unit:'%'} + * splitUnit('+123%')//=>{value:123,unit:'%'} + * splitUnit('-123%')//=>{value:-123,unit:'%'} + * splitUnit('-=123%',true)//=>{value:'-=123',unit:'%'} + * splitUnit('+=123%',true)//=>{value:'+=123',unit:'%'} + * + * + * ``` + * + * @returns {object} + */ +export function splitUnit(value,relative=false) { + let v, unit = ''; + let reg; + if(relative){ + reg=regex.relativeNumberWithUnit + }else{ + reg=regex.numberWithUnit + } + + if (reg.test(value)) { + + let temp = RegExp.$1; + unit = RegExp.$2; + if (regex.number.test(temp)) { + v = Number(temp); + } else { + v = temp; + } + } + + return { + value:v, unit + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004647_server-info.service.js b/pool/shard000/JavaScript/0004647_server-info.service.js new file mode 100644 index 0000000000000000000000000000000000000000..29278f3766df3e295664ae86bef6e5c20ece4e5f --- /dev/null +++ b/pool/shard000/JavaScript/0004647_server-info.service.js @@ -0,0 +1,27 @@ +(function() { + 'use strict'; + + angular.module('app.services') + .factory('ServerInfo', ServerInfo); + + /** @ngInject */ + function ServerInfo($q) { + var factory = {}; + factory.data = {}; + factory.promise = $q(function(resolve) { + factory.set = function(data) { + factory.data = { + user: data.identity.name, + role: data.identity.role, + version: data.server_info.version + '.' + data.server_info.build, + server: data.server_info.appliance, + }; + resolve(factory.data); + + return data; + }; + }); + + return factory; + } +})(); diff --git a/pool/shard000/JavaScript/0004648_data.js b/pool/shard000/JavaScript/0004648_data.js new file mode 100644 index 0000000000000000000000000000000000000000..900fd7ac95ca3d428727a93fe9386a0c90b3994e --- /dev/null +++ b/pool/shard000/JavaScript/0004648_data.js @@ -0,0 +1,189 @@ +var mysql = require('mysql'); +var async = require('async'); +var dates = require("./dates"); + +var connectionOptions = { + host : process.env.DB_HOST, + user : process.env.DB_USER, + password : process.env.DB_PASSWORD, + database : process.env.DB_NAME, + port : process.env.DB_PORT +}; + +if (process.env.DB_SSL) { + // SSL is used for Amazon RDS, but not necessarily for local dev + connectionOptions.ssl = process.env.DB_SSL; +} + +// var pool = mysql.createPool(connectionOptions); + + + + +/* +* RESET THE DATABASE +* Allows the DB to be rebuilt from scratch +*/ +exports.resetDatabaseYesIreallyWantToDoThis = function resetDatabaseYesIreallyWantToDoThis(callback) { + + var connection = mysql.createConnection(connectionOptions); + connection.connect(function connectionAttempted (err) { + if (err) { + console.log(err); + } else { + async.parallel ([ + function truncateCounts (callback) { + connection.query('TRUNCATE counts;', + function queryComplete (err, result) { + if (err) console.log(err); + callback(null); + }); + }, + function truncateCountsLatest (callback) { + connection.query('TRUNCATE counts_latest;', + function queryComplete (err, result) { + if (err) console.log(err); + callback(null); + }); + } + ], + // parallel callback + function (err, results) { + if (err) console.log(err); + connection.end(); + callback(null); + }); + } + }); +}; + + + +/* +* QUERY +*/ +exports.getAggregateNumbers = function getAggregateNumbers (teamname, callback) { + + var connection = mysql.createConnection(connectionOptions); + connection.connect(function connectionAttempted (err) { + + if (err) { + console.log(err); + return callback(null, null); + } + else { + var query = 'SELECT DATE_FORMAT(date, "%Y-%m-%d") as wkcommencing, sum(total_active) as totalactive, sum(new) as new FROM counts'; + if (teamname) { + query = query + ' WHERE team = ' + connection.escape(teamname); + } + query = query + ' GROUP BY date ORDER BY date'; + connection.query(query, function queryComplete (err, result) { + if (err) { + console.log(err); + callback(null, null); + } + connection.end(); + callback(null, result); + }); + } + }); +}; + + +exports.getLatestNumbers = function getLatestNumbers (teamname, callback) { + + var connection = mysql.createConnection(connectionOptions); + connection.connect(function connectionAttempted (err) { + + if (err) { + console.log(err); + return callback(null, null); + } + else { + var latest = {}; + + async.parallel ([ + function getBuckets (callback) { + var query = 'SELECT bucket, DATE_FORMAT(date, "%Y-%m-%d") as last_updated, ' + + 'sum(total_active) as total_active, sum(new) as new ' + + 'FROM counts_latest'; + if (teamname) { + query = query + ' WHERE team = ' + connection.escape(teamname); + } + query = query + ' GROUP BY bucket ORDER BY bucket'; + connection.query(query, function queryComplete (err, result) { + if (err) { + console.log(err); + callback(null); + } + latest.buckets = result; + callback(null); + }); + }, + function getTotal (callback) { + var query = 'SELECT DATE_FORMAT(date, "%Y-%m-%d") as last_updated, ' + + 'sum(total_active) as total_active, sum(new) as new ' + + 'FROM counts_latest'; + if (teamname) { + query = query + ' WHERE team = ' + connection.escape(teamname); + } + connection.query(query, function queryComplete (err, result) { + if (err) { + console.log(err); + callback(null); + } + latest.total = result[0]; // only looking a single result + callback(null); + }); + } + ], + // parallel callback + function (err, results) { + if (err) console.log(err); + connection.end(); + callback(null, latest); + }); + } + }); +}; + + +/* +* SAVE +*/ +exports.saveItem = function saveItem(team, bucket, date, description, total_active, new_active, table_name, callback) { + + var connection = mysql.createConnection(connectionOptions); + connection.connect(function connectionAttempted (err) { + + if (err) { + console.error(err); + callback(err); + + } else { + + var entry = { + team : team, + bucket : bucket, + date : new Date(date), + description : description, + total_active : total_active, + new : new_active + }; + + // Using REPLACE INTO to avoid worrying about duplicate entries + // There is a unique key set across all team + bucket + date + description + connection.query('REPLACE INTO ' + table_name + ' SET ?', entry, function(err, result) { + if(err) { + console.error(err); + callback(err); + } else { + // console.log('saved activity'); + // console.log(activity); + } + connection.end(); + callback(null); + }); + } + }); +}; diff --git a/pool/shard000/JavaScript/0004649_cart.component.js b/pool/shard000/JavaScript/0004649_cart.component.js new file mode 100644 index 0000000000000000000000000000000000000000..728329efacf913ec003678512c4cf4a5186b264b --- /dev/null +++ b/pool/shard000/JavaScript/0004649_cart.component.js @@ -0,0 +1,122 @@ +import templateUrl from './cart.html'; +export const cartComponent = { + bindings: { + cartObj: '<' + }, + templateUrl, + controller: class cartComponent { + constructor($http){ + 'ngInject' + this.total = 0; + this.checkbox = []; + this.$http = $http; + } + + $oninit(){ + this.items = this.cartObj.data; + } + + $onChange(changes){ + if(changes.cartObj){ + this.items = Object.assign({}, this.cartObj.data) + } + } + + cb_change(e, title) { + var checkbox = e.target; + var action = checkbox.checked ? 'add' : 'remove'; + + this.cb_update(action, title); + } + + cb_update(action, title) { + if (action === 'add' && this.checkbox.indexOf(title) === -1) { + this.checkbox.push(title); + } + if (action === 'remove' && this.checkbox.indexOf(title) !== -1) { + this.checkbox.splice(this.checkbox.indexOf(title), 1); + } + } + + cb_delete(){ + for(let i = 0; i < this.cartObj.data.length; i++){ + if(this.checkbox[0] === this.cartObj.data[i].title){ + this.cartObj.data.splice(i, 1); + } + } + + + this.$http({ + method: 'DELETE', + url: '/cart/' + this.checkbox[0], + params: {'title': this.checkbox } + }); + + + } + + kakaopay(cb){ + var IMP = window.IMP; + this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + window.sessionStorage.getItem('accessToken'); + this.$http({ + url: '/getUserInfo', + method: 'GET' + }) + .success(function(userInfo){ + IMP.init('imp10130927'); + IMP.request_pay({ + pg : 'kakao', + pay_method : 'card', + merchant_uid : 'merchant_' + new Date().getTime(), + name : cb.toString(), + amount : cb.length, + buyer_email : userInfo.email, + buyer_name : userInfo.name, + buyer_addr : '뮤직트랙 사이트에서 음원 구입', + buyer_postcode : '123-456' + }, function(rsp) { + if ( rsp.success ) { + + jQuery.ajax({ + url: "/payments/complete", //cross-domain error가 발생하지 않도록 동일한 도메인으로 전송 + type: 'POST', + dataType: 'json', + data: { + imp_uid : rsp.imp_uid + //기타 필요한 데이터가 있으면 추가 전달 + } + }).done(function(data) { + //[2] 서버에서 REST API로 결제정보확인 및 서비스루틴이 정상적인 경우 + if ( everythings_fine ) { + var msg = '결제가 완료되었습니다.'; + msg += '\n고유ID : ' + rsp.imp_uid; + msg += '\n상점 거래ID : ' + rsp.merchant_uid; + msg += '\결제 금액 : ' + rsp.paid_amount; + msg += '카드 승인번호 : ' + rsp.apply_num; + + alert(msg); + } else { + //[3] 아직 제대로 결제가 되지 않았습니다. + //[4] 결제된 금액이 요청한 금액과 달라 결제를 자동취소처리하였습니다. + } + }); + + } else { + var msg = '결제에 실패하였습니다. 왜 일까요?'; + msg += '\n에러내용 : ' + rsp.error_msg.split('.')[0] + '.\n' + rsp.error_msg.split('. ')[1]; + } + + alert(msg); + }); + }) + .error(function(){ + + }); + + }; + + + + + } +} diff --git a/pool/shard000/JavaScript/0004650_Scraper.js b/pool/shard000/JavaScript/0004650_Scraper.js new file mode 100644 index 0000000000000000000000000000000000000000..54e661cb9fab23501cac000977a63f3f46cdde9d --- /dev/null +++ b/pool/shard000/JavaScript/0004650_Scraper.js @@ -0,0 +1,75 @@ +var request = require('request') + cheerio = require('cheerio') + _ = require('underscore') + exec = require('child_process').exec + fs = require('fs'); + url = process.argv[2] || "https://medium.com/" + depth = process.argv[3] || 2 + +function setParams (callback){ + var main = url, + method = "GET", + pool = 5; + callback(null, main, method, pool); +}; + +function makeRequest (url, method, pool, callback){ + request ({'url':url, 'method':method, 'pool.maxSockets': pool}, function(err, resp, body){ + if(body){ + $ = cheerio.load(body); + links = $('a'); + toSave = ""; + data = []; + $(links).each(function(i, link){ + var uri = $(link).attr('href'); + if(uri && uri != url && (uri.startsWith('https://') || uri.startsWith('http://') || uri.startsWith('//'))){ + data.push(uri); + } + }); + data = _.uniq(data); + toSave = data.join('\r\n'); + if (data[2]) + callback(null, data, toSave); + else + callback("Not Sufficient links found"); + } + else + callback(null, [], toSave); + }); +}; + +function saveData (list, data, callback){ + fs.appendFile('data/temp-sync.csv', data, function(err){ + if (err) + callback(err); + callback(err, list); + }); +}; + +exec("rm -rf data/temp-sync.csv"); +setParams(function(err, web, meth, conn){ + makeRequest(web,meth,conn, function(err, list, links){ + if(links){ + saveData(list, links, function(err, res){ + console.log("All HyperLinks at LEVEL 1 saved Sucessfully"); + for (var i=2; i<=depth; i++){ + if (i===2) + nextSet = _.uniq(res); + else + nextSet = _.uniq(finalRes) + finalRes = [] + nextSet.forEach(function(uri){ + makeRequest(uri,meth,conn, function(err, arr, data){ + if(data){ + saveData(arr, data, function(err, res){ + finalRes = finalRes.concat(res); + }); + } + }) + }); + console.log("All HyperLinks at LEVEL " + i.toString() + " saved Sucessfully"); + } + }); + } + }); +}); diff --git a/pool/shard000/JavaScript/0004651_chipsDirective.js b/pool/shard000/JavaScript/0004651_chipsDirective.js new file mode 100644 index 0000000000000000000000000000000000000000..dc854fc9b7f297e383e2bc564f186de810dd8132 --- /dev/null +++ b/pool/shard000/JavaScript/0004651_chipsDirective.js @@ -0,0 +1,252 @@ +(function () { + 'use strict'; + angular + .module('material.components.chips') + .directive('mdChips', MdChips); + + /** + * @ngdoc directive + * @name mdChips + * @module material.components.chips + * + * @description + * `` is an input component for building lists of strings or objects. The list items are + * displayed as 'chips'. This component can make use of an `` element or an + * `` element. + * + * Custom `` template + * A custom template may be provided to render the content of each chip. This is achieved by + * specifying an `` element as a child of ``. Note: Any attributes on + * `` will be dropped as only the innerHTML is used for the chip template. The + * variables `$chip` and `$index` are available in the scope of ``, representing + * the chip object and its index in the list of chips, respectively. + * To override the chip delete control, include an element (ideally a button) with the attribute + * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element + * is also placed as a sibling to the chip content (on which there are also click listeners) to + * avoid a nested ng-click situation. + * + *

      Pending Features

      + *
        + * + *
          Style + *
        • Colours for hover, press states (ripple?).
        • + *
        + * + *
          List Manipulation + *
        • delete item via DEL or backspace keys when selected
        • + *
        + * + *
          Validation + *
        • de-dupe values (or support duplicates, but fix the ng-repeat duplicate key issue)
        • + *
        • allow a validation callback
        • + *
        • hilighting style for invalid chips
        • + *
        + * + *
          Item mutation + *
        • Support ` + * ` template, show/hide the edit element on tap/click? double tap/double + * click? + *
        • + *
        + * + *
          Truncation and Disambiguation (?) + *
        • Truncate chip text where possible, but do not truncate entries such that two are + * indistinguishable.
        • + *
        + * + *
          Drag and Drop + *
        • Drag and drop chips between related `` elements. + *
        • + *
        + *
      + * + * + * Warning: This component is a WORK IN PROGRESS. If you use it now, + * it will probably break on you in the future. + * + * + * @param {string=|object=} ng-model A model to bind the list of items to + * @param {string=} placeholder Placeholder text that will be forwarded to the input. + * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input, + * displayed when there is at least on item in the list + * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding + * the input and delete buttons + * @param {expression} md-on-append An expression expected to convert the input string into an + * object when adding a chip. + * @param {string=} delete-hint A string read by screen readers instructing users that pressing + * the delete key will remove the chip. + * @param {string=} delete-button-label A label for the delete button. Also hidden and read by + * screen readers. + * + * @usage + * + * + * + * + * + */ + + + var MD_CHIPS_TEMPLATE = '\ + \ + \ +
      \ +
      \ +
      \ +
      \ + \ + '; + + var CHIP_INPUT_TEMPLATE = '\ + '; + + var CHIP_DEFAULT_TEMPLATE = '\ + {{$chip}}'; + + var CHIP_REMOVE_TEMPLATE = '\ + \ + \ + \ + {{$mdChipsCtrl.deleteButtonLabel}}\ + \ + '; + + /** + * MDChips Directive Definition + */ + function MdChips ($mdTheming, $compile, $timeout) { + return { + template: function(element, attrs) { + // Clone the element into an attribute. By prepending the attribute + // name with '$', Angular won't write it into the DOM. The cloned + // element propagates to the link function via the attrs argument, + // where various contained-elements can be consumed. + attrs['$mdUserTemplate'] = element.clone(); + attrs['tabindex'] = '-1'; + return MD_CHIPS_TEMPLATE; + }, + require: ['mdChips'], + restrict: 'E', + controller: 'MdChipsCtrl', + controllerAs: '$mdChipsCtrl', + bindToController: true, + compile: compile, + scope: { + readonly: '=readonly', + placeholder: '@', + secondaryPlaceholder: '@', + mdOnAppend: '&', + deleteHint: '@', + deleteButtonLabel: '@' + } + }; + + /** + * Builds the final template for `md-chips` and returns the postLink function. + * + * Building the template involves 3 key components: + * static chips + * chip template + * input control + * + * If no `ng-model` is provided, only the static chip work needs to be done. + * + * If no user-passed `md-chip-template` exists, the default template is used. This resulting + * template is appended to the chip content element. + * + * The remove button may be overridden by passing an element with an md-chip-remove attribute. + * + * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for + * transclusion later. The transclusion happens in `postLink` as the parent scope is required. + * If no user input is provided, a default one is appended to the input container node in the + * template. + * + * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for + * transclusion in the `postLink` function. + * + * + * @param element + * @param attr + * @returns {Function} + */ + function compile(element, attr) { + // Grab the user template from attr and reset the attribute to null. + var userTemplate = attr['$mdUserTemplate']; + attr['$mdUserTemplate'] = null; + + // Set the chip remove, chip contents and chip input templates. The link function will put + // them on the scope for transclusion later. + var chipRemoveTemplate = getTemplateByQuery('[md-chip-remove]') || CHIP_REMOVE_TEMPLATE, + chipContentsTemplate = getTemplateByQuery('md-chip-template') || CHIP_DEFAULT_TEMPLATE, + chipInputTemplate = getTemplateByQuery('md-autocomplete') + || getTemplateByQuery('input') + || CHIP_INPUT_TEMPLATE, + staticChips = userTemplate.find('md-chip'); + + function getTemplateByQuery (query) { + if (!attr.ngModel) return; + var element = userTemplate[0].querySelector(query); + return element && element.outerHTML; + } + + /** + * Configures controller and transcludes. + */ + return function postLink(scope, element, attrs, controllers) { + $mdTheming(element); + element.attr('tabindex', '-1'); + var mdChipsCtrl = controllers[0]; + mdChipsCtrl.chipContentsTemplate = chipContentsTemplate; + mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate; + mdChipsCtrl.chipInputTemplate = chipInputTemplate; + + if (attr.ngModel) { + mdChipsCtrl.configureNgModel(element.controller('ngModel')); + + // If an `md-on-append` attribute was set, tell the controller to use the expression + // when appending chips. + if (attrs.mdOnAppend) mdChipsCtrl.useMdOnAppendExpression(); + + // The md-autocomplete and input elements won't be compiled until after this directive + // is complete (due to their nested nature). Wait a tick before looking for them to + // configure the controller. + if (chipInputTemplate != CHIP_INPUT_TEMPLATE) { + $timeout(function() { + if (chipInputTemplate.indexOf(' 0) { + var compiledStaticChips = $compile(staticChips)(scope.$parent); + $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); }); + } + }; + } + } +})(); diff --git a/pool/shard000/JavaScript/0004654_home.js b/pool/shard000/JavaScript/0004654_home.js new file mode 100644 index 0000000000000000000000000000000000000000..6eec2a7eb980286aac7610c031b5afbba3ba44f3 --- /dev/null +++ b/pool/shard000/JavaScript/0004654_home.js @@ -0,0 +1,95 @@ +'use strict'; + +angular.module('myApp.home', ['ngRoute','firebase']) + +// Declared route +.config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/home', { + templateUrl: 'home/home.html', + controller: 'HomeCtrl' + }); +}]) + +// Home controller +.controller('HomeCtrl', ['$scope','$location','$firebaseAuth','CommonProp',function($scope,$location,$firebaseAuth,CommonProp) { + + var firebaseObj = new Firebase("https://intense-fire-5714.firebaseio.com"); + var loginObj = $firebaseAuth(firebaseObj); + + var login = {}; + + $scope.login = login; + + $scope.SignIn = function(user) + { + event.preventDefault(); // To prevent form refresh + var username = user.email; + var password = user.password; + login.loading = true; + console.log("email" + user.email) + loginObj.$authWithPassword ({ + email: username, + password: password + }) + .then(function(user) { + // Success callback + console.log('Authentication successful'); + CommonProp.setUser(user.password.email); + login.loading = false; + $location.path('/main'); + }, function(error) { + // Failure callback + console.log('Authentication failure'); + login.loading = false; + }); + + + // Auth Logic will be here + } +}]) + +.service('CommonProp',['$location','$firebaseAuth',function($location,$firebaseAuth) { + var user = ''; + var firebaseObj = new Firebase("https://intense-fire-5714.firebaseio.com"); + var loginObj = $firebaseAuth(firebaseObj); + + return { + getUser: function() { + if(user == ''){ + user = localStorage.getItem('userEmail'); + } + return user; + }, + setUser: function(value) { + localStorage.setItem("userEmail", value); + user = value; + }, + logoutUser:function(){ + console.log("log out"); + loginObj.$unauth(); + user=''; + localStorage.removeItem('userEmail'); + $location.path('/home'); + } + }; +}]) + +.directive('laddaLoading', [ + function() { + return { + link: function(scope, element, attrs) { + var Ladda = window.Ladda; + var ladda = Ladda.create(element[0]); + // Watching login.loading for change + scope.$watch(attrs.laddaLoading, function(newVal, oldVal) { + // Based on the value start and stop the indicator + if (newVal) { + ladda.start(); + } else { + ladda.stop(); + } + }); + } + }; + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004655_sha-validator.js b/pool/shard000/JavaScript/0004655_sha-validator.js new file mode 100644 index 0000000000000000000000000000000000000000..0ee38c09e513f21f0939be783ae6f5500bd25333 --- /dev/null +++ b/pool/shard000/JavaScript/0004655_sha-validator.js @@ -0,0 +1,122 @@ +var _ = require('lodash') + , async = require('async') + , utils = require('./general') + , log = require('./logger').logger + ; + +function coloredStatus(status) { + if (status == 'success') { + return status.green; + } else if (status == 'pending') { + return status.yellow; + } else { + return status.red; + } +} + +function postNewNupicStatus(statusContext, sha, statusDetails, repoClient) { + log.info('Posting new NuPIC Status (' + + coloredStatus(statusDetails.state) + ') for ' + sha + ' to GitHub'); + var payload = { + owner: repoClient.org + , repo: repoClient.repo + , sha: sha + , state: statusDetails.state + , context: statusContext + , description: statusDetails.description + , target_url: statusDetails.target_url + }; + repoClient.github.repos.createStatus(payload); +} + +function triggerBuildsOnAllOpenPullRequests(repoClient, callback) { + repoClient.getAllOpenPullRequests(function(err, prs) { + var triggers = []; + if (err) { + return callback(err); + } + log.debug('Found ' + prs.length + ' open pull requests...'); + _.each(prs, function(pr) { + triggers.push(function(localCallback) { + repoClient.triggerTravisForPullRequest(pr.number, localCallback); + // AppVeyor only gives us one resource and queues the rest, which + // takes a really long time. We decided to turn off automatic PR + // rebuilds for AV because of this. Any bugs that slip through + // will still be caught on master branch builds. + // repoClient.triggerAppVeyorForPullRequest(pr.number, localCallback); + }); + }); + async.parallel(triggers, callback); + }); +} + +function performCompleteValidation(sha + , githubUser + , repoClient + , validators + , postStatus + , cb + ) { + var callback = cb + , searchString = sha + '+state:open' + ; + // default dummy callback for simpler code later + if (! cb) { + callback = function() {}; + } + + repoClient.searchIssues(searchString, function(err, payload) { + var prs; + var validationFunctions = {}; + if (err) { + return callback(err); + } + prs = payload.data; + if (prs.total_count == 0) { + // No PR for this commit, so no point in validating. + log.warn('Skipping validation of ' + sha + ' because it has no PR.'); + return callback(); + } + + // There may be more than one PR associated with a commit SHA if someone + // created one PR based on the changes presented in another PR. In this + // case we will validate them all. + _.each(prs.items, function(pr) { + log.info('Validating %s at %s', pr.html_url, sha); + _.each(validators, function(validator) { + validationFunctions[pr.number + '-' + validator.name] = + function(asyncCallback) { + log.debug(sha + ': Running commit validator: ' + + validator.name); + validator.validate( + sha + , githubUser + , repoClient + , function(err, validationResult) { + if (!err && postStatus) { + postNewNupicStatus( + validator.name, sha, + validationResult, repoClient + ); + } + asyncCallback(err, validationResult); + } + ); + }; + }); + }); + + async.parallel(validationFunctions, function(err, results) { + callback(null, sha, results, repoClient); + }); + + }); + + +} + +module.exports = { + performCompleteValidation: performCompleteValidation, + triggerBuildsOnAllOpenPullRequests: triggerBuildsOnAllOpenPullRequests, + postNewNupicStatus: postNewNupicStatus // for testing +}; diff --git a/pool/shard000/JavaScript/0004657_helpers.js b/pool/shard000/JavaScript/0004657_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..ff851291f119878bd2fcf27b49b79d064e0a8d95 --- /dev/null +++ b/pool/shard000/JavaScript/0004657_helpers.js @@ -0,0 +1,54 @@ +import Graph from './graph' +import DirectedGraph from './directedGraph' + +class GraphHelpers { + static copy (graph) { + let result = new Graph(graph.size) + + for (let i = 0; i < graph.size; i += 1) { + graph.adjacencyList[i].forEach((edge) => { + if (!result.isExistEdge(i, edge.vertex)) { + result.addEdge(i, edge.vertex, edge.weight) + } + }) + } + + return result + } + + static getDirectedGraph (graph, start) { + start = start || 0 + + let result = new DirectedGraph() + GraphHelpers.addEdges(graph, result, start) + + return result + } + + static addEdges (graph, result, start) { + result.addNode(start) + graph.adjacencyList[start].forEach((edge) => { + if (!result.isExistEdge(start, edge.vertex) && !result.isExistEdge(edge.vertex, start)) { + result.addNode(edge.vertex) + result.addEdge(start, edge.vertex, edge.weight) + + GraphHelpers.addEdges(graph, result, edge.vertex) + } + }) + } + + static isEqual (tree1, tree2) { + for (let i = 0; i < tree1.adjacencyList.length; i += 1) { + if (tree1.adjacencyList[i] instanceof Array) { + for (let j = 0; j < tree1.adjacencyList[i].length; j += 1) { + if (!tree2.isExistEdge(i, tree1.adjacencyList[i][j].vertex)) { + return false + } + } + } + } + return true + } +} + +export default GraphHelpers diff --git a/pool/shard000/JavaScript/0004659_bootstrap-datetimepicker.es-ES.js b/pool/shard000/JavaScript/0004659_bootstrap-datetimepicker.es-ES.js new file mode 100644 index 0000000000000000000000000000000000000000..2aa41d8f67de92525eb1872d24dab9cd2a30ea70 --- /dev/null +++ b/pool/shard000/JavaScript/0004659_bootstrap-datetimepicker.es-ES.js @@ -0,0 +1,19 @@ +/** + * Spanish translation for bootstrap-datetimepicker + * Bruno Bonamin + */ +(function ($) { + $.fn.fdatetimepicker.dates['es-ES'] = { + days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"], + daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"], + daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"], + months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], + monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"], + today: "Hoy", + suffix: [], + meridiem: [], + format: "dd/mm/yyyy hh:ii", + formatDate: "dd/mm/yyyy" + }; + $.fn.fdatetimepicker.defaults = $.fn.fdatetimepicker.dates['es-ES']; +}(jQuery)); diff --git a/pool/shard000/JavaScript/0004662_test-net-listen-exclusive-random-ports.js b/pool/shard000/JavaScript/0004662_test-net-listen-exclusive-random-ports.js new file mode 100644 index 0000000000000000000000000000000000000000..9ca023cfa4088dd6712669b0506c0982f66ded64 --- /dev/null +++ b/pool/shard000/JavaScript/0004662_test-net-listen-exclusive-random-ports.js @@ -0,0 +1,35 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); + +if (cluster.isMaster) { + const worker1 = cluster.fork(); + + worker1.on('message', function(port1) { + assert.strictEqual(port1, port1 | 0, 'first worker could not listen'); + const worker2 = cluster.fork(); + + worker2.on('message', function(port2) { + assert.strictEqual(port2, port2 | 0, 'second worker could not listen'); + assert.notStrictEqual(port1, port2, 'ports should not be equal'); + worker1.kill(); + worker2.kill(); + }); + }); +} else { + const server = net.createServer(common.noop); + + server.on('error', function(err) { + process.send(err.code); + }); + + server.listen({ + port: 0, + exclusive: true + }, function() { + process.send(server.address().port); + }); +} diff --git a/pool/shard000/JavaScript/0004667_Homepage.js b/pool/shard000/JavaScript/0004667_Homepage.js new file mode 100644 index 0000000000000000000000000000000000000000..0e9a47d6d09005bbb2598162395e79563a28edf7 --- /dev/null +++ b/pool/shard000/JavaScript/0004667_Homepage.js @@ -0,0 +1,117 @@ +'use strict'; + +var React = require('react-native'); +var _ = require('underscore'); + +var { + Platform, + StyleSheet, + Text, + TextInput, + View +} = React; + +var Artists = require('./Artists'); +var Button = require('apsl-react-native-button'); +var dismissKeyboard = require('dismissKeyboard'); + +var Homepage = React.createClass({ + getInitialState: function() { + return { + artistName: '' + }; + }, + searchArtist: function() { + var artistName = this.state.artistName; + if (Platform.OS === 'ios') { + if (!_.isEmpty(artistName)) { + this.props.navigator.push({ + title: 'Artists', + component: Artists, + passProps: { query: artistName } + }); + } + } else { + dismissKeyboard(); + this.props.navigator.push({ + title: 'Artists', + name: 'artists', + query: artistName, + }); + } + }, + render: function() { + return ( + + + Search for an artist you want to listen to: + + this.setState({ artistName })}/> + + + ); + } +}); + +/*TODO: + Export styles to a separate file + let {StyleSheet} = React; + + var home = StyleSheet.create({}); + var search = StyleSheet.create({}); + + let Styles = { + home: home, + search: search + } + module.exports = Styles; +*/ +const styles = StyleSheet.create({ + button: { + alignSelf: 'center', + backgroundColor: '#0C8B4E', + borderColor: '#0C8B4E', + marginTop: 10, + width: 100 + }, + buttonText: { + color: '#F0F2F2', + fontSize: 16 + }, + container: { + backgroundColor: '#444', + flex: 1, + justifyContent: 'center', + alignItems: 'center' + }, + instructions: { + color: '#F2F2F2', + fontSize: 18, + textAlign: 'center', + margin: 10, + }, + textInput: { + alignSelf: 'center', + backgroundColor: '#F2F2F2', + borderColor: '#F0F2F2', + borderRadius: 5, + borderWidth: 1, + height: 40, + width: 250 + }, + title: { + fontSize: 20, + textAlign: 'center', + margin: 10, + } +}); + +module.exports = Homepage; diff --git a/pool/shard000/JavaScript/0004668_observer.js b/pool/shard000/JavaScript/0004668_observer.js new file mode 100644 index 0000000000000000000000000000000000000000..77201e93334f4f93335ca5768d540f140aba1197 --- /dev/null +++ b/pool/shard000/JavaScript/0004668_observer.js @@ -0,0 +1,93 @@ +'use strict'; + +/** + * Observer wrapper (choosing wisely between MutationObserver and MutationEvents) + * @name Observer + * @package Kontext + */ +function Observer() { // eslint-disable-line no-unused-vars + var observer = this, + mutation; + + /** + */ + function init() { + var mutationObserver = global.MutationObserver || global.webkitMutationObserver || false; + + // if-included istanbul ignore next + if (mutationObserver) { + mutation = { + observer: mutationObserver, + config: { + characterData: true, + characterDataOldValue: true + } + }; + } + } + + /** + * Cast a value into the same type as the origin, enabling coercion + * @name cast + * @access internal + * @param mixed origin + * @param mixed value + * @return mixed casted value + */ + function cast(origin, value) { + var type = typeof origin; + + switch (type) { + case 'boolean': + return !!value; + + case 'number': + return +value; + } + + return value; + } + + /** + * Persist a value to the model + * @name persist + * @access internal + * @param function delegate + * @param mixed value + * @return void + */ + function persist(delegation, value) { + var current = delegation(), + casted = cast(current, value); + + if (casted !== current) { + delegation(casted); + } + } + + /** + * Observe the DOMElement(s) bound to the model key and persist changes from outside Kontext + * @name monitor + * @access public + * @param DOMText text + * @param function delegate + * @return void + */ + observer.monitor = function(text, delegation) { + // if-included istanbul ignore next + if (mutation) { + new mutation.observer(function(mutations) { // eslint-disable-line new-cap + mutations.forEach(function(mutated) { + persist(delegation, mutated.target.nodeValue); + }); + }).observe(text, mutation.config); + } + else if (text.addEventListener) { + text.addEventListener('DOMCharacterDataModified', function(event) { + persist(delegation, event.newValue); + }); + } + }; + + init(); +} diff --git a/pool/shard000/JavaScript/0004673_crypto.js b/pool/shard000/JavaScript/0004673_crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..f588f0e63ae02e71cca50ea1b5781936607adbb1 --- /dev/null +++ b/pool/shard000/JavaScript/0004673_crypto.js @@ -0,0 +1,230 @@ +/** + * @file Crypto-functions for WebIDP + * @copyright 2013-2014 BFH - Bern University of Applied Sciences -- {@link http://bfh.ch} + * @license MIT, see included file LICENSE or {@link http://opensource.org/licenses/MIT} + * @author Pascal Mainini + * @version 0.0.6 + * + * This module provides helper functions for the cryptographical operations needed. + */ + +/*jshint node:true, bitwise:true, curly:true, immed:true, indent:2, latedef:true, newcap:true, noarg: true, noempty:true, nonew:true, quotmark:single, undef:true, unused: true, trailing:true, white:false */ + +/*********************************************************** + * Initialisation + **********************************************************/ + +'use strict'; + +var fs = require('fs'), + forge = require('node-forge'), + cfg = require('./config.js'); + +var pki = forge.pki; + + +/*********************************************************** + * Function definitions + **********************************************************/ + +//////////////////// Helpers + +/** + * Generates challenges/random data for encryption of the sessions and for + * the clientside keypair generation with HTML-. + * + * @returns {String} 32 Bytes of Base64-encoded random data + */ +module.exports.generateChallenge = function generateChallenge() { + return forge.util.encode64(forge.random.getBytesSync(32)); +}; + +/** + * Generates serial numbers used when creating certificates in accordance with + * https://tools.ietf.org/html/rfc5280#section-4.1.2.2 + * + * It is important to note that the number gets interpreted as signed, thus the + * highest bit gets turned to 0 by &0x7f - reducing the number space to 2^159. + * + * @returns {String} 20 Bytes of random data as hexadecimal string + */ +module.exports.generateSerial = function generateSerial() { + return forge.util.createBuffer().putByte(forge.random.getBytesSync(1).charCodeAt(0) & 0x7f).putBytes(forge.random.getBytesSync(19)).toHex(); +}; + +/** + * Retrieves the public key from a Signed Public Key and Challenge (SPKAC). + * IMPORTANT: Currently neither the challenge nor the signature gets verified, + * this is a security risk which was accepted for the proof of concept. + * + * @todo Use a forge-validator-construct and verify signature and challenge. + * See also http://middleware.internet2.edu/pki03/presentations/10.pdf + * + * @param {String} spkac Base64 encoded SPKAC in ASN.1 DER form. + * @returns {Object} A node-forge public key + */ +var spkacToPublicKey = function spkacToPublicKey(spkac) { + var asn1 = forge.asn1.fromDer(forge.util.decode64(spkac)); + return forge.pki.publicKeyFromAsn1(asn1.value[0].value[0]); +}; +module.exports.spkacToPublicKey = spkacToPublicKey; + +/** + * Hashes a given value with SHA-256. + * + * @param {String} value The value to hash + * @returns {String} SHA-256 hash of the value given as hexadecimal string + */ +module.exports.sha256 = function sha256(value) { + var md = forge.md.sha256.create(); + md.update(value); + return md.digest().toHex(); +}; + + +//////////////////// Certificate creation functions + +/** + * Creates an x.509 certificate authority (CA) certificate. + * + * @param {Object} subject Subject of the certificate, an object with attributes corresponding to DN + * @param {Object} keys A node-forge keypair (only public key used) + * @param {String} serial The serialnumber for the certificate, hexadecimal string + * @param {boolean} sha256 Use SHA-256 for signing (SHA-1 when false) + * @returns {Object} A node-forge certificate + */ +module.exports.createCACertificate = function createCACertificate(subject, keys, serial, sha256) { + var cert = pki.createCertificate(); + cert.setSubject(subject); + cert.setIssuer(subject); + cert.publicKey = keys.publicKey; + cert.serialNumber = serial; + cert.validity.notBefore = cfg.getValidityStart(); + cert.validity.notAfter = cfg.getValidityEnd(); + cert.setExtensions([{ name: 'basicConstraints', cA: true, pathLenConstraint: 0 }, + { name: 'keyUsage', keyCertSign: true, cRLSign: true }, + { name: 'subjectKeyIdentifier' }]); + + if (sha256) { + cert.sign(keys.privateKey, forge.md.sha256.create()); + } else { + cert.sign(keys.privateKey); + } + + return cert; +}; + +/** + * Creates an x.509 server certificate. + * + * @param {Object} subject Subject of the certificate, an object with attributes corresponding to DN + * @param {String} ip IP-address of the server, used for subject alternate name + * @param {Object} keys A node-forge keypair (only public key used) + * @param {String} serial The serialnumber for the certificate, hexadecimal string + * @param {Object} caCert Certificate of the certificate authority used for signing, retrieved from config if omited + * @param {Object} caKeys Keypair of the certificate authority used for signing, retrieved from config if omited + * @param {boolean} sha256 Use SHA-256 for signing (SHA-1 when false) + * @returns {Object} A node-forge certificate + */ +module.exports.createServerCertificate = function createServerCertificate(subject, ip, keys, serial, caCert, caKeys, sha256) { + var signingKey; + if (arguments.length <= 5) { + sha256 = caCert; + caCert = forge.pki.certificateFromPem(fs.readFileSync(cfg.get('ca:cert'), 'utf8')); + signingKey = forge.pki.privateKeyFromPem(fs.readFileSync(cfg.get('ca:key'), 'utf8')); + } else { + signingKey = caKeys.privateKey; + } + + var cert = pki.createCertificate(); + cert.setSubject(subject); + cert.setIssuer(caCert.subject.attributes); + cert.publicKey = keys.publicKey; + cert.serialNumber = serial; + cert.validity.notBefore = cfg.getValidityStart(); + cert.validity.notAfter = cfg.getValidityEnd(); + cert.setExtensions([{ name: 'basicConstraints', cA: false }, + { name: 'keyUsage', digitalSignature: true, keyEncipherment: true }, + { name: 'extKeyUsage', serverAuth: true }, + { name: 'nsCertType', server: true }, + { name: 'subjectAltName', critical: true, altNames: [ + { type: 7, ip: ip } + ]}, + { name: 'subjectKeyIdentifier' }]); + + if (sha256) { + cert.sign(signingKey, forge.md.sha256.create()); + } else { + cert.sign(signingKey); + } + + return cert; +}; + +/** + * Creates an x.509 client certificate conforming to the WebID-specification. + * See http://www.w3.org/2005/Incubator/webid/spec/ + * + * @param {String} id URI identifying the WebID + * @param {Object} cn CommonName-attribute of the certificate, the rest of the DN is retrieved from config + * @param {String} email Email-address of the holder of the WebID + * @param {Object} keys Either a node-forge keypair or a Base64 encoded SPKAC (see above) + * @param {String} serial The serialnumber for the certificate, hexadecimal string + * @param {Object} caCert Certificate of the certificate authority used for signing, retrieved from config if omited + * @param {Object} caKeys Keypair of the certificate authority used for signing, retrieved from config if omited + * @param {boolean} sha256 Use SHA-256 for signing (SHA-1 when false) + * @returns {Object} A node-forge certificate + */ +module.exports.createWebIDCertificate = function createWebIDCertificate(id, cn, email, keys, serial, caCert, caKeys, sha256) { + var signingKey; + if (arguments.length <= 6) { + sha256 = caCert; + caCert = forge.pki.certificateFromPem(fs.readFileSync(cfg.get('ca:cert'), 'utf8')); + signingKey = forge.pki.privateKeyFromPem(fs.readFileSync(cfg.get('ca:key'), 'utf8')); + } else { + signingKey = caKeys.privateKey; + } + + var publicKey; + if (! keys.publicKey) { + // not a forge-keypair, trying to parse it from SPKAC instead + publicKey = spkacToPublicKey(keys); + } else { + publicKey = keys.publicKey; + } + + var subject = [{'name': 'commonName', 'value': cn}]; + for (var k in cfg.get('webid:subject')) { + subject.push({'name': k, 'value': cfg.get('webid:subject')[k]}); + } + + var cert = pki.createCertificate(); + cert.setSubject(subject); + cert.setIssuer(caCert.subject.attributes); + cert.publicKey = publicKey; + cert.serialNumber = serial; + cert.validity.notBefore = cfg.getValidityStart(); + cert.validity.notAfter = cfg.getValidityEnd(); + cert.setExtensions([{ name: 'basicConstraints', cA: false}, + { name: 'keyUsage', digitalSignature: true, }, + { name: 'extKeyUsage', clientAuth: true, emailProtection: true }, + { name: 'subjectAltName', critical: true, altNames: [ + { type: 6, value: id }, + { type: 1, value: email } + ]}, + { name: 'nsCertType', client: true }, + { name: 'subjectKeyIdentifier' }]); + + if (sha256) { + cert.sign(signingKey, forge.md.sha256.create()); + } else { + cert.sign(signingKey); + } + + var bytes = forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes(); + return { + 'cert': cert, + 'der': bytes, + 'base64DER': forge.util.encode64(bytes) + }; +}; diff --git a/pool/shard000/JavaScript/0004676_ComplexFeatureTextContainer.js b/pool/shard000/JavaScript/0004676_ComplexFeatureTextContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..56f34773289f3fa221c66c20450526524863e97f --- /dev/null +++ b/pool/shard000/JavaScript/0004676_ComplexFeatureTextContainer.js @@ -0,0 +1,34 @@ +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; +import ComplexFeatureText from '../../components/ComplexFeatureText/components.jsx'; + +// include actions as they are needed by each component +// they are called via dispatch() + +const propTypes = { + dispatch: PropTypes.func, + content: PropTypes.object +}; + +// in here, we determine the props to be passed down to the specific component needed +class ComplexFeatureTextContainer extends Component { + + render () { + return ( + + ); + } +} + +ComplexFeatureTextContainer.propTypes = propTypes; + +function mapStateToProps(state) { + const cdnImageBase = state.urls.cdnImageBase; + const cdnUrl = state.urls.cdnUrl + return { + cdnUrl, + cdnImageBase + }; +} + +export default connect(mapStateToProps)(ComplexFeatureTextContainer); diff --git a/pool/shard000/JavaScript/0004678_books.js b/pool/shard000/JavaScript/0004678_books.js new file mode 100644 index 0000000000000000000000000000000000000000..0a6ffe40c3efa9071224250a4612c16ff4bd0978 --- /dev/null +++ b/pool/shard000/JavaScript/0004678_books.js @@ -0,0 +1,16 @@ +var bookApp = bookApp || {}; + +$(function() { + // front end initial books data + var books = [ + { title: 'Slam it to your left', author: 'Baby Spice', releaseDate: '2008', keywords: 'JavaScript Programming' }, + { title: 'If you\'re having a good time', author: 'Alex MacCaw', releaseDate: '2012', keywords: 'CoffeeScript Programming' }, + { title: 'Shake it to your right', author: 'Cay S. Horstmann', releaseDate: '2012', keywords: 'Scala Programming' }, + { title: 'If you know that you feel fine', author: 'Sporty', releaseDate: '1991', keywords: 'Novel Splatter' }, + { title: 'Chicas to the left', author: 'Hi C YA hold tight', releaseDate: '2011', keywords: 'JavaScript Programming' } + ]; + + new bookApp.LibraryView( books ); + + // new bookApp.LibraryView(); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004679_tests.js b/pool/shard000/JavaScript/0004679_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..9e1f1d5b02aa6741837170b7a5f86f90e7c87b8e --- /dev/null +++ b/pool/shard000/JavaScript/0004679_tests.js @@ -0,0 +1,165 @@ +'use strict'; + +/* global require, describe, it: true */ + +const vCard = require('../index'); +const assert = require('assert'); + +/** + * Test values. + */ +const TEST_VALUE_UID = '69531f4a-c34d-4a1e-8922-bd38a9476a53'; +const TEST_FILENAME = './test/testCard.vcf'; + +/** + * Get vCard value by field name. + * @param {string} fieldName + * @param {Array} lines + * @return {string} + */ +let getValueByFieldName = (fieldName, lines) => { + + for (let i=0; i 0 && lines[0] === 'BEGIN:VCARD'); + done(); + }); + + it('should be well-formed', function(done) { + var line = ''; + var segments = ''; + + for (var i=0; i 0) { + segments = line.split(':'); + assert(segments.length >= 2 || segments[0].indexOf(';') === 0); + } + } + done(); + }); + + it('should encode [\\n,\',;] properly (3.0+)', function(done) { + var line = ''; + + for (var i=0; i { + assert(getValueByFieldName('UID', lines) === TEST_VALUE_UID); + done(); + }); + + it('should end with END:VCARD', function(done) { + assert(lines.length > 2 && lines[lines.length-2] === 'END:VCARD'); + done(); + }); + + it(`should save to ${TEST_FILENAME}`, function(done) { + testCard.saveToFile(TEST_FILENAME); + done(); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004680_SearchStore.js b/pool/shard000/JavaScript/0004680_SearchStore.js new file mode 100644 index 0000000000000000000000000000000000000000..9460c81323ad3eadfc9b8970c8535b30c2fbb575 --- /dev/null +++ b/pool/shard000/JavaScript/0004680_SearchStore.js @@ -0,0 +1,26 @@ +/** + * Created by daiyingheng on 16/9/9. + */ +import alt from '../alt'; +import SearchActions from '../actions/SearchActions'; +import {assign} from 'underscore'; + +class SearchStore { + constructor() { + this.bindActions(SearchActions); + this.animes = []; + this.articles=[] + + } + + onSearchSuccess(data) { + this.animes = data.anime; + this.articles = data.article; + } + + onSearchFail(errorMessage) { + toastr.error(errorMessage); + } +} + +export default alt.createStore(SearchStore); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004681_index.js b/pool/shard000/JavaScript/0004681_index.js new file mode 100644 index 0000000000000000000000000000000000000000..23964a20f608e1416c562feda5fe09e87673c8a4 --- /dev/null +++ b/pool/shard000/JavaScript/0004681_index.js @@ -0,0 +1,26 @@ +// main routing file. +var express = require('express'); +var router = express.Router(); +var low = require('lowdb'); + +// lowdb configuration things. +const FileSync = require('../../node_modules/lowdb/adapters/FileSync.js') +console.log(__dirname) +const adapter = new FileSync('./private/websiteConfig.json'); +const db = low(adapter); + +// setup the defaults for the website. +db.defaults({ + website: { + domainName: "mikecole.co" + } +}).write(); + +// +router.get('/', function(req, res) { + res.render('../templates/index.ejs', { + websiteDomainName: db.get('website.domainName').value() + }); +}); + +module.exports = router; diff --git a/pool/shard000/JavaScript/0004683_config_spec.js b/pool/shard000/JavaScript/0004683_config_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e99e739d630f67e203979950691c35595fd643cd --- /dev/null +++ b/pool/shard000/JavaScript/0004683_config_spec.js @@ -0,0 +1,172 @@ +import { expect } from 'chai'; +import { assert } from 'chai'; +import { newConfig } from 'src/config'; + +const utils = require('src/utils'); + +let getConfig; +let setConfig; +let setDefaults; + +describe('config API', () => { + let logErrorSpy; + beforeEach(() => { + const config = newConfig(); + getConfig = config.getConfig; + setConfig = config.setConfig; + setDefaults = config.setDefaults; + logErrorSpy = sinon.spy(utils, 'logError'); + }); + + afterEach(() => { + utils.logError.restore(); + }); + + it('setConfig is a function', () => { + expect(setConfig).to.be.a('function'); + }); + + it('getConfig returns an object', () => { + expect(getConfig()).to.be.a('object'); + }); + + it('sets and gets arbitrary configuarion properties', () => { + setConfig({ baz: 'qux' }); + expect(getConfig('baz')).to.equal('qux'); + }); + + it('only accepts objects', () => { + setConfig('invalid'); + expect(getConfig('0')).to.not.equal('i'); + }); + + it('sets multiple config properties', () => { + setConfig({ foo: 'bar' }); + setConfig({ biz: 'buz' }); + var config = getConfig(); + expect(config.foo).to.equal('bar'); + expect(config.biz).to.equal('buz'); + }); + + it('overwrites existing config properties', () => { + setConfig({ foo: {biz: 'buz'} }); + setConfig({ foo: {baz: 'qux'} }); + expect(getConfig('foo')).to.eql({baz: 'qux'}); + }); + + it('sets debugging', () => { + setConfig({ debug: true }); + expect(getConfig('debug')).to.be.true; + }); + + // remove test when @deprecated $$PREBID_GLOBAL$$.logging removed + it('gets legacy logging in deprecation window', () => { + $$PREBID_GLOBAL$$.logging = false; + expect(getConfig('debug')).to.equal(false); + }); + + it('sets bidderTimeout', () => { + setConfig({ bidderTimeout: 1000 }); + expect(getConfig('bidderTimeout')).to.be.equal(1000); + }); + + // remove test when @deprecated $$PREBID_GLOBAL$$.bidderTimeout removed + it('gets legacy bidderTimeout in deprecation window', () => { + $$PREBID_GLOBAL$$.bidderTimeout = 5000; + expect(getConfig('bidderTimeout')).to.equal(5000); + }); + + it('gets user-defined publisherDomain', () => { + setConfig({ publisherDomain: 'fc.kahuna' }); + expect(getConfig('publisherDomain')).to.equal('fc.kahuna'); + }); + + // remove test when @deprecated $$PREBID_GLOBAL$$.publisherDomain removed + it('gets legacy publisherDomain in deprecation window', () => { + $$PREBID_GLOBAL$$.publisherDomain = 'ad.example.com'; + expect(getConfig('publisherDomain')).to.equal('ad.example.com'); + }); + + it('gets default userSync config', () => { + const DEFAULT_USERSYNC = { + syncEnabled: true, + pixelEnabled: true, + syncsPerBidder: 5, + syncDelay: 3000 + }; + setDefaults({'userSync': DEFAULT_USERSYNC}); + expect(getConfig('userSync')).to.eql(DEFAULT_USERSYNC); + }); + + it('has subscribe functionality for adding listeners to config updates', () => { + const listener = sinon.spy(); + + getConfig(listener); + + setConfig({ foo: 'bar' }); + + sinon.assert.calledOnce(listener); + sinon.assert.calledWith(listener, { foo: 'bar' }); + }); + + it('subscribers can unsubscribe', () => { + const listener = sinon.spy(); + + const unsubscribe = getConfig(listener); + + unsubscribe(); + + setConfig({ logging: true }); + + sinon.assert.notCalled(listener); + }); + + it('subscribers can subscribe to topics', () => { + const listener = sinon.spy(); + + getConfig('logging', listener); + + setConfig({ logging: true, foo: 'bar' }); + + sinon.assert.calledOnce(listener); + sinon.assert.calledWithExactly(listener, { logging: true }); + }); + + it('topic subscribers are only called when that topic is changed', () => { + const listener = sinon.spy(); + const wildcard = sinon.spy(); + + getConfig('subject', listener); + getConfig(wildcard); + + setConfig({ foo: 'bar' }); + + sinon.assert.notCalled(listener); + sinon.assert.calledOnce(wildcard); + }); + + it('sets priceGranularity', () => { + setConfig({ priceGranularity: 'low' }); + expect(getConfig('priceGranularity')).to.be.equal('low'); + }); + + it('sets priceGranularity and customPriceBucket', () => { + const goodConfig = { + 'buckets': [{ + 'min': 0, + 'max': 3, + 'increment': 0.01, + 'cap': true + }] + }; + setConfig({ priceGranularity: goodConfig }); + expect(getConfig('priceGranularity')).to.be.equal('custom'); + expect(getConfig('customPriceBucket')).to.equal(goodConfig); + }); + + it('should log error for invalid priceGranularity', () => { + setConfig({ priceGranularity: '' }); + const error = 'Prebid Error: no value passed to `setPriceGranularity()`'; + assert.ok(logErrorSpy.calledWith(error), 'expected error was logged'); + }); +}); diff --git a/pool/shard000/JavaScript/0004685_makeElementScreenshot.js b/pool/shard000/JavaScript/0004685_makeElementScreenshot.js new file mode 100644 index 0000000000000000000000000000000000000000..0fca06da2cc8c8755a2b241eee9786f43361026e --- /dev/null +++ b/pool/shard000/JavaScript/0004685_makeElementScreenshot.js @@ -0,0 +1,32 @@ +import debug from 'debug'; + +import makeAreaScreenshot from './makeAreaScreenshot'; +import beforeScreenshot from './beforeScreenshot'; +import afterScreenshot from './afterScreenshot'; + +import groupBoundingRect from '../utils/groupBoundingRect'; +import getBoundingRects from '../scripts/getBoundingRects'; + +const log = debug('wdio-screenshot:makeElementScreenshot'); + + +export default async function makeElementScreenshot(browser, elementSelector, options = {}) { + log('start element screenshot'); + + // hide scrollbars, scroll to start, hide & remove elements, wait for render + await beforeScreenshot(browser, options); + + // get bounding rect of elements + const boundingRects = await browser.selectorExecute(elementSelector, getBoundingRects); + const boundingRect = groupBoundingRect(boundingRects); + + // make screenshot of area + const base64Image = await makeAreaScreenshot(browser, boundingRect.left, boundingRect.top, boundingRect.right, boundingRect.bottom, options); + + // show scrollbars, show & add elements + await afterScreenshot(browser, options); + + log('end element screenshot'); + + return base64Image; +} diff --git a/pool/shard000/JavaScript/0004688_publications.js b/pool/shard000/JavaScript/0004688_publications.js new file mode 100644 index 0000000000000000000000000000000000000000..fc483475d9f895198a2832a6d2ce136eef356690 --- /dev/null +++ b/pool/shard000/JavaScript/0004688_publications.js @@ -0,0 +1,40 @@ +Meteor.publish('dropzones', function() { // publish dropzones to everyone who are logged in + if (!this.userId) { + return this.ready(); + } + return Dropzones.find(); +}); + +Meteor.publish('myVtrs', function() { // publish vtrs created by user him/herself + var currentUserId = this.userId; + if (currentUserId) { + return Vtr.find({createdBy: currentUserId}, {sort: {date: -1}}); + } else { + this.ready(); + } +}); + +Meteor.publish('dzVtrs', function() { // publish vtrs created at dropzone user is responsible at + if (!this.userId) { + return this.ready(); + } + var currentUserEmail = Meteor.users.findOne(this.userId).emails[0].address; + var currentUserDzs = Dropzones.find({$or:[ + {headOfTraining: currentUserEmail}, + {viceHeadOfTraining: currentUserEmail}, + {headOfSafety: currentUserEmail}]}).fetch(); + var currentUserDzIds = _.map(currentUserDzs,function (value){ return value._id;}); + if (currentUserDzIds) { + return Vtr.find({happenedDz: {$in: currentUserDzIds}}, {fields: {phoneNumber: 0, age: 0}, sort: {date: -1}}); + } else { + this.ready(); + } +}); + +Meteor.publish('AllVtrs', function() { // publish all vtrs to admins + if (Roles.userIsInRole(this.userId,['admin'])) { + return Vtr.find({}, {sort: {date: -1}}); + } else { + this.ready(); + } +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004689_UserController.js b/pool/shard000/JavaScript/0004689_UserController.js new file mode 100644 index 0000000000000000000000000000000000000000..b6aabf0dcb12f570c37322a593426bc1f91e1af4 --- /dev/null +++ b/pool/shard000/JavaScript/0004689_UserController.js @@ -0,0 +1,98 @@ +/** + * UserController + * + * @description :: Server-side logic for managing users + * @help :: See http://links.sailsjs.org/docs/controllers + */ +require('../services/utils') +module.exports = { + create: function (req, res, next) { + + var params = req.params.all(); + //Verifica el digito verificador + params.rut = utils.verifyRut(params.rut); + + if (params.rut ==='') { + //ejecuta error en caso de no coincidir los valores + res.status(500); + err='Digito verificador incorrecto' + return next(err); + } + + else { + + User.create(params, function(err, user) { + + if (err) return next(err); + + res.status(201); + + res.json(user); + + }); + }; + }, + + + + find: function (req, res, next) { + + function isShortcut(id) { + if (id === 'find' || id === 'update' || id === 'create' || id === 'destroy') { + return true; + + } + }; + + var id = req.param('id'); + + var idShortCut = isShortcut(id); + console.log("idShortCut es ", idShortCut) + if (idShortCut === true) { + console.log("entra al idShortCut ") + return next(); + } + + if (id) { + User.findOne(id, function(err, user) { + if (user===undefined) return res.notFound(); + + if (err) return next(err); + + res.json(user); + + }); + + } else { + var where = req.param('where'); + + if (_.isString(where)) { + where = JSON.parse(where); + } + + var options = { + limit: req.param('limit') || undefined, + skip: req.param('skip') || undefined, + sort: req.param('sort') || undefined, + where: where || undefined + }; + + //console.log("This is the options", options); + + User.find(where, function(err, user) { + console.log("This is the options", where); + console.log("entra al buscador ..", user) + if(user === undefined) return res.notFound(); + + if (err) return next(err); + + res.json(user); + + }); + + }; + + + } +}; + diff --git a/pool/shard000/JavaScript/0004693_showon.es6.js b/pool/shard000/JavaScript/0004693_showon.es6.js new file mode 100644 index 0000000000000000000000000000000000000000..65e81efd1eb46343a0b7e639bee6f51469ccaa2e --- /dev/null +++ b/pool/shard000/JavaScript/0004693_showon.es6.js @@ -0,0 +1,248 @@ +/** + * @copyright (C) 2018 Open Source Matters, Inc. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ +((document) => { + 'use strict'; + + /* + * JField 'showon' class + */ + class Showon { + /* + * Constructor + * + * @param {HTMLElement} cont Container element + */ + constructor(cont) { + const self = this; + this.container = cont || document; + this.fields = { + // origin-field-name: { + // origin: ['collection of all the trigger nodes'], + // targets: ['collection of nodes to be controlled control'] + // } + }; + + this.showonFields = [].slice.call(this.container.querySelectorAll('[data-showon]')); + // Populate the fields data + if (this.showonFields.length) { + // @todo refactor this, dry + this.showonFields.forEach((field) => { + // Set up only once + if (field.hasAttribute('data-showon-initialised')) { + return; + } + field.setAttribute('data-showon-initialised', ''); + + const jsondata = field.getAttribute('data-showon') || ''; + const showonData = JSON.parse(jsondata); + let localFields; + + if (showonData.length) { + localFields = [].slice.call(self.container.querySelectorAll(`[name="${showonData[0].field}"], [name="${showonData[0].field}[]"]`)); + + if (!this.fields[showonData[0].field]) { + this.fields[showonData[0].field] = { + origin: [], + targets: [], + }; + } + + // Add trigger elements + localFields.forEach((cField) => { + if (this.fields[showonData[0].field].origin.indexOf(cField) === -1) { + this.fields[showonData[0].field].origin.push(cField); + } + }); + + // Add target elements + this.fields[showonData[0].field].targets.push(field); + + // Data showon can have multiple values + if (showonData.length > 1) { + showonData.forEach((value, index) => { + if (index === 0) { + return; + } + + localFields = [].slice.call(self.container.querySelectorAll(`[name="${value.field}"], [name="${value.field}[]"]`)); + + if (!this.fields[showonData[0].field]) { + this.fields[showonData[0].field] = { + origin: [], + targets: [], + }; + } + + // Add trigger elements + localFields.forEach((cField) => { + if (this.fields[showonData[0].field].origin.indexOf(cField) === -1) { + this.fields[showonData[0].field].origin.push(cField); + } + }); + + // Add target elements + if (this.fields[showonData[0].field].targets.indexOf(field) === -1) { + this.fields[showonData[0].field].targets.push(field); + } + }); + } + } + }); + + // Do some binding + this.linkedOptions = this.linkedOptions.bind(this); + + // Attach events to referenced element, to check condition on change and keyup + Object.keys(this.fields).forEach((key) => { + if (this.fields[key].origin.length) { + this.fields[key].origin.forEach((elem) => { + // Initialize the showon behaviour for the given HTMLElement + self.linkedOptions(key); + + // Setup listeners + elem.addEventListener('change', () => { self.linkedOptions(key); }); + elem.addEventListener('keyup', () => { self.linkedOptions(key); }); + elem.addEventListener('click', () => { self.linkedOptions(key); }); + }); + } + }); + } + } + + /** + * + * @param key + */ + linkedOptions(key) { + // Loop through the elements that need to be either shown or hidden + this.fields[key].targets.forEach((field) => { + const elementShowonDatas = JSON.parse(field.getAttribute('data-showon')) || []; + let showfield = true; + let itemval; + + // Check if target conditions are satisfied + elementShowonDatas.forEach((elementShowonData, index) => { + const condition = elementShowonData || {}; + condition.valid = 0; + + // Test in each of the elements in the field array if condition is valid + this.fields[key].origin.forEach((originField) => { + if (originField.name !== elementShowonData.field) { + return; + } + + const originId = originField.id; + + // If checkbox or radio box the value is read from properties + if (originField.getAttribute('type') && ['checkbox', 'radio'].indexOf(originField.getAttribute('type').toLowerCase()) !== -1) { + if (!originField.checked) { + // Unchecked fields will return a blank and so always match + // a != condition so we skip them + return; + } + + itemval = document.getElementById(originId).value; + } else { + // Select lists, text-area etc. Note that multiple-select list returns + // an Array here s0 we can always treat 'itemval' as an array + itemval = document.getElementById(originId).value; + // A multi-select name = node} id="Name"/> +
      +
      + Email:          + email = node} id="Email" /> +
      +
      + Birthday:      + birthday = node} id="Birthday" /> +
      +
      + Phone:         + phone = node} id="Phone" /> +
      +
      + Zipcode:       + zipcode = node} id="Zipcode" /> +
      +
      + Password:     + pw1 = node} id="YourPassword" /> +
      +
      + PW Confirm:  + pw2 = node} id="PasswordConfirmation" /> +
      +
      + + {event.preventDefault(); + validateInfo(dispatch, + pw1,pw2,name,email,phone,zipcode,birthday)} + }/> + +
      {errRegInfo}
      + + + +) +} +//validate the input information +const validateInfo=(dispatch,Pw1,Pw2, + Name,Email,Phone,Zipcode,Birthday)=>{ + // dispatch({type: 'IS_REG_ERROR', errRegInfo:str}) + var flag=true; + var str="Alert: " + var errorNum=0 + //validate accountname + if(!validate(Name)){ + str+="You must fill in your name."; + flag=false; + } + else if(!validateAccountName(Name)){ + str+="Name can only consist with upper/lower letters/numbers and cannot start with a number. "; + flag=false; + } + //validate email + if(!validate(Email)){ + str+="You must fill in your e-mail address."; + flag=false; + } + else if(!validateEmail(Email)){ + str+="You must fill in your e-mail address in correct form.(x@x.x) "; + flag=false; + } + if(!validate(Birthday)){ + str+="You must fill in your Birthday. "; + flag=false; + } + //validate phone + if(!validate(Phone)){ + str+="You must fill in your phone number. "; + flag=false; + } + else if(!validatePhone(Phone)){ + str+="You must fill in your phone number in correct form.(xxx-xxx-xxxx) "; + flag=false; + } + //validate zipcode + if(!validate(Zipcode)){ + str+="You must fill in your zipcode. "; + flag=false; + } + else if(!validateZipCode(Zipcode)){ + str+="You must fill in your ZipCode in correct form.(xxxxx) "; + flag=false; + } + + //password + if(!validate(Pw1)){ + str+="You must fill in your pasword. "; + flag=false; + } + if(!validate(Pw2)){ + str+="You must fill in your pasword Confirmation. "; + flag=false; + } + if(!validatePassword(Pw1,Pw2)){ + str+="Two passwords are not the same. "; + flag=false; + } + + if(flag){ + addthisOne(dispatch,Pw1, + Name,Email,Phone,Zipcode,Birthday); + } + else{ + dispatch({type: 'IS_REG_ERROR', errRegInfo:str}) + } +} +//validate if the element exists +const validate=(element)=>{ + if(element.value == ""||element.value == null){ + return false; + } + return true; +} +//add this to the state tree and turn to the main page +const addthisOne=(dispatch,Pw1,Name,Email,Phone,Zipcode,Birthday)=>{ + var user={ + username:Name.value, + email:Email.value, + zipcode:Zipcode.value, + password:Pw1.value, + dob:Birthday.value + } + dispatch(register({user})); +} +//validate the name by regular expression +const validateAccountName=(element)=>{ + var reg=/^([a-zA-Z]{1})([a-zA-Z0-9]{1})+$/; + if(element.value.match(reg)||!(validate(element))){ + return true; + } + return false; +} +//validate the email by regular expression +const validateEmail=(element)=>{ + var reg=/^([a-zA-Z0-9\_\.\-])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})$/; + if(element.value.match(reg)||(!validate(element))){ + return true; + } + return false; +} +//validate the phone by regular expression +const validatePhone=(element)=>{ + var reg = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/; + if(element.value.match(reg)||(!validate(element))){ + return true; + } + return false; +} +//validate the zipcode by regular expression +const validateZipCode=(element)=>{ + var reg = /^([0-9]{5})$/; + if(element.value.match(reg)||(!validate(element))){ + return true; + } + return false; +} +//validate the password by regular expression +const validatePassword=(element1,element2)=>{ + if(element1.value!=element2.value + && validate(element1) && validate(element2)){ + return false; + } + return true; +} +//check the type +Register.propTypes = { + errRegInfo: PropTypes.string.isRequired, + user: PropTypes.object.isRequired +} +export default connect( + (state) => { + return { + errRegInfo: state.errRegInfo, + user: state.user + } + },null +)(Register) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004744_writePlus.js b/pool/shard000/JavaScript/0004744_writePlus.js new file mode 100644 index 0000000000000000000000000000000000000000..173cf5b2fd0d576daa2031ee33d9a8a0424d3c07 --- /dev/null +++ b/pool/shard000/JavaScript/0004744_writePlus.js @@ -0,0 +1,180 @@ +/** + * Created by jszhou on 2017/1/5. + */ +/** + * 解决的问题 + * 1.含document.write的广告内容的异步加载 + */ +(function () { + var doc = document, + outerScriptNum = 0, + oldWrite = doc.write.bind(doc), + writeQueue = [], + writeStarted = false, + doNothing = function () {}, + /** + * 把类数组对象转换为数组。 + */ + toArray = Array.from || function (arg) { + return Array.prototype.slice.call(arg); + }; + + /** + * 判断参数是否为节点对象。 + * @param {*} arg + * @return {boolean} + */ + function isNode(arg) { + return arg instanceof Node; + } + + /** + * 判断参数是否为script节点对象。 + * @param {*} arg + * @return {boolean} + */ + function isScript(arg) { + return isNode(arg) && arg.nodeName.toLowerCase() === 'script'; + } + + /** + * 判断参数是否为函数。 + * @param {*} arg + * @return {boolean} + */ + function isFunction(arg) { + return typeof arg === 'function'; + } + + /** + * 复制script节点对象,复制以后script标签的内容可以运行。 + * @param {object} script script节点对象 + * @return {object} 返回新的script节点对象 + */ + function copyScript(script) { + var newScript = document.createElement('script'); + function loadFn() { + --outerScriptNum; + if(writeQueue.length > 0){ + var args = writeQueue.shift(); + write(args[0], args[1],args[2]); + } + if(outerScriptNum === 0){ + doc.write = oldWrite; + writeStarted = false; + } + newScript.removeEventListener('load', loadFn, false); + } + + // 复制属性 + toArray(script.attributes).forEach(function (item) { + newScript.setAttribute(item.nodeName, item.nodeValue); + }); + + if(!newScript.src){ + newScript.innerHTML = script.innerHTML; + return newScript; + } + + ++outerScriptNum; + newScript.addEventListener('load', loadFn, false); + + return newScript; + } + + /** + * 替代script节点对象,替代以后script标签的内容可以运行。 + * @param {object} node 节点对象 + * @return {object} 返回script被替代的节点对象(script节点对象被替代成可以运行的) + */ + function replaceAllScript(node) { + Array.prototype.forEach.call(node.childNodes, function (item) { + // 如果是script节点对象,则替代为可运行的script节点对象 + if(isScript(item)) { + item.parentNode.replaceChild(copyScript(item), item); + return; + } + // 递归 + if(item.childNodes.length > 0){ + replaceAllScript(item); + } + }); + + return node; + } + + /** + * 字符串转成文档片段节点对象。 + * @param {String} str 字符串,可以包含script标签,转换完插入文档以后可以运行。 + * @return {Object} 返回文档片段节点对象 + */ + function strToNode(str) { + var docFrag = document.createDocumentFragment(), + div = document.createElement('div'); + + div.innerHTML = str; + + toArray(replaceAllScript(div).childNodes).forEach(function (item) { + docFrag.appendChild(item); + }); + + return docFrag; + } + + /** + * 这个是用于把html写入指定节点 + * @param {Element} el 写入内容的节点对象 + * @param {String} html html字符串 + * @param {Function} done html中的内容加载并运行完以后的回调函数 + */ + function write(el, html, done) { + var hasOuterScript = false, + docFrag = document.createDocumentFragment(); + + docFrag.appendChild(strToNode(String(html))); + toArray(docFrag.querySelectorAll('script')).forEach(function (item) { + if(item.src){ + hasOuterScript = true; + } + }); + el.appendChild(docFrag); + + done = isFunction(done) ? done : doNothing; + done(); + + if(!hasOuterScript){ + if(writeQueue.length > 0){ + var args = writeQueue.shift(); + write(args[0], args[1],args[2]); + } + + if(outerScriptNum === 0){ + doc.write = oldWrite; + writeStarted = false; + } + } + + } + /** + * + * @param {Element} el 写入内容的节点对象 + * @param {String} html html字符串 + * @param {Function} done html中的内容加载并运行完以后的回调函数 + */ + Document.prototype.writePlus = function (el, html, done) { + if(!writeStarted) { + writeStarted = true; + + doc.write = function () { + var str = toArray(arguments).join(''); + el.appendChild(strToNode(str)); + }; + + write(el, html, done) + }else{ + writeQueue.push([el, html, done]); + } + + return oldWrite; + }; +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004749_privatename-valid-no-earlyerr.js b/pool/shard000/JavaScript/0004749_privatename-valid-no-earlyerr.js new file mode 100644 index 0000000000000000000000000000000000000000..31065dc19e144f957129f35ae0e0e3d1d3aa660d --- /dev/null +++ b/pool/shard000/JavaScript/0004749_privatename-valid-no-earlyerr.js @@ -0,0 +1,47 @@ +// Copyright (C) 2017 Valerie Young. All rights reserved. +// This code is governed by the BSD license found in the LICENSE file. +/*--- +esid: sec-module-semantics-static-semantics-early-errors +description: Referencing privatename in class within class does not error. +info: | + Static Semantics: Early Errors + Module : ModuleBody + It is a Syntax Error if AllPrivateNamesValid of ModuleBody with an empty List as an argument is false. + + Static Semantics: AllPrivateNamesValid + AllPrivateNamesValid is an abstract operation which takes names as an argument. + + MemberExpression : MemberExpression . PrivateName + 1. If StringValue of PrivateName is in names, return true. + 2. Return false. + + CallExpression : CallExpression . PrivateName + 1. If StringValue of PrivateName is in names, return true. + 2. Return false. + + ClassBody:ClassElementList + 1. Let newNames be the concatenation of names with PrivateBoundNames of ClassBody. + 2.Return AllPrivateNamesValid of ClassElementList with the argument newNames. + + For all other grammatical productions, recurse on subexpressions/substatements, passing in the names of the caller. If all pieces return true, then return true. If any returns false, return false. +flags: [module] +features: [class, class-fields-private] +---*/ + +class outer { + #x = 42; + + f() { + var self = this; + return class inner { + g() { + return self.#x; + } + } + } +} + +var innerclass = new outer().f(); +var test = new innerclass().g(); + +assert.sameValue(test, 42); diff --git a/pool/shard000/JavaScript/0004752_server.js b/pool/shard000/JavaScript/0004752_server.js new file mode 100644 index 0000000000000000000000000000000000000000..781e04b4f8ecf0535b3c27c6335e5bb7d2a17394 --- /dev/null +++ b/pool/shard000/JavaScript/0004752_server.js @@ -0,0 +1,32 @@ +var compress = require('compression'), + config = require('../config'), + express = require('express'), + gulp = require('gulp'), + gutil = require('gulp-util'), + logger = require('morgan'), + open = require('open'), + path = require('path'); + +var settings = { + root: path.resolve(process.cwd(), config.root.dest), + port: process.env.PORT || 5000, + logLevel: process.env.NODE_ENV ? 'combined' : 'dev', + staticOptions: { + extensions: ['html'], + maxAge: '31556926' + } +}; + +gulp.task('server', function() { + var url = 'http://localhost:' + settings.port; + //express + express() + .use(compress()) + .use(logger(settings.logLevel)) + .use('/', express.static(settings.root, settings.staticOptions)) + .listen(settings.port); + + gutil.log('production server started on ' + gutil.colors.green(url)); + // open(url); +}); + diff --git a/pool/shard000/JavaScript/0004753_name.js b/pool/shard000/JavaScript/0004753_name.js new file mode 100644 index 0000000000000000000000000000000000000000..984d777da8846b1bfd61e613fbc2ca35dcfaa324 --- /dev/null +++ b/pool/shard000/JavaScript/0004753_name.js @@ -0,0 +1,59 @@ +/* eslint-env mocha */ +'use strict' + +const sinon = require('sinon') +const YargsPromise = require('yargs-promise') +const clearModule = require('clear-module') + +describe('name', () => { + let cli + let cliUtils + beforeEach(() => { + cliUtils = require('../../src/cli/utils') + cli = new YargsPromise(require('../../src/cli/parser')) + }) + afterEach(() => { + sinon.restore() + // TODO: the lines below shouldn't be necessary, cli needs refactor to simplify testability + // Force the next require to not use require cache + clearModule('../../src/cli/utils') + clearModule('../../src/cli/parser') + }) + + it('resolve', async () => { + const resolveFake = sinon.fake() + + sinon + .stub(cliUtils, 'getIPFS') + .callsArgWith(1, null, { name: { resolve: resolveFake } }) + + // TODO: the lines below shouldn't be necessary, cli needs refactor to simplify testability + // Force the next require to not use require cache + clearModule('../../src/cli/commands/name/resolve.js') + + await cli.parse(`name resolve test`) + sinon.assert.calledWith(resolveFake, 'test', { nocache: false, recursive: true }) + }) + + it('publish', async () => { + const publishFake = sinon.fake.returns({ name: 'name', value: 'value' }) + const printSpy = sinon.spy(cliUtils, 'print') + + sinon + .stub(cliUtils, 'getIPFS') + .callsArgWith(1, null, { name: { publish: publishFake } }) + + // TODO: the lines below shouldn't be necessary, cli needs refactor to simplify testability + // Force the next require to not use require cache + clearModule('../../src/cli/commands/name/publish.js') + + await cli.parse(`name publish test --silent`) + sinon.assert.calledWith(printSpy, 'Published to name: value') + sinon.assert.calledWith(publishFake, 'test', { + resolve: true, + lifetime: '24h', + key: 'self', + ttl: '' + }) + }) +}) diff --git a/pool/shard000/JavaScript/0004754_SigninPage.js b/pool/shard000/JavaScript/0004754_SigninPage.js new file mode 100644 index 0000000000000000000000000000000000000000..9828b80cd5cc00a66d197f40c48389fc490f7ed9 --- /dev/null +++ b/pool/shard000/JavaScript/0004754_SigninPage.js @@ -0,0 +1,23 @@ +import React from 'react'; +import Helmet from 'react-helmet'; +import { withRouter } from 'react-router'; +import SigninContainer from '../../redux/containers/SigninContainer'; + +const SigninPage = () => { + return ( +
      + +

      Sign In

      + + +
      + ); +}; +SigninPage.propTypes = {}; +SigninPage.defaultProps = {}; + +export default withRouter(SigninPage); diff --git a/pool/shard000/JavaScript/0004757_script.js b/pool/shard000/JavaScript/0004757_script.js new file mode 100644 index 0000000000000000000000000000000000000000..4f633aca8c59090f1de107c166bffb3a10db231b --- /dev/null +++ b/pool/shard000/JavaScript/0004757_script.js @@ -0,0 +1,149 @@ +angular.module('vatraModule',[]) + .directive('ngVatra',[function(){ + return { + restrict:'E', + scope:{ + ngData:'=', + ngMasterData:'=', + tkDuThue:'=', + tTienNt:'=', + tTien:'=', + tenVt:'=', + maKh:'=' + }, + templateUrl:'modules/vouchers/vatra/templates/table.html', + controller:function($scope,$modal,dmkh,dmvat,$timeout){ + $scope.status = {isOpened:false}; + $scope.isNotRowwSelected = function(dt){ + return (_.filter(dt,function(r){return r.sel==true}).length==0); + } + $scope.deleteRow = function(dt){ + var rc = _.reject(dt,function(r){return r.sel==true}); + dt.length =0; + var i=0; + rc.forEach(function(r){ + r.line = i; + dt.push(r) + i++; + }); + } + $scope.addDetail = function(){ + if(!$scope.ngData){ + $scope.ngData = []; + } + var line =$scope.ngData.length; + $scope.dt_master = null; + $scope.dt_current ={line:line}; + if(!$scope.ngData){ + $scope.ngData =[]; + } + if($scope.ngMasterData){ + $scope.dt_current.ngay_hd = $scope.ngMasterData.ngay_ct; + + if($scope.tkDuThue){ + $scope.dt_current.tk_du_thue =$scope.tkDuThue; + } + if($scope.tTienNt){ + $scope.dt_current.t_tien_nt = $scope.tTienNt; + } + if($scope.tTien){ + $scope.dt_current.t_tien = $scope.tTien; + } + if($scope.tenVt){ + $scope.dt_current.ten_vt = $scope.tenVt; + } + if($scope.maKh){ + $scope.dt_current.ma_kh = $scope.maKh; + dmkh.list(id_app,{ma_kh:$scope.maKh}).success(function(data){ + if(data.length==1){ + $scope.dt_current.ten_kh = data[0].ten_kh; + $scope.dt_current.dia_chi = data[0].dia_chi; + $scope.dt_current.ma_so_thue = data[0].ma_so_thue; + } + }); + } + } + $scope.openDetail('lg'); + } + $scope.editDetail = function(line){ + $scope.dt_master = _.find($scope.ngData,function(r){return r.line==line}); + $scope.dt_current ={}; + _.extend($scope.dt_current,$scope.dt_master); + $scope.openDetail('lg'); + } + $scope.openDetail = function (size,template) { + var modalInstance = $modal.open({ + templateUrl: 'modules/vouchers/vatra/templates/edit.html', + controller: function($scope, $modalInstance,parentScope){ + $scope.ngData = parentScope.ngData; + $scope.dt_master = parentScope.dt_master; + $scope.dt_current = parentScope.dt_current; + $scope.ngMasterData=parentScope.ngMasterData; + $scope.status=parentScope.status; + + $scope.updateDetail = function (){ + if(!$scope.dt_master){ + $scope.dt_master = {}; + $scope.ngData.push($scope.dt_master); + } + for(var k in $scope.dt_current){ + $scope.dt_master[k] = $scope.dt_current[k]; + } + $modalInstance.close(); + + }; + $scope.cancelDetail = function () { + $modalInstance.dismiss('cancel'); + }; + }, + size: size, + resolve: { + parentScope: function () { + $scope.status.isOpened = false; + return $scope; + } + } + }); + modalInstance.opened.then(function(){ + $timeout(function(){ + $scope.status.isOpened = true; + },100); + + }); + modalInstance.result.then(function(result){ + $scope.status.isOpened = false; + }); + } + }, + link:function(scope,elem,attrs,ctr){ + scope.$watch('dt_current.thue_suat',function(newData){ + if(scope.status.isOpened){ + scope.dt_current.t_thue_nt = scope.dt_current.t_tien_nt * scope.dt_current.thue_suat/100; + scope.dt_current.t_thue = scope.dt_current.t_thue_nt * scope.ngMasterData.ty_gia; + } + }); + + scope.$watch('dt_current.t_thue_nt',function(newData){ + if(scope.status.isOpened){ + scope.dt_current.t_thue = scope.dt_current.t_thue_nt * scope.ngMasterData.ty_gia; + } + }); + scope.$watch('dt_current.t_tien_nt',function(newData){ + if(scope.status.isOpened){ + scope.dt_current.t_tien = scope.dt_current.t_tien_nt * scope.ngMasterData.ty_gia; + + scope.dt_current.t_thue_nt = scope.dt_current.t_tien_nt * scope.dt_current.thue_suat/100; + scope.dt_current.t_thue = scope.dt_current.t_thue_nt * scope.ngMasterData.ty_gia; + } + }); + + scope.$watch('dt_current.t_tien',function(newData){ + if(scope.status.isOpened){ + scope.dt_current.t_thue = scope.dt_current.t_tien * scope.dt_current.thue_suat/100; + } + }); + + + } + } +}]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004758_authenticate.js b/pool/shard000/JavaScript/0004758_authenticate.js new file mode 100644 index 0000000000000000000000000000000000000000..e20d2ffa45667b17371eb645f5921e9eb31f91b7 --- /dev/null +++ b/pool/shard000/JavaScript/0004758_authenticate.js @@ -0,0 +1,44 @@ +/* global API */ +import { unescape } from 'plug-message-split' +import fetch from './fetch' + +const jsonHeaders = { + Accept: 'application/json', + 'Content-Type': 'application/json' +} + +function getBlurb () { + return fetch('/_/users/me', { credentials: 'same-origin' }) + .then(res => unescape(res.data[0].blurb)) +} + +function setBlurb (blurb) { + return fetch('/_/profile/blurb', { + credentials: 'same-origin', + method: 'put', + headers: jsonHeaders, + body: JSON.stringify({ blurb: blurb }) + }) +} + +function authenticate ({ + user = API.getUser().id, + transport +} = {}) { + let oldBlurb + + return transport.getToken({ user }) + .then((data) => { + return getBlurb().then((blurb) => { + oldBlurb = blurb + return setBlurb(`_auth_blurb=${data.blurb}`) + }) + }) + .then(() => transport.verify({ user })) + .then( + (result) => setBlurb(oldBlurb).then(() => result && result.token ? result : null), + (err) => setBlurb(oldBlurb).then(() => { throw err }) + ) +} + +export default authenticate diff --git a/pool/shard000/JavaScript/0004760_getSchema.js b/pool/shard000/JavaScript/0004760_getSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..324f74b718a702d3fcfdd844f639a6df420d955b --- /dev/null +++ b/pool/shard000/JavaScript/0004760_getSchema.js @@ -0,0 +1,25 @@ +'use strict' +const fs = require('fs') + +module.exports = function (request, reply) { + const schema = request.params.schema + if (schema === undefined) { + let path = `${__dirname}/../schemas` + fs.readdir(path, (err, dir) => { + if (err) { + return reply(err) + } else { + return reply(dir) + } + }) + } else { + let path = `${__dirname}/../schemas/${schema}.json` + fs.readFile(path, (err, file) => { + if (err) { + return reply(err) + } else { + return reply(file.toString()) + } + }) + } +} diff --git a/pool/shard000/JavaScript/0004763_CombatDefendTask.js b/pool/shard000/JavaScript/0004763_CombatDefendTask.js new file mode 100644 index 0000000000000000000000000000000000000000..4238c4554214ecf4c796492dda9a68ee2cad0e1f --- /dev/null +++ b/pool/shard000/JavaScript/0004763_CombatDefendTask.js @@ -0,0 +1,194 @@ +import InputValidator from "../../common/js/InputValidator.js"; +import GameEvent from "../../artifact/js/GameEvent.js"; +import Action from "./Action.js"; +import CardAction from "./CardAction.js"; +import QueueProcessor from "./QueueProcessor.js"; + +function CombatDefendTask(store, agent) +{ + InputValidator.validateNotNull("store", store); + InputValidator.validateNotNull("agent", agent); + + this.store = function() + { + return store; + }; + + this.agent = function() + { + return agent; + }; + + var queue = []; + + this.queue = function(queueIn) + { + if (queueIn !== undefined) + { + queue = queueIn; + } + + return queue; + }; +} + +CombatDefendTask.prototype.doIt = function(callback) +{ + InputValidator.validateNotNull("callback", callback); + + // 1. Choose an enemy. + var agent = this.agent(); + this.queue(agent.engagementArea()); + this.processQueue(callback); +}; + +CombatDefendTask.prototype.processQueue = function(callback) +{ + InputValidator.validateNotNull("callback", callback); + + LOGGER.debug("CombatDefendTask.processQueue() this.queue().length = " + this.queue().length); + + if (this.queue().length === 0) + { + this.finishPhase(callback); + return; + } + + var attacker = this.queue().shift(); + LOGGER.debug("CombatDefendTask.processQueue() attacker = " + attacker); + var store = this.store(); + var adjudicator = store.getState().adjudicator; + + if (adjudicator.canAttack(attacker)) + { + this.declareDefender(attacker, callback); + } + else + { + this.processQueue(callback); + } +}; + +CombatDefendTask.prototype.declareDefender = function(attacker, callback) +{ + var agent = this.agent(); + + // 2. Declare defender. + var characters = agent.defenders(); + LOGGER.debug("CombatDefendTask characters = " + characters); + + if (characters.length > 0) + { + var resolveShadowEffectFunction = this.resolveShadowEffect.bind(this); + var myCallback = function(defender) + { + resolveShadowEffectFunction(attacker, defender, callback); + }; + + agent.chooseCharacterDefender(attacker, characters, myCallback); + } + else + { + this.resolveShadowEffect(attacker, undefined, callback); + } +}; + +CombatDefendTask.prototype.resolveShadowEffect = function(attacker, defender, callback) +{ + LOGGER.debug("CombatDefendTask.resolveShadowEffect() defender = " + defender); + + var store = this.store(); + + if (defender !== undefined) + { + store.dispatch(CardAction.setReady(defender, false)); + } + + // 3. Resolve shadow effect, if any. + var shadowCards = attacker.shadowCards(); + + if (shadowCards.length > 0) + { + var determineCombatDamage = this.determineCombatDamage.bind(this); + var myCallback = function() + { + determineCombatDamage(attacker, defender, callback); + }; + var elementFunction = function(cardInstance, queueCallback) + { + store.dispatch(CardAction.setFaceUp(cardInstance, true)); + var context = { + cardInstance: attacker, + shadowInstance: cardInstance, + }; + store.dispatch(Action.enqueueEvent(GameEvent.SHADOW_CARD_REVEALED, context, queueCallback)); + }; + var delay = store.getState().delay; + + var queueProcessor = new QueueProcessor(shadowCards, myCallback, elementFunction, undefined, delay); + queueProcessor.processQueue(); + } + else + { + this.determineCombatDamage(attacker, defender, callback); + } +}; + +CombatDefendTask.prototype.determineCombatDamage = function(attacker, defender, callback) +{ + // 4. Determine combat damage. + var agent = this.agent(); + LOGGER.debug("CombatDefendTask attacker = " + attacker); + LOGGER.debug("CombatDefendTask defender = " + defender); + var attack = attacker.attack(); + + if (defender !== undefined) + { + var defense = defender.defense(); + var damage = attack - defense; + LOGGER.debug("CombatDefendTask damage = " + damage); + var store = this.store(); + store.dispatch(Action.setUserMessage("Defender combat damage: " + damage)); + agent.addCardWounds(defender, damage); + + this.processQueue(callback); + } + else + { + // Undefended. + var heroes = agent.tableauHeroes(); + if (heroes.length > 0) + { + var finishUndefendedDamageFunction = this.finishUndefendedDamage.bind(this); + var myCallback = function(hero) + { + finishUndefendedDamageFunction(attacker, hero, callback); + }; + + agent.chooseUndefendedAttackHero(attacker, heroes, myCallback); + } + else + { + this.processQueue(callback); + } + } +}; + +CombatDefendTask.prototype.finishUndefendedDamage = function(attacker, hero, callback) +{ + var agent = this.agent(); + var attack = attacker.attack(); + LOGGER.debug("CombatDefendTask undefended damage = " + attack); + agent.addCardWounds(hero, attack); + + this.processQueue(callback); +}; + +CombatDefendTask.prototype.finishPhase = function(callback) +{ + InputValidator.validateNotNull("callback", callback); + + callback(); +}; + +export default CombatDefendTask; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004764_AchievementState.js b/pool/shard000/JavaScript/0004764_AchievementState.js new file mode 100644 index 0000000000000000000000000000000000000000..ae53c96fc59ed433ac042fbd8370a2e45fd5007e --- /dev/null +++ b/pool/shard000/JavaScript/0004764_AchievementState.js @@ -0,0 +1,66 @@ +// Copy this file, rename to name of state and add to StateManager +function AchievementState() { +}; + +AchievementState.prototype.init = function() { + this.elements = []; + var source = $("#achievements-list-template").html(); + this.template = Handlebars.compile(source); + + this.achievement_data = new Achievements(); +}; + +AchievementState.prototype.pause = function() { + $('#wrapper').empty().removeClass('achievements'); + $('.back-button').off('click'); +}; + +AchievementState.prototype.resume = function() { + var achievements = this.getAchievements(); + + var html = this.template({achievements: achievements}); + + this.$achievement_template = $('.achievements.template').clone() + .removeClass('template'); + this.$achievement_template.html(html); + $('#wrapper').addClass('achievements').append(this.$achievement_template); + + $('.back-button').on('click touchstart', function() { + sm.changeState('menu'); + }); +}; + +AchievementState.prototype.render = function(ctx) { +}; + +AchievementState.prototype.update = function() { + if (KEYS[27]) { + sm.changeState("menu"); + } +}; + +AchievementState.prototype.getAchievements = function() { + var json_data = getCookie("cuteanimals_stats"); + if (json_data === undefined) { + return [ + { + name: "No achievements", + description: "You should try the game, and come back later!", + custom_image: "default" + } + ]; + } + var data = JSON.parse(json_data); + var uniqueNames = []; + $.each(data.achievements, function(i, el) { + if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); + }); + var achievements = []; + for (var i = 0; i < uniqueNames.length; i++) { + achievements[i] = this.achievement_data.achievements[uniqueNames[i]]; + if (achievements[i].custom_image === undefined) { + achievements[i].custom_image = uniqueNames[i]; + } + } + return achievements; +}; diff --git a/pool/shard000/JavaScript/0004765_index.js b/pool/shard000/JavaScript/0004765_index.js new file mode 100644 index 0000000000000000000000000000000000000000..be76911791b8b24421c950a704ced42a87ce012b --- /dev/null +++ b/pool/shard000/JavaScript/0004765_index.js @@ -0,0 +1,20 @@ +(function(){ + 'use strict'; + + var db = document.body, + dd = document.documentElement; + + var beforeScrollTop = db.scrollTop || dd.scrollTop; + + window.addEventListener('scroll', function(event) { + var scrollTop = db.scrollTop || dd.scrollTop; + + if (scrollTop > beforeScrollTop) { + console.log('scroll down'); + } else { + console.log('scroll up'); + } + + beforeScrollTop = scrollTop; + }); +}()); diff --git a/pool/shard000/JavaScript/0004769_StudentCal.js b/pool/shard000/JavaScript/0004769_StudentCal.js new file mode 100644 index 0000000000000000000000000000000000000000..cbf9e6cc3efe38cf341d5f05ede0cdd0817cc3c1 --- /dev/null +++ b/pool/shard000/JavaScript/0004769_StudentCal.js @@ -0,0 +1,98 @@ +//StudentCal.js +import React, { Component } from 'react'; +import BigCalendar from 'react-big-calendar'; +import axios from 'axios'; +import moment from 'moment'; +import 'react-big-calendar/lib/css/react-big-calendar.css'; + +function convertEvent(event) { + return { + title: "Shift", + start: new Date(event.start), + end: new Date(event.end), + hexColor: event.hexColor + } +} + +BigCalendar.setLocalizer( + BigCalendar.momentLocalizer(moment) +); +var origin = window.location.origin; + +class StudentCal extends Component { + constructor() { + super(); + + let timeRangeFormat = ({ start, end }, culture, local)=> + local.format(start, 'h:mm', culture) + + '-' + local.format(end, 'h:mm', culture) + let dayFormat = 'ddd MM/DD'; + let formats = { + dayFormat:dayFormat, + eventTimeRangeFormat: timeRangeFormat + }; + + let scrollToTime = new Date().setHours(7); + + this.retrieveEvents(); + this.state = { + format: formats, + scrollTime : scrollToTime, + events: [{}] + }; + + this.retrieveEvents = this.retrieveEvents.bind(this); + this.eventStyleGetter = this.eventStyleGetter.bind(this); + } + + retrieveEvents() { + var url = origin + '/api/studentcalendar'; + axios.get(url) + .then(res => { + var jsevents = res.data.events.map( + event => convertEvent(event)); + var newevents = this.state.events.concat(jsevents); + this.setState({ events: newevents }); + }) + .catch(function (error) { + console.log(error); + }); + } + + eventStyleGetter(event) { + console.log(event); + var backgroundColor = event.hexColor; + var style = { + backgroundColor: backgroundColor, + borderRadius: '0px', + opacity: 0.8, + color: 'black', + border: '0px', + display: 'block' + }; + return { + style: style + }; + } + + render() { + const now = moment(); + return ( +
      + alert(event.title + event.hexColor)} + eventPropGetter={(this.eventStyleGetter)} + /> +
      + ) + } +} + +export default StudentCal; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004770_mathjaxutils.js b/pool/shard000/JavaScript/0004770_mathjaxutils.js new file mode 100644 index 0000000000000000000000000000000000000000..e98158fab2ff21d13aee8ed6e1408adbcf134fed --- /dev/null +++ b/pool/shard000/JavaScript/0004770_mathjaxutils.js @@ -0,0 +1,212 @@ +// Copyright (c) Jupyter Development Team. +// Distributed under the terms of the Modified BSD License. + +define([ + 'jquery', + 'base/js/utils', + 'base/js/dialog', +], function($, utils, dialog) { + "use strict"; + + var init = function () { + if (window.MathJax) { + // MathJax loaded + MathJax.Hub.Config({ + tex2jax: { + inlineMath: [ ['$','$'], ["\\(","\\)"] ], + displayMath: [ ['$$','$$'], ["\\[","\\]"] ], + processEscapes: true, + processEnvironments: true + }, + // Center justify equations in code and markdown cells. Elsewhere + // we use CSS to left justify single line equations in code cells. + displayAlign: 'center', + "HTML-CSS": { + availableFonts: [], + imageFont: null, + preferredFont: null, + webFont: "STIX-Web", + styles: {'.MathJax_Display': {"margin": 0}}, + linebreaks: { automatic: true } + } + }); + MathJax.Hub.Configured(); + } else if (window.mathjax_url !== "") { + // Don't have MathJax, but should. Show dialog. + dialog.modal({ + title : "Failed to retrieve MathJax from '" + window.mathjax_url + "'", + body : $("

      ").addClass('dialog').text( + "Math/LaTeX rendering will be disabled." + ), + buttons : { + OK : {class: "btn-danger"} + } + }); + } + }; + + // Some magic for deferring mathematical expressions to MathJax + // by hiding them from the Markdown parser. + // Some of the code here is adapted with permission from Davide Cervone + // under the terms of the Apache2 license governing the MathJax project. + // Other minor modifications are also due to StackExchange and are used with + // permission. + + var inline = "$"; // the inline math delimiter + + // MATHSPLIT contains the pattern for math delimiters and special symbols + // needed for searching for math in the text input. + var MATHSPLIT = /(\$\$?|\\(?:begin|end)\{[a-z]*\*?\}|\\[\\{}$]|[{}]|(?:\n\s*)+|@@\d+@@)/i; + + // The math is in blocks i through j, so + // collect it into one block and clear the others. + // Replace &, <, and > by named entities. + // For IE, put
      at the ends of comments since IE removes \n. + // Clear the current math positions and store the index of the + // math, then push the math string onto the storage array. + // The preProcess function is called on all blocks if it has been passed in + var process_math = function (i, j, pre_process, math, blocks) { + var block = blocks.slice(i, j + 1).join("").replace(/&/g, "&") // use HTML entity for & + .replace(//g, ">") // use HTML entity for > + ; + if (utils.browser === 'msie') { + block = block.replace(/(%[^\n]*)\n/g, "$1
      \n"); + } + while (j > i) { + blocks[j] = ""; + j--; + } + blocks[i] = "@@" + math.length + "@@"; // replace the current block text with a unique tag to find later + if (pre_process){ + block = pre_process(block); + } + math.push(block); + return blocks; + }; + + // Break up the text into its component parts and search + // through them for math delimiters, braces, linebreaks, etc. + // Math delimiters must match and braces must balance. + // Don't allow math to pass through a double linebreak + // (which will be a paragraph). + // + var remove_math = function (text) { + var math = []; // stores math strings for later + var start; + var end; + var last; + var braces; + + // Except for extreme edge cases, this should catch precisely those pieces of the markdown + // source that will later be turned into code spans. While MathJax will not TeXify code spans, + // we still have to consider them at this point; the following issue has happened several times: + // + // `$foo` and `$bar` are varibales. --> $foo ` and `$bar are variables. + + var hasCodeSpans = /`/.test(text), + de_tilde; + if (hasCodeSpans) { + text = text.replace(/~/g, "~T").replace(/(^|[^\\])(`+)([^\n]*?[^`\n])\2(?!`)/gm, function (wholematch) { + return wholematch.replace(/\$/g, "~D"); + }); + de_tilde = function (text) { + return text.replace(/~([TD])/g, function (wholematch, character) { + return { T: "~", D: "$" }[character]; + }); + }; + } else { + de_tilde = function (text) { return text; }; + } + + var blocks = utils.regex_split(text.replace(/\r\n?/g, "\n"),MATHSPLIT); + + for (var i = 1, m = blocks.length; i < m; i += 2) { + var block = blocks[i]; + if (block.charAt(0) === "@") { + // + // Things that look like our math markers will get + // stored and then retrieved along with the math. + // + blocks[i] = "@@" + math.length + "@@"; + math.push(block); + } + else if (start) { + // + // If we are in math, look for the end delimiter, + // but don't go past double line breaks, and + // and balance braces within the math. + // + if (block === end) { + if (braces) { + last = i; + } + else { + blocks = process_math(start, i, de_tilde, math, blocks); + start = null; + end = null; + last = null; + } + } + else if (block.match(/\n.*\n/)) { + if (last) { + i = last; + blocks = process_math(start, i, de_tilde, math, blocks); + } + start = null; + end = null; + last = null; + braces = 0; + } + else if (block === "{") { + braces++; + } + else if (block === "}" && braces) { + braces--; + } + } + else { + // + // Look for math start delimiters and when + // found, set up the end delimiter. + // + if (block === inline || block === "$$") { + start = i; + end = block; + braces = 0; + } + else if (block.substr(1, 5) === "begin") { + start = i; + end = "\\end" + block.substr(6); + braces = 0; + } + } + } + if (last) { + blocks = process_math(start, last, de_tilde, math, blocks); + start = null; + end = null; + last = null; + } + return [de_tilde(blocks.join("")), math]; + }; + + // + // Put back the math strings that were saved, + // and clear the math array (no need to keep it around). + // + var replace_math = function (text, math) { + text = text.replace(/@@(\d+)@@/g, function (match, n) { + return math[n]; + }); + return text; + }; + + var mathjaxutils = { + init : init, + remove_math : remove_math, + replace_math : replace_math + }; + + return mathjaxutils; +}); diff --git a/pool/shard000/JavaScript/0004771_RemoteSwitch.js b/pool/shard000/JavaScript/0004771_RemoteSwitch.js new file mode 100644 index 0000000000000000000000000000000000000000..55d5b4023c12bff3552be4c6ad9ecfaf608d2f5e --- /dev/null +++ b/pool/shard000/JavaScript/0004771_RemoteSwitch.js @@ -0,0 +1,48 @@ +module.exports = function (five) { + return (function () { + function RemoteSwitch (opts) { + if (!(this instanceof RemoteSwitch)) { + return new RemoteSwitch(opts); + } + five.Board.Component.call(this, opts = five.Board.Options(opts)); + + this.pins = opts.pins; + this.duration = opts.duration || 500; + this.isOn = undefined; + this.isActive = false; + this.queue = []; + + this.io.pinMode(this.pins.on, this.io.MODES.OUTPUT); + this.io.pinMode(this.pins.off, this.io.MODES.OUTPUT); + } + + RemoteSwitch.prototype.toggle = function (turnOn) { + if (this.isActive) { + this.queue.push(turnOn); + return; + } + this.isActive = true; + if (typeof turnOn === 'undefined') { + turnOn = !this.isOn; + } + const pin = (turnOn) ? this.pins.on : this.pins.off; + this.io.digitalWrite(pin, 1); + setTimeout(() => { + this.io.digitalWrite(pin, 0); + this.isActive = false; + this.isOn = !!turnOn; + if (this.queue.length) { + this.toggle(this.queue.shift()); + } + }, this.duration); + }; + + RemoteSwitch.prototype.on = function () { + this.toggle(true); + }; + RemoteSwitch.prototype.off = function () { + this.toggle(false); + }; + return RemoteSwitch; + }()); +}; diff --git a/pool/shard000/JavaScript/0004774_tcp.js b/pool/shard000/JavaScript/0004774_tcp.js new file mode 100644 index 0000000000000000000000000000000000000000..76d2aebe8eb10b3caebdbe6e3af6f3a72b6c3f79 --- /dev/null +++ b/pool/shard000/JavaScript/0004774_tcp.js @@ -0,0 +1,37 @@ + +var expect = require('must'); +var protocol = require('../lib/main'); +var MockApi = require('./mock-api'); +var MockAuth = require('./mock-auth'); +var net = require('net'); + +describe('tcp access', function() { + var instance; + var api; + var auth; + var logger = { + info: function() {}, + error: function() {} + } + var server; + + beforeEach(function(done) { + api = new MockApi(); + auth = new MockAuth(); + server = protocol().start(api, auth, logger); + server.on('listening', function() { + instance = net.connect({ host: 'localhost', port: 3223 }); + done(); + }) + }); + + it('must handle unknown commands', function(done) { + + instance.on('data', function(data) { + expect(data.toString()).to.eql('no such command\n'); + done(); + }); + + instance.write('unknown command\n') + }); +}); diff --git a/pool/shard000/JavaScript/0004775_bootstrap.js b/pool/shard000/JavaScript/0004775_bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8d31756e0841513fd92a5ac1e2a3d080980915 --- /dev/null +++ b/pool/shard000/JavaScript/0004775_bootstrap.js @@ -0,0 +1,22 @@ +const puppeteer = require('puppeteer'); + +// puppeteer options +const opts = { + headless: true, + args: ['--no-sandbox', '--disable-setuid-sandbox'] +}; + +let chrome; + +// expose variables +before (async function () { + chrome = await puppeteer.launch(opts); + global.browser = await chrome.newPage(); + browser.on('console', msg => console.log('PAGE LOG:', msg.text())); + await browser.goto(`file://${__dirname}/test.html`); +}); + +// close browser and reset global variables +after (async function () { + await chrome.close(); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004777_2d.transformation.transform.multiply.worker.js b/pool/shard000/JavaScript/0004777_2d.transformation.transform.multiply.worker.js new file mode 100644 index 0000000000000000000000000000000000000000..a764edddcc5e5960a10ba96a7593b134f952e156 --- /dev/null +++ b/pool/shard000/JavaScript/0004777_2d.transformation.transform.multiply.worker.js @@ -0,0 +1,29 @@ +// DO NOT EDIT! This test has been generated by /offscreen-canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.transformation.transform.multiply +// Description:transform() multiplies the CTM +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/2dcontext/resources/canvas-tests.js"); + +var t = async_test("transform() multiplies the CTM"); +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.fillRect(0, 0, 100, 50); +ctx.transform(1,2, 3,4, 5,6); +ctx.transform(-2,1, 3/2,-1/2, 1,-2); +ctx.fillStyle = '#0f0'; +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/shard000/JavaScript/0004780_errors.js b/pool/shard000/JavaScript/0004780_errors.js new file mode 100644 index 0000000000000000000000000000000000000000..eb6c49bb7517d998326b175883bfa3674bdb2651 --- /dev/null +++ b/pool/shard000/JavaScript/0004780_errors.js @@ -0,0 +1,77 @@ +var PROVIDER = { + name: "errors", + collection: "errorMetrics", + rawCollection: "rawErrorMetrics", + scope: {}, + + map: function() { + var self = this; + var timeWithSeconds = new Date(this.value.startTime); + var timeSeconds = timeWithSeconds % (PROFILE.timeRange); + var time = new Date(timeWithSeconds - timeSeconds); + var appId = this.value.appId; + var name = this.value.name || ""; + var type = this.value.type; + var subType = this.value.subType; + + // only pick the last 300 chars + name = name.substring(0, 300); + + var key = { + appId: appId, + name: name, + type: type, + subType: subType, + time: time, + // need to add the resolution, otherwise it will confilict with + // other resolutions + res: PROFILE.name + }; + + var value = { + count: this.value.count || 1, + _expires: self.value._expires || new Date(Date.now() + 1000*60*60*24*2), + subShard: self.value.subShard || 0 + }; + + emit(key, value); + return [key, value]; + }, + + reduce: function(key, values) { + var reducedVal = {count: 0, _expires: new Date()}; + + values.forEach(function(value) { + reducedVal.count += value.count; + if(value._expires.getTime() > reducedVal._expires.getTime()) { + reducedVal._expires = value._expires; + } + }); + + if (values[0]) { + reducedVal.subShard = values[0].subShard || 0; + } else { + reducedVal.subShard = 0; + } + + + return reducedVal; + }, + + finalize: function(key, reducedVal) { + var finalValue = { + appId: key.appId, + name: key.name, + type: key.type, + subType: key.subType, + startTime: key.time, + count: reducedVal.count, + res: PROFILE.name, + subShard: reducedVal.subShard || 0 + }; + + finalValue._expires = reducedVal._expires || new Date(Date.now() + 1000*60*60*24*2); + + return finalValue; + } +} diff --git a/pool/shard000/JavaScript/0004787_test.js b/pool/shard000/JavaScript/0004787_test.js new file mode 100644 index 0000000000000000000000000000000000000000..2507968c58330a9ac22603c160a1367333097fcb --- /dev/null +++ b/pool/shard000/JavaScript/0004787_test.js @@ -0,0 +1,111 @@ +var assert = require('assert') +var path = require('path') +var fs = require('fs-extra') + +var proxyquire = require('proxyquire').noCallThru() +var _ = require('underscore') +var Q = require('q') +var broccoli = require('broccoli') + +var BroccoliKarma = proxyquire('..', { + // Normally karma dependency is on the same level as plugin, + // but we can't have it in test. + '../karma': require('karma'), +}) + +describe('broccoli-karma', function() { + this.timeout(8000) + + var ORIG_DIR = path.join(__dirname, 'files') + var DIR = path.join(__dirname, 'files-copy') + + var fakeReporter = require(path.join(__dirname, 'fakeReporter')) + + var OPTIONS = { + files: ['ok.js'], + browsers: ['PhantomJS'], + frameworks: ['mocha'], + plugins: [ + 'karma-mocha', + 'karma-phantomjs-launcher', + path.join(__dirname, 'fakeReporter') + ], + reporters: ['fake', 'progress'], + singleRun: true + } + + var FAIL_OPTIONS = _.extend({}, OPTIONS, { files: ['fail.js'] }) + + var builder + + beforeEach(function() { + // Copy files because we change them to trigger autoWatch + fs.copySync(ORIG_DIR, DIR) + }) + + afterEach(function() { + if (builder) builder.cleanup() + fs.removeSync(DIR) + fakeReporter.spy.reset() + }) + + it('runs tests and exit in singleRun', function() { + var tree = BroccoliKarma(DIR, OPTIONS) + builder = new broccoli.Builder(tree) + return builder.build(). + then(function() { + var results = fakeReporter.spy.firstCall.args[0].getResults() + assert.equal(results.success, 1) + }) + }) + + it('fails build when test fails in singleRun', function(done) { + var tree = BroccoliKarma(DIR, FAIL_OPTIONS) + builder = new broccoli.Builder(tree) + builder.build() + .then(function() { + done(new Error('Build did not failed')) + }) + .catch(function(error) { + assert.equal(error.message, 'Karma exited with error') + var results = fakeReporter.spy.firstCall.args[0].getResults() + assert.equal(results.failed, 1) + done() + }) + }) + + it('runs karma in background without singleRun', function() { + var options = _.extend({}, OPTIONS, {singleRun: false}) + var tree = BroccoliKarma(DIR, options) + builder = new broccoli.Builder(tree) + // 1. build + return builder.build() + // 2. wait until tests ran + .then(function() { + var deferred = Q.defer() + fakeReporter.callback = function() { deferred.resolve() } + return deferred.promise + }) + .then(function() { + // 3. test should be run + var results = fakeReporter.spy.firstCall.args[0].getResults() + assert.equal(results.success, 1) + // 4. change file + fs.appendFileSync(path.join(DIR, 'ok.js'), ';') + // 5. build again + return builder.build() + }) + // 6. wait until tests run again + .then(function() { + var deferred = Q.defer() + fakeReporter.callback = function() { deferred.resolve() } + return deferred.promise + }) + // 7. test should be run again + .then(function() { + var results = fakeReporter.spy.secondCall.args[0].getResults() + assert.equal(results.success, 1) + }) + }) + +}) diff --git a/pool/shard000/JavaScript/0004788_editor_template_src.js b/pool/shard000/JavaScript/0004788_editor_template_src.js new file mode 100644 index 0000000000000000000000000000000000000000..d8a926cd439665eeef115ef4c2b71013467fe27a --- /dev/null +++ b/pool/shard000/JavaScript/0004788_editor_template_src.js @@ -0,0 +1,103 @@ +/* + * 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. + */ + +/** + * editor_template_src.js + * + * Copyright 2009, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://tinymce.moxiecode.com/license + * Contributing: http://tinymce.moxiecode.com/contributing + */ + +(function() { + var DOM = tinymce.DOM; + + // Tell it to load theme specific language pack(s) + tinymce.ThemeManager.requireLangPack('simple'); + + tinymce.create('tinymce.themes.SimpleTheme', { + init : function(ed, url) { + var t = this, states = ['Bold', 'Italic', 'Underline', 'Strikethrough', 'InsertUnorderedList', 'InsertOrderedList'], s = ed.settings; + + t.editor = ed; + ed.contentCSS.push(url + "/skins/" + s.skin + "/content.css"); + + ed.onInit.add(function() { + ed.onNodeChange.add(function(ed, cm) { + tinymce.each(states, function(c) { + cm.get(c.toLowerCase()).setActive(ed.queryCommandState(c)); + }); + }); + }); + + DOM.loadCSS((s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : '') || url + "/skins/" + s.skin + "/ui.css"); + }, + + renderUI : function(o) { + var t = this, n = o.targetNode, ic, tb, ed = t.editor, cf = ed.controlManager, sc; + + n = DOM.insertAfter(DOM.create('span', {id : ed.id + '_container', 'class' : 'mceEditor ' + ed.settings.skin + 'SimpleSkin'}), n); + n = sc = DOM.add(n, 'table', {cellPadding : 0, cellSpacing : 0, 'class' : 'mceLayout'}); + n = tb = DOM.add(n, 'tbody'); + + // Create iframe container + n = DOM.add(tb, 'tr'); + n = ic = DOM.add(DOM.add(n, 'td'), 'div', {'class' : 'mceIframeContainer'}); + + // Create toolbar container + n = DOM.add(DOM.add(tb, 'tr', {'class' : 'last'}), 'td', {'class' : 'mceToolbar mceLast', align : 'center'}); + + // Create toolbar + tb = t.toolbar = cf.createToolbar("tools1"); + tb.add(cf.createButton('bold', {title : 'simple.bold_desc', cmd : 'Bold'})); + tb.add(cf.createButton('italic', {title : 'simple.italic_desc', cmd : 'Italic'})); + tb.add(cf.createButton('underline', {title : 'simple.underline_desc', cmd : 'Underline'})); + tb.add(cf.createButton('strikethrough', {title : 'simple.striketrough_desc', cmd : 'Strikethrough'})); + tb.add(cf.createSeparator()); + tb.add(cf.createButton('undo', {title : 'simple.undo_desc', cmd : 'Undo'})); + tb.add(cf.createButton('redo', {title : 'simple.redo_desc', cmd : 'Redo'})); + tb.add(cf.createSeparator()); + tb.add(cf.createButton('cleanup', {title : 'simple.cleanup_desc', cmd : 'mceCleanup'})); + tb.add(cf.createSeparator()); + tb.add(cf.createButton('insertunorderedlist', {title : 'simple.bullist_desc', cmd : 'InsertUnorderedList'})); + tb.add(cf.createButton('insertorderedlist', {title : 'simple.numlist_desc', cmd : 'InsertOrderedList'})); + tb.renderTo(n); + + return { + iframeContainer : ic, + editorContainer : ed.id + '_container', + sizeContainer : sc, + deltaHeight : -20 + }; + }, + + getInfo : function() { + return { + longname : 'Simple theme', + author : 'Moxiecode Systems AB', + authorurl : 'http://tinymce.moxiecode.com', + version : tinymce.majorVersion + "." + tinymce.minorVersion + } + } + }); + + tinymce.ThemeManager.add('simple', tinymce.themes.SimpleTheme); +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004789_file.js b/pool/shard000/JavaScript/0004789_file.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc141a267c48f5f188009e8ddaa53c5855f7c87 --- /dev/null +++ b/pool/shard000/JavaScript/0004789_file.js @@ -0,0 +1,28 @@ +define(['./module'], function (controllers) { + 'use strict'; + + controllers.controller('FileNewCtrl', ['$scope', '$state', function ($scope, $state) { + console.log("Loading file new controller"); + + $scope.dismiss = function() { + $scope.$dismiss(); + }; + + $scope.create = function() { + // Perform save action here + $scope.$close(true); + }; + + }]); + + controllers.controller('FileOpenCtrl', ['$scope', '$state', function ($scope, $state) { + console.log("Loading file open controller"); + }]); + + controllers.controller('FileViewCtrl', ['$scope', '$state', '$stateParams', 'file', function ($scope, $state, $stateParams, file) { + console.log("Loading file view controller for file", file); + $scope.file = file; + $scope.path = $stateParams.path; + }]); + +}); diff --git a/pool/shard000/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js b/pool/shard000/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js new file mode 100644 index 0000000000000000000000000000000000000000..0eb579c841e0f493b80f97d8e77eb49113f0b46a --- /dev/null +++ b/pool/shard000/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js @@ -0,0 +1,60 @@ +// Given an unsorted array of integers, find the length of the longest consecutive elements sequence. + +// Your algorithm should run in O(n) complexity. + +// Example: + +// Input: [100, 4, 200, 1, 3, 2] +// Output: 4 +// Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. + +/** + * @param {number[]} nums + * @return {number} + * score:30.77(80ms) + * time:O(nlogn) + * space:O(n) + */ +var longestConsecutive = function (nums) { + nums = Array.from(new Set(nums)); + if (nums.length < 1) { + return 0; + } + nums.sort((a, b) => a - b); + let max = 1; + let cur = 1; + for (let i = 1; i < nums.length; i++) { + if (nums[i] - nums[i - 1] === 1) { + cur++; + } else { + if (cur > max) { + max = cur; + } + cur = 1; + } + } + + return Math.max(cur, max); +}; + +/** + * @param {number[]} nums + * @return {number} + * score:94.51(54ms) + * time:O(n) + * space:O(n) + */ +var longestConsecutive2 = function (nums) { + let best = 0; + let s = new Set(nums); + for (let i of s) { + if (!s.has(i - 1)) { + let cur = i + 1; + while (s.has(cur)) { + cur++; + } + best = Math.max(best, cur - i); + } + } + return best; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004793_Bonestore.test.js b/pool/shard000/JavaScript/0004793_Bonestore.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3970a6ab0a6a4ba636281706c5b7b4836ce8744c --- /dev/null +++ b/pool/shard000/JavaScript/0004793_Bonestore.test.js @@ -0,0 +1,119 @@ +import Bonestore from './Bonestore'; +import Store from './stores/Store'; +import CollectionStore from './stores/CollectionStore'; +import MemoryAdapter from './adapters/MemoryAdapter'; + +describe('Bonestore', () => { + describe('model', () => { + it('should define store', () => { + const memoryAdapter = new MemoryAdapter(); + const data = new Bonestore(); + const store = new Store({ + adapter: memoryAdapter, + }); + data.defineStore('user', store); + expect(data.getStore('user')).toBe(store); + }); + it('should use default adapter', () => { + const memoryAdapter = new MemoryAdapter(); + const data = new Bonestore({ + defaultAdapter: memoryAdapter, + }); + data.defineStore('user', new Store()); + expect(data.getStore('user').adapter).toBe(memoryAdapter); + }); + it('should create and find data', () => { + const memoryAdapter = new MemoryAdapter(); + const data = new Bonestore(); + data.defineStore('user', new Store({ + adapter: memoryAdapter, + })); + return data.getStore('user') + .create({ name: 'Test' }) + .then((newUser) => { + expect(newUser.name).toBe('Test'); + return data.getStore('user').find().then((user) => { + expect(user.name).toBe('Test'); + }); + }); + }); + }); + + describe('collection', () => { + it('should create new id in collections', () => { + const data = new Bonestore(); + data.defineStore('posts', new CollectionStore({ + adapter: new MemoryAdapter(), + })); + return data.getStore('posts') + .create({ topic: 'Test' }) + .then((newPost) => { + expect(newPost).toEqual({ + topic: 'Test', + id: expect.anything(), + }); + return data.getStore('posts').findAll().then((posts) => { + expect(posts[0]).toEqual({ + topic: 'Test', + id: expect.anything(), + }); + }); + }); + }); + }); + + describe('events', () => { + let data; + beforeEach(() => { + data = new Bonestore({ + defaultAdapter: new MemoryAdapter(), + }); + data.defineStore('user', new Store({})); + }); + it('should emit create event', () => + new Promise((resolve) => { + data.onStoreChange('user', (storeName, changeType, payload) => { + expect(storeName).toBe('user'); + expect(changeType).toBe('create'); + expect(payload.name).toBe('Test'); + resolve(); + }); + data.getStore('user').create({ name: 'Test' }); + }) + ); + it('should emit update event', () => + new Promise((resolve) => { + data.onStoreChange('user', (storeName, changeType, payload) => { + expect(changeType).toBe('update'); + expect(payload.name).toBe('Test'); + resolve(); + }); + data.getStore('user').update({ name: 'Test' }); + }) + ); + it('should emit delete event', () => + new Promise((resolve) => { + data.onStoreChange('user', (storeName, changeType) => { + expect(changeType).toBe('delete'); + resolve(); + }); + data.getStore('user').delete(); + }) + ); + it('should not emit event', () => + new Promise((resolve) => { + let emited = false; + const listener = () => { + emited = true; + }; + data.onStoreChange('user', listener); + data.offStoreChange('user', listener); + data.getStore('user').delete(); + setTimeout(() => { + expect(emited).toBe(false); + resolve(); + }, 1); + }) + ); + }); +}); diff --git a/pool/shard000/JavaScript/0004797_marquee.js b/pool/shard000/JavaScript/0004797_marquee.js new file mode 100644 index 0000000000000000000000000000000000000000..76e5959ab288d8fcf02d6667551428a2eb489746 --- /dev/null +++ b/pool/shard000/JavaScript/0004797_marquee.js @@ -0,0 +1,77 @@ + + $('#text').bind('input', function() { + startAnim(); // get the current value of the input field. + }); + + var letters_red = null, + sMessage = "", + canvas = null, + ctx = null, + LETTER_HEIGHT = 350, + LETTER_WIDTH = 266.7, + iStep = 0, + iDrawPhase = 0, + job = null; + + function drawLetter(iSpriteRow, iSpriteCol, iPos) { + var xPos = (LETTER_WIDTH * iPos) - iStep; + if ((xPos > 0 - LETTER_WIDTH) && (xPos < 1200 + LETTER_WIDTH)) { + ctx.drawImage(letters_red, iSpriteCol * LETTER_WIDTH, iSpriteRow, LETTER_WIDTH, LETTER_HEIGHT, xPos, 0, LETTER_WIDTH, LETTER_HEIGHT); + } + } + + function draw() { + var iCounter = 0, + iCharCode = 0, + iSpriteCol = 0, + iSpriteRow = 0; + for ( iCounter = 0; iCounter < sMessage.length; iCounter++) { + iCharCode = sMessage.charCodeAt(iCounter); + if (iCharCode > 64 && iCharCode < 91) { + iSpriteCol = Math.abs(65 - iCharCode) ; + iSpriteRow = 0; + } else { + iSpriteCol = 26; + iSpriteRow = 0; + } + drawLetter(iSpriteRow, iSpriteCol, iCounter); + } + iSpriteCol = 1; + iSpriteRow = 5; + for (iCounter; iCounter < sMessage.length; iCounter++) { + drawLetter(iSpriteCol, iSpriteRow, iCounter); + } + iDrawPhase += 1; + iStopPoint = (8 * sMessage.length); + console.log('stop:'+iStopPoint); + console.log('draw:'+iDrawPhase); + if (iDrawPhase < iStopPoint) { + iStep += 38.2; + } else { + clearInterval(job); + startAnim(); + } + } + + function startAnim() { + clearInterval(job); + sMessage = document.getElementById('text').value.toUpperCase(); + iDrawPhase = 0; + iStep = 0; + // Add 5 spaces padding so the text start off right + sMessage = " " + sMessage; + // Start the timer + job = setInterval(draw, 100); + } + + function init() { + canvas = document.getElementById('led'); + if (canvas.getContext('2d')) { + ctx = canvas.getContext('2d'); + letters_red = new Image(); + letters_red.src = 'letters-red.jpg?v=1'; + letters_red.onload = startAnim; + } else { + alert("Canvas not supported!"); + } + } \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004799_present.js b/pool/shard000/JavaScript/0004799_present.js new file mode 100644 index 0000000000000000000000000000000000000000..f50153828b14f2011cdf2f1955adcca62739fc8f --- /dev/null +++ b/pool/shard000/JavaScript/0004799_present.js @@ -0,0 +1,264 @@ +// { "framework": "Vue" } +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ 0: +/***/ (function(module, exports, __webpack_require__) { + + var __vue_exports__, __vue_options__ + var __vue_styles__ = [] + + /* styles */ + __vue_styles__.push(__webpack_require__(45) + ) + __vue_styles__.push(__webpack_require__(46) + ) + + /* script */ + __vue_exports__ = __webpack_require__(47) + + /* template */ + var __vue_template__ = __webpack_require__(48) + __vue_options__ = __vue_exports__ = __vue_exports__ || {} + if ( + typeof __vue_exports__.default === "object" || + typeof __vue_exports__.default === "function" + ) { + if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} + __vue_options__ = __vue_exports__ = __vue_exports__.default + } + if (typeof __vue_options__ === "function") { + __vue_options__ = __vue_options__.options + } + __vue_options__.__file = "/Users/zhengjiangrong/Desktop/ok/src/present.vue" + __vue_options__.render = __vue_template__.render + __vue_options__.staticRenderFns = __vue_template__.staticRenderFns + __vue_options__._scopeId = "data-v-eb374494" + __vue_options__.style = __vue_options__.style || {} + __vue_styles__.forEach(function (module) { + for (var name in module) { + __vue_options__.style[name] = module[name] + } + }) + if (typeof __register_static_styles__ === "function") { + __register_static_styles__(__vue_options__._scopeId, __vue_styles__) + } + + module.exports = __vue_exports__ + module.exports.el = 'true' + new Vue(module.exports) + + +/***/ }), + +/***/ 45: +/***/ (function(module, exports) { + + module.exports = { + "text": { + "fontSize": 50 + } + } + +/***/ }), + +/***/ 46: +/***/ (function(module, exports) { + + module.exports = { + "header": { + "backgroundColor": "#FF0000", + "flex": 1, + "flexDirection": "row" + }, + "tz": { + "color": "#FF0000" + }, + "logo": { + "width": 300, + "height": 300, + "marginTop": 80 + }, + "k1": { + "alignItems": "center" + }, + "titleback": { + "flex": 1, + "alignItems": "center" + }, + "title": { + "color": "#FFFFFF", + "flex": 1, + "marginTop": 73, + "fontWeight": "bold" + }, + "leftimage": { + "width": 30, + "height": 45, + "bottom": 25, + "left": 30, + "position": "absolute" + }, + "rightimage": { + "width": 45, + "height": 45, + "bottom": 23, + "right": 32, + "position": "absolute" + }, + "bottomline": { + "height": 1, + "backgroundColor": "#000000", + "position": "absolute", + "bottom": 0, + "left": 0, + "right": 0, + "flex": 1 + }, + "btn": { + "backgroundColor": "#0085ee", + "height": 100, + "width": 200, + "marginTop": 50, + "borderRadius": 10, + "alignItems": "center", + "justifyContent": "center", + "backgroundColor:active": "#006ce7" + } + } + +/***/ }), + +/***/ 47: +/***/ (function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + + + exports.default = { + data: function data() { + return { + text: 'Hello World.', + param: '' + }; + }, + + methods: { + ok: function ok() { + + this.param = "dsds"; + }, + dismiss: function dismiss() { + var navigator = weex.requireModule('navigator'); + navigator.dismissFull({ ok: this.param }, true); + } + }, + + created: function created() { + + var self = this; + var globalEvent = weex.requireModule('globalEvent'); + globalEvent.addEventListener("onPageInit", function (e) { + + var nav = weex.requireModule('navbar'); + nav.setTitle('带参数页面'); + nav.setTitleColor('#ffffff'); + nav.setBack(true); + nav.setBackgroundColor('#000000'); + nav.setRightImage('img/scan.png', function (res) { + + modal.alert({ message: "ok" }); + }); + var navigator = weex.requireModule('navigator'); + self.param = navigator.param().a; + }); + } + }; + module.exports = exports['default']; + +/***/ }), + +/***/ 48: +/***/ (function(module, exports) { + + module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; + return _c('div', [_c('text', [_vm._v("参数值:" + _vm._s(_vm.param))]), _c('div', { + staticClass: ["btn"], + on: { + "click": function($event) { + _vm.dismiss() + } + } + }, [_c('text', { + staticStyle: { + color: "white" + } + }, [_vm._v("(dismiss);返回")])])]) + },staticRenderFns: []} + module.exports.render._withStripped = true + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004800_SongPlayer.js b/pool/shard000/JavaScript/0004800_SongPlayer.js new file mode 100644 index 0000000000000000000000000000000000000000..4a3c98fe6722afeeaa9794eaacfc4dbc854e57d6 --- /dev/null +++ b/pool/shard000/JavaScript/0004800_SongPlayer.js @@ -0,0 +1,189 @@ +(function() { + /** + * @function SongPlayer + * @desc Factory to set up SongPlayer service + * @param {Object} Fixtures service + * @returns {Object} SongPlayer + */ + function SongPlayer($rootScope, Fixtures) { + var SongPlayer = {}; + + /** + * @desc Current Album object + * @type {Object} + */ + var currentAlbum = Fixtures.getAlbum(); + /** + * @desc Buzz object audio file + * @type {Object} + */ + var currentBuzzObject = null; + + /** + * @function setSong + * @desc Stops currently playing song and loads new audio file as currentBuzzObject + * @param {Object} song + */ + var setSong = function(song) { + if (currentBuzzObject) { + stopSong(); + } + + currentBuzzObject = new buzz.sound(song.audioUrl, { + formats: ['mp3'], + preload: true + }); + + currentBuzzObject.bind('timeupdate', function() { + $rootScope.$apply(function() { + SongPlayer.currentTime = currentBuzzObject.getTime(); + }); + }); + + SongPlayer.currentSong = song; + }; + + /** + * @function playSong + * @desc Plays song stored in currentBuzzObject and currentSong by SongPlayer.play + */ + var playSong = function() { + currentBuzzObject.play(); + SongPlayer.currentSong.playing = true; + }; + + /** + * @function stopSong + * @desc Stops the currently playing song + */ + var stopSong = function() { + currentBuzzObject.stop(); + SongPlayer.currentSong.playing = null; + }; + + /** + * @function getSongIndex + * @desc Returns the index of the currently playing song + * @param {Object} song + * @return {Number} + */ + var getSongIndex = function(song) { + return currentAlbum.songs.indexOf(song); + }; + + /** + * @desc Javascript song object from album.songs + * @type {Object} + */ + SongPlayer.currentSong = null; + + /** + * @desc Current playback time in seconds of currently playing song + * @type {Number} + */ + SongPlayer.currentTime = null; + + /** + * @desc Current volume for the SongPlayer + * @type {Number} + */ + SongPlayer.volume = 80; // default + + /** + * @function SongPlayer.play + * @desc Takes song object and determines how to play the song + * @param {Object} song + */ + SongPlayer.play = function(song) { + song = song || SongPlayer.currentSong; + if (SongPlayer.currentSong !== song) { + setSong(song); + playSong(); + } + + else if (SongPlayer.currentSong === song) + { + if (currentBuzzObject.isPaused()) { + playSong(); + } + } + }; + + /** + * @function SongPlayer.pause + * @desc Takes a song object and pauses it + * @param {Object} song + */ + SongPlayer.pause = function(song) { + song = song || SongPlayer.currentSong; + currentBuzzObject.pause(); + song.playing = false; + }; + + /** + * @function SongPlayer.previous + * @desc Sets the current song to the previous song in currentAlbum if possible, or stops the SongPlayer + */ + SongPlayer.previous = function() { + var currentSongIndex = getSongIndex(SongPlayer.currentSong); + currentSongIndex--; + + if (currentSongIndex < 0) { + stopSong(); + } + + else { + var song = currentAlbum.songs[currentSongIndex]; + setSong(song); + playSong(song); + } + } + + /** + * @function SongPlayer.next + * @desc Sets the current song to the next song in currentAlbum if possible, or stops the SongPlayer + */ + SongPlayer.next = function() { + var currentSongIndex = getSongIndex(SongPlayer.currentSong); + currentSongIndex++; + + if (currentSongIndex >= currentAlbum.songs.length) { + stopSong(); + } + + else { + var song = currentAlbum.songs[currentSongIndex]; + setSong(song); + playSong(song); + } + }; + + /** + * @function SongPlayer.setCurrentTime + * @desc Sets the time for the currently playing song if it exists + * @param {Number} time + */ + SongPlayer.setCurrentTime = function(time) { + if (currentBuzzObject) { + currentBuzzObject.setTime(time); + } + }; + + /** + * @function SongPlayer.setCurrentVolume + * @desc Sets the volume for the currently playing song if it exists + * @param {Number} volume + */ + SongPlayer.setVolume = function(volume) { + if (currentBuzzObject) { + currentBuzzObject.setVolume(volume); + } + }; + + return SongPlayer; + } + + angular + .module('blocJams') + .factory('SongPlayer',['$rootScope', 'Fixtures', SongPlayer]); +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004802_myro.js b/pool/shard000/JavaScript/0004802_myro.js new file mode 100644 index 0000000000000000000000000000000000000000..f17b73e9f6c641746803e85a05a90617e940566b --- /dev/null +++ b/pool/shard000/JavaScript/0004802_myro.js @@ -0,0 +1,150 @@ +import myro from '../src' + +describe('myro', function() { + + it('matches routes', function() { + const router = myro({ + '/foo/bar/:baz': 'foobarbaz', + '/foo/bar': 'foobar' + }); + + expect(router('/foo/bar').name).toEqual('foobar'); + + const bazMatch = router('/foo/bar/qux'); + expect(bazMatch.name).toEqual('foobarbaz'); + expect(bazMatch.params).toEqual({baz:'qux'}); + }); + + it('works recursively', function() { + const router = myro({ + '/foo': { + name: 'foo', + routes: { + '/bar': 'bar' + } + } + }); + expect(router('/foo').name).toEqual('foo'); + expect(router('/foo/bar').name).toEqual('foo.bar'); + }); + + it('is bidirectional', function() { + const router = myro({ + '/foo': { + name: 'foo', + routes: { + '/bar/:baz': 'bar' + } + } + }); + + expect(router.foo()).toEqual('/foo'); + expect(router.foo.bar({baz:'qux'})).toEqual('/foo/bar/qux'); + }); + + it('works with arbitrary payloads', function() { + const router = myro({ + '/foo': { + name: 'foo', + props: { + item1: 'data1', + item2: 'data2' + } + } + }); + const match = router('/foo'); + expect(match.props.item1).toEqual('data1'); + expect(match.props.item2).toEqual('data2'); + }); + + it('does partial matching', function() { + const router = myro({ + '/foo/bar': 'foo' + }); + const match = router('/foo/bar/baz'); + expect(match.route).toBe(router.foo); + expect(match.remaining).toEqual('/baz'); + }); + + it('matches sequentially', function() { + const router = myro({ + '/foo': 'foo', + '/foo/bar': 'foobar' + }); + expect(router('/foo/bar').name).toEqual('foo'); + }); + + it('provides a parent chain', function() { + const route = myro({ + '/a': { + name: 'a', + props: {foo: 'prop-a'}, + routes: { + '/b': { + name: 'b', + props: {foo: 'prop-b'}, + routes: { + '/c': { + name: 'c', + props: {foo: 'prop-c'}, + routes: { + '/d': { + name: 'd', + props: {foo: 'prop-d'} + } + } + } + } + } + } + } + }) + const match = route('/a/b/c/d') + expect(match.props.foo).toEqual('prop-d') + expect(match.parent.props.foo).toEqual('prop-c') + expect(match.parent.parent.props.foo).toEqual('prop-b') + expect(match.parent.parent.parent.props.foo).toEqual('prop-a') + expect(match.parent.parent.parent.parent).toEqual(null) + }) + + it('merges params from parent and child', function() { + const route = myro({ + '/foo/:x': { + name: 'foo', + routes: { + '/bar/:y': 'bar' + } + } + }) + expect(route('/foo/x-val/bar/y-val').params).toEqual({x: 'x-val', y: 'y-val'}) + expect(route.foo({x: 'the-x'})).toEqual('/foo/the-x') + expect(route.foo.bar({x: 'the-x', y: 'the-y'})).toEqual('/foo/the-x/bar/the-y') + }) + + it('overwrites parent params with child params', function() { + const route = myro({ + '/foo/:x': { + name: 'foo', + routes: { + '/bar/:x': 'bar' + } + } + }) + const match = route('/foo/foo-val/bar/bar-val') + expect(match.params.x).toEqual('bar-val') + expect(match.parent.params.x).toEqual('foo-val') + }) + + it('matches root with empty string', function() { + const route = myro({ + '': { + name: 'foo', + routes: { + '/bar': 'bar' + } + } + }) + expect(route('/').name).toEqual('foo') + expect(route('/bar').name).toEqual('foo.bar') + }) +}); diff --git a/pool/shard000/JavaScript/0004809_helloworldSocketIO.js b/pool/shard000/JavaScript/0004809_helloworldSocketIO.js new file mode 100644 index 0000000000000000000000000000000000000000..81e5f2c6206913b08cb99f35b970c0488e4faef1 --- /dev/null +++ b/pool/shard000/JavaScript/0004809_helloworldSocketIO.js @@ -0,0 +1,13 @@ +var app = require('express')(); +var http = require('http').Server(app); +var io = require('socket.io')(http); + +io.on('connection', function (socket) { + socket.on('hello', function () { + console.log("HelloWorld!"); + }); +}); + +http.listen('3000', function(){ + console.log('Lisening on port 3000'); +}); diff --git a/pool/shard000/JavaScript/0004812_bundle.js b/pool/shard000/JavaScript/0004812_bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..c4db2a415e996832b501697738424a965646aa21 --- /dev/null +++ b/pool/shard000/JavaScript/0004812_bundle.js @@ -0,0 +1,63 @@ +/******/ (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) { + + 'use strict'; + + var labels = [1, 2, 3]; + var series = [[{ meta: 'description', value: 1 }, { meta: 'meta data', value: 5 }, { meta: 'woot woot', value: 3 }], [{ meta: 'foo', value: 2 }, { meta: 'bar', value: 4 }, { meta: 'some other', value: 2 }]]; + var plugins = [Chartist.plugins.lrTooltip({ + template: '

      {{meta}}

      $ {{y}}

      ', + labelOffset: { + x: 15 + } + })]; + + var chart = new Chartist.Bar('#myChart', { labels: labels, series: series }, { plugins: plugins, stackBars: true }); + var chartLine = new Chartist.Line('#myChartLine', { labels: labels, series: series }, { plugins: plugins }); + +/***/ } +/******/ ]); +//# sourceMappingURL=bundle.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004816_data-handling.js b/pool/shard000/JavaScript/0004816_data-handling.js new file mode 100644 index 0000000000000000000000000000000000000000..3624baf4c11cd7c37069e8ffbb2862d42d822074 --- /dev/null +++ b/pool/shard000/JavaScript/0004816_data-handling.js @@ -0,0 +1,222 @@ +// Slype data handling processes + +function scatterPlot ( data ) { + var $graphCanvas = $('#current-graph'), + w = $graphCanvas.innerWidth(), + h = $graphCanvas.innerHeight(), + padding = 0.1 * $graphCanvas.innerHeight(); + + console.log('Plotting a scatter graph...'); + console.log('Current canvas width is ' + w + ' and current height is ' + h); + //console.log(data); + + var svg = d3.select('#current-graph').append('svg') + .attr('width', w) + .attr('height', h) + .attr('class', 'slype-graph'), + scaleX = d3.scale.linear() + .domain([0, 100]) + .range([padding, w - padding / 3]), + scaleY = d3.scale.linear() + .domain([0, 100]) + .range([h - padding, padding / 3]), + axisX = d3.svg.axis() + .scale(scaleX) + .orient('bottom'), + axisY = d3.svg.axis() + .scale(scaleY) + .orient('left'), + noOfSeries = Object.keys(data[0]).length - 1, + seriesNames = [], + xColName = Object.keys(data[0])[0], + seriesReport = 'Series names: ', + groups = [], + colors = ['red', 'green', 'blue']; + + for ( var i = 1; i < Object.keys(data[0]).length; i++ ) { + var currentSeriesName = Object.keys(data[0])[i]; + seriesNames.push(currentSeriesName); + seriesReport += currentSeriesName + ' '; + } + + console.log('There are ' + noOfSeries + ' data series'); + console.log(seriesReport); + + svg.append('g') + .attr('class', 'axis') + .attr("transform", "translate(0, " + (h - padding) + ")") + .call(axisX); + + svg.append('g') + .attr('class', 'axis') + .attr("transform", "translate(" + padding + ", 0)") + .call(axisY); + + for ( var i = 0; i < seriesNames.length; i++ ) { + var currentSeriesName = seriesNames[i], + currentGroup = svg.append('g').attr('id', 'group-' + currentSeriesName); + + console.log('Working on series ' + currentSeriesName + ' which has id ' + currentGroup.attr('id') + ' and class scatter-series-' + i); + + groups.push(currentGroup); + + currentGroup.selectAll('circle') + .data(data) + .enter() + .append('circle') + .attr('class', 'scatter-series-' + i) + .attr('cx', function (d) { + return scaleX(d[xColName]); + }) + .attr('cy', function (d) { + return scaleY(d[seriesNames[i]]); + }) + .attr('r', 0) + .attr('opacity', 0.5) + .transition() + .delay(500) + .duration(3000) + .attr('r', 8); + } + + $graphCanvas.removeAttr('id'); +} + + +function barChart ( data ) { + var $graphCanvas = $('#current-graph'), + w = $graphCanvas.innerWidth(), + h = $graphCanvas.innerHeight(), + padding = 0.08 * w; + + console.log('Plotting a bar chart...'); + console.log('Current canvas width is ' + w + ' and current height is ' + h); + //console.log(data); + + var svg = d3.select('#current-graph').append('svg') + .attr('width', w) + .attr('height', h) + .attr('class', 'slype-graph'); + + var noOfSeries = Object.keys(data[0]).length - 1, + xColName = Object.keys(data[0])[0], + seriesNames = [], + seriesReport = 'Series names: ', + groups = []; + + var scaleX = d3.scale.linear() + .domain([0, data.length]) + .range([padding, w - padding / 3]), + scaleY = d3.scale.linear() + .domain([0, 100]) + .range([h - padding, padding / 3]), +// axisX = d3.svg.axis() +// .scale(scaleX) +// .orient('bottom'), + axisY = d3.svg.axis() + .scale(scaleY) + .orient('left'); + + var barSpacing = w / (6 * noOfSeries); + + for ( var i = 1; i < Object.keys(data[0]).length; i++ ) { + var currentSeriesName = Object.keys(data[0])[i]; + seriesNames.push(currentSeriesName); + seriesReport += currentSeriesName + ' '; + } + + console.log('There are ' + noOfSeries + ' data series related to ' + xColName); + console.log(seriesReport); + +// svg.append('g') +// .attr('class', 'axis') +// .attr("transform", "translate(0, " + (h - padding) + ")") +// .call(axisX); + + svg.append('g') + .attr('class', 'axis') + .attr("transform", "translate(" + 0.5 * padding + ", 0)") + .call(axisY); + + var xValues = svg.append('g') + .attr('class','axis-values'), + xLabel = svg.append('g') + .attr('class', 'axis-label'); + + xValues.selectAll('text') + .data(data) + .enter() + .append('text') + .attr('y', h - 0.6 * padding) + .attr('x', function (d, i) { + return scaleX(i) + (w - 4 * padding / 3 ) / (2 * 6); + }) + .text(function (d, i) { + return d[xColName]; + }); + + xLabel.append('text') + .attr('x', (w - 4 * padding / 3) / 2) + .attr('y', h - 0.1 * padding) + .text(xColName); + + + for ( var i = 0; i < seriesNames.length; i++ ) { + var currentSeriesName = seriesNames[i], + currentGroup = svg.append('g') + .attr('id', 'group-' + currentSeriesName); + + console.log('Working on series ' + currentSeriesName + ' which has id ' + currentGroup.attr('id') + ' and class bar-series-' + i); + + groups.push(currentGroup); + + currentGroup.selectAll('rect') + .data(data) + .enter() + .append('rect') + .attr('class', 'bar-series-' + i) + .attr('width', barSpacing) + .attr('x', function (d, k) { + return scaleX(k) + i * barSpacing; + }) + .attr('y', h - padding) + .attr('height', 0) + .transition() + .delay(500) + .duration(3000) + .attr('height', function (d) { + return scaleY(d[seriesNames[i]]); + }) + .attr('y', function (d) { + return h - padding - scaleY(d[seriesNames[i]]); + }); + } + + $graphCanvas.removeAttr('id'); +} + + +function dataHandler ( $domObject ) { + var $graphs = $domObject.find('.graph'), + csvPaths = new Array; + + for ( var i = 0; i < $graphs.length; i++ ) { + var $currentGraph = $graphs[i]; + var currentPath = $currentGraph.getAttribute('data-csv'); + + console.log('Loading data from ' + currentPath); + csvPaths.push(currentPath); + + //console.log($currentGraph); + + $currentGraph.setAttribute('id', 'current-graph'); + + if ( $currentGraph.classList.contains('scatter') ) { + d3.csv(currentPath, scatterPlot); + } else if ( $currentGraph.classList.contains('bar') ) { + d3.csv(currentPath, barChart); + } else { + // + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004818_trie-node.js b/pool/shard000/JavaScript/0004818_trie-node.js new file mode 100644 index 0000000000000000000000000000000000000000..4f5b3981a82c6d740a8ee4ad9b1b7bee56990f8b --- /dev/null +++ b/pool/shard000/JavaScript/0004818_trie-node.js @@ -0,0 +1,67 @@ +var TrieNode = (function() { + function TrieNode(character) { + this.character = character || ''; + this.children = {}; + this.strings = []; + } + + TrieNode.prototype.add = function(string, index) { + var currChar = string[index]; + + if (currChar) { + currChar = currChar.toLowerCase(); + if (!this.children[currChar]) { + this.children[currChar] = new TrieNode(currChar); + } + this.children[currChar].add(string, index + 1); + } else { + this.strings.push(string); + } + }; + + TrieNode.prototype.search = function(string, index) { + var currChar = string[index]; + + if (currChar) { + currChar = currChar.toLowerCase(); + if (!this.children[currChar]) { + return []; + } else { + return this.children[currChar].search(string, index + 1); + } + } else if (index === 0) { + return []; + } else { + return collectStrings(this); + } + }; + + var collectStrings = function(node) { + var strings = node.strings.slice(); + + for (var child in node.children) { + strings = strings.concat(collectStrings(node.children[child])); + } + + return strings; + }; + + TrieNode.prototype.find = function(string, index) { + var currChar = string[index]; + + if (currChar) { + currChar = currChar.toLowerCase(); + if (!this.children[currChar]) { + return false; + } else { + return this.children[currChar].find(string, index + 1); + } + } else { + return this.strings.indexOf(string) > -1 ? true : false; + } + }; + + return TrieNode; +})(); + +module.exports = TrieNode; diff --git a/pool/shard000/JavaScript/0004819_auth.js b/pool/shard000/JavaScript/0004819_auth.js new file mode 100644 index 0000000000000000000000000000000000000000..3714876dc5d9cd19123bdca5a3f94621fb59ceef --- /dev/null +++ b/pool/shard000/JavaScript/0004819_auth.js @@ -0,0 +1,24 @@ +/** 登录权限认证 */ + +//必须是登录之前才能访问 +var afterLogin = function(req,res,next){ + if(req.session.user){ //如果session有值,则进入下一步 + next(); + }else{ //如果没有session值 + req.flash('error','必须登录才能访问'); //设置一次性错误提示 + res.redirect('/users/login'); //跳到登录页面 + } +} + +//必须登录前才能访问 +var beforeLogin = function(req,res,next){ + if(req.session.user){ //session有值,说明已经登录 + req.flash('error','必须登录前才能访问'); //设置回显消息 + res.redirect('/') //跳到首页 + }else{ + next(); //继续下一步 + } +} + +exports.aferLogin = afterLogin; +exports.beforeLogin = beforeLogin; diff --git a/pool/shard000/JavaScript/0004824_index.js b/pool/shard000/JavaScript/0004824_index.js new file mode 100644 index 0000000000000000000000000000000000000000..5fbc98932318b2793f08b924caf14905a965999d --- /dev/null +++ b/pool/shard000/JavaScript/0004824_index.js @@ -0,0 +1,109 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import invariant from 'invariant'; + +import humanize from './utils/humanize'; +import assign from 'object-assign'; +import { inputValueLookup } from 'react-form-utils'; +import { layout, section, col } from 'react-layout-builder'; + +export default class FormWithLayout extends React.Component { + constructor(props, context) { + super(props, context); + + invariant( + props.renderLayout && props.renderField, + 'props.renderLayout and props.renderField is required.' + ); + + this.renderField = this.renderField.bind(this); + } + + render() { + const { props } = this; + + const formProps = { + action: props.action, + method: props.method, + onSubmit: props.onSubmit + }; + + const formBuilder = { layout: layout, section: section }; + formBuilder.col = col.bind(null, this.renderField); + + const children = + this.props.showAll && props.renderExpandedLayout + ? props.renderExpandedLayout(formBuilder, props) + : props.renderLayout(formBuilder, props); + + return ( +
      (this.form = c)} + {...formProps} + className={props.className || 'form-horizontal'} + > + {children} + {props.renderButtons ? props.renderButtons(props) :
      } + + ); + } + + renderField(name) { + const formProps = this.props; + const fieldProps = formProps.getFieldProps(name); + + const label = + typeof fieldProps.label !== 'undefined' + ? fieldProps.label + : humanize(name); + + // fieldProps.disabled > formProps.disabled > + const disabled = + typeof fieldProps.disabled !== 'undefined' + ? fieldProps.disabled + : formProps.disabled; + + // fieldProps.defaultValue > formProps.defaultValues(field).defaultValue + const defaultValue = + typeof fieldProps.defaultValue !== 'undefined' + ? fieldProps.defaultValue + : inputValueLookup(formProps.defaultValues || {}, name); + + // fieldProps.value > formProps.values(field).value + const value = + typeof fieldProps.value !== 'undefined' + ? fieldProps.value + : inputValueLookup(formProps.values || {}, name); + + const inputProps = assign({}, fieldProps, { + name: name, + value: value, + label: label, + disabled: disabled, + + defaultValue: typeof value !== 'undefined' ? undefined : defaultValue, + formProps: formProps + }); + + return fieldProps.input + ? React.createElement(fieldProps.input, inputProps) + : formProps.renderField(name, inputProps); + } +} + +FormWithLayout.propTypes = { + renderLayout: PropTypes.func.isRequired, + renderField: PropTypes.func.isRequired, + getFieldProps: PropTypes.func.isRequired, + + values: PropTypes.object, + defaultValues: PropTypes.object, + + errors: PropTypes.object, + disabled: PropTypes.bool, + className: PropTypes.string, + + renderButtons: PropTypes.func, + renderExpandedLayout: PropTypes.func, + showAll: PropTypes.bool +}; diff --git a/pool/shard000/JavaScript/0004825_infoController.js b/pool/shard000/JavaScript/0004825_infoController.js new file mode 100644 index 0000000000000000000000000000000000000000..794e03e13e47f5888e798577b1bc486e5b85a8a5 --- /dev/null +++ b/pool/shard000/JavaScript/0004825_infoController.js @@ -0,0 +1,14 @@ +angular.module('info', []) + .controller('InfoController', ['$scope', 'Info', 'Version', 'Settings', + function ($scope, Info, Version, Settings) { + $scope.info = {}; + $scope.docker = {}; + $scope.endpoint = Settings.endpoint; + + Version.get({}, function (d) { + $scope.docker = d; + }); + Info.get({}, function (d) { + $scope.info = d; + }); + }]); diff --git a/pool/shard000/JavaScript/0004830_aspose_cloud_presentation_importer.js b/pool/shard000/JavaScript/0004830_aspose_cloud_presentation_importer.js new file mode 100644 index 0000000000000000000000000000000000000000..6557ff1b8e9d4a3b302b4cf4a44d1423a9f0ea9c --- /dev/null +++ b/pool/shard000/JavaScript/0004830_aspose_cloud_presentation_importer.js @@ -0,0 +1,92 @@ +jQuery(document).ready(function($){ + + jQuery.ajax + ({ + type : "post", + dataType : "html", + url : AsposeParams['aspose_files_url'], + data : {appSID: AsposeParams['appSID'], appKey : AsposeParams['appKey']}, + success: function(response) { + $('#aspose_cloud_ppt').append(response); + + } + }); + + $('#aspose_folder_name').live('change',function() { + var selected_folder_name = $(this).val(); + if(selected_folder_name != '') { + jQuery.ajax + ({ + type : "post", + dataType : "html", + url : AsposeParams['aspose_files_url'], + data : {appSID: AsposeParams['appSID'], appKey : AsposeParams['appKey'], aspose_folder : selected_folder_name}, + success: function(response) { + $('#aspose_cloud_ppt').html(response); + + } + }); + } + }); + + + + $('#tabs').tabs(); + $('#aspose_ppt_popup').live("click",function(){ + $("#aspose_ppt_popup_container").dialog('open'); + + }); + $("#aspose_ppt_popup_container").dialog({ + autoOpen: false, + resizable: false, + modal: true, + width:'auto', + height:'300', + }); + + + $('#insert_ppt_content').live('click',function(){ + var filename = $('#ppt_file_name').val(); + $("#aspose_ppt_popup_container").dialog('close'); + $body = $("body"); + $body.addClass("loading"); + + jQuery.ajax + ({ + type : "post", + dataType : "html", + url : AsposeParams['insert_ppt_url'], + data : {appSID: AsposeParams['appSID'], appKey : AsposeParams['appKey'], filename : filename, uploadpath: AsposeParams['uploadpath']}, + success: function(response) { + $body.removeClass("loading"); + + window.send_to_editor(response); + } + }); + }); + + $('#insert_aspose_ppt_content').live('click',function(){ + var filename = $('input[name="aspose_filename"]:checked').val(); + $("#aspose_ppt_popup_container").dialog('close'); + $body = $("body"); + $body.addClass("loading"); + + jQuery.ajax + ({ + type : "post", + dataType : "html", + url : AsposeParams['insert_ppt_url'], + data : {appSID: AsposeParams['appSID'], appKey : AsposeParams['appKey'], filename : filename, uploadpath: AsposeParams['uploadpath'] , aspose : '1'}, + success: function(response) { + $body.removeClass("loading"); + window.send_to_editor(response); + } + }); + + }); + + +}); + + + diff --git a/pool/shard000/JavaScript/0004832_index.js b/pool/shard000/JavaScript/0004832_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e23701fb91c1580311426cb7ad376324340f4c07 --- /dev/null +++ b/pool/shard000/JavaScript/0004832_index.js @@ -0,0 +1,425 @@ +'use strict'; +/* jshint -W003, -W079 */ +var Promise = require('bluebird'); +var _ = require('lodash'); +var limiter = require('limiter'); + +Promise.promisifyAll(limiter.TokenBucket.prototype); + +/** + * Manages the set of `TokenBucket`s limitting AJAX requests. + * + * @constructor + * @param {Object} [options] Optional root `TokenBucket` options + */ + +function AjaxLimited(options) { + this.childBuckets = {}; + this.targets = []; + if(options) { + this.options = options; + this.bucket = new limiter.TokenBucket( + options.bucketSize, + options.tokensPerInterval, + options.interval + ); + } +} + +/** + * Configures rate limitting into an object. + * + * @param {Object} target + * @param {Object} [options] + */ + +AjaxLimited.prototype.configure = function(target, options) { + required(target, 'target'); + required(target.ajax, 'target.ajax'); + this.targets.push(target); + + if(options) { + this.options = options; + this.bucket = new limiter.TokenBucket( + options.bucketSize, + options.tokensPerInterval, + options.interval + ); + } + + this.injectInto(target); +}; + +/** + * Restores the original ajax method on the configured targets or a target + * object. + * + * @param {Object} [target] + * @return {Function} originalAjax + */ + +AjaxLimited.prototype.restore = function(target) { + if(target) { + target.ajax = this.originalAjax; + return this.originalAjax; + } + + _.each(this.targets, function(target) { + target.ajax = this.originalAjax; + }, this); + + return this.originalAjax; +}; + +/** + * Finds and returns the appropriate bucket for a set of `ajax` parameters. + * + * @param {Array|Object} args + * @return {TokenBucket} + */ + +AjaxLimited.prototype.getBucketFor = function(args) { + var url = args[0]; + var settings = args[1]; + if(typeof url !== 'string') { + settings = url; + url = settings.url; + } + + if(!settings) { + settings = {}; + } + + var method = (settings.method && settings.method.toLowerCase()) || + (settings.type && settings.type.toLowerCase()) || + 'get'; + + return this.childBuckets[method] || this.bucket; +}; + +/** + * Injects the limited `ajax` method into a `target`. Suitable `target` values + * are `Backbone` and `jQuery`. + * + * @param {Object} target + * @param {Function} target.ajax + */ + +AjaxLimited.prototype.injectInto = function(target) { + this.originalAjax = target.ajax; + target.ajax = this.ajax.bind(this); +}; + +/** + * Rate limitted version of `ajax`. Depends on buckets and `originalAjax` to be + * initialized. Should behave just like `$.ajax` except for rate limitting. + */ + +AjaxLimited.prototype.ajax = function() { + var _this = this; + var args = arguments; + var bucket = this.getBucketFor(args); + return bucket.removeTokensAsync(1).then(function() { + var settings = _.isString(args[0]) ? args[1] : args[0]; + return Promise.resolve(_this.originalAjax.apply(_this.targets[0], args)); + }); +}; + +/** + * Register a new bucket to handle `method` requests, defaulting to the root + * bucket's options. Uses nesting to prevent from going over the shared limit. + * + * @param {String} method + * @param {Object} options Same as options passed to + * `AjaxLimited.prototype.configure` + * @return {TokenBucket} bucket The updated or created bucket + */ + +AjaxLimited.prototype.registerBucket = function(method, options) { + var bucket; + var defaults = _.pick(this.childBuckets[method] || this.bucket, [ + 'bucketSize', + 'tokensPerInterval', + 'interval', + ]); + options = _.defaults(options, defaults); + + if(method === 'all') { + bucket = this.bucket; + } else if(this.childBuckets[method]) { + bucket = this.childBuckets[method]; + } else { + // Create bucket if missing + this.childBuckets[method] = new limiter.TokenBucket( + options.bucketSize, + options.tokensPerInterval, + options.interval, + this.bucket + ); + return this.childBuckets[method]; + } + + // Update existing bucket + bucket.bucketSize = options.bucketSize; + bucket.tokensPerInterval = options.tokensPerInterval; + bucket.interval = options.interval; + + return bucket; +}; + +_.each(['get', 'put', 'patch', 'post', 'delete', 'all'], function(method) { + AjaxLimited.prototype[method] = function(options) { + return this.registerBucket(method, options); + }; +}); + +/** + * Receives initial options for each HTTP method (or all of them), modifies + * buckets so they start with them and slowly transitions rate limitting until + * the original rates are reached. + * + * @param {Object} options + * + * @example + * ajaxLimited.slowStart({ + * get: { + * bucketSize: 9, + * tokensPerInterval: 9 + * }, + * 'put,patch,post,delete': { + * bucketSize: 9, + * tokensPerInterval: 0, + * }, + * transitionTime: 9000, + * interval: 3000 + * }); + */ + +AjaxLimited.prototype.slowStart = function(options) { + this.previousChildBuckets = _.mapValues(this.childBuckets, function(bucket) { + return _.cloneDeep(bucket); + }); + + this.childBuckets = {}; + _.each(['get', 'put', 'patch', 'post', 'delete'], function(method) { + if(options[method]) { + this.registerBucket(method, options[method]); + } else if(this.previousChildBuckets[method]) { + this.childBuckets[method] = this.previousChildBuckets[method]; + } + }, this); + + if(options.all) { + this.previousBucket = _.cloneDeep(this.bucket); + this.registerBucket('all', options.all); + } + + _.each(options, function(value, key) { + if(!_.contains(key, ',')) { + return; + } + + var methods = key.split(','); + _.each(methods, function(method) { + this.registerBucket(method, options[key]); + }, this); + }, this); + + var transitionTime = options.transitionTime || 5 * this.bucket.interval; + var interval = required(options.interval, 'options.interval'); + var steps = this.getBucketSteps(transitionTime, interval); + + return this.slowStartStep(interval, steps); +}; + +/** + * Steps through the slow start process every `interval` milliseconds. Applies + * `steps` to each of the corresponding routes on each scheduled call and stops + * when done. Returns a promise to the end of the process. + * + * @param {Number} interval + * @param {Array} steps + * @param {Number} steps[i].bucketSize + * @param {Number} steps[i].tokensPerInterval + * @return {Promise} + */ + +AjaxLimited.prototype.slowStartStep = function(interval, steps) { + var _this = this; + return Promise.delay(interval).then(function() { + // Step + _.each(steps, _this.applyBucketStep, _this); + + // Recurse unless done + if(!_this.isSlowStartDone()) { + return _this.slowStartStep(interval, steps); + } + + // Restore initial state + if(_this.previousBucket) { + _this.registerBucket('all', _this.previousBucket); + delete _this.previousBucket; + } + + if(_this.previousChildBuckets) { + _.each(_this.previousChildBuckets, function(bucket, method) { + _this.registerBucket(method, bucket); + }); + } + }); +}; + +/** + * Applies a `step` to the `method` bucket. If no `method` is provided, applies + * it to the root bucket. + * + * @param {Object} step + * @param {Number} step.tokensPerInterval + * @param {Number} step.bucketSize + * @param {String} method + */ + +AjaxLimited.prototype.applyBucketStep = function(step, method) { + var bucket = method === 'all' ? this.bucket : this.childBuckets[method]; + return this.registerBucket(method, { + bucketSize: bucket.bucketSize + step.bucketSize, + tokensPerInterval: bucket.tokensPerInterval + step.bucketSize, + }); +}; + +/** + * Returns whether the slow start process has finished. + * + * @returns {Boolean} + */ + +AjaxLimited.prototype.isSlowStartDone = function() { + // Check if any method specific bucket is pending + var childPending = _.any(this.childBuckets, function(slowBucket, method) { + var fastBucket = this.previousChildBuckets[method] || this.bucket; + return bucketIsFaster(slowBucket, fastBucket); + }, this); + + if(childPending) { + return false; + } + + // Check if the root bucket is pending + if(this.previousBucket) { + return bucketIsFaster(this.bucket, this.previousBucket); + } + + return true; +}; + +/** + * Calculates the optimal slow start step interval, so that we get back to + * normal in `transitionTime` milliseconds. + * + * @param {Number} transitionTime + * @param {Object} steps + */ + +AjaxLimited.prototype.getOptimalInterval = function(transitionTime, steps) { + var minStep = _.reduce(steps, function(min, step) { + if(step.deltas.tokensPerIntervalDelta < min.deltas.tokensPerIntervalDelta) { + return step; + } else return min; + }); + + return minStep.deltas.tokensPerIntervalDelta / minStep.tokensPerInterval; +}; + +/** + * Given slow start state has already been initialized, returns an object + * representation of the bucket steps for child and root buckets. + * + * @param {Number} transitionTime + * @param {Number} interval + * @return {Object} steps + */ + +AjaxLimited.prototype.getBucketSteps = function(transitionTime, interval) { + var steps = _.mapValues(this.childBuckets, function(bucket, method) { + return this.getBucketStep( + transitionTime, + interval, + this.previousChildBuckets[method] || this.bucket, + bucket + ); + }, this); + + steps.all = this.getBucketStep( + transitionTime, + interval, + this.previousBucket, + this.bucket + ); + + return steps; +}; + +/** + * Returns the step for a certain bucket, given with which params it'll start, + * where it should end and how long it should take. + * + * @param {Number} transitionTime + * @param {Number} interval + * @param {TokenBucket} start + * @param {TokenBucket} end + * @return {Object} step + * @return {Number} step.tokensPerInterval + * @return {Number} step.bucketSize + */ + +AjaxLimited.prototype.getBucketStep = function(transitionTime, interval, start, end) { + if(!start) { + return { + bucketSize: 0, + tokensPerInterval: 0, + }; + } + + var bucketSizeDelta = start.bucketSize - end.bucketSize; + var tokensPerIntervalDelta = start.tokensPerInterval - end.tokensPerInterval; + var nsteps = transitionTime / interval; + + return { + bucketSize: bucketSizeDelta / nsteps, + tokensPerInterval: tokensPerIntervalDelta / nsteps, + }; +}; + +exports = module.exports = new AjaxLimited(); +exports.AjaxLimited = AjaxLimited; + +/** + * Returns true if the first bucket parameter is "faster" than the second. + * + * @param {TokenBucket} b1 + * @param {TokenBucket} b2 + * @return {Boolean} + */ + +function bucketIsFaster(b1, b2) { + var ret = b1.tokensPerInterval * b1.interval >= b2.tokensPerInterval * b2.interval; + return ret; +} + +/** + * Throws an error if `p` doesn't exist + * + * @param {Mixed} p + * @param {String} name + */ + +function required(p, name) { + if(p == null) { + throwMissingParam(name); + } + return p; +} + +function throwMissingParam(name) { + throw new TypeError('Missing required param ' + name); +} diff --git a/pool/shard000/JavaScript/0004833_cantina-validators.js b/pool/shard000/JavaScript/0004833_cantina-validators.js new file mode 100644 index 0000000000000000000000000000000000000000..a84a221ffcff4591e5d918f68d3621b9f4f8d594 --- /dev/null +++ b/pool/shard000/JavaScript/0004833_cantina-validators.js @@ -0,0 +1,166 @@ +var moment = require('moment'); + +var email_regex = new RegExp( + '^' + + '[a-z0-9!#$%&\'*+/=?^_`{|}~-]+' + // local name + '(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*' + // optional local name dot suffix + '@' + + '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+' + // second-level and lower domains with trailing . + '(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)' + // top-level domain + '$' , + 'i') + , url_regex = new RegExp( + '(ftp|http|https)://' + // protocol + '(\\w+:{0,1}\\w*@)?' + // credentials (optional) + '([^:/\\s]+)' + // hostname + '(:[0-9]+)?' + // port (optional) + '(/(?:[/?#%\\w-.~!$&\'()*+,;=:@]*))?' , // path + query + hash (optional); "/" followed by zero or more valid characters + // valid characters are: + // '/' / '?' / '#' / '%' - the reserved characters: + // '\w' - word characters [A-Za-z0-9_] + // '-' / '.' / '~' - unreserved ('_' is included in '\w') + // '!' / '$' / '&' / ''' / - sub-delimiters + // '(' / ')' / '*' / '+' / + // ',' / ';' / '=' + // ':' / '@' - other allowed characters + 'i') + , phone_number_regex = new RegExp( + '^' + + '\\+?' + // leading "+" (optional) + '[0-9()-. ]+' + // digits or customary punctuation + '(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?' + // extension (optional) + '$' , + 'i') + , id_regex = /^[0-9a-zA-Z]{16}$/; + +var validators = { + isFlag: function isFlag (val) { + return val === 0 || val === 1; + }, + + isEmail: function isEmail (val) { + return email_regex.test(val); + }, + + isEmpty: function isEmpty (val) { + return (val === ''); + }, + + isNotEmpty: function isNotEmpty (val) { + return (typeof val === 'string' && val.length); + }, + + isEmailOrEmpty: function isEmailOrEmpty (val) { + return validators.isEmpty(val) || validators.isEmail(val); + }, + + isUrl: function isUrl (val) { + return url_regex.test(val); + }, + + isPhoneNumber: function isPhoneNumber (val) { + return phone_number_regex.test(val); + }, + + isId: function isId (val) { + return typeof val === 'string' && id_regex.test(val); + }, + + isIdOrEmpty: function isIdOrEmpty (val) { + return validators.isEmpty(val) || validators.isId(val); + }, + + isFutureDate: function isFutureDate (val) { + var utc_val = moment(val).endOf('day').utc(); + var utc_now = moment().startOf('day').utc(); + return utc_val.isAfter(utc_now); + }, + + isPastDate: function isPastDate (val) { + var utc_val = moment(val).endOf('day').utc(); + var utc_now = moment().startOf('day').utc(); + return utc_val.isBefore(utc_now); + }, + + isType: function (type) { + return function isType (val) { + switch (type) { + case 'object': + return {}.toString.call(val) === '[object Object]'; + case 'array': + return {}.toString.call(val) === '[object Array]'; + case 'date': + return {}.toString.call(val) === '[object Date]'; + case 'regexp': + case 'regex': + return {}.toString.call(val) === '[object RegExp]'; + case 'null': + return {}.toString.call(val) === '[object Null]'; + default: + return typeof val === type; + } + }; + }, + + isIn: function (values) { + return function isIn (val) { + return values.indexOf(val) >= 0; + }; + }, + + isJSON: function isJSON (str) { + try { + JSON.parse(str); + } catch (e) { + if (e instanceof SyntaxError) { + return false; + } + } + return true; + }, + + matches: function (regex) { + return function matches (val) { + return typeof val === 'string' && regex.test(val); + }; + }, + + maxLength: function (length, ignore) { + if (ignore) { + Array.isArray(ignore) || (ignore = [ignore]); + } + return function maxLength (val) { + if (ignore) { + return ignore.reduce(function (str, pattern) { + return str.replace(pattern, ''); + }, val).length <= length; + } + else { + return val.length <= length; + } + }; + }, + + minLength: function (length, ignore) { + if (ignore) { + Array.isArray(ignore) || (ignore = [ignore]); + } + return function minLength (val) { + if (ignore) { + return ignore.reduce(function (str, pattern) { + return str.replace(pattern, ''); + }, val).length >= length; + } + else { + return val.length >= length; + } + }; + } +}; + +module.exports = function (app) { + app.validators = validators; +}; +Object.keys(validators).forEach(function (key) { + module.exports[key] = validators[key]; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004835_elevator.0.3.0.js b/pool/shard000/JavaScript/0004835_elevator.0.3.0.js new file mode 100644 index 0000000000000000000000000000000000000000..d4587366fd3ffa2c6c54a94447d0522ad8a30154 --- /dev/null +++ b/pool/shard000/JavaScript/0004835_elevator.0.3.0.js @@ -0,0 +1,138 @@ +/* Version 0.3.0 */ + +(function(){ + var directionMap = { + X: 'left', + Y: 'top' + }; + + var Elevator = Widget.extend({ + attrs: { + direction: 'Y', + classNames: { + item: 'elevator-item' + }, + selecters: { + target: '.elevator-target' + }, + targetContainer: document, + template: '
        ', + _elementOffset: 0, + _itemsPosition: [] + }, + setup: function(){ + this._bindEvent(); + }, + refresh: function(){ + var attrs = this.get(); + var itemClass = attrs.classNames.item; + var targetList = $(attrs.selecters.target, attrs.targetContainer); + + var itemHtmlList = []; + + targetList.each(function(index, item){ + itemHtmlList.push('
      • '+$(item).data('key')+'
      • '); + }); + + this.$element.html(itemHtmlList.join('')); + + _elementOffset = this.set('_elementOffset',this.$element.offset()[directionMap[attrs.direction]]); + _itemsPosition = this.set('_itemsPosition',getPositionList($('.'+itemClass, this.$element), attrs.direction)); + }, + _bindEvent: function(){ + var me = this, + $element = this.$element, + direction = this.get('direction'), + position, + orgPosition, + index; + + $element.on('touchstart', function(e){ + var _elementOffset = me.get('_elementOffset'), + _itemsPosition = me.get('_itemsPosition'); + + e.preventDefault(); + e.stopPropagation(); + + position = e.touches[0]['page'+direction] - _elementOffset; + index = getIndex(position, _itemsPosition); + + me.trigger('jump', [{index: index, position: position}]); + }).on('touchmove', function(e){ + var _elementOffset = me.get('_elementOffset'), + _itemsPosition = me.get('_itemsPosition'); + + e.preventDefault(); + e.stopPropagation(); + + var touch = e.touches[0]; + + orgPosition = position; + position = touch['page'+direction] - _elementOffset; + + var i = getIndex(position, _itemsPosition, index, orgPosition); + + if (i != index) { + index = i; + me.trigger('jump', [{index: index, position: position}]); + } + + }).on('touchend', function(e){ + me.trigger('jumpend', [{index: index, position: position}]); + }); + } + }); + + /*getIndex(position, _itemsPosition, index, orgPosition);*/ + function getIndex(p, pl, startIndex, op){ + if(pl.length == 0){ return null; } + + var i = startIndex; + + if(startIndex === undefined) { + + if (p p){ + return i; + } + } + + return pl.length-1; + } else { + op === undefined && (op = p); + if (p-op>0) { + if (p p){ + return i; + } + } + + return pl.length-1; + } else if(p-op<0) { + if(pl[i] <= p){ return i; } + + for (; i > 0; i--) { + if(pl[i] > p && pl[i-1] <= p){ + return i-1; + } + } + + return 0; + } + } + + return i; + } + + function getPositionList(els, direction){ + return els.map(function(index,item){ + return $(item).position()[directionMap[direction]]; + }); + } + + this.Elevator = Elevator; +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004840_iot_simulator.js b/pool/shard000/JavaScript/0004840_iot_simulator.js new file mode 100644 index 0000000000000000000000000000000000000000..dd068ede0ab13c0224f140fb9594cd78fa9d1f06 --- /dev/null +++ b/pool/shard000/JavaScript/0004840_iot_simulator.js @@ -0,0 +1,124 @@ +//Variables that nees setting + +var variables = require('./variables'); + +var rootFolder = variables.rootFolder; +var certsFolder = variables.certsFolder; +var deviceID = variables.deviceID; +var awsRegion = variables.awsRegion; +var sensorTopic = variables.sensorTopic; +var buzzerTopic = variables.buzzerTopic; +var thingName = variables.thingName; + + +var ip = require("ip"); +const EventEmitter = require('events'); +class MyEmitter extends EventEmitter {} +const eventEmitter = new MyEmitter(); +var awsIot = require('aws-iot-device-sdk'); +var device = awsIot.device({ + keyPath: certsFolder+"/private.pem", + certPath: certsFolder+"/certificate.crt", + caPath: certsFolder+"/root-CA.crt", + clientId: deviceID, + region: awsRegion +}); + +var currentShadow = { + "state": { + "desired": { + "TEMPERATURE": 0, + "LIGHT": 0, + "TOUCH": 0 + }, + "reported": { + "TEMPERATURE": 0, + "LIGHT": 0, + "TOUCH": 0 + } + } +}; + +device.on('connect', function() { + console.log('connect'); + device.subscribe(buzzerTopic); + eventEmitter.emit('awsIOTInitialized'); + setInterval( function() { + device.publish('$aws/things/'+thingName+'/shadow/update', JSON.stringify(currentShadow)); + }, 5000 ); + + +}); + +device.on('message', function(topic, payload) { + console.log('message', topic, payload.toString()); + if (topic == buzzerTopic && payload.toString() == 'buzzeron') { + console.log('Buzzer goes on'); + //buzzerOutput.write(1); + } + if (topic == buzzerTopic && payload.toString() == 'buzzeroff') { + console.log('Buzzer goes off'); + //buzzerOutput.write(0); + } + +}); + +var lightSensor = null; +var tempSensor = null; +var touchSensor = null; +var buzzerOutput = null; + +eventEmitter.on('awsIOTInitialized', function() { + setInterval(function (){ + lightSensorCallback(Math.random() * (200 - 50) + 50); + },5000); + setInterval(function (){ + tempSensorCallback(Math.random() * (50 - 10) + 10); + },5000); + setInterval(function (){ + touchSensorCallback(Math.random()); + },5000); +}); + +function lightSensorCallback(value) { + if (value > 0) { + var messagePayload = { + "DEVICEID" : deviceID, + "TIMESTAMP" : Number(new Date()).toString(), + "SENSOR" : "LIGHT", + "VALUE" : Math.round(value), + "MYIP" : ip.address() + }; + currentShadow.state.desired.LIGHT = Math.round(value); + currentShadow.state.reported.LIGHT = Math.round(value); + device.publish(sensorTopic+'/LIGHT', JSON.stringify(messagePayload)); + } +} + +function tempSensorCallback(value) { + if (value > 0) { + var messagePayload = { + "DEVICEID" : deviceID, + "TIMESTAMP" : Number(new Date()).toString(), + "SENSOR" : "TEMPERATURE", + "VALUE" : Math.round(value), + "MYIP" : ip.address() + }; + currentShadow.state.desired.TEMPERATURE = Math.round(value); + currentShadow.state.reported.TEMPERATURE = Math.round(value); + device.publish(sensorTopic+'/TEMPERATURE', JSON.stringify(messagePayload)); + } +} + +function touchSensorCallback(value) { + var messagePayload = { + "DEVICEID" : deviceID, + "TIMESTAMP" : Number(new Date()).toString(), + "SENSOR" : "TOUCH", + "VALUE" : Math.round(value), + "MYIP" : ip.address() + }; + currentShadow.state.desired.TOUCH = Math.round(value); + currentShadow.state.reported.TOUCH = Math.round(value); + device.publish(sensorTopic+'/TOUCH', JSON.stringify(messagePayload)); +} diff --git a/pool/shard000/JavaScript/0004841_editor.js b/pool/shard000/JavaScript/0004841_editor.js new file mode 100644 index 0000000000000000000000000000000000000000..5ef9e2909ff50053e69d827ff78a726d62259dae --- /dev/null +++ b/pool/shard000/JavaScript/0004841_editor.js @@ -0,0 +1,34 @@ +var editor, $tb; + +function make_editor(el, opts) { + var config = { + lineNumbers: true, + lineWrapping: true, + autoClearEmptyLines: true, + matchBrackets: true, + mode: opts.mode || 'text/css' + }; + django.jQuery.extend(config, opts); + editor = CodeMirror.fromTextArea(document.getElementById(el), config); + $editor = django.jQuery(editor.getWrapperElement()); + $tb = django.jQuery('
        '); + $editor.prepend($tb); +} + +function add_button(opts) { + var $el = django.jQuery(''); + $el.on('click', opts.action); + $tb.append($el); +} + +function reindent () { + var sel = editor.somethingSelected(), + i = sel ? editor.getCursor().line : 0, + l = sel ? editor.getCursor(false).line : editor.lineCount(); + + for( ; i < l ; i++ ) { + var row = editor.getLine(i).replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + editor.indentLine(i); + } +}; + diff --git a/pool/shard000/JavaScript/0004843_max-record-number.js b/pool/shard000/JavaScript/0004843_max-record-number.js new file mode 100644 index 0000000000000000000000000000000000000000..c0d26d0ad46dd20d142467ed40105449f8c703ba --- /dev/null +++ b/pool/shard000/JavaScript/0004843_max-record-number.js @@ -0,0 +1,29 @@ +'use strict' + +/* application modules */ +const sql = require('../sql') + +/* exports */ +module.exports = maxRecordNumber + +/** + * @function maxRecordNumber + * + * get max record (n)umber with optional where + * + * @param {object} args + * @param {object} args.session + * @param {object} args.where + * + * @returns {Promise} + */ +function maxRecordNumber (args) { + // get sql + var select = sql.maxRecordNumber(this, args) + // do query + return this.mysql().query(select.sql, select.params) + // get n value from response + .then(res => { + return res[0][0].n + }) +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004844_tpl.js b/pool/shard000/JavaScript/0004844_tpl.js new file mode 100644 index 0000000000000000000000000000000000000000..38ccf4adb7782ea74ca35f4bf01de38cf346f46b --- /dev/null +++ b/pool/shard000/JavaScript/0004844_tpl.js @@ -0,0 +1,69 @@ +// RequireJS UnderscoreJS template plugin +// http://github.com/jfparadis/requirejs-tpl +// +// An alternative to http://github.com/ZeeAgency/requirejs-tpl +// +// Using UnderscoreJS micro-templates at http://underscorejs.org/#template +// Using and RequireJS text.js at http://requirejs.org/docs/api.html#text +// @author JF Paradis +// @version 0.0.2 +// +// Released under the MIT license +// +// Usage: +// require(['backbone', 'tpl!mytemplate'], function (Backbone, mytemplate) { +// return Backbone.View.extend({ +// initialize: function(){ +// this.render(); +// }, +// render: function(){ +// this.$el.html(mytemplate({message: 'hello'})); +// }); +// }); +// +// Configuration: (optional) +// require.config({ +// tpl: { +// extension: '.tpl' // default = '.html' +// } +// }); + +/*jslint nomen: true */ +/*global define: false */ + +define(['text', 'underscore'], function (text, _) { + 'use strict'; + + var buildMap = {}, + buildTemplateSource = "define('{pluginName}!{moduleName}', function () { return {source}; });\n"; + + return { + version: '0.0.2', + + load: function (moduleName, parentRequire, onload, config) { + if (buildMap[moduleName]) { + onload(buildMap[moduleName]); + + } else { + var ext = (config.tpl && config.tpl.extension) || '.html'; + var path = (config.tpl && config.tpl.path) || ''; + text.load(path + moduleName + ext, parentRequire, function (source) { + buildMap[moduleName] = _.template(source); + onload(buildMap[moduleName]); + }, config); + } + }, + + write: function (pluginName, moduleName, write) { + var build = buildMap[moduleName], + source = build && build.source; + if (source) { + write.asModule(pluginName + '!' + moduleName, + buildTemplateSource + .replace('{pluginName}', pluginName) + .replace('{moduleName}', moduleName) + .replace('{source}', source)); + } + } + }; +}); diff --git a/pool/shard000/JavaScript/0004847_cluster.js b/pool/shard000/JavaScript/0004847_cluster.js new file mode 100644 index 0000000000000000000000000000000000000000..4212db9c691076fb7b443566299b11531a727ce2 --- /dev/null +++ b/pool/shard000/JavaScript/0004847_cluster.js @@ -0,0 +1,41 @@ +'use strict'; + +const _ = require('lodash'); +const autoBind = require('auto-bind'); +const Promise = require('bluebird'); +const Client = require('./client'); + +class Cluster extends Client { + constructor(config) { + super(config); + autoBind(this); + } + + state() { + return this.get('/cluster/state'); + } + + stats() { + return this.get('/cluster/stats'); + } + + slicers() { + return this.get('/cluster/slicers'); + } + + txt(type) { + const validTypes = ['assets', 'slicers', 'ex', 'jobs', 'nodes', 'workers']; + const isValid = _.some(validTypes, validType => _.startsWith(type, validType)); + if (!isValid) { + const error = new Error(`"${type}" is not a valid type. Must be one of ${JSON.stringify(validTypes)}`); + return Promise.reject(error); + } + return this.get(`/txt/${type}`, { json: false }); + } + + nodes() { // eslint-disable-line + // not sure why this empty? + } +} + +module.exports = Cluster; diff --git a/pool/shard000/JavaScript/0004848_statisticsTests.js b/pool/shard000/JavaScript/0004848_statisticsTests.js new file mode 100644 index 0000000000000000000000000000000000000000..5f0686d0653da8d27a9fc5198e8b7a81f84a8efe --- /dev/null +++ b/pool/shard000/JavaScript/0004848_statisticsTests.js @@ -0,0 +1,224 @@ +'use strict'; + +let assert = require('assert'), + Statistics = require('../../lib/support/statistics').Statistics; + +describe('statistics', function() { + let stats; + + beforeEach(function() { + stats = new Statistics(); + }); + + describe('#add', function() { + it('should be possible to add multiple keys', function() { + for (let i = 0; i < 11; i++) { + stats.add('foo', i + 1); + stats.add('bar', 11 - i); + } + let result = stats.summarize(); + assert.deepEqual(result.foo, result.bar); + }); + + it('should handle keys with dots', function() { + stats.add('1.2.3', 42.0); + let result = stats.summarize(); + assert.deepEqual(result['1.2.3'].mean, 42.0); + }); + + it('should require string keys', function() { + assert.throws(function() { + stats.add(3, 3); + }, TypeError); + }); + + it('should require numeric values', function() { + assert.throws(function() { + stats.add('a', 'a'); + }, TypeError); + }); + + it('should require finite values', function() { + assert.throws(function() { + stats.add('a', NaN); + }, RangeError); + assert.throws(function() { + stats.add('a', Infinity); + }, RangeError); + }); + }); + + describe('#addAll', function() { + it('should be possible to add an object with numeric values', function() { + stats.addAll({ + a: 1, + b: 2, + c: 3 + }); + stats.addAll({ + a: 2, + b: 2, + c: 2 + }); + stats.addAll({ + a: 3, + b: 2, + c: 1 + }); + + let result = stats.summarize(); + assert.deepEqual(result.a, result.c); + assert.equal(result.a.mean, result.b.mean); + }); + + it('should be possible to add an array of objects with numeric values', function() { + let samples = [ + { + a: 1, + b: 2, + c: 3 + }, + { + a: 2, + b: 2, + c: 2 + }, + { + a: 3, + b: 2, + c: 1 + } + ]; + stats.addAll(samples); + + let result = stats.summarize(); + assert.equal(3, Object.keys(result).length); + assert.deepEqual(result.a, result.c); + assert.equal(result.a.mean, result.b.mean); + }); + }); + + describe('#addDeep', function() { + it('should be possible to add a deep structure', function() { + stats.addDeep({ + a: 1, + b: { + c: 2, + d: 3 + } + }); + stats.addDeep( + { + userTimings: { + marks: [ + { + name: 'headerTime', + startTime: 2457.125 + }, + { + name: 'logoTime', + startTime: 2654.805 + }, + { + name: 'timing.good.times', + startTime: 123.456 + } + ], + measures: [] + } + }, + (keyPath, value) => { + const equals = (a1, a2) => JSON.stringify(a1) === JSON.stringify(a2); + if (equals(keyPath, ['userTimings', 'marks'])) { + return value.reduce((result, mark) => { + result[mark.name] = mark.startTime; + return result; + }, {}); + } else if (equals(keyPath, ['userTimings', 'measures'])) { + return value.reduce((result, mark) => { + result[mark.name] = mark.duration; + return result; + }, {}); + } + + return value; + } + ); + stats.addDeep({ + a: 3, + b: { + c: 2, + d: 1 + } + }); + stats.addDeep({ + a: 2, + b: { + c: 2, + d: 2 + } + }); + + let result = stats.summarizeDeep({ decimals: 3 }); + assert.deepEqual(result.a, result.b.d); + assert.equal(result.b.c.mean, result.b.d.mean); + assert.equal(result.userTimings.marks['timing.good.times'].max, 123.456); + }); + }); + + describe('#summarize', function() { + it('should summarize correctly', function() { + stats.addAll({ + a: 1, + b: 2, + c: 3 + }); + stats.addAll({ + a: 2, + b: 2, + c: 2 + }); + stats.addAll({ + a: 3, + b: 2, + c: 1 + }); + + let result = stats.summarize(); + assert.equal(1, result.a.min); + assert.equal(3, result.a.max); + assert.equal(2, result.a.mean); + assert.equal(2, result.a.median); + assert.equal(result.a.mean, result.b.mean); + assert.deepEqual(result.a, result.c); + }); + + it('should summarize specified percentiles', function() { + stats.addAll({ + a: 1, + b: 2, + c: 3 + }); + stats.addAll({ + a: 2, + b: 2, + c: 2 + }); + stats.addAll({ + a: 3, + b: 2, + c: 1 + }); + + let result = stats.summarize({ + percentiles: [0, 99, 99.9] + }); + assert.equal(1, result.a.min); + assert.equal(3, result.a.p99); + assert.equal(null, result.a.p90); + assert.equal(3, result.a.p99_9); + assert.equal(2, result.a.mean); + assert.equal(2, result.a.median); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004856_kefir.js b/pool/shard000/JavaScript/0004856_kefir.js new file mode 100644 index 0000000000000000000000000000000000000000..635bcf47462c1237c22d6953d3307f2fac72e61c --- /dev/null +++ b/pool/shard000/JavaScript/0004856_kefir.js @@ -0,0 +1,20 @@ +import { Kefir as originalKefir } from 'kefir'; + +originalKefir.emitter = () => { + let emitter; + const stream = Kefir.stream(_emitter => { + emitter = _emitter; + return () => emitter = null; + }); + + stream.emit = x => { + emitter && emitter.emit(x); + return stream; + } + + // TODO: other methods .error, .end, .emitEvent if needed + + return stream; +}; + +export const Kefir = originalKefir; diff --git a/pool/shard000/JavaScript/0004862_mqtt-send-msg.js b/pool/shard000/JavaScript/0004862_mqtt-send-msg.js new file mode 100644 index 0000000000000000000000000000000000000000..3ff04c0d56f3477a53c23612cfdb97e8a830b44a --- /dev/null +++ b/pool/shard000/JavaScript/0004862_mqtt-send-msg.js @@ -0,0 +1,27 @@ +var mqtt = require('mqtt'); +var client = mqtt.connect('mqtt://127.0.0.1', { + username: process.env.TOKEN +}); + +client.on('connect', function () { + console.log('connected'); + client.subscribe('v1/devices/me/rpc/response/+'); + var requestId = 1; + var request = { + method: "sendMsg", + params: { + deviceId: "aa435e80-9fce-11e6-8080-808080808080", + timeout: 2000, + oneway: false, + body: { + param1: "value1" + } + } + }; + client.publish('v1/devices/me/rpc/request/' + requestId, JSON.stringify(request)); +}); + +client.on('message', function (topic, message) { + console.log('response.topic: ' + topic); + console.log('response.body: ' + message.toString()); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004863_js.js b/pool/shard000/JavaScript/0004863_js.js new file mode 100644 index 0000000000000000000000000000000000000000..8b9ec045cf4bd7d811bc90d32b3fb245532af267 --- /dev/null +++ b/pool/shard000/JavaScript/0004863_js.js @@ -0,0 +1,135 @@ +(function() { + var COLORS, Confetti, NUM_CONFETTI, PI_2, canvas, confetti, context, drawCircle, i, range, resizeWindow, xpos; + + NUM_CONFETTI = 200; + + COLORS = [[123, 187, 94], [234, 76, 137], [0, 182, 227], [255, 136, 51], [248, 182, 70]]; + + PI_2 = 2 * Math.PI; + + canvas = document.getElementById("world"); + + context = canvas.getContext("2d"); + + window.w = 0; + + window.h = 0; + + resizeWindow = function() { + window.w = canvas.width = window.innerWidth; + return window.h = canvas.height = window.innerHeight; + }; + + window.addEventListener('resize', resizeWindow, false); + + window.onload = function() { + return setTimeout(resizeWindow, 0); + }; + + range = function(a, b) { + return (b - a) * Math.random() + a; + }; + + drawCircle = function(x, y, r, w, h, style) { + context.fillStyle = style; + return context.fillRect(x, y, w, h); + }; + + xpos = 0.5; + + document.onmousemove = function(e) { + return xpos = e.pageX / w; + }; + + window.requestAnimationFrame = (function() { + return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { + return window.setTimeout(callback, 1000 / 60); + }; + })(); + + Confetti = (function() { + function Confetti() { + this.style = COLORS[~~range(0, 5)]; + this.rgb = "rgba(" + this.style[0] + "," + this.style[1] + "," + this.style[2]; + this.r = ~~range(2, 6); + this.h = Math.floor(2 + Math.random() * 20); + this.w = Math.floor(2 + Math.random() * 10); + this.r2 = 2 * this.r; + this.replace(); + } + + Confetti.prototype.replace = function() { + this.opacity = 0; + this.dop = 0.03 * range(1, 4); + this.x = range(-this.r2, w - this.r2); + this.y = range(-20, h - this.r2); + this.xmax = w - this.r; + this.ymax = h - this.r; + this.vx = range(0, 2) + 8 * xpos - 5; + return this.vy = 0.7 * this.r + range(-1, 1); + }; + + Confetti.prototype.draw = function() { + var ref; + this.x += this.vx; + this.y += this.vy; + this.opacity += this.dop; + if (this.opacity > 1) { + this.opacity = 1; + this.dop *= -1; + } + if (this.opacity < 0 || this.y > this.ymax) { + this.replace(); + } + if (!((0 < (ref = this.x) && ref < this.xmax))) { + this.x = (this.x + this.xmax) % this.xmax; + } + return drawCircle(~~this.x, ~~this.y, this.r, this.w, this.h, this.rgb + "," + this.opacity + ")"); + }; + + return Confetti; + + })(); + + confetti = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = NUM_CONFETTI; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new Confetti); + } + return results; + })(); + + window.step = function() { + var c, j, len, results; + requestAnimationFrame(step); + context.clearRect(0, 0, w, h); + results = []; + for (j = 0, len = confetti.length; j < len; j++) { + c = confetti[j]; + results.push(c.draw()); + } + return results; + }; + + step(); + +}).call(this); + + + +$(document).ready(function(){ + $(".c-button--register").click(function(){ + console.log(); + $(".js-title--main").animate({marginTop: '-50px'}); + }); +}); + + + + + + + + + diff --git a/pool/shard000/JavaScript/0004864_BWCall.js b/pool/shard000/JavaScript/0004864_BWCall.js new file mode 100644 index 0000000000000000000000000000000000000000..5982745adea79d8feb85496c4c24428a29854557 --- /dev/null +++ b/pool/shard000/JavaScript/0004864_BWCall.js @@ -0,0 +1,186 @@ +"use strict"; +var EventEmitter = require("events").EventEmitter; +var Joi = require("joi"); +var _ = require("lodash"); +var globalConfig = require("./configFile.js"); +var Util = require("./Util"); + +function BWCall(data) { + var self = this; + var callOptions = { + media : { + constraints : { + audio : true, + video : false + } + }, + extraHeaders : [] + }; + if (data.authToken){ + callOptions.extraHeaders.push("X-Callsign-Token: " + data.authToken); + } + if (data.options && data.options.identity){ + var e164 = Util.parsePhoneNumber(data.options.identity); + callOptions.extraHeaders.push("P-Preferred-Identity: "); + } + var remoteAudioElement = new global.Audio(); + var ringingAudio = new global.Audio(globalConfig.ringAudio); + data.info.status = "connecting"; + data.info.microphoneMuted = false; + + var dtmfSenders = []; + + if (data.info.direction === "out"){ + //do not invite until next tick, to allow event listeners to attach + setTimeout(function () { + data.session = data.userAgent.invite(data.info.remoteUri, callOptions); + data.session.on("connecting",function () { + playRinging(); + }); + data.session.on("accepted",onAccepted); + data.session.on("rejected",onCallEnded); + data.session.on("bye",onCallEnded); + data.session.on("cancel",onCallEnded); + self.emit("connecting"); + },0); + } + else { + data.session.on("cancel",onCallEnded); + } + this.setMicrophoneId = function (id) { + if (data.info.status !== "connecting"){ + throw new Error("must set microphone before the call connects"); + } + callOptions.media.constraints.audio = { + optional :[ + { + sourceId : id + } + ] + }; + }; + this.setRemoteAudioElement = function (element) { + remoteAudioElement = element; + if (remoteAudioElement && data.session){ + var remoteStream = data.session.getRemoteStreams()[ 0 ]; + remoteAudioElement.src = global.URL.createObjectURL(remoteStream); + remoteAudioElement.play(); + } + }; + + this.getInfo = function () { + return _.cloneDeep(data.info); + }; + + this.hangup = function () { + if (data.info.status === "connected"){ + data.info.status = "ended"; + data.session.bye(); + data.session = null; + } + else if (data.info.status === "connecting"){ + data.info.status = "ended"; + data.session.cancel(); + data.session = null; + } + else { + throw new Error("can only hangup a call in 'connected' or 'connecting' status"); + } + }; + + this.accept = function () { + if (data.notification){ + data.notification.close(); + } + if (data.info.direction !== "in" || data.info.status !== "connecting"){ + throw new Error("can only accept incoming calls in 'connecting' status"); + } + data.session.on("bye",function () { + data.info.status = "ended"; + self.emit("ended"); + }); + data.session.on("accepted",onAccepted); + data.session.accept(); + }; + this.reject = function () { + if (data.notification){ + data.notification.close(); + } + if (data.info.direction !== "in" || data.info.status !== "connecting"){ + throw new Error("can only reject incoming calls in 'connecting' status"); + } + data.session.reject(); + data.info.status = "ended"; + self.emit("ended"); + }; + this.mute = function () { + data.info.microphoneMuted = true; + if (data.session){ + data.session.mute(); + } + }; + this.unmute = function () { + data.info.microphoneMuted = false; + if (data.session){ + data.session.unmute(); + } + }; + this.sendDtmf = function (tone) { + tone = tone || null; + Joi.validate(tone,Joi.string().min(1).max(1),function (err) { + if (err){ + throw err; + } + }); + + if (data.info.status !== "connected"){ + throw new Error("can only send DTMF when in 'connected' status"); + } + + _.forEach(dtmfSenders, function (dtmfSender) { + dtmfSender.insertDTMF(tone); + }); + }; + function configureDTMF () { + var peerConnection = data.session.mediaHandler.peerConnection; + var localStreams = data.session.mediaHandler.getLocalStreams(); + for (var a = 0; a < localStreams.length; a += 1){ + if (peerConnection.createDTMFSender){ + var track = localStreams[a].getAudioTracks()[ 0 ]; + dtmfSenders.push(peerConnection.createDTMFSender(track)); + } + } + } + + function onCallEnded () { + data.info.status = "ended"; + stopRinging(); + self.emit("ended"); + } + function playRinging () { + ringingAudio.currentTime = 0; + ringingAudio.addEventListener("ended",ringingEndedHandler); + ringingAudio.play(); + } + function stopRinging () { + ringingAudio.removeEventListener("ended",ringingEndedHandler); + ringingAudio.pause(); + } + function ringingEndedHandler () { + ringingAudio.currentTime = 0; + ringingAudio.play(); + } + + function onAccepted () { + stopRinging(); + if (data.info.microphoneMuted){ + self.mute(); + } + self.setRemoteAudioElement(remoteAudioElement); + configureDTMF(); + data.info.status = "connected"; + self.emit("connected"); + } +} +BWCall.prototype = Object.create(EventEmitter.prototype); +module.exports = BWCall; diff --git a/pool/shard000/JavaScript/0004866_check-eslint.js b/pool/shard000/JavaScript/0004866_check-eslint.js new file mode 100644 index 0000000000000000000000000000000000000000..1924acaae16186d6cf5521cc6521bc34a984201c --- /dev/null +++ b/pool/shard000/JavaScript/0004866_check-eslint.js @@ -0,0 +1,22 @@ +module.exports = (gulp, config) => () => { + const esLint = require('gulp-eslint'); + const path = require('path'); + const packageJson = require(path.join(config.projectDir, 'package.json')); + + return gulp.src([ + path.join(config.configDir, '**', '*.js'), + '!' + path.join(config.projectDir, packageJson.jspm.configFile), + path.join(config.taskDir, '**', '*.js'), + 'gulpfile.js' + ]) + // eslint() attaches the lint output to the eslint property + // of the file object so it can be used by other modules. + .pipe(esLint()) + // eslint.format() outputs the lint results to the console. + // Alternatively use eslint.formatEach() (see Docs). + .pipe(esLint.format()) + // To have the process exit with an error code (1) on + // lint error, return the stream and pipe to failAfterError last. + .pipe(esLint.failAfterError()); + +}; diff --git a/pool/shard000/JavaScript/0004871_featurestore_service.batch_read_feature_values.js b/pool/shard000/JavaScript/0004871_featurestore_service.batch_read_feature_values.js new file mode 100644 index 0000000000000000000000000000000000000000..b1aadd555ac32c6eb5c88d632f1c5dfa21542458 --- /dev/null +++ b/pool/shard000/JavaScript/0004871_featurestore_service.batch_read_feature_values.js @@ -0,0 +1,108 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(featurestore, destination, entityTypeSpecs) { + // [START aiplatform_v1_generated_FeaturestoreService_BatchReadFeatureValues_async] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Each read instance consists of exactly one read timestamp and one or more + * entity IDs identifying entities of the corresponding EntityTypes whose + * Features are requested. + * Each output instance contains Feature values of requested entities + * concatenated together as of the read time. + * An example read instance may be `foo_entity_id, bar_entity_id, + * 2020-01-01T10:00:00.123Z`. + * An example output instance may be `foo_entity_id, bar_entity_id, + * 2020-01-01T10:00:00.123Z, foo_entity_feature1_value, + * bar_entity_feature2_value`. + * Timestamp in each read instance must be millisecond-aligned. + * `csv_read_instances` are read instances stored in a plain-text CSV file. + * The header should be: + * ENTITY_TYPE_ID1, ENTITY_TYPE_ID2, ..., timestamp + * The columns can be in any order. + * Values in the timestamp column must use the RFC 3339 format, e.g. + * `2012-07-30T10:43:17.123Z`. + */ + // const csvReadInstances = {} + /** + * Similar to csv_read_instances, but from BigQuery source. + */ + // const bigqueryReadInstances = {} + /** + * Required. The resource name of the Featurestore from which to query Feature values. + * Format: + * `projects/{project}/locations/{location}/featurestores/{featurestore}` + */ + // const featurestore = 'abc123' + /** + * Required. Specifies output location and format. + */ + // const destination = {} + /** + * When not empty, the specified fields in the *_read_instances source will be + * joined as-is in the output, in addition to those fields from the + * Featurestore Entity. + * For BigQuery source, the type of the pass-through values will be + * automatically inferred. For CSV source, the pass-through values will be + * passed as opaque bytes. + */ + // const passThroughFields = 1234 + /** + * Required. Specifies EntityType grouping Features to read values of and settings. + * Each EntityType referenced in + * BatchReadFeatureValuesRequest.entity_type_specs must have a column + * specifying entity IDs in the EntityType in + * BatchReadFeatureValuesRequest.request . + */ + // const entityTypeSpecs = 1234 + + // Imports the Aiplatform library + const {FeaturestoreServiceClient} = require('@google-cloud/aiplatform').v1; + + // Instantiates a client + const aiplatformClient = new FeaturestoreServiceClient(); + + async function callBatchReadFeatureValues() { + // Construct request + const request = { + featurestore, + destination, + entityTypeSpecs, + }; + + // Run request + const [operation] = await aiplatformClient.batchReadFeatureValues(request); + const [response] = await operation.promise(); + console.log(response); + } + + callBatchReadFeatureValues(); + // [END aiplatform_v1_generated_FeaturestoreService_BatchReadFeatureValues_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/pool/shard000/JavaScript/0004872_samsung-send.js b/pool/shard000/JavaScript/0004872_samsung-send.js new file mode 100644 index 0000000000000000000000000000000000000000..24bc87d5b5cacd31cbbfa60b8b88e2165dde0e7f --- /dev/null +++ b/pool/shard000/JavaScript/0004872_samsung-send.js @@ -0,0 +1,79 @@ +/* + * bin/commands/samsung-send.js + * + * David Janes + * IOTDB.org + * 2014-12-31 + * + * HomeStar command line control: "homestar add-id" + * Add a IDs to Groups + * + * Copyright [2013-2015] [David P. Janes] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +"use strict"; + +var iotdb = require('iotdb'); +var _ = iotdb.helpers; +var cfg = iotdb.cfg; + +var SamsungRemote = require('samsung-remote'); + +exports.command = "samsung-send"; +exports.summary = "testing: send a command to a Samsung TV"; + +exports.help = function () { + console.log("usage: homestar samsung-send "); + console.log(""); + console.log("e.g. homestar samsung-send KEY_HDMI"); +}; + +exports.run = function (ad) { + var self = this; + + if (ad._.length !== 2) { + console.log("#", "COMMAND argument is required (e.g KEY_HDMI, KEY_TV)"); + exports.help(); + process.exit(1); + } + + var command = ad._[1]; + + var cp = require("iotdb-upnp").control_point(); + + console.log("+", "looking for Samsung TV using UPnP"); + + cp.on("device", function (device) { + if (device.deviceType !== "urn:samsung.com:device:RemoteControlReceiver:1") { + return; + } + + console.log("+", "found one!", device.host); + + var native = new SamsungRemote({ + ip: device.host, + }); + + native.send(command, function(error) { + if (error) { + console.log("#", "command failed", _.error.message(error)); + process.exit(1); + } else { + console.log("+", "command sent!"); + process.exit(0); + } + }); + }); +}; diff --git a/pool/shard000/JavaScript/0004873_nanmskmin.js b/pool/shard000/JavaScript/0004873_nanmskmin.js new file mode 100644 index 0000000000000000000000000000000000000000..90a96ac4bf4358a74ab55ae9642ea7026ee8d74d --- /dev/null +++ b/pool/shard000/JavaScript/0004873_nanmskmin.js @@ -0,0 +1,99 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var isNegativeZero = require( '@stdlib/math/base/assert/is-negative-zero' ); + + +// MAIN // + +/** +* Computes the minimum value of a strided array according to a mask, ignoring `NaN` values. +* +* @param {PositiveInteger} N - number of indexed elements +* @param {NumericArray} x - input array +* @param {integer} strideX - `x` stride length +* @param {NumericArray} mask - mask array +* @param {integer} strideMask - `mask` stride length +* @returns {number} minimum value +* +* @example +* var x = [ 1.0, -2.0, -4.0, 2.0, NaN ]; +* var mask = [ 0, 0, 1, 0, 0 ]; +* +* var v = nanmskmin( x.length, x, 1, mask, 1 ); +* // returns -2.0 +*/ +function nanmskmin( N, x, strideX, mask, strideMask ) { + var min; + var ix; + var im; + var v; + var i; + + if ( N <= 0 ) { + return NaN; + } + if ( strideX < 0 ) { + ix = (1-N) * strideX; + } else { + ix = 0; + } + if ( strideMask < 0 ) { + im = (1-N) * strideMask; + } else { + im = 0; + } + for ( i = 0; i < N; i++ ) { + v = x[ ix ]; + if ( v === v && mask[ im ] === 0 ) { + break; + } + ix += strideX; + im += strideMask; + } + if ( i === N ) { + return NaN; + } + min = v; + i += 1; + for ( i; i < N; i++ ) { + ix += strideX; + im += strideMask; + if ( mask[ im ] ) { + continue; + } + v = x[ ix ]; + if ( isnan( v ) ) { + continue; + } + if ( v < min || ( v === min && isNegativeZero( v ) ) ) { + min = v; + } + } + return min; +} + + +// EXPORTS // + +module.exports = nanmskmin; diff --git a/pool/shard000/JavaScript/0004874_proxy.js b/pool/shard000/JavaScript/0004874_proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..b14a7a2c4caf9199c4ad16c6ddb5944eb3250e3a --- /dev/null +++ b/pool/shard000/JavaScript/0004874_proxy.js @@ -0,0 +1,94 @@ +/** + * Copyright 2018 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS-IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const express = require('express'); +const app = express(); +const AmpOptimizerMiddleware = require('amp-toolbox-optimizer-express'); +const ampOptimizer = require('amp-toolbox-optimizer'); +const compression = require('compression'); +const httpProxy = require('http-proxy'); +const https = require('https'); +const runtimeVersion = require('amp-toolbox-runtime-version'); +const apicache = require('apicache'); + +const cache = apicache.middleware; + +// Configure the transformers to be used. +// otherwise a default configuration is used. +ampOptimizer.setConfig({ + transformers: [ + 'PreloadImages', + 'AddAmpLink', + 'ServerSideRendering', + 'RemoveAmpAttribute', + // needs to run after ServerSideRendering + 'AmpBoilerplateTransformer', + // needs to run after ServerSideRendering + 'ReorderHeadTransformer', + // needs to run after ReorderHeadTransformer + 'RewriteAmpUrls', + 'GoogleFontsPreconnect' + ] +}); + +// Read proxy for command line, or default to ampbyexample.com. +const target = process.argv[2] || 'https://www.ampbyexample.com'; + +// Create a HTTP Proxy server the target +const proxy = httpProxy.createProxyServer({ + agent: https.globalAgent, + changeOrigin: true, + target: target, + headers: { + // We force encoding to avoid issues with data decompression. + 'accept-encoding': 'none' + } +}); + +// http-proxy doesn't handle errors by default, and crashes the server. Se we add our own handler. +proxy.on('error', (err, req, res) => { + res.writeHead(404, { + 'Content-Type': 'text/plain' + }); + + res.end('Page not Found'); +}); + +// Enable caching +app.use(cache('20 minutes')); + +// Enable compression +app.use(compression()); + +// Enable versioned AMP urls. +const currentVersion = () => runtimeVersion.currentVersion(); + +// Enable the Optimizer middleware. +app.use(AmpOptimizerMiddleware.create({ + ampOptimizer: ampOptimizer, + runtimeVersion: currentVersion +})); + +// Handle requests through the proxy. +app.use((req, res) => { + proxy.web(req, res); +}); + +const port = process.env.PORT || 8080; +app.listen(port); +console.log(`Proxying ${target} on port ${port}`); diff --git a/pool/shard000/JavaScript/0004877_CommandManager.js b/pool/shard000/JavaScript/0004877_CommandManager.js new file mode 100644 index 0000000000000000000000000000000000000000..552787e9aaee12d2bc87d76b3112539153bb17a1 --- /dev/null +++ b/pool/shard000/JavaScript/0004877_CommandManager.js @@ -0,0 +1,82 @@ +const Command = require('./Command'); + +class CommandManager { + constructor(client) { + this.client = client; + this.commands = {}; + this.pluginCommands = {}; + this.regexCmd = new RegExp(/^!(\S+)/); + this.cachedHelpText = null; + + this.registerCommand(new Command( + 'help', + 'Display this help text', + this.handleHelp.bind(this) + )); + + this.client.on('message', this.handleMessage.bind(this)); + } + + getNumCommands() { + return Object.keys(this.commands).length + } + + registerCommand(command) { + if (command.name in command) { + throw new Error("Attempted to register duplicate command: " + command.name); + } + + this.commands[command.name] = command; + } + + registerPluginCommands(commands) { + commands.forEach((command) => { + this.registerCommand(command); + }); + } + + handleHelp(message) { + const { member } = message; + const helpTexts = []; + let cmd = null; + + for (const i in this.commands) { + cmd = this.commands[i]; + if (!member.hasPermissions(cmd.permissions)) { + continue; + } + helpTexts.push('!' + cmd.name + ' - ' + cmd.description); + } + + return "```" + helpTexts.join('\n') + "```"; + } + + handleMessage(message) { + if (message.author == this.client.user) { + return; + } + + const match = this.regexCmd.exec(message.content) + + // Check if message is a command + if (match === null || !(match[1] in this.commands)) { + return; + } + + // Check permissions on command + const { member } = message; + const { + permissions, + callback + } = this.commands[match[1]]; + + if (permissions.length > 0 && (member === null || !member.hasPermissions(permissions))) { + return; + } + + // Execute command + message.channel.sendMessage(callback(message), {split: true}); + } +} + +module.exports = CommandManager; diff --git a/pool/shard000/JavaScript/0004880_waterfall.js b/pool/shard000/JavaScript/0004880_waterfall.js new file mode 100644 index 0000000000000000000000000000000000000000..39cbb9ac4407233b9d9211b9c110435596c0e8c2 --- /dev/null +++ b/pool/shard000/JavaScript/0004880_waterfall.js @@ -0,0 +1,43 @@ +$(window).on("load", function () { + waterfall(); + var dataInt = {"data": [{"src": "0.jpg"}, {"src": "1.jpg"}, {"src": "2.jpg"}, {"src": "3.jpg"}, {"src": "4.jpg"}]}; + $(window).on("scroll", function () { + if (checkScrollSlide) { + $.each(dataInt.data, function (key, value) { + var oBlock = $("
        ").addClass("block").appendTo($("#main")); + var oBox = $("
        ").addClass("box").appendTo($(oBlock)); + $("").attr("src", "img/" + $(value).attr("src")).appendTo($(oBox)); + waterfall(); + }) + } + }) +}) +function waterfall() { + var $blocks = $("#main>div"); + var w = $blocks.eq(0).outerWidth();//得到block的宽度 + var cols = Math.floor($(window).width() / w);//列数 = 屏幕宽度/block宽度 + $("#main").width(w * cols).css("margin", "0 auto"); //设定#main的div宽度+位置居中 + var hArr = []; //新数组存储各个block高度 + $blocks.each(function (index, value) { + var h = $blocks.eq(index).outerHeight(); + if (index < cols) { + hArr[index] = h; + } else { + var minH = Math.min.apply(null, hArr); + var minHindex = $.inArray(minH, hArr); + $(value).css({ + "position": "absolute", + "top": minH + "px", + "left": minHindex * w + "px" + }) + hArr[minHindex] += $blocks.eq(index).outerHeight(); + } + }) +} +function checkScrollSlide() { //懒加载 + var $lastBox = $("#main>div").last(); + var lastBoxDis = $lastBox.offset().top + Math.floor($lastBox.outerHeight() / 2); + var scrollTop = $(window).scrollTop(); + var documentH = $(window).height(); + return (lastBoxDis < scrollTop + documentH) ? true : false; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004882_passwordCheck.js b/pool/shard000/JavaScript/0004882_passwordCheck.js new file mode 100644 index 0000000000000000000000000000000000000000..3348a156c8be5e12407ea815434bd242c0bae56e --- /dev/null +++ b/pool/shard000/JavaScript/0004882_passwordCheck.js @@ -0,0 +1,58 @@ +function passStrength(password) +{ + var pass_strength = 0; + var re = /[a-z]/.test(password); + if(re == true) + { + pass_strength++; + } + var re = /[A-Z]/.test(password); + if(re == true) + { + pass_strength++; + } + var re = /[0-9]/.test(password); + if(re == true) + { + pass_strength++; + } + var spec_chars = /[^a-z0-9]/i; + var re = spec_chars.test(password); + if(re == true) + { + pass_strength++; + } + + return pass_strength; +} + +function updateStrengthDisplay(password) +{ + + + var str_text = document.getElementById('strength_text'); + if(password.length == 0) { + str_text.innerHTML = ''; + return; + } + + var pass_str = passStrength(password); + + if(pass_str <= 2) + { + str_text.innerHTML = 'Light'; + str_text.style.color = 'red'; + str_text.style.fontWeight = 'bold'; + + } + if(pass_str == 3) + { + str_text.innerHTML = 'Moderate'; + str_text.style.color = 'orange'; + } + if(pass_str == 4) + { + str_text.innerHTML = 'Strong'; + str_text.style.color = 'green'; + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004883_Reddit.js b/pool/shard000/JavaScript/0004883_Reddit.js new file mode 100644 index 0000000000000000000000000000000000000000..2e4f543b885de04bd1a20615b52938d8b8a850c0 --- /dev/null +++ b/pool/shard000/JavaScript/0004883_Reddit.js @@ -0,0 +1,70 @@ +const Plugin = require("../Plugin"); +const Util = require("./../Util"); +const request = require("request-promise-native"); + +module.exports = class Reddit extends Plugin { + static get plugin() { + return { + name: "Reddit", + description: "Get a random post from the Reddit frontpage or a subreddit", + help: `\`/reddit\` gets a random post; \`/reddit sub\` gets a random post from the subreddit. + \`/redimg _subreddit_\` : gets a random image from _subreddit_ + ` + }; + } + + async sendRequest(url) { + return request(url); + } + + subCommand(command,body) { + const results = JSON.parse(body).data.children; + switch (command) { + case "reddit": + return this.reddit(results); + case "redimg": + return this.redimg(results); + } + } + + + async onCommand({message, command, args}) { + if (command !== "reddit" && command !== "redimg") + return; + + const sub = args[0]; + return this.sendRequest("https://reddit.com/" + (sub ? `r/${sub}` : "") + ".json") + .then(body => this.subCommand(command, body)) + .catch(() => "Reddit down or subreddit banned.") + + } + + reddit(results) { + const item = results[Math.floor(Math.random() * results.length)].data; + return { + type: "text", + text: `${Util.makeHTMLLink(item.title, "https://reddit.com" + item.permalink)} - r/${item.subreddit}`, + options: { + parse_mode: "HTML" + } + }; + } + + redimg(results) { + results = results + .map(c => c.data) + .filter(c => c.post_hint === "image"); + + if (results.length == 0) return "Subreddit not found!" + + const item = results[Math.floor(Math.random() * results.length)]; + return { + type: "photo", + photo: item.url, + options: { + caption: `${item.title}\n\n${item.url}` + } + }; + } +}; + diff --git a/pool/shard000/JavaScript/0004885_Empty3DTileContentSpec.js b/pool/shard000/JavaScript/0004885_Empty3DTileContentSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..86dbf32b94386683abb57e4561d66d97fd3b01ec --- /dev/null +++ b/pool/shard000/JavaScript/0004885_Empty3DTileContentSpec.js @@ -0,0 +1,32 @@ +/*global defineSuite*/ +defineSuite([ + 'Scene/Empty3DTileContent' + ], function( + Empty3DTileContent) { + 'use strict'; + + it('destroys', function() { + var content = new Empty3DTileContent(); + expect(content.isDestroyed()).toEqual(false); + content.destroy(); + expect(content.isDestroyed()).toEqual(true); + }); + + it('gets properties', function() { + var mockTileset = {}; + var mockTile = {}; + var content = new Empty3DTileContent(mockTileset, mockTile); + expect(content.featuresLength).toBe(0); + expect(content.pointsLength).toBe(0); + expect(content.trianglesLength).toBe(0); + expect(content.geometryByteLength).toBe(0); + expect(content.texturesByteLength).toBe(0); + expect(content.batchTableByteLength).toBe(0); + expect(content.innerContents).toBeUndefined(); + expect(content.readyPromise).toBeUndefined(); + expect(content.tileset).toBe(mockTileset); + expect(content.tile).toBe(mockTile); + expect(content.url).toBeUndefined(); + expect(content.batchTable).toBeUndefined(); + }); +}); diff --git a/pool/shard000/JavaScript/0004888_db.js b/pool/shard000/JavaScript/0004888_db.js new file mode 100644 index 0000000000000000000000000000000000000000..7bb1a616e95aa6591cc54c11bbd84df6591758ab --- /dev/null +++ b/pool/shard000/JavaScript/0004888_db.js @@ -0,0 +1,23 @@ +/** + * Created by xiyuyizhi on 2016/9/5. + */ +var MongoClient = require('mongodb'), + Config=require('../config'), + url = Config.DBUrl; + +module.exports = { + connect: function (callback) { + MongoClient.connect(url, function(err,db){ + callback(err,db); + return false; + }); + }, + generatorObjectId: function (id) { + if(id){ + return new MongoClient.ObjectId(id) + }else{ + return new MongoClient.ObjectId() + } + + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004889_FloatInput.js b/pool/shard000/JavaScript/0004889_FloatInput.js new file mode 100644 index 0000000000000000000000000000000000000000..ee7524e6f7ba68f43fcde9c17426ce49a5980434 --- /dev/null +++ b/pool/shard000/JavaScript/0004889_FloatInput.js @@ -0,0 +1,60 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +import TextField from 'material-ui/TextField'; + +class FloatInput extends React.Component { + constructor(props) { + super(props); + this.state = { + value : this.props.field.defaultValue || "", + validationMessage: "" + }; + } + + onBlur(e) { + var value = e.target.value; + var float = Number(value); + var success = value && Number.isFinite(float); + var validationMessage = success ? "" : `"${value}" is not a float`; + this.setState({ + value: value, + validationMessage: validationMessage + }); + if (success) { + this.props.onSuccessfulParse(float); + } + } + + onChange(e) { + this.setState({ + value: e.target.value, + validationMessage: "" + }); + } + + render() { + return ( +
        + +
        + ); + } +} + +FloatInput.propTypes = { + field: PropTypes.object, + onSuccessfulParse: PropTypes.func, + theme: PropTypes.object +}; + +export default FloatInput; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004891_queryParser.js b/pool/shard000/JavaScript/0004891_queryParser.js new file mode 100644 index 0000000000000000000000000000000000000000..6eb59691ff9b80d68df56bc1048904ace57aa4a0 --- /dev/null +++ b/pool/shard000/JavaScript/0004891_queryParser.js @@ -0,0 +1,47 @@ +import currencies from '../data/currencies.js'; +import localeCurrency from '../data/locale-currency.js'; +import i18n from '../locales/i18n.js'; + +function isNumber(item) { + return !isNaN(parseInt(item, 10)); +} + +module.exports = function(queryString, pathname) { + queryString = queryString || {}; + var localesData = i18n.intlDataFor(i18n.urlOverrideLang(pathname).lang); + var presets = queryString.presets || ""; + var locale = localesData.locales[0]; + + var queryStringCurrencyCode = queryString.currency; + var localeCurrencyCode = localeCurrency[locale]; + var amount = ""; + var frequency = "single"; + var currency = currencies[queryStringCurrencyCode] || currencies[localeCurrencyCode] || currencies.usd; + + if (queryString.amount && !isNaN(queryString.amount)) { + amount = queryString.amount.trim(); + } + if (queryString.frequency === "monthly") { + frequency = "monthly"; + } + + // We didn't get valid presets from the query string, + // so default to the currency and frequency preset. + presets = presets.split(","); + if (presets.length !== 4 || !presets.every(isNumber)) { + presets = currency.presets[frequency]; + } + + return { + test: queryString.test, + currency: currency, + presets: presets, + currencies: currencies, + amount: amount, + frequency: frequency, + messages: localesData.messages, + locales: localesData.locales, + email: queryString.email || "", + country: queryString.country || "" + }; +}; diff --git a/pool/shard000/JavaScript/0004894_TimeChangeRecurrence.js b/pool/shard000/JavaScript/0004894_TimeChangeRecurrence.js new file mode 100644 index 0000000000000000000000000000000000000000..1341fcc3fb67a3b5909c0cb6f7ac9392bca4ed46 --- /dev/null +++ b/pool/shard000/JavaScript/0004894_TimeChangeRecurrence.js @@ -0,0 +1,18 @@ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var ComplexProperty_1 = require("./ComplexProperty"); +var TimeChangeRecurrence = (function (_super) { + __extends(TimeChangeRecurrence, _super); + function TimeChangeRecurrence() { + _super.apply(this, arguments); + } + TimeChangeRecurrence.prototype.ReadElementsFromXmlJsObject = function (reader) { throw new Error("TimeChangeRecurrence.ts - TryReadElementFromXmlJsObject : Not implemented."); }; + TimeChangeRecurrence.prototype.WriteElementsToXml = function (writer) { throw new Error("TimeChangeRecurrence.ts - WriteElementsToXml : Not implemented."); }; + return TimeChangeRecurrence; +}(ComplexProperty_1.ComplexProperty)); +exports.TimeChangeRecurrence = TimeChangeRecurrence; +//} diff --git a/pool/shard000/JavaScript/0004898_test.js b/pool/shard000/JavaScript/0004898_test.js new file mode 100644 index 0000000000000000000000000000000000000000..3343b0f23b736b2804c35aced695d1034565d527 --- /dev/null +++ b/pool/shard000/JavaScript/0004898_test.js @@ -0,0 +1,114 @@ + +// Just to make sure that the package.json is created properly, navigate to one +// folder above this packages directory. +var ljs_req = require('../../ljswitchboard-require'); +var req = ljs_req.require; +var path = require('path'); + +var rootDirectory = process.cwd().split(path.sep).join('/'); +var testDirectory = rootDirectory + '/test'; +var expectedDirectories = ['', '.', testDirectory]; + +var expectedTestObjKeys = ['testVar', 'tFunc', 'req']; + +exports.basic_test = { + 'add a directory': function(test) { + expectedDirectories.push(rootDirectory); + ljs_req.addDirectory(rootDirectory); + + // Test the directory addition + var msg = 'ljs-req search directories var is invalid'; + test.deepEqual(ljs_req.getDirectories(), expectedDirectories, msg); + test.done(); + }, + 'add multiple directories': function(test) { + + var directories = ['dir_a','dir_b']; + for(var i = 0; i < directories.length; i++) { + directories[i] = testDirectory + '/' + directories[i]; + } + expectedDirectories.push.apply(expectedDirectories, directories); + + ljs_req.addDirectories(directories); + + // Test the addition of directories + var msg = 'ljs-req search directories var is invalid'; + test.deepEqual(ljs_req.getDirectories(), expectedDirectories, msg); + test.done(); + }, + 'require "test-module"': function(test) { + try { + var test_module = req('test-module'); + + var msgs = [ + 'Required object has invalid keys', + 'Required object returned an invalid result' + ]; + var foundKeys = Object.keys(test_module); + test.deepEqual(foundKeys, expectedTestObjKeys, msgs[0]); + var expectedTestVar = 'test-module: index.js'; + test.strictEqual(test_module.testVar, expectedTestVar, msgs[1]); + test.ok(true); + } catch (err) { + console.log('ERROR',err); + test.ok(false); + } + test.done(); + }, + 'require "sub_test.js"': function(test) { + try { + var test_module = req('sub_test.js'); + + var msgs = [ + 'Required object has invalid keys', + 'Required object returned an invalid result' + ]; + var foundKeys = Object.keys(test_module); + test.deepEqual(foundKeys, expectedTestObjKeys, msgs[0]); + var expectedTestVar = 'sub_test.js'; + test.strictEqual(test_module.testVar, expectedTestVar, msgs[1]); + test.ok(true); + } catch (err) { + console.log('ERROR',err); + test.ok(false); + } + test.done(); + }, + 'require "test_file.js"': function(test) { + try { + var test_module = req('test_file.js'); + + var msgs = [ + 'Required object has invalid keys', + 'Required object returned an invalid result' + ]; + var foundKeys = Object.keys(test_module); + test.deepEqual(foundKeys, expectedTestObjKeys, msgs[0]); + var expectedTestVar = 'test-file.js'; + test.strictEqual(test_module.testVar, expectedTestVar, msgs[1]); + test.ok(true); + } catch (err) { + console.log('ERROR',err); + test.ok(false); + } + test.done(); + }, + 'require an invalid module': function(test) { + try { + var test_module = req('test-modulea'); + console.log('Module some how found', test_module); + test.ok(false); + } catch (err) { + var expectedMessage = "Can not find module 'test-modulea'"; + var msgs = [ + 'Invalid err.message returned', + 'Invalid err.code returned' + ]; + + test.strictEqual(err.message, expectedMessage, msgs[0]); + test.strictEqual(err.code, 'MODULE_NOT_FOUND', msgs[1]); + test.ok(true); + } + test.done(); + }, +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004899_remind-me.js b/pool/shard000/JavaScript/0004899_remind-me.js new file mode 100644 index 0000000000000000000000000000000000000000..11aa47bdfc0dae7bd3543e65163b4c43c7d8a3ae --- /dev/null +++ b/pool/shard000/JavaScript/0004899_remind-me.js @@ -0,0 +1,31 @@ +// Description: +// Reminds you to do something after a specified waiting time +// +// Commands: +// hubot remind me to in seconds - Send a reminder in secs +// +// Notes: +// If the hubot is shut down, all reminders are cleared. +// +'use strict'; + +module.exports = function(robot) { + // Handler for "hubot remind me to in seconds" + robot.respond(/remind me to (.+) in (\d+) seconds?$/i, function(msg) { + const task = msg.match[1]; + const numSeconds = msg.match[2]; + const milliseconds = numSeconds * 1000; + const plural_suf = numSeconds == 1 ? '' : 's'; + + msg.reply( + `OK. I'll remind you to ${task} in ${numSeconds} second${plural_suf}.` + ); + + setTimeout( + () => { + msg.reply(`Don't forget to ${task}!`); + }, + milliseconds + ); + }); +}; diff --git a/pool/shard000/JavaScript/0004901_ui.js b/pool/shard000/JavaScript/0004901_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..2a6e618120eb0b04f6a54ed7257180864c1a689b --- /dev/null +++ b/pool/shard000/JavaScript/0004901_ui.js @@ -0,0 +1,30 @@ +(function () { + "use strict"; + + let switcher = document.getElementById("datasets"); + switcher.innerHTML = Object.keys(window.datasets) + .map(key => ``) + .join(" \u2502 "); + switcher.datasetType[0].checked = true; + switcher.addEventListener("change", () => { + window.postMessage({type: "recalc", datasetType: switcher.datasetType.value}, "*"); + }); + + window.addEventListener("load", () => { + window.postMessage({type: "recalc", datasetType: switcher.datasetType.value}, "*"); + }); + + window.addEventListener("message", ({data = {}}) => { + if (data.type !== "recalcDone") { + return; + } + let output = ""; + Object.entries(data.result).forEach(([name, result]) => { + output += `================== ${name} ==================\n`; + output += JSON.stringify(result.potential, null, 4); + output += `\nR² = ${result.rSqr}\n`; + output += `points: ${JSON.stringify(result.points, null, 4)}\n\n`; + }); + document.getElementById("result").textContent = output; + }); +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004906_doctorsController.js b/pool/shard000/JavaScript/0004906_doctorsController.js new file mode 100644 index 0000000000000000000000000000000000000000..279382ed94a83e64bad700381409694d87ba55eb --- /dev/null +++ b/pool/shard000/JavaScript/0004906_doctorsController.js @@ -0,0 +1,103 @@ +class DoctorsController { + constructor($scope, $rootScope, $state, doctorsService, toasterService, modalService) { + const pageSize = 4; + var pageCount = 0; + $scope.doctors = []; + + $scope.getList = () => { + $rootScope.loading = true; + doctorsService.getList(pageSize, pageCount) + .then((doctors) => { + if (doctors.length < pageSize) { + $scope.noMoreData = true; + } + doctors.forEach((doctor) => { + $scope.doctors.push(doctor); + }); + pageCount ++; + $scope.refreshSelectedItems(); + + if (!$scope.doctors.length) { + $scope.noData = true; + } + }) + .catch((error) => { + toasterService.showServerError(error); + }) + .finally(() => { + $rootScope.loading = false; + }); + }; + + $scope.nagivateToDetail = (doctorId) => { + doctorId ? $state.transitionTo('doctor', { id: doctorId }) : $state.transitionTo('doctor'); + }; + + $scope.refreshSelectedItems = (all) => { + if (all) { + $scope.doctors.forEach((doctor) => { + doctor.selected = $scope.everySelected; + }); + } + + $scope.anySelected = $scope.doctors.some((doctor) => { + return doctor.selected; + }); + + $scope.everySelected = $scope.doctors.every((doctor) => { + return doctor.selected; + }); + }; + + $scope.remove = (doctor) => { + var severalDoctors = doctor === undefined; + + modalService.showConfirmModal({ + messages: { + title: `Remove doctor${severalDoctors?'s':''}`, + body: `Are you sure you want to remove the selected doctor${severalDoctors?'s':''}?`, + ok: 'Yes, remove', + cancel: 'Cancel' + } + }) + .then(() => { + var doctorIdList; + if (doctor) { + doctorIdList = [doctor.DoctorId]; + } else { + doctorIdList = $scope.doctors + .map((doctorItem) => { + if (doctorItem.selected) { + return doctorItem.DoctorId; + } + return null; + }); + } + + doctorIdList.forEach((doctorId) => { + doctorsService.remove(doctorId) + .then((response) => { + if (response.status === 200) { + $scope.doctors.forEach((doctorItem) => { + if (doctorId === doctorItem.DoctorId) { + let index = $scope.doctors.indexOf(doctorItem); + $scope.doctors.splice(index, 1); + } + }); + } + }) + .catch((error) => { + toasterService.showServerError(error); + }); + }); + + $scope.refreshSelectedItems(); + }); + }; + + $scope.getList(); + } +} + + +export default DoctorsController; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004907_server.js b/pool/shard000/JavaScript/0004907_server.js new file mode 100644 index 0000000000000000000000000000000000000000..4ba9eac992f2a1f714e273976b89b26fe43a0e7e --- /dev/null +++ b/pool/shard000/JavaScript/0004907_server.js @@ -0,0 +1,71 @@ +var async = require("async"), + wifi_manager = require("./app/wifi_manager")(), + dependency_manager = require("./app/dependency_manager")(), + config = require("./config.json"); + +/*****************************************************************************\ + 1. Check for dependencies + 2. Check to see if we are connected to a wifi AP + 3. If connected to a wifi, do nothing -> exit + 4. Convert RPI to act as a AP (with a configurable SSID) + 5. Host a lightweight HTTP server which allows for the user to connect and + configure the RPIs wifi connection. The interfaces exposed are RESTy so + other applications can similarly implement their own UIs around the + data returned. + 6. Once the RPI is successfully configured, reset it to act as a wifi + device (not AP anymore), and setup its wifi network based on what the + user picked. + 7. At this stage, the RPI is named, and has a valid wifi connection which + its bound to, reboot the pi and re-run this script on startup. +\*****************************************************************************/ +async.series([ + + // 1. Check if we have the required dependencies installed + function test_deps(next_step) { + dependency_manager.check_deps({ + "binaries": ["dhcpcd", "hostapd", "iw", "dnsmasq"] + }, function(error) { + if (error) console.log(" * Dependency error, did you run `sudo npm run-script provision`?"); + next_step(error); + }); + }, + + // 2. Check if wifi is enabled / connected + function test_is_wifi_enabled(next_step) { + wifi_manager.is_wifi_enabled(function(error, result_ip) { + // console.log(result_ip) + if (result_ip) { + console.log("\nWifi is enabled, and IP " + result_ip + " assigned"); + process.exit(0); + } else { + console.log("\nWifi is not enabled, Enabling AP for self-configure"); + } + next_step(error); + }); + }, + + // 3. Turn RPI into an access point + function enable_rpi_ap(next_step) { + wifi_manager.enable_ap_mode(config.access_point.ssid, function(error) { + if(error) { + console.log("... AP Enable ERROR: " + error); + } else { + console.log("... AP Enable Success!"); + } + next_step(error); + }); + }, + + // 4. Host HTTP server while functioning as AP, the "api.js" + // file contains all the needed logic to get a basic express + // server up. It uses a small angular application which allows + // us to choose the wifi of our choosing. + function start_http_server(next_step) { + require("./app/api.js")(wifi_manager, next_step); + }, + +], function(error) { + if (error) { + console.log("ERROR: " + error); + } +}); diff --git a/pool/shard000/JavaScript/0004908_UpdateChat.js b/pool/shard000/JavaScript/0004908_UpdateChat.js new file mode 100644 index 0000000000000000000000000000000000000000..97b8857da71c579854aac177d2a5d77009ec8214 --- /dev/null +++ b/pool/shard000/JavaScript/0004908_UpdateChat.js @@ -0,0 +1,53 @@ +import React, { PropTypes, Component } from 'react'; +import { connect } from 'react-redux'; +import fU from '../Utils.js'; +import * as actions from '../actions'; +import ChatForm from './elements/ChatForm'; +// import languages from '../translate.js'; + +class UpdateChat extends Component { + componentDidMount() { + this.props.initU().get('chats/' + this.props.params.id + '.json', actions.noAction, actions.setChat, actions.noAction); + } + updateChat(data) { + this.props.initU().put('chats/' + this.props.params.id, actions.noAction, actions.noAction, actions.noAction, data, {Authorization: this.props.user.token} ); + } + render() { + return ( +
        +

        {this.props.languages[this.props.language].actualizar_chat.actualizar_chat}

        + +
        + ); + } +} + +UpdateChat.propTypes = { + register: PropTypes.func, + registerWithMail: PropTypes.func, + chat: PropTypes.object, + params: PropTypes.object, + initU: PropTypes.func, + user: PropTypes.object, + language: PropTypes.string, languages: PropTypes.object, +}; + +const mapStateToProps = (state) => { + return { + chat: state.chat, + categories: state.categories, + user: state.user, + language: state.language, languages: state.languages, + }; +}; + +const mapDispatchToProps = (dispatch) => { + return { + initU: () => { return fU(dispatch); } + }; +}; + +export default connect( + mapStateToProps, + mapDispatchToProps +)(UpdateChat); diff --git a/pool/shard000/JavaScript/0004909_config.js b/pool/shard000/JavaScript/0004909_config.js new file mode 100644 index 0000000000000000000000000000000000000000..325d2ac4f02c2737f0b918bc3e0004a4aa6a3674 --- /dev/null +++ b/pool/shard000/JavaScript/0004909_config.js @@ -0,0 +1,23 @@ +'use strict'; + +// Init the application configuration module for AngularJS application +var ApplicationConfiguration = (function() { + // Init module configuration options + var applicationModuleName = 'bookmark-manager'; + var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils']; + + // Add a new vertical module + var registerModule = function(moduleName) { + // Create angular module + angular.module(moduleName, []); + + // Add the module to the AngularJS configuration file + angular.module(applicationModuleName).requires.push(moduleName); + }; + + return { + applicationModuleName: applicationModuleName, + applicationModuleVendorDependencies: applicationModuleVendorDependencies, + registerModule: registerModule + }; +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004910_init.js b/pool/shard000/JavaScript/0004910_init.js new file mode 100644 index 0000000000000000000000000000000000000000..06b3d6179d9fd66e2d2c24990f357693cf49ffae --- /dev/null +++ b/pool/shard000/JavaScript/0004910_init.js @@ -0,0 +1,40 @@ +'use strict'; + +angular.element(document).ready(function() { + + // Run copayApp after device is ready. + var startAngular = function() { + angular.bootstrap(document, ['copayApp']); + }; + + + function handleOpenURL(url) { + if ('cordova' in window) { + cordova.fireDocumentEvent('handleopenurl', { + url: url + }); + } else { + console.log("ERROR: Cannont handle open URL in non-cordova apps") + } + }; + + /* Cordova specific Init */ + if ('cordova' in window) { + + window.handleOpenURL = handleOpenURL; + + + document.addEventListener('deviceready', function() { + + window.open = cordova.InAppBrowser.open; + + // Create a sticky event for handling the app being opened via a custom URL + cordova.addStickyDocumentEventHandler('handleopenurl'); + startAngular(); + }, false); + + } else { + startAngular(); + } + +}); diff --git a/pool/shard000/JavaScript/0004911_payoutitem.js b/pool/shard000/JavaScript/0004911_payoutitem.js new file mode 100644 index 0000000000000000000000000000000000000000..e959d717720a677dda4774482407ae36798ed6b4 --- /dev/null +++ b/pool/shard000/JavaScript/0004911_payoutitem.js @@ -0,0 +1,398 @@ +"use strict"; +// The content of this file was automatically generated +var PayoutItem = /** @class */ (function () { + /** + * PayoutItem constructor + * @param {ProcessOut} client + * @param {array} prefill (optional) + */ + function PayoutItem(client, prefill) { + this.client = null; + /** + * ID of the payout item + * @type {string} + */ + this.id = null; + /** + * Project to which the payout item belongs + * @type {p.Project} + */ + this.project = null; + /** + * ID of the project to which the payout item belongs + * @type {string} + */ + this.projectId = null; + /** + * Payout to which the item belongs + * @type {p.Payout} + */ + this.payout = null; + /** + * ID of the payout to which the item belongs + * @type {string} + */ + this.payoutId = null; + /** + * Transaction linked to this payout item. Can be null + * @type {p.Transaction} + */ + this.transaction = null; + /** + * ID of the transaction linked to this payout item. Can be null + * @type {string} + */ + this.transactionId = null; + /** + * Type of the payout item + * @type {string} + */ + this.type = null; + /** + * ID of the payout item from the payment gateway + * @type {string} + */ + this.gatewayResourceId = null; + /** + * Amount related to this specific payout item. Can be null or 0. + * @type {string} + */ + this.amount = null; + /** + * Fee linked to this specific payout item. Can be null or 0. + * @type {string} + */ + this.fees = null; + /** + * Metadata related to the payout item, in the form of a dictionary (key-value pair) + * @type {any} + */ + this.metadata = null; + /** + * Date at which the payout item was created + * @type {string} + */ + this.createdAt = null; + if (typeof client === 'undefined') + throw new Error("The PayoutItem object must be instanciated with the ProcessOut client. You can create one using new ProcessOut('project-id', 'project-secret').newPayoutItem()"); + this.client = client; + if (typeof prefill !== 'undefined') + this.fillWithData(prefill); + } + PayoutItem.prototype.getProcessOutObjectClass = function () { + return "PayoutItem"; + }; + /** + * Get Id + * ID of the payout item + * @return {string} + */ + PayoutItem.prototype.getId = function () { + return this.id; + }; + /** + * Set Id + * ID of the payout item + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setId = function (val) { + this.id = val; + return this; + }; + /** + * Get Project + * Project to which the payout item belongs + * @return {p.Project} + */ + PayoutItem.prototype.getProject = function () { + return this.project; + }; + /** + * Set Project + * Project to which the payout item belongs + * @param {p.Project} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setProject = function (val) { + if (val.getProcessOutObjectClass && + val.getProcessOutObjectClass() == this.client.newProject().getProcessOutObjectClass()) + this.project = val; + else { + var obj = this.client.newProject(); + obj.fillWithData(val); + this.project = obj; + } + return this; + }; + /** + * Get ProjectId + * ID of the project to which the payout item belongs + * @return {string} + */ + PayoutItem.prototype.getProjectId = function () { + return this.projectId; + }; + /** + * Set ProjectId + * ID of the project to which the payout item belongs + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setProjectId = function (val) { + this.projectId = val; + return this; + }; + /** + * Get Payout + * Payout to which the item belongs + * @return {p.Payout} + */ + PayoutItem.prototype.getPayout = function () { + return this.payout; + }; + /** + * Set Payout + * Payout to which the item belongs + * @param {p.Payout} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setPayout = function (val) { + if (val.getProcessOutObjectClass && + val.getProcessOutObjectClass() == this.client.newPayout().getProcessOutObjectClass()) + this.payout = val; + else { + var obj = this.client.newPayout(); + obj.fillWithData(val); + this.payout = obj; + } + return this; + }; + /** + * Get PayoutId + * ID of the payout to which the item belongs + * @return {string} + */ + PayoutItem.prototype.getPayoutId = function () { + return this.payoutId; + }; + /** + * Set PayoutId + * ID of the payout to which the item belongs + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setPayoutId = function (val) { + this.payoutId = val; + return this; + }; + /** + * Get Transaction + * Transaction linked to this payout item. Can be null + * @return {p.Transaction} + */ + PayoutItem.prototype.getTransaction = function () { + return this.transaction; + }; + /** + * Set Transaction + * Transaction linked to this payout item. Can be null + * @param {p.Transaction} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setTransaction = function (val) { + if (val.getProcessOutObjectClass && + val.getProcessOutObjectClass() == this.client.newTransaction().getProcessOutObjectClass()) + this.transaction = val; + else { + var obj = this.client.newTransaction(); + obj.fillWithData(val); + this.transaction = obj; + } + return this; + }; + /** + * Get TransactionId + * ID of the transaction linked to this payout item. Can be null + * @return {string} + */ + PayoutItem.prototype.getTransactionId = function () { + return this.transactionId; + }; + /** + * Set TransactionId + * ID of the transaction linked to this payout item. Can be null + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setTransactionId = function (val) { + this.transactionId = val; + return this; + }; + /** + * Get Type + * Type of the payout item + * @return {string} + */ + PayoutItem.prototype.getType = function () { + return this.type; + }; + /** + * Set Type + * Type of the payout item + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setType = function (val) { + this.type = val; + return this; + }; + /** + * Get GatewayResourceId + * ID of the payout item from the payment gateway + * @return {string} + */ + PayoutItem.prototype.getGatewayResourceId = function () { + return this.gatewayResourceId; + }; + /** + * Set GatewayResourceId + * ID of the payout item from the payment gateway + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setGatewayResourceId = function (val) { + this.gatewayResourceId = val; + return this; + }; + /** + * Get Amount + * Amount related to this specific payout item. Can be null or 0. + * @return {string} + */ + PayoutItem.prototype.getAmount = function () { + return this.amount; + }; + /** + * Set Amount + * Amount related to this specific payout item. Can be null or 0. + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setAmount = function (val) { + this.amount = val; + return this; + }; + /** + * Get Fees + * Fee linked to this specific payout item. Can be null or 0. + * @return {string} + */ + PayoutItem.prototype.getFees = function () { + return this.fees; + }; + /** + * Set Fees + * Fee linked to this specific payout item. Can be null or 0. + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setFees = function (val) { + this.fees = val; + return this; + }; + /** + * Get Metadata + * Metadata related to the payout item, in the form of a dictionary (key-value pair) + * @return {any} + */ + PayoutItem.prototype.getMetadata = function () { + return this.metadata; + }; + /** + * Set Metadata + * Metadata related to the payout item, in the form of a dictionary (key-value pair) + * @param {any} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setMetadata = function (val) { + this.metadata = val; + return this; + }; + /** + * Get CreatedAt + * Date at which the payout item was created + * @return {string} + */ + PayoutItem.prototype.getCreatedAt = function () { + return this.createdAt; + }; + /** + * Set CreatedAt + * Date at which the payout item was created + * @param {string} val + * @return {PayoutItem} + */ + PayoutItem.prototype.setCreatedAt = function (val) { + this.createdAt = val; + return this; + }; + /** + * Fills the current object with the new values pulled from the data + * @param {array} data + * @return {PayoutItem} + */ + PayoutItem.prototype.fillWithData = function (data) { + if (data["id"]) + this.setId(data["id"]); + if (data["project"]) + this.setProject(data["project"]); + if (data["project_id"]) + this.setProjectId(data["project_id"]); + if (data["payout"]) + this.setPayout(data["payout"]); + if (data["payout_id"]) + this.setPayoutId(data["payout_id"]); + if (data["transaction"]) + this.setTransaction(data["transaction"]); + if (data["transaction_id"]) + this.setTransactionId(data["transaction_id"]); + if (data["type"]) + this.setType(data["type"]); + if (data["gateway_resource_id"]) + this.setGatewayResourceId(data["gateway_resource_id"]); + if (data["amount"]) + this.setAmount(data["amount"]); + if (data["fees"]) + this.setFees(data["fees"]); + if (data["metadata"]) + this.setMetadata(data["metadata"]); + if (data["created_at"]) + this.setCreatedAt(data["created_at"]); + return this; + }; + /** + * Implements a JSON custom marshaller + * @return {any} + */ + PayoutItem.prototype.toJSON = function () { + return { + "id": this.getId(), + "project": this.getProject(), + "project_id": this.getProjectId(), + "payout": this.getPayout(), + "payout_id": this.getPayoutId(), + "transaction": this.getTransaction(), + "transaction_id": this.getTransactionId(), + "type": this.getType(), + "gateway_resource_id": this.getGatewayResourceId(), + "amount": this.getAmount(), + "fees": this.getFees(), + "metadata": this.getMetadata(), + "created_at": this.getCreatedAt(), + }; + }; + return PayoutItem; +}()); +module.exports = PayoutItem; +//# sourceMappingURL=payoutitem.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004914_minecraft.js b/pool/shard000/JavaScript/0004914_minecraft.js new file mode 100644 index 0000000000000000000000000000000000000000..158deb480104d89fffccb2d791b115f2c1cbb787 --- /dev/null +++ b/pool/shard000/JavaScript/0004914_minecraft.js @@ -0,0 +1,21 @@ +function setCarouselHeight(id) { + var slideHeight = []; + $(id + ' .carousel-item').each(function () { + // add all slide heights to an array + slideHeight.push($(this).height()); + }); + + // find the tallest item + max = Math.max.apply(null, slideHeight); + + // set the slide's height + $(id + ' .carousel-content').each(function () { + $(this).css('height', max + 'px'); + }); +} + +setCarouselHeight('#slideshow'); + +window.onorientationchange = function() { + setCarouselHeight('#slideshow'); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004916_example1.js b/pool/shard000/JavaScript/0004916_example1.js new file mode 100644 index 0000000000000000000000000000000000000000..9b8a8834813b93ec655b78196e311e263f121dc8 --- /dev/null +++ b/pool/shard000/JavaScript/0004916_example1.js @@ -0,0 +1,104 @@ + var columnDefs = [ + {headerName: "Person", field: 'name', width: 400, + cellStyle: {'background-color': 'rgba(255, 255, 180, 0.5)'} // light yellow background + }, + { + headerName: 'Weekly Editable Values', + children: [ + {headerName: "Monday", field: "mon", newValueHandler: numberNewValueHandler, editable: true}, + {headerName: "Tuesday", field: "tue", newValueHandler: numberNewValueHandler, editable: true}, + {headerName: "Wednesday", field: "wed", newValueHandler: numberNewValueHandler, editable: true}, + {headerName: "Thursday", field: "thur", newValueHandler: numberNewValueHandler, editable: true}, + {headerName: "Friday", field: "fri", newValueHandler: numberNewValueHandler, editable: true} + ] + }, + { + headerName: 'Volatile Summary', + children: [ + {headerName: "Total", + valueGetter: "data.mon + data.tue + data.wed + data.thur + data.fri", + volatile: true, + cellStyle: {'background-color': 'rgba(180, 255, 255, 0.5)'}, // light blue background + cellClassRules: { + 'bold-and-red': 'x>20' + } + }, + {headerName: "Avg", + valueGetter: "(data.mon + data.tue + data.wed + data.thur + data.fri) / 5", + volatile: true, + cellStyle: {'background-color': 'rgba(180, 255, 255, 0.5)'} // light blue background + } + ] + }, + { + headerName: 'Hard Summary', + children: [ + {headerName: "Total", + valueGetter: "data.mon + data.tue + data.wed + data.thur + data.fri", + cellStyle: {'background-color': 'rgba(255, 180, 255, 0.5)'}, // light red background + cellClassRules: { + 'bold-and-red': 'x>20' + } + }, + {headerName: "Avg", + valueGetter: "(data.mon + data.tue + data.wed + data.thur + data.fri) / 5", + cellStyle: {'background-color': 'rgba(255, 180, 255, 0.5)'} // light red background + } + ] + } + ]; + + var data = [ + {name: 'Saoirse Ronan', nationality: 'Irish', mon: 1, tue: 1, wed: 1, thur: 1, fri: 1}, + {name: 'Colin Farrell', nationality: 'Irish',mon: 5, tue: 5, wed: 5, thur: 5, fri: 5}, + {name: 'Cillian Murphy', nationality: 'Irish',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Pierce Brosnan', nationality: 'Irish',mon: 1, tue: 1, wed: 1, thur: 1, fri: 1}, + {name: 'Liam Neeson', nationality: 'Irish',mon: 5, tue: 5, wed: 5, thur: 5, fri: 5}, + {name: 'Gabriel Byrne', nationality: 'Irish',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Stephen Rea', nationality: 'Irish',mon: 1, tue: 1, wed: 1, thur: 1, fri: 1}, + {name: 'Michael Fassbender', nationality: 'Irish',mon: 5, tue: 5, wed: 5, thur: 5, fri: 5}, + {name: 'Richard Harris', nationality: 'Irish',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Brendan Gleeson', nationality: 'Irish',mon: 1, tue: 1, wed: 1, thur: 1, fri: 1}, + {name: 'Colm Meaney', nationality: 'Irish',mon: 5, tue: 5, wed: 5, thur: 5, fri: 5}, + {name: 'Niall Crosby', nationality: 'Irish',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Brad Pitt', nationality: 'American',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Edward Norton', nationality: 'American',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Laurence Fishburne', nationality: 'American',mon: 1, tue: 2, wed: 3, thur: 4, fri: 5}, + {name: 'Bruce Willis', nationality: 'American' ,mon: 1, tue: 2, wed: 3, thur: 4, fri: 5} + ]; + + function numberNewValueHandler(params) { + var valueAsNumber = parseInt(params.newValue); + if (isNaN(valueAsNumber)) { + window.alert("Invalid value " + params.newValue + ", must be a number"); + } else { + params.data[params.colDef.field] = valueAsNumber; + } + } + + function cellValueChangedFunction() { + // after a value changes, get the volatile cells to update + gridOptions.api.softRefreshView(); + } + + var gridOptions = { + columnDefs: columnDefs, + rowData: data, + groupHeaders: true, + rowSelection: 'single', + enableSorting: true, + onCellValueChanged: cellValueChangedFunction, + onGridReady: function(event) { + event.api.sizeColumnsToFit(); + } + }; + + function onHardRefresh() { + gridOptions.api.refreshView(); + } + + // setup the grid after the page has finished loading + document.addEventListener('DOMContentLoaded', function() { + var gridDiv = document.querySelector('#myGrid'); + new agGrid.Grid(gridDiv, gridOptions); + }); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004919_file.js b/pool/shard000/JavaScript/0004919_file.js new file mode 100644 index 0000000000000000000000000000000000000000..f8c159667a6400787615b2e80f2489e0add83fcc --- /dev/null +++ b/pool/shard000/JavaScript/0004919_file.js @@ -0,0 +1,96 @@ +/* + * Provides bless.js as Grunt task + * + * Copyright (c) Aki Alexandra Nofftz + * Licensed under the MIT license. + */ + +'use strict'; + +var _getIterator = require('babel-runtime/core-js/get-iterator')['default']; + +var EXTENSION = 'css'; +exports.EXTENSION = EXTENSION; +var SOURCEMAP_EXTENSION = 'css.map'; + +exports.SOURCEMAP_EXTENSION = SOURCEMAP_EXTENSION; +var EXTENSION_SEP = '.'; + +function name(base, nth_file, suffix, extension) { + if (nth_file < 0) { + throw new Error('The file number should not be negative'); + } + + // if it isn't the main file add the suffix to the filename + return base + (!nth_file ? '' : '.' + suffix + nth_file) + EXTENSION_SEP + extension; +} + +function strip_extension(filename) { + var output_filename_parts = filename.split(EXTENSION_SEP); + + if (output_filename_parts[output_filename_parts.length - 1] === EXTENSION) { + output_filename_parts.pop(); + } + + return output_filename_parts.join(EXTENSION_SEP); +} + +function imports(options) { + var current = options.numFiles - 1, + statements = ''; + + while (current > 0) { + var _name = name(options.output, current, options.suffix, EXTENSION), + _splitted = _name.split('/'); + + _name = _splitted[_splitted.length - 1]; + statements += '@import "' + options.root + _name + '";' + options.linefeed; + + current--; + } + + return statements; +} + +function concat(grunt_file, input) { + var data = ''; + + // Read and concat files + if (Array.isArray(input.src)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError; + var _iterator, _step; + + try { + for (_iterator = _getIterator(input.src), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var file = _step.value; + + data += grunt_file.read(file); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator['return']) { + _iterator['return'](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + console.log('it is not an array.'); + data += grunt_file.read(input); + } + + return data; +} + +exports.name = name; +exports.strip_extension = strip_extension; +exports.imports = imports; +exports.concat = concat; diff --git a/pool/shard000/JavaScript/0004920_grid-challenge.js b/pool/shard000/JavaScript/0004920_grid-challenge.js new file mode 100644 index 0000000000000000000000000000000000000000..55a2e665ff328aae8be9a69f470da8179bc2bb87 --- /dev/null +++ b/pool/shard000/JavaScript/0004920_grid-challenge.js @@ -0,0 +1,52 @@ +'use strict'; + +// https://www.hackerrank.com/challenges/grid-challenge + +function main() { + input = input.split('\n'); + let output = ''; + const t = + input.shift(); + + for (let i = 0; i < t; i++) { + const n = + input.shift(); + const square = input.splice(0, n).map(line => line.split('').sort()); + output += isSorted(square) + '\n'; + } + + process.stdout.write(output); +} + +function isSorted(square) { + for (let i = 0; i < square.length; i++) + for (let j = 0; j < square.length - 1; j++) + if (square[j][i] > square[j + 1][i]) + return 'NO'; + + return 'YES'; +} + +process.stdin.resume(); +process.stdin.setEncoding('ascii'); + +let input = ""; + +process.stdin.on('data', function (data) { + input += data; +}); + +process.stdin.on('end', main); + +if (process.argv[2] === 'test') { + process.stdin.pause(); + input = ` + 1 + 5 + ebacd + fghij + olmkn + trpqs + xywuv + `.replace(/^\s+/mg, "").trim(); + process.stdout.write(`Input:\n${input}\n\nOutput:\n`); + main(); +} diff --git a/pool/shard000/JavaScript/0004925_script.js b/pool/shard000/JavaScript/0004925_script.js new file mode 100644 index 0000000000000000000000000000000000000000..01587032f613f9c8a71bb563a3da8174ede03c64 --- /dev/null +++ b/pool/shard000/JavaScript/0004925_script.js @@ -0,0 +1,202 @@ +// Code goes here +(function(){ + var app = angular.module('plunker', []); + + app.controller('MainCtrl', function($rootScope, $scope) { + $scope.tags = [ + { label: "Super Fantastic Sandwiches" }, + { label: "Super Horrible Sandwiches" }, + { label: "Yummy Burgers" }, + { label: "Tastey Apples" }, + { label: "Silly Kids Burgers" }, + { label: "Yum" }, + { label: "Gross" }, + { label: "Whatever" }, + { label: "Food Fight Super Long Title - And more!!!" } + ]; + + $scope.submittedTags = []; + + $scope.submitTags = function(tags) { + $scope.submittedTags = tags; + }; + }); + + app.directive('tagsInterface', ['$rootScope', '$timeout', '$window', function($rootScope, $timeout, $window){ + return { + restrict: 'E', + replace: true, + templateUrl: 'tags-interface.tpl.html', + scope: { + tags: '=', + onSubmit: '=' + }, + link: function(scope, element) { + var KEY_BACKSPACE = 8; + var KEY_ENTER = 13; + var KEY_LEFT = 37; + var KEY_RIGHT = 39; + + var $tagsWindow = element.find('.tags-window'); + var $tagsSlider = element.find('.tags-slider'); + var $input = element.find('input'); + + var totalWidth = 0; + var tagsWindowMaxWidth = 0; + var desiredWidth = 0; + + scope.newTagLabel = ''; + scope.cursorPosition = scope.tags.length; + + scope.hasTags = function() { + return scope.tags.length > 0; + }; + + scope.removeTag = function($index) { + scope.tags = _.filter(scope.tags, function(item, index) { + return index !== $index; + }); + + scope.calcTagContainerWidth(element); + }; + + scope.keypress = function(e) { + var key = e.which; + + switch (key) { + case KEY_ENTER: + return enter(); + case KEY_BACKSPACE: + return backspace(); + case KEY_LEFT: + return moveCursor(-1); + case KEY_RIGHT: + return moveCursor(1); + default: + setCursor(scope.tags.length); + } + }; + + var addTag = function() { + scope.tags.push(createTag(scope.newTagLabel, '0')); + scope.newTagLabel = ''; + scope.cursorPosition = scope.tags.length; + + scope.calcTagContainerWidth(element); + }; + + var enter = function() { + if (scope.newTagLabel.length === 0 && scope.tags.length > 0) { + scope.onSubmit(scope.tags); + } else if (scope.newTagLabel.length > 0 ) { + addTag(); + } + }; + + var backspace = function() { + if (scope.cursorPosition < scope.tags.length) { + scope.removeTag(scope.cursorPosition); + } else { + if (scope.newTagLabel.length === 0) { + removeHeadTag(); + } + } + }; + + var moveCursor = function(delta) { + var newPosition = scope.cursorPosition; + newPosition += delta; + newPosition = Math.min(newPosition, scope.tags.length); + newPosition = Math.max(newPosition, 0); + + setCursor(newPosition); + }; + + var setCursor = function(newPosition) { + scope.cursorPosition = newPosition; + scrollTags(); + }; + + var removeHeadTag = function() { + if (scope.tags.length > 0) { + scope.removeTag(scope.tags.length - 1); + scope.cursorPosition = scope.tags.length; + } + }; + + var createTag = function(label, value) { + return { + label: label, + searchValue: value + }; + }; + + var scrollTags = function() { + var scroll = 0; + + if (scope.cursorPosition < scope.tags.length) { + var selectedEl = scope.tagElements[scope.cursorPosition]; + var selectedLeft = $(selectedEl).position().left; + var offset = desiredWidth - selectedLeft; + var availableWidth = $tagsWindow.width(); + var delta = availableWidth - offset; + + if (delta < 0) { + scroll = delta; + } + } + + $tagsSlider.css({right: scroll + 'px'}); + }; + + scope.calcTagContainerWidth = function(element) { + totalWidth = element.width(); + tagsWindowMaxWidth = totalWidth / 2.0; + desiredWidth = 0; + + var tagElements = element.find('.tag'); + var tagMaxWidth = Math.floor(tagsWindowMaxWidth * 0.35); + var inputWidth = 0; + + scope.tagElements = tagElements; + + // disabled for now, truncated titles are not desired + // var sizeTag = function($el) { + // // var $control = $el.find('.control'); + // // var tagWidth = $el.width(); + // // var controlWidth = $control.outerWidth() + 3; + // // $el.find('.display').outerWidth(tagWidth - controlWidth); + // }; + + // tagElements.each(function(index, el) { + // var $el = $(el); + // // $el.css({width: 'auto', maxWidth: tagMaxWidth + 'px'}); + + // $timeout(function() { + // sizeTag($el); + // }, 1); + // }); + + return $timeout(function() { + desiredWidth = $tagsSlider.outerWidth(); + + var w = Math.min(tagsWindowMaxWidth, desiredWidth); + $tagsWindow.outerWidth(w); + + inputWidth = element.width() - $tagsWindow.outerWidth(); + $input.outerWidth(inputWidth); + }, 2); + }; + + // init + angular.element($window).bind('resize', function() { + scope.calcTagContainerWidth(element).then(scrollTags); + }); + + $timeout(function() { + scope.calcTagContainerWidth(element); + }, 10); + } + }; + }]); +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004926_PrefFilterTree.js b/pool/shard000/JavaScript/0004926_PrefFilterTree.js new file mode 100644 index 0000000000000000000000000000000000000000..5c854cbd8a1807ff575ce48d212a5bcdf5f6b6d7 --- /dev/null +++ b/pool/shard000/JavaScript/0004926_PrefFilterTree.js @@ -0,0 +1,102 @@ +require(["dojo/_base/declare", "dojo/data/ItemFileWriteStore"], function (declare) { + + return declare("fox.PrefFilterStore", dojo.data.ItemFileWriteStore, { + + _saveEverything: function (saveCompleteCallback, saveFailedCallback, + newFileContentString) { + + dojo.xhrPost({ + url: "backend.php", + content: { + op: "pref-filters", method: "savefilterorder", + payload: newFileContentString + }, + error: saveFailedCallback, + load: saveCompleteCallback + }); + }, + + }); +}); + +require(["dojo/_base/declare", "dojo/dom-construct", "lib/CheckBoxTree"], function (declare, domConstruct) { + + return declare("fox.PrefFilterTree", lib.CheckBoxTree, { + _createTreeNode: function(args) { + var tnode = this.inherited(arguments); + + var enabled = this.model.store.getValue(args.item, 'enabled'); + var param = this.model.store.getValue(args.item, 'param'); + var rules = this.model.store.getValue(args.item, 'rules'); + + if (param) { + param = dojo.doc.createElement('span'); + param.className = (enabled != false) ? 'labelParam' : 'labelParam filterDisabled'; + param.innerHTML = args.item.param[0]; + domConstruct.place(param, tnode.rowNode, 'first'); + } + + if (rules) { + param = dojo.doc.createElement('span'); + param.className = 'filterRules'; + param.innerHTML = rules; + domConstruct.place(param, tnode.rowNode, 'next'); + } + + if (this.model.store.getValue(args.item, 'id') != 'root') { + var img = dojo.doc.createElement('img'); + img.src ='images/filter.png'; + img.className = 'markedPic'; + tnode._filterIconNode = img; + domConstruct.place(tnode._filterIconNode, tnode.labelNode, 'before'); + } + + return tnode; + }, + + getLabel: function(item) { + var label = item.name; + + var feed = this.model.store.getValue(item, 'feed'); + var inverse = this.model.store.getValue(item, 'inverse'); + + if (feed) + label += " (" + __("in") + " " + feed + ")"; + + if (inverse) + label += " (" + __("Inverse") + ")"; + + /* if (item.param) + label = "" + label + + "" + item.param[0]; */ + + return label; + }, + getIconClass: function (item, opened) { + return (!item || this.model.mayHaveChildren(item)) ? (opened ? "dijitFolderOpened" : "dijitFolderClosed") : "invisible"; + }, + getLabelClass: function (item, opened) { + var enabled = this.model.store.getValue(item, 'enabled'); + return (enabled != false) ? "dijitTreeLabel labelFixedLength" : "dijitTreeLabel labelFixedLength filterDisabled"; + }, + getRowClass: function (item, opened) { + return (!item.error || item.error == '') ? "dijitTreeRow" : + "dijitTreeRow Error"; + }, + checkItemAcceptance: function(target, source, position) { + var item = dijit.getEnclosingWidget(target).item; + + // disable copying items + source.copyState = function() { return false; }; + + return position != 'over'; + }, + onDndDrop: function() { + this.inherited(arguments); + this.tree.model.store.save(); + }, + }); + +}); + + diff --git a/pool/shard000/JavaScript/0004930_school-list.js b/pool/shard000/JavaScript/0004930_school-list.js new file mode 100644 index 0000000000000000000000000000000000000000..ce3c854565418a041b80182919bd2697d01f4577 --- /dev/null +++ b/pool/shard000/JavaScript/0004930_school-list.js @@ -0,0 +1,71 @@ +import Ember from 'ember'; +import { validator, buildValidations } from 'ember-cp-validations'; +import ValidationErrorDisplay from 'ilios/mixins/validation-error-display'; + +const { Component, computed, inject } = Ember; +const { sort } = computed; +const { service } = inject; + +const Validations = buildValidations({ + title: [ + validator('presence', true), + validator('length', { + max: 60, + descriptionKey: 'general.title' + }), + ], + iliosAdministratorEmail: [ + validator('presence', true), + validator('length', { + max: 100 + }), + validator('format', { + type: 'email' + }), + ], +}); + +export default Component.extend(ValidationErrorDisplay, Validations, { + store: service(), + classNames: ['school-list'], + tagName: 'section', + schools: [], + newSchools: [], + title: null, + iliosAdministratorEmail: null, + isSavingNewSchool: false, + + sortSchoolsBy: ['title'], + sortedSchools: sort('schools', 'sortSchoolsBy'), + showNewSchoolForm: false, + actions: { + toggleNewSchoolForm(){ + this.set('showNewSchoolForm', !this.get('showNewSchoolForm')); + }, + hideNewSchoolForm(){ + this.set('showNewSchoolForm', false); + this.set('title', null); + }, + createNewSchool: function(){ + this.set('isSavingNewSchool', true); + this.send('addErrorDisplayFor', 'title'); + this.send('addErrorDisplayFor', 'iliosAdministratorEmail'); + this.validate().then(({validations}) => { + if (validations.get('isValid')) { + const title = this.get('title'); + const iliosAdministratorEmail = this.get('iliosAdministratorEmail'); + let newSchool = this.get('store').createRecord('school', {title, iliosAdministratorEmail}); + newSchool.save().then(school => { + this.get('newSchools').pushObject(school); + }).finally(() => { + this.send('clearErrorDisplay'); + this.set('title', null); + this.set('showNewSchoolForm', false); + this.set('isSavingNewSchool', false); + + }); + } + }); + }, + } +}); diff --git a/pool/shard000/JavaScript/0004931_patternChange.js b/pool/shard000/JavaScript/0004931_patternChange.js new file mode 100644 index 0000000000000000000000000000000000000000..a04730b2feee1b69b3a9d08e448f4bc21e7f6b66 --- /dev/null +++ b/pool/shard000/JavaScript/0004931_patternChange.js @@ -0,0 +1,20 @@ +const patternChange = ( pattern, flags ) => { + try { + const reg = new RegExp( pattern, flags.replace( /\s/g, '' ) ); + return { + type: 'PATTERN_CHANGE', + flags: flags, + pattern: pattern, + validate: true + }; + } catch ( err ) { + return { + type: 'PATTERN_CHANGE', + flags: flags, + pattern: pattern, + validate: false + }; + } +}; + +export default patternChange; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004932_miner.js b/pool/shard000/JavaScript/0004932_miner.js new file mode 100644 index 0000000000000000000000000000000000000000..12fc050c5463e5c1dffa4b0d9777d08d62972e0d --- /dev/null +++ b/pool/shard000/JavaScript/0004932_miner.js @@ -0,0 +1,26 @@ + +// http://gateway.marvel.com/v1/public/characters?ts=1&apikey=326b9124ce39cf26bf0c3746d03d5e73&hash=9921fd504791b84506e01303bb73edbe&limit=100&offset=300 +var request = require("request"); +var fs = require("fs"); +var characters = []; +for (var i = 0; i <= 1485; i += 100) { + request.get("http://gateway.marvel.com/v1/public/characters?ts=1&apikey=326b9124ce39cf26bf0c3746d03d5e73&hash=9921fd504791b84506e01303bb73edbe&limit=100&offset=" + i, function (err, res, body) { + if (!err) { + var resultsObj = JSON.parse(body); + characters.push.apply(characters, resultsObj.data.results); + //console.log(resultsObj.data.results); + if (i > 1485) { + var str = JSON.stringify(characters); + + fs.writeFile("characters_all.json", str, function (err) { + if (err) { + return console.log(err); + } + + console.log("The file was saved!"); + }); + } + } + }); +} + diff --git a/pool/shard000/JavaScript/0004935_viewJobVacancySuccess.js b/pool/shard000/JavaScript/0004935_viewJobVacancySuccess.js new file mode 100644 index 0000000000000000000000000000000000000000..a92d122c53a270f057a2c528979001c757f8cbf1 --- /dev/null +++ b/pool/shard000/JavaScript/0004935_viewJobVacancySuccess.js @@ -0,0 +1,145 @@ +$(document).ready(function() { + + $('#frmList_ohrmListComponent').attr('name','frmList_ohrmListComponent'); + + $('#btnDelete').attr('disabled','disabled'); + + $("#ohrmList_chkSelectAll").click(function() { + $('table.table input[id^="ohrmList_chkSelectRecord_"]').attr('checked', ($(this).attr('checked') == 'checked')); + if($(":checkbox").length == 1) { + $('#btnDelete').attr('disabled','disabled'); + } + else { + if($("#ohrmList_chkSelectAll").is(':checked')) { + $('#btnDelete').removeAttr('disabled'); + } else { + $('#btnDelete').attr('disabled','disabled'); + } + } + }); + + + $(':checkbox[name*="chkSelectRow[]"]').click(function() { + if($(':checkbox[name*="chkSelectRow[]"]').is(':checked')) { + $('#btnDelete').removeAttr('disabled'); + } else { + $('#btnDelete').attr('disabled','disabled'); + } + }); + + + $('#dialogDeleteBtn').click(function() { + document.frmList_ohrmListComponent.submit(); + }); + + $('#btnRst').click(function() { + + $('#vacancySearch_jobTitle').val(""); + $('#vacancySearch_jobVacancy').val(""); + $('#vacancySearch_hiringManager').val(""); + $('#vacancySearch_status').val(""); + $('#frmSrchJobVacancy').submit(); + }); + + $('#btnSrch').click(function() { + $('#frmSrchJobVacancy').submit(); + }); + + var jobTitle = $('#vacancySearch_jobTitle').val(); + var vacancyId = $('#vacancySearch_jobVacancy').val(); + var hiringManagerId = $('#vacancySearch_hiringManager').val(); + + var vcUrl = vacancyListUrl + jobTitle; + getVacancyListJson(vcUrl, vacancyId) + + var url1 = hiringManagerListUrlForVacancyId + vacancyId; + getHiringManagerListJson(url1, hiringManagerId); + + if(vacancyId == ""){ + var url = hiringManagerListUrlForJobTitle + jobTitle; + getHiringManagerListJson(url, hiringManagerId); + } + + + + $('#vacancySearch_jobTitle').change(function() { + + var jobTitle = $('#vacancySearch_jobTitle').val(); + var vcUrl = vacancyListUrl + jobTitle; + var url = hiringManagerListUrlForJobTitle + jobTitle; + + getVacancyListJson(vcUrl) + getHiringManagerListJson(url); + + }); + + $('#vacancySearch_jobVacancy').change(function() { + var jobTitle = $('#vacancySearch_jobTitle').val(); + var vacancyId = $('#vacancySearch_jobVacancy').val(); + var url = hiringManagerListUrlForVacancyId + vacancyId; + getHiringManagerListJson(url); + if(vacancyId == ""){ + url = hiringManagerListUrlForJobTitle + jobTitle; + getHiringManagerListJson(url); + } + + }); + +}); + +function addJobVacancy(){ + window.location.replace(addJobVacancyUrl); +} + +function getHiringManagerListJson(url, para){ + + $.getJSON(url, function(data) { + + //var data = $.unique(data1); + + var numOptions = data.length; + var optionHtml = ''; + + for (var i = 0; i < numOptions; i++) { + + // escape name + var name = $('
        ').text(data[i].name).html(); + + if(data[i].id == para){ + optionHtml += ''; + }else{ + optionHtml += ''; + } + } + + $("#vacancySearch_hiringManager").html(optionHtml); + + }) + +} + +function getVacancyListJson(vcUrl, para){ + $.getJSON(vcUrl, function(data) { + var numOptions = 0; + if(data != null){ + numOptions = data.length; + } + var optionHtml = ''; + + for (var i = 0; i < numOptions; i++) { + + // escape name + var name = $('
        ').text(data[i].name).html(); + + if(data[i].id == para){ + optionHtml += ''; + } + else{ + optionHtml += ''; + } + } + + $("#vacancySearch_jobVacancy").html(optionHtml); + + }) +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004937_meta-provider-spec.js b/pool/shard000/JavaScript/0004937_meta-provider-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..be40cc76ed955c0fcb794ab9e2da169e0730b0fd --- /dev/null +++ b/pool/shard000/JavaScript/0004937_meta-provider-spec.js @@ -0,0 +1,84 @@ +'use babel' + +import InsertMetaProvider from '../lib/providers/insert-meta-provider' +import SQLMetaProvider from '../lib/providers/sql-meta-provider' + +describe('InsertMetaProvider', () => { + describe('Get columns', () => { + let editor = { + dataAceColumns: [{ + name: 'test_col', + tableName: 'tbl', + type: 'varchar' + }, + { + name: 'other_col', + tableName: 'tbl', + type: 'bool' + }] + } + it('filters by table name including the ALL suggestion when no previous columns exist', () => { + let cols = InsertMetaProvider.getTableColumnNames(editor, 'tbl', []) + expect(cols).toContain({text: 'test_col', rightLabelHTML: 'Column', leftLabel: 'varchar'}) + expect(cols.length).toEqual(3) + }) + it('filters by table name and only includes columns that are not existing already', () => { + let cols = InsertMetaProvider.getTableColumnNames(editor, 'tbl', ['test_col']) + expect(cols).toContain({text: 'other_col', rightLabelHTML: 'Column', leftLabel: 'bool'}) + expect(cols.length).toEqual(1) + }) + }) +}) + +describe('SQLMetaProvider', () => { + describe('Get table names', () => { + it('filters by prefix', () => { + let editor = { + dataAceTables: [ + { + name: 'test_table', + schemaName: 'something', + type: 'Table' + }, + { + name: 'other_table', + schemaName: 'something', + type: 'Table' + }, + { + name: 'test_table_2', + schemaName: 'something', + type: 'Table' + } + ]} + let tables = SQLMetaProvider.getTableNames(editor, 'test', 'something') + + expect(tables).not.toContain({text: 'other_table', rightLabelHTML: 'Table'}) + expect(tables).toContain({text: 'test_table', rightLabelHTML: 'Table'}) + expect(tables).toContain({text: 'test_table_2', rightLabelHTML: 'Table'}) + expect(tables.length).toEqual(2) + }) + }) + + describe('Get column names', () => { + it('filters by prefix', () => { + let editor = { + dataAceColumns: [ + { + name: 'test_col', + tableName: 'tbl', + type: 'varchar' + }, + { + name: 'other_col', + tableName: 'tbl', + type: 'bool' + } + ] + } + let cols = SQLMetaProvider.getColumnNames(editor, 'test', 'tbl') + expect(cols).toContain({text: 'test_col', rightLabelHTML: 'Column', leftLabel: 'varchar'}) + expect(cols.length).toEqual(1) + }) + }) +}) diff --git a/pool/shard000/JavaScript/0004938_my-groups.js b/pool/shard000/JavaScript/0004938_my-groups.js new file mode 100644 index 0000000000000000000000000000000000000000..d791e6000ccfa5018d31e222adfcea4675f79119 --- /dev/null +++ b/pool/shard000/JavaScript/0004938_my-groups.js @@ -0,0 +1,41 @@ +/** +* Created by Mauriel on 3/9/2017. +*/ + +// Preview profile picture +function readURL(input) { + if (input.files && input.files[0]) { + var reader = new FileReader(); + reader.onload = function (e) { + + }; + + reader.readAsDataURL(input.files[0]); + } +} + +// File name preview for picture field, change method +$(document).on('change', '.btn-file :file', function () { + var input = $(this); + var numFiles = input.get(0).files ? input.get(0).files.length : 1; + var label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); + input.trigger('fileselect', [numFiles, label]); +}); + +$(document).ready(function () { + $("title").text("My Groups | xDCIShare"); // Fix page title + + // File name preview for picture field, file select method + $('.btn-file :file').on('fileselect', function (event, numFiles, label) { + var input = $(this).parents('.input-group').find(':text'); + input.val(label); + }); + $("#show-deleted-groups").click(function () { + if ($(this).text() === "Show deleted groups"){ + $(this).text("Hide deleted groups"); + } + else { + $(this).text("Show deleted groups"); + } + }) +}); diff --git a/pool/shard000/JavaScript/0004940_auctions.server.controller.js b/pool/shard000/JavaScript/0004940_auctions.server.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..ab46c2a7b05ffa29607d1b55619a43b332f96748 --- /dev/null +++ b/pool/shard000/JavaScript/0004940_auctions.server.controller.js @@ -0,0 +1,204 @@ +'use strict'; + +/** + * Module dependencies + */ +var path = require('path'), + fs = require('fs'), + multer = require('multer'), + config = require(path.resolve('./config/config')), + mongoose = require('mongoose'), + Auction = mongoose.model('Auction'), + errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); + +/** + * Show the current article + */ +exports.read = function (req, res) { + // convert mongoose document to JSON + var auction = req.auction ? req.auction.toJSON() : {}; + + // Add a custom field to the auction, for determining if the current User is the "owner". + // NOTE: This field is NOT persisted to the database, since it doesn't exist in the auction model. + auction.isCurrentUserOwner = getOwnerity(req.user, auction); + res.json(auction); +}; + +/** + * List of bid + */ +exports.index = function (req, res) { + + Auction.find().sort('-created').populate('user', 'displayName').exec(function (err, items) { + if (err) { + return res.status(422).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.json(items); + } + }); +}; + +/** + * Create an auction + */ +exports.create = function (req, res) { + var auction = new Auction(req.body); + auction.user = req.user; + + auction.save(function (err) { + if (err) { + return res.status(422).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.json(auction); + } + }); +}; + +/** + * Update an auction + */ +exports.update = function (req, res) { + var auction = req.auction; + + auction.title = req.body.title; + auction.desc = req.body.desc; + + auction.save(function (err) { + if (err) { + return res.status(422).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + auction = auction.toJSON(); + auction.isCurrentUserOwner = getOwnerity(req.user, auction); + res.json(auction); + } + }); +}; + +/** + * Delete an auction + */ +exports.delete = function (req, res) { + var auction = req.auction; + + auction.remove(function (err) { + if (err) { + return res.status(422).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.json(auction); + } + }); +}; + +/** + * Update profile picture + */ +exports.changeCoverImage = function (req, res) { + var user = req.user; + var auction = req.auction; + var uploadDest = config.uploads.coverUpload.dest + auction._id + '/'; + var upload = multer({ dest: uploadDest }).single('newCoverImage'); + var existingImageUrl; + + // Filtering to upload only images + upload.fileFilter = require(path.resolve('./config/lib/multer')).extensionFilter; + + if (user && auction) { + existingImageUrl = auction.coverImageURL; + uploadImage() + .then(updateAuction) + .then(deleteOldImage) + .then(function () { + res.json(auction); + }) + .catch(function (err) { + res.status(422).send(err); + }); + } else { + res.status(401).send({ + message: 'User is not signed in' + }); + } + + function uploadImage () { + return new Promise(function (resolve, reject) { + upload(req, res, function (uploadError) { + if (uploadError) { + reject(errorHandler.getErrorMessage(uploadError)); + } else { + resolve(); + } + }); + }); + } + + function updateAuction () { + return new Promise(function (resolve, reject) { + auction.coverImageURL = uploadDest + req.file.filename; + console.log(uploadDest) + auction.save(function (err, theuser) { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); + } + + function deleteOldImage () { + return new Promise(function (resolve, reject) { + if (existingImageUrl !== Auction.schema.path('coverImageURL').defaultValue) { + fs.unlink(existingImageUrl, function (unlinkError) { + if (unlinkError) { + console.log(unlinkError); + reject({ + message: 'Error occurred while deleting old profile picture' + }); + } else { + resolve(); + } + }); + } else { + resolve(); + } + }); + } + +}; + + +function getOwnerity (user, auction) { + return !!(user && auction.user && auction.user._id.toString() === user._id.toString()); +} + +/** + * Auction middleware + */ +exports.auctionByID = function (req, res, next, id) { + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).send({ + message: 'Auction is invalid' + }); + } + + Auction.findById(id).populate('user', 'displayName').exec(function (err, auction) { + if (err) { + return next(err); + } else if (!auction) { + return res.status(404).send({ + message: 'No auction with that identifier has been found' + }); + } + req.auction = auction; + next(); + }); +}; diff --git a/pool/shard000/JavaScript/0004944_msPathway-spec.js b/pool/shard000/JavaScript/0004944_msPathway-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9e751aeb39909e39cb61f8c8da9e2a82c4fac9e8 --- /dev/null +++ b/pool/shard000/JavaScript/0004944_msPathway-spec.js @@ -0,0 +1,23 @@ +define(['msPathway', 'jquery'], (Widget, $) => { + 'use strict'; + describe('Test the msPathway widget', () => { + it('Should load the module', () => { + expect(ModelSeedPathway).toEqual(jasmine.any(Function)); + }); + + it('Should do something or other', () => { + const nodeName = 'path-node'; + $('body').append('
        '); + const pathwayWidget = new ModelSeedPathway({ + elem: nodeName, + mapName: '', + mapData: { + groups: [], + reactions: [], + compounds: [], + linkedmaps: [], + }, + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004947_GameEngine.js b/pool/shard000/JavaScript/0004947_GameEngine.js new file mode 100644 index 0000000000000000000000000000000000000000..21fe5309af21a4e51214f05752312c334c6488b5 --- /dev/null +++ b/pool/shard000/JavaScript/0004947_GameEngine.js @@ -0,0 +1,240 @@ +(function () { + var __bind = function (fn, me) { + return function () { + return fn.apply(me, arguments); + }; + }; + + define(['lodash', 'jaws', 'Ship', 'Planet', 'Star', 'GameOver', 'Bullet', 'Explosion'], function (_, jaws, Ship, Planet, Star, GameOver, Bullet, Explosion) { + var GameEngine; + return GameEngine = (function () { + + function GameEngine() { + this.checkForCollisions = __bind(this.checkForCollisions, this); + + this.explosionCheck = __bind(this.explosionCheck, this); + + this.isOutside = __bind(this.isOutside, this); + + this.onTouchStop = __bind(this.onTouchStop, this); + + this.onTouchMove = __bind(this.onTouchMove, this); + + this.onTouchStart = __bind(this.onTouchStart, this); + + } + + GameEngine.prototype.setup = function () { + jaws.preventDefaultKeys(["left", "right", "up", "down", "space"]); + this.difficulty = 0; + this.levelUp = 0; + this.score = 0; + this.howManyPlanets = 0; + this.canShoot = true; + this.scoreView = document.getElementById('score'); + this.viewport = new jaws.Viewport({ + max_x: jaws.width, + max_y: jaws.height + }); + this.ship = new Ship({ + 'x': jaws.width / 2, + 'y': jaws.height - 225 + }, this.viewport); + this.currentX = false; + this.addTouchListeners(); + this.planets = new jaws.SpriteList; + this.stars = new jaws.SpriteList; + this.bullets = new jaws.SpriteList; + this.explosions = new jaws.SpriteList; + return this.textLocation = 180; + }; + + GameEngine.prototype.showInstructions = function () { + jaws.context.font = "bold 60pt terminal"; + jaws.context.lineWidth = 10; + jaws.context.fillStyle = "Green"; + jaws.context.strokeStyle = "rgba(200,200,200,0.0)"; + jaws.context.fillText("Arrow keys and space", 60, this.textLocation); + jaws.context.fillText("or swipe with touch", 60, this.textLocation + 100); + return ++this.textLocation; + }; + + GameEngine.prototype.addTouchListeners = function () { + var body; + body = document.body; + body.addEventListener('touchstart', this.onTouchStart, false); + body.addEventListener('touchmove', this.onTouchMove, false); + return body.addEventListener('touchend', this.onTouchStop, false); + }; + + GameEngine.prototype.onTouchStart = function (event) { + if (this.multiFinger(event)) { + return; + } + event.preventDefault(); + return this.currentX = event.touches[0].pageX; + }; + + GameEngine.prototype.onTouchMove = function (event) { + if (this.multiFinger(event)) { + return; + } + event.preventDefault(); + return this.currentX = event.touches[0].pageX; + }; + + GameEngine.prototype.onTouchStop = function (event) { + if (this.multiFinger(event)) { + return; + } + event.preventDefault(); + return this.currentX = false; + }; + + GameEngine.prototype.multiFinger = function (event) { + return event.touches.length > 1 || (event.scale && event.scale === !1); + }; + + GameEngine.prototype.update = function () { + var rand; + rand = _.random(0, 100); + this.handlePlayerInput(); + this.createEnemies(rand); + this.createStars(rand); + this.moveThings(); + return this.checkForCollisions(); + }; + + GameEngine.prototype.draw = function () { + jaws.context.clearRect(0, 0, jaws.width, jaws.height); + this.ship.draw(); + this.planets.draw(); + this.stars.draw(); + this.bullets.draw(); + this.explosions.draw(); + if (this.textLocation < jaws.height && !this.noInstructions) { + return this.showInstructions(); + } + }; + + GameEngine.prototype.handlePlayerInput = function () { + if (jaws.pressed("left")) { + this.ship.moveLeft(); + } + if (jaws.pressed("right")) { + this.ship.moveRight(); + } + if (jaws.pressed("space")) { + this.shoot(); + } + if (this.currentX > 0) { + this.shoot(); + return this.ship.goTo(this.currentX); + } + }; + + GameEngine.prototype.shoot = function () { + var bullet1, bullet2, _this = this; + if (!this.canShoot) { + return; + } + this.canShoot = false; + setTimeout(function () { + return _this.canShoot = true; + }, 500); + bullet1 = new Bullet({ + 'x': this.ship.x + 3, + 'y': this.ship.y + }); + this.bullets.push(bullet1); + bullet2 = new Bullet({ + 'x': this.ship.x + 72, + 'y': this.ship.y + }); + return this.bullets.push(bullet2); + }; + + GameEngine.prototype.createEnemies = function (rand) { + var planet; + if ((0 <= rand && rand <= this.difficulty)) { + ++this.levelUp; + ++this.howManyPlanets; + if (this.levelUp === 5) { + this.levelUp = 0; + ++this.difficulty; + } + planet = new Planet(this.viewport); + this.planets.push(planet); + return this.showScore(); + } + }; + + GameEngine.prototype.showScore = function () { + return this.scoreView.innerHTML = "SCORE: " + (this.howManyPlanets * (this.difficulty + 1)) + " - fps: " + jaws.game_loop.fps; + }; + + GameEngine.prototype.createStars = function (rand) { + var star; + if ((75 < rand && rand < 100)) { + star = new Star(this.viewport); + return this.stars.push(star); + } + }; + + GameEngine.prototype.moveThings = function () { + this.planets.forEach(function (planet) { + return planet.moveIt(); + }); + this.planets.removeIf(this.isOutside); + this.stars.forEach(function (star) { + return star.moveDown(); + }); + this.stars.removeIf(this.isOutside); + this.bullets.forEach(function (bullet) { + return bullet.moveIt(); + }); + this.bullets.removeIf(this.isOutside); + this.explosions.forEach(function (explosion) { + return explosion.moveIt(); + }); + return this.explosions.removeIf(this.explosionCheck); + }; + + GameEngine.prototype.isOutside = function (item) { + return this.viewport.isOutside(item); + }; + + GameEngine.prototype.explosionCheck = function (explosion) { + return explosion.removeMe(); + }; + + GameEngine.prototype.checkForCollisions = function () { + var _this = this; + jaws.collideOneWithMany(this.ship, this.planets).forEach(function (planet) { + planet.stop(); + _this.ship.stop(); + GameEngine.prototype.noInstructions = true; + return jaws.switchGameState(GameOver); + }); + return jaws.collideManyWithMany(this.bullets, this.planets).forEach(function (pair) { + var bullet, explosion, planet; + bullet = pair[0]; + planet = pair[1]; + explosion = new Explosion({ + 'x': planet.x, + 'y': planet.y + }); + _this.explosions.push(explosion); + _this.bullets.remove(bullet); + _this.planets.remove(planet); + _this.howManyPlanets += 1; + return _this.showScore(); + }); + }; + + return GameEngine; + + })(); + }); + +}).call(this); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004948_12-httpuppercaserer.js b/pool/shard000/JavaScript/0004948_12-httpuppercaserer.js new file mode 100644 index 0000000000000000000000000000000000000000..acf9bcef23221fb4cc94be8e568aa163a8c62868 --- /dev/null +++ b/pool/shard000/JavaScript/0004948_12-httpuppercaserer.js @@ -0,0 +1,10 @@ +var http = require('http') +var map = require('through2-map') + +http.createServer(function(request, response){ + if(request.method != 'POST') return response.end('Only POST requests are allowed!'); + + request.pipe(map(function(chunk){ + return chunk.toString().toUpperCase() + })).pipe(response) +}).listen(Number(process.argv[2])) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004950_logger.js b/pool/shard000/JavaScript/0004950_logger.js new file mode 100644 index 0000000000000000000000000000000000000000..c875510349cec3b58f2b381899ff2821c19b2a7a --- /dev/null +++ b/pool/shard000/JavaScript/0004950_logger.js @@ -0,0 +1,53 @@ +import path from 'path' +import winston from 'winston' +import config from './../../config' + +const isProd = process.env.NODE_ENV === 'production' +const isDev = process.env.NODE_ENV === 'development' +const mode = isDev ? 'dev' : 'prod' +const logsFolder = config.logging.file.dir +const logToFile = config.logging.file.enabled +const loggingLevel = config.logging.file.level +const fileName = config.logging.file.filename + +winston.emitErrs = true + +const infoLogFile = `${logsFolder}/${fileName}-${mode}-${loggingLevel}-info.log` // path.join(__dirname, '../../.logs/info.json') +const exLogFile = `${logsFolder}/${fileName}-${mode}-${loggingLevel}-exceptions.log` // path.join(__dirname, '../../.logs/exceptions.json') + +// LEVELS : { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 } + +const logger = new (winston.Logger)({ + transports: [ + new winston.transports.File({ + level: loggingLevel, + filename: infoLogFile, + handleExceptions: true, + json: true, + prettyPrint: false, + maxsize: 5242880, // 5MB + maxFiles: 5, + colorize: false, + }), + new winston.transports.Console({ + level: config.logging.level, + handleExceptions: true, + json: isProd, + prettyPrint: !isProd, + colorize: !isProd, + timestamp: true, + }), + ], + exceptionHandlers: [ + new winston.transports.File({ filename: exLogFile }), + ], + exitOnError: false, +}) + +logger.stream = { + write: (message) => { + logger.info(message) + }, +} + +export default logger diff --git a/pool/shard000/JavaScript/0004952_config-mongodb.js b/pool/shard000/JavaScript/0004952_config-mongodb.js new file mode 100644 index 0000000000000000000000000000000000000000..147c0c7207962d6b3fe70b39c54069eb1c581923 --- /dev/null +++ b/pool/shard000/JavaScript/0004952_config-mongodb.js @@ -0,0 +1,40 @@ +/** + * @author booleanhunter + * @about Creating a single open instance of mongoDb and returning it, this single instance is used for all db operations + */ + +var mongodb = require('mongodb'); +var MongoClient, mongoClientInstance, ObjectID, that = this; + +function configure(callback) { + that.MongoClient = mongodb.MongoClient, + Server = mongodb.Server; + var server = 'mongodb://localhost:27017/todoAppDB'; + + that.MongoClient.connect(server, function(err, db){ + if(err){ + var error = { + message: 'MongoDB connect failed', + error: err + } + callback(error); + }else{ + that.mongoClientInstance = db; + that.ObjectID = mongodb.ObjectID; + callback(null, 'Connection with mongodb established'); + } + + }); +} + +function mongoClientDB(){ + return that.mongoClientInstance; +} + +function mongoObjectId(){ + return that.ObjectID; +} + +exports.configure = configure; +exports.mongoClientDB = mongoClientDB; +exports.mongoObjectId = mongoObjectId; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004958_main.js b/pool/shard000/JavaScript/0004958_main.js new file mode 100644 index 0000000000000000000000000000000000000000..6c7eeed899a0d7761753b58203f36b3f1ff507d1 --- /dev/null +++ b/pool/shard000/JavaScript/0004958_main.js @@ -0,0 +1,192 @@ +define(function(require, exports, module) { + // 通过 require 引入依赖 + require('../jquery-1.11.3.min'); + //slideX用于实现图片轮播 + // formatDate用于转换时间显示格式 + var slideX = require('./slideX'); + var formatDate = require('./formatDate'); + // 对newsClass、recCountNews、localCountNews、entertainmentCountNews进行初始化赋值; + var newsClass = "recommendation"; + var recCountNews = 5; + var localCountNews = 5; + var entertainmentCountNews = 5; + // showNews用于将返回的json格式的data数据依次提取出title、img、content、addtime数据,并输出html元素最后添加到".newslist"中; + function showNews(data) { + var innerHtml = ""; + $.each(data, function(index, value) { + var newsTitle = $(value).attr("newstitle"); + var newsImg = $(value).attr("newsimg"); + var newsContent = $(value).attr("newscontent"); + var addTime = $(value).attr("addtime"); + addTime = addTime.substring(0, 19).replace("T", " "); + var newsdate = new Date(addTime); + var datanow = new Date(); + // 8小时的时间差,北京时间 + var differ = datanow.getTime() - 8 * 3600 * 1000 - newsdate.getTime(); + addTime = formatDate(differ) + "前"; + if (newsImg == '') { + innerHtml += "

        " + newsTitle + "

        " + newsContent + "

        " + addTime + "
        "; + + } else { + innerHtml += "
        news-img

        " + newsTitle + "

        " + newsContent + "

        " + addTime + "
        "; + + } + $(".news-list").html(innerHtml); + }); + } + $(document).ready(function() { + //当页面加载完成时,执行图片轮播,并且读取当前显示屏的宽度,并调整相应标签的样式 + slideX.init(); + var width = ($(window).width() - 20); + $('.img-tab-wrapper').css({ + 'width': width + 'px', + 'height': width * 0.6 + 'px' + }); + $('.img-tab a img').css({ + 'width': width + 'px', + 'height': width * 0.6 + 'px' + }); + $('.img-info').css({ + 'width': width + 'px', + 'height': width * 0.081 + 'px', + 'line-height': width * 0.081 + 'px' + }); + $('.img-tab').css('width', width * 3 + 'px'); + $('.rec-img-tab').css('width', width * 3 + 'px'); + $('.local').css('width', width * 3 + 'px'); + $('.entertainment-img-tab').css('width', width * 3 + 'px'); + $('#rec-refresh').show().siblings().hide(); + //同时在页面加载完成时,读取类型为recommendation的新闻信息展示在页面上; + $.ajax({ + type: "get", + url: "/index/recommendation/", + data: { + "newsclass": "recommendation", + "countnews": recCountNews, + }, + success: function(data) { + recCountNews = recCountNews + 5; + showNews(data); + $('#rec-line3').show(); + $('#entertainment-line3').hide(); + $('#local-line3').hide(); + } + }); + //当对导航栏进行点选时,切换轮播的图片,同时在后台查询相符合的新闻信息进行展示 + $('.btn-recommendation').click(function() { + $('#rec-refresh').show().siblings().hide(); + recCountNews = 5; + $('.rec-img-tab').show().siblings().hide(); + $('#rec-line3').show(); + $('#entertainment-line3').hide(); + $('#local-line3').hide(); + newsClass = "recommendation"; + console.log(newsClass); + slideX.thisDiv = $(".rec-img-tab"); + slideX.thisA = $('.rec-img-tab a'); + $.ajax({ + type: "get", + url: "/index/recommendation/", + data: { + "newsclass": "recommendation", + "countnews": recCountNews, + }, + success: function(data) { + recCountNews = recCountNews + 5; + showNews(data); + } + }); + }); + $('.btn-local').click(function() { + $('#local-refresh').show().siblings().hide(); + localCountNews = 5; + $('.local-img-tab').show().siblings().hide(); + $('#rec-line3').hide(); + $('#entertainment-line3').hide(); + $('#local-line3').show(); + newsClass = "local"; + console.log(newsClass); + slideX.thisDiv = $(".local-img-tab"); + slideX.thisA = $('.local-img-tab a'); + $.ajax({ + type: "get", + url: "/index/local/", + data: { + "newsclass": "local", + "countnews": localCountNews, + }, + success: function(data) { + localCountNews = localCountNews + 5; + showNews(data); + } + }); + }); + $('.btn-entertainment').click(function() { + entertainmentCountNews = 5; + $('#entertainment-refresh').show().siblings().hide(); + $('.entertainment-img-tab').show().siblings().hide(); + $('#rec-line3').hide(); + $('#entertainment-line3').show(); + $('#local-line3').hide(); + newsClass = "entertainment"; + console.log(newsClass); + slideX.thisDiv = $(".entertainment-img-tab"); + slideX.thisA = $('.entertainment-img-tab a'); + $.ajax({ + type: "get", + url: "/index/entertainment/", + data: { + "newsclass": "entertainment", + "countnews": entertainmentCountNews, + }, + success: function(data) { + entertainmentCountNews = entertainmentCountNews + 5; + showNews(data); + } + }); + }); + // 当点击加载更多新闻按钮时,countNews的值传递给php用于显示后五条新闻,并且在数据加载完成后countNews值自加5 + $('#rec-refresh').click(function() { + $.ajax({ + type: "get", + url: "/index/recommendation/", + data: { + "newsclass": "recommendation", + "countnews": recCountNews, + }, + success: function(data) { + recCountNews = recCountNews + 5; + showNews(data); + } + }); + }); + $('#local-refresh').click(function() { + $.ajax({ + type: "get", + url: "/index/local/", + data: { + "newsclass": "local", + "countnews": localCountNews, + }, + success: function(data) { + localCountNews = localCountNews + 5; + showNews(data); + } + }); + }); + $('#entertainment-refresh').click(function() { + $.ajax({ + type: "get", + url: "/index/entertainment/", + data: { + "newsclass": "entertainment", + "countnews": entertainmentCountNews, + }, + success: function(data) { + entertainmentCountNews = entertainmentCountNews + 5; + showNews(data); + } + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004962_PipelinelatestRunartifacts.js b/pool/shard000/JavaScript/0004962_PipelinelatestRunartifacts.js new file mode 100644 index 0000000000000000000000000000000000000000..7d56845a73a8b2e971555c97114e8aae4e8aa2bd --- /dev/null +++ b/pool/shard000/JavaScript/0004962_PipelinelatestRunartifacts.js @@ -0,0 +1,102 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _ApiClient = _interopRequireDefault(require("../ApiClient")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + +/** + * The PipelinelatestRunartifacts model module. + * @module model/PipelinelatestRunartifacts + * @version 1.1.2-pre.0 + */ +var PipelinelatestRunartifacts = /*#__PURE__*/function () { + /** + * Constructs a new PipelinelatestRunartifacts. + * @alias module:model/PipelinelatestRunartifacts + */ + function PipelinelatestRunartifacts() { + _classCallCheck(this, PipelinelatestRunartifacts); + + PipelinelatestRunartifacts.initialize(this); + } + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + + + _createClass(PipelinelatestRunartifacts, null, [{ + key: "initialize", + value: function initialize(obj) {} + /** + * Constructs a PipelinelatestRunartifacts from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/PipelinelatestRunartifacts} obj Optional instance to populate. + * @return {module:model/PipelinelatestRunartifacts} The populated PipelinelatestRunartifacts instance. + */ + + }, { + key: "constructFromObject", + value: function constructFromObject(data, obj) { + if (data) { + obj = obj || new PipelinelatestRunartifacts(); + + if (data.hasOwnProperty('name')) { + obj['name'] = _ApiClient["default"].convertToType(data['name'], 'String'); + } + + if (data.hasOwnProperty('size')) { + obj['size'] = _ApiClient["default"].convertToType(data['size'], 'Number'); + } + + if (data.hasOwnProperty('url')) { + obj['url'] = _ApiClient["default"].convertToType(data['url'], 'String'); + } + + if (data.hasOwnProperty('_class')) { + obj['_class'] = _ApiClient["default"].convertToType(data['_class'], 'String'); + } + } + + return obj; + } + }]); + + return PipelinelatestRunartifacts; +}(); +/** + * @member {String} name + */ + + +PipelinelatestRunartifacts.prototype['name'] = undefined; +/** + * @member {Number} size + */ + +PipelinelatestRunartifacts.prototype['size'] = undefined; +/** + * @member {String} url + */ + +PipelinelatestRunartifacts.prototype['url'] = undefined; +/** + * @member {String} _class + */ + +PipelinelatestRunartifacts.prototype['_class'] = undefined; +var _default = PipelinelatestRunartifacts; +exports["default"] = _default; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004964_component.js b/pool/shard000/JavaScript/0004964_component.js new file mode 100644 index 0000000000000000000000000000000000000000..ef06b4f4da9fe4281dc000e1dd1f368fc2081ec3 --- /dev/null +++ b/pool/shard000/JavaScript/0004964_component.js @@ -0,0 +1,82 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { observer, inject } from 'mobx-react'; + +import ConditionSetFormField from '../ConditionSetFormField/component'; +import AddConditionLink from '../AddConditionLink/component'; + +@inject('conditionSetStore') +@observer +class DisplayLogicFormField extends React.Component { + static propTypes = { + conditionSetStore: PropTypes.object.isRequired, + type: PropTypes.string, + displayIf: PropTypes.string, + }; + + constructor(props) { + super(props); + const { displayIf } = this.props; + this.state = { displayIf }; + } + + displayIfChanged = (event) => { + const { conditionSetStore } = this.props; + const displayIf = event.target.value; + this.setState({ displayIf }); + conditionSetStore.hide = displayIf === 'always'; + }; + + displayIfOptionTags = () => { + const { type } = this.props; + const displayIfOptions = ['always', 'all_met', 'any_met']; + return displayIfOptions.map((option) => ( + + )); + }; + + render() { + const { conditionSetStore, type } = this.props; + const { refableQings } = conditionSetStore; + const { displayIf } = this.state; + + if (refableQings.length === 0) { + return ( +
        + {I18n.t('condition.no_refable_qings')} +
        + ); + } + const displayIfProps = { + className: 'form-control', + name: `${type}[display_if]`, + id: `${type}_display_logic`, + value: displayIf, + onChange: this.displayIfChanged, + }; + + return ( +
        + +
        + + {displayIf !== 'always' && ( + + )} +
        +
        + ); + } +} + +export default DisplayLogicFormField; diff --git a/pool/shard000/JavaScript/0004965_jjsearch.js b/pool/shard000/JavaScript/0004965_jjsearch.js new file mode 100644 index 0000000000000000000000000000000000000000..034658d555795ce3a42dccf0c4b294e0bd94ac46 --- /dev/null +++ b/pool/shard000/JavaScript/0004965_jjsearch.js @@ -0,0 +1,193 @@ +/* + * jjsearch.js - v1.0.0 + * lite search engine writen in JS to process JSON + * https://github.com/EldonMcGuinness/jjsearch.js + * + * Made by Eldon McGuinness + * Under MIT License + * + * Parameters: + * callback: A function to be run when the search results returns + * source: the source of the search string, this is needed so the + * querystring can be parsed and populated into it when the + * page loads. + * debug: enables debug logging to the console. + */ + +var jjsearch = function(callback, source, debug){ + //Enable and disable debugging + this.qsdebug = debug || false; + + // The HTML element's ID that we should pull the search + // string from + this.source = document.getElementById(source) || ''; + + // The callback to fire when the searching is done + this.callback = callback || null; + + // Context for "this", needed in hotlinking to refer to "this" + var context = this; + + window.onload = function () { + //Grab just the first instance of the "q" item + var qs = jjsearch.querystring(); + //if (qsdebug == true) console.log(qs["q"]); + if (typeof(qs["q"]) == "object"){ + qs = qs["q"][0]; + }else if (typeof(qs["q"]) == "string"){ + qs = qs["q"]; + } + if (typeof(qs) == "string") { + context.source.value = context.doSearch(qs); + } + }; + + // Collect the valid hits that match the search terms + this.getHits = function(terms, json) { + var hits = []; + + if (Array.isArray(terms)) { + if (this.qsdebug == true) console.log("array found"); + } else { + + // Replace basic boolean objects + terms = [terms.replace(/\s*[\+\*\?]\s*/g, '.*') + .replace('||', '|')]; + + if (this.qsdebug == true) console.log(terms); + for (var i = 0; i < json.length; i++) { + for (var j = 0; j < terms.length; j++) { + if (this.linkExists(json[i], hits)) { + break; + } + if (this.qsdebug == true) console.log("Counts ["+i+"]["+j+"]"); + if (this.qsdebug == true) console.log("Checking Title ["+json[i]["title"]+"]["+terms[j]+"]"); + if (json[i]["title"].search(new RegExp(terms[j], "i")) > -1 || json[i]["content"].search(new RegExp(terms[j], "i")) > -1) { + hits.push(json[i]); + break; + } + } + } + + if (this.qsdebug == true) console.log(hits); + return hits; + } + }; + + + // check to see if the search link is already in the array + this.linkExists = function(obj, arr) { + if (this.qsdebug == true) console.log(obj); + if (this.qsdebug == true) console.log(arr); + for (var i = 0; i < arr.length; i++) { + if (this.qsdebug == true) console.log("comparing"+obj["link"]+"|"+arr[i]["link"]); + if (obj["link"] == arr[i]["link"]) { + return true; + } + } + return false; + }; + + + // Populate the search results, this calls the callback + this.populateResults = function(results){ + this.callback(results); + }; + + + // Main search function, this is what triggers the search + this.doSearch = function(str){ + + var json = null; + var terms = ''; + var context = this; + var r = new XMLHttpRequest(); + + // Check to see if we were given a valid id + if (str == null){ + terms = this.source.value.trim(); + }else{ + terms = str; + } + + //If the search query is less than 4 characters prompt for more + if (terms.length < 4) { + this.callback(1); + return terms + } + + r.open("GET", "/search.json", true); + r.onreadystatechange = function () { + if (r.readyState != 4 || r.status != 200) return; + var hits = context.getHits(terms, JSON.parse(r.response)); + context.populateResults(hits); + }; + r.send(); + + return terms; + }; +}; + + +// querystring function, borrowed from https://github.com/EldonMcGuinness/querystring.js +// This is used to parse the querystring and allow for hotlinking +// to search results +jjsearch.querystring = function(str) { + var qso = {}; + var qs = (str || document.location.search); + + // Check for an empty querystring + if (qs == ""){ + return qso; + } + + // Normalize the querystring + qs = qs.replace(/(^\?)/,'') + .replace(/;/g,'&'); + while (qs.indexOf("&&") != -1){ + qs = qs.replace(/&&/g,'&'); + } + qs = qs.replace(/([\&]+$)/,''); + + // Break the querystring into parts + + qs = qs.split("&"); + + // Build the querystring object + for (var i=0; i < qs.length; i++){ + var qi = qs[i].split("="); + + qi = qi.map(function (n) {return decodeURIComponent(n)}); + + if (qso[qi[0]] != undefined){ + + // If a key already exists then make this an object + if (typeof(qso[qi[0]]) == "string"){ + var temp = qso[qi[0]]; + if (qi[1] == ""){ + qi[1] = null; + } + //console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]"); + qso[qi[0]] = []; + qso[qi[0]].push(temp); + qso[qi[0]].push(qi[1]); + + }else if (typeof(qso[qi[0]]) == "object"){ + if (qi[1] == ""){ + qi[1] = null; + } + //console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]"); + qso[qi[0]].push(qi[1]); + } + }else{ + // If no key exists just set it as a string + if (qi[1] == ""){ + qi[1] = null; + } + //console.log("New key: ["+qi[0]+"]["+qi[1]+"]"); + qso[qi[0]] = qi[1]; + } + } + + return qso; +}; diff --git a/pool/shard000/JavaScript/0004966_processNgModuleDocs.spec.js b/pool/shard000/JavaScript/0004966_processNgModuleDocs.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..24f72c91cc6d04fcbd91666e2dce70cc8363b7cd --- /dev/null +++ b/pool/shard000/JavaScript/0004966_processNgModuleDocs.spec.js @@ -0,0 +1,119 @@ +const testPackage = require('../../helpers/test-package'); +const Dgeni = require('dgeni'); + +describe('processNgModuleDocs processor', () => { + let processor; + let injector; + beforeEach(() => { + const dgeni = new Dgeni([testPackage('angular-api-package')]); + injector = dgeni.configureInjector(); + processor = injector.get('processNgModuleDocs'); + }); + + it('should be available on the injector', () => { + expect(processor.$process).toBeDefined(); + }); + + it('should run before the correct processor', () => { + expect(processor.$runBefore).toEqual(['createSitemap']); + }); + + it('should run after the correct processor', () => { + expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); + }); + + it('should non-arrayNgModule options to arrays', () => { + const docs = [{ + docType: 'ngmodule', + ngmoduleOptions: { + a: ['AAA'], + b: 'BBB', + c: 42 + } + }]; + processor.$process(docs); + expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); + expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); + expect(docs[0].ngmoduleOptions.c).toEqual([42]); + }); + + it('should link directive/pipe docs with their NgModule docs', () => { + const aliasMap = injector.get('aliasMap'); + const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; + const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; + const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; + const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; + const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; + const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; + const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; + const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; + + aliasMap.addDoc(ngModule1); + aliasMap.addDoc(ngModule2); + processor.$process([ngModule1, ngModule2, directive1, directive2, directive3, pipe1, pipe2, pipe3]); + + expect(ngModule1.directives).toEqual([directive1, directive3]); + expect(ngModule1.pipes).toEqual([pipe1, pipe3]); + expect(ngModule2.directives).toEqual([directive2, directive3]); + expect(ngModule2.pipes).toEqual([pipe2, pipe3]); + + expect(directive1.ngModules).toEqual([ngModule1]); + expect(directive2.ngModules).toEqual([ngModule2]); + expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); + + expect(pipe1.ngModules).toEqual([ngModule1]); + expect(pipe2.ngModules).toEqual([ngModule2]); + expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); + }); + + it('should error if a pipe/directive does not have a `@ngModule` tag', () => { + const log = injector.get('log'); + expect(() => { + processor.$process([{ docType: 'directive', id: 'Directive1' }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); + + expect(() => { + processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); + }); + + it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { + const log = injector.get('log'); + expect(() => { + processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); + + expect(() => { + processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); + }); + + it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { + const aliasMap = injector.get('aliasMap'); + const log = injector.get('log'); + const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; + const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; + aliasMap.addDoc(ngModule1); + aliasMap.addDoc(ngModule2); + + expect(() => { + processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); + + expect(() => { + processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); + }).toThrowError('Failed to process NgModule relationships.'); + expect(log.error).toHaveBeenCalledWith( + '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); + }); +}); diff --git a/pool/shard000/JavaScript/0004967_SensorsActions.js b/pool/shard000/JavaScript/0004967_SensorsActions.js new file mode 100644 index 0000000000000000000000000000000000000000..ba176b8dd9f42a5577a1cb5fd3bedc6c278ed20d --- /dev/null +++ b/pool/shard000/JavaScript/0004967_SensorsActions.js @@ -0,0 +1,22 @@ +module.exports = { + readFrame: function readSensorFrame(frame) { + const reader = frame.reader; + const samples = frame.samples; + + return { + sensors: samples.map((sample) => { + return Object.assign({ + reader: reader + }, sample); + }) + }; + }, + purge: function purgeSensors(ttl) { + //TODO: Implement in store + return { + purgeSensors: { + ttl: ttl + } + }; + } +}; diff --git a/pool/shard000/JavaScript/0004972_title.js b/pool/shard000/JavaScript/0004972_title.js new file mode 100644 index 0000000000000000000000000000000000000000..8d80733be496eacbb80fb215c9ad68c1a79612db --- /dev/null +++ b/pool/shard000/JavaScript/0004972_title.js @@ -0,0 +1,243 @@ +"use strict"; +/** + * Angular Title dyamically updates the document title when navigating views + * defined in `ngRoute`'s `$routeProvider`. Simply define the title of the + * page in your `$routeProvider` config using the `title` key. + * + * If you place the name of the site inside the `title` element the directive + * will append this string to the end of the title on each page e.g. + * `My Site Name` would become `pageone - My Site Name`. The + * original string is also used as a fallback if the title attribute for a + * route has not been defined. In that case the title for that route would be + * `My Site Name`. + * + * @example + $routeProvider + .when("/pageone", { + controller: "pageoneCtrl" + title: "pageone", + templateUrl: "partials/pageone.html" + }) + .when("/pagetwo", { + controller: "pagetwoCtrl" + title: "pagetwo", + templateUrl: "partials/pagetwo.html" + }) + * @main sn.title + * @module sn.title + * @author SOON_ + */ +angular.module("sn.title", []) +/** + * Title text to display when $routeChangeError + * event occurs. + * @constant + * @property ROUTE_CHANGE_ERROR_TITLE + * @type {String} + */ +.constant("ROUTE_CHANGE_ERROR_TITLE", "Page Error") +/** + * @constant + * @property EVENTS + * @type {Object} + */ +.constant("EVENTS", { + SET_TITLE: "sn.title:setTitle", + ROUTE_CHANGE_SUCCESS: "$routeChangeSuccess", + ROUTE_CHANGE_ERROR: "$routeChangeError", +}) +/** + * Title element directive which updates it's content to + * update the page title. Place the name of you site inside + * the directive and it will be appended to the end of every + * page title. eg. Page Title - My Site Name + * @example + My Site Name + * @class title + * @module sn.title + * @author SOON_ + */ +.directive("title", [ + "$rootScope", + "snTitle", + "EVENTS", + "ROUTE_CHANGE_ERROR_TITLE", + /** + * @constructor + * @param {Service} $rootScope + * @param {Service} snTitle + * @param {String} EVENTS + * @param {String} ROUTE_CHANGE_ERROR_TITLE + */ + function ($rootScope, snTitle, EVENTS, ROUTE_CHANGE_ERROR_TITLE) { + return { + restrict: "E", + scope: { + updateOnPageChange: "=" + }, + link: function ($scope, $element) { + + /** + * The name of the site. We use this to append to all page titles. + * We use various sources to get the site title, here is the list + * in order of priority: + * 1. First attempt to get the site title from snTitle service + * 2. Fallback to text inside element for site title + * 3. Set title as undefined + * @property siteTitle + * @type {String} + * @example + "My Site Name" + */ + var siteTitle = + (snTitle.getSiteTitle() && snTitle.getSiteTitle().length > 0) ? + snTitle.getSiteTitle() : + ($element.html().length > 0 ? $element.html() : undefined) ; + + /** + * If true will update the page title on every route change. + * This is useful if updating the page title manually to disable + * updates on route change. + * @property updateOnPageChange + * @type {Boolean} + * @default true + */ + var updateOnPageChange = ($scope.updateOnPageChange === false) ? false : true; + + /** + * Update the content of the title element to the value + * of the title key in the object of the current route + * @method setTitle + * @param {Event} $event Angular event object + * @param {String} pageTitle Value to set the document title to + */ + var setTitle = function setTitle($event, pageTitle){ + + // route title & site title + if (pageTitle && siteTitle){ + $element.html(pageTitle + " - " + siteTitle); + + // route title only + } else if (pageTitle){ + $element.html(pageTitle); + + // site title only + } else if (siteTitle){ + $element.html(siteTitle); + } + }; + + /** + * Update the content of the title element to the value + * of the title key in the object of the current route + * @method onRouteChangeSuccess + * @param {event} $event '$routeChangeSuccess' event from ngRoute service + * @param {Object} current The requested route object + */ + var onRouteChangeSuccess = function onRouteChangeSuccess($event, current){ + + if ( updateOnPageChange ) { + + var pageTitle = null; + + if (current && current.$$route && current.$$route.title){ + pageTitle = current.$$route.title; + } + + setTitle($event, pageTitle); + } + }; + + /** + * Update the content of the title element to the value + * of ROUTE_CHANGE_ERROR_TITLE constant when $routeChangeError + * event is triggered. + * @method onRouteChangeError + */ + var onRouteChangeError = function onRouteChangeError(){ + + if ( updateOnPageChange ) { + + if (siteTitle){ + $element.html(ROUTE_CHANGE_ERROR_TITLE + " - " + siteTitle); + } else { + $element.html(ROUTE_CHANGE_ERROR_TITLE); + } + + } + + }; + + $rootScope.$on(EVENTS.SET_TITLE, setTitle); + + $rootScope.$on(EVENTS.ROUTE_CHANGE_SUCCESS, onRouteChangeSuccess); + $rootScope.$on(EVENTS.ROUTE_CHANGE_ERROR, onRouteChangeError); + + } + }; + } +]) +/** + * Service that sets the title of the document by specifying + * the page title and the site title. + * @example + angular.module("myApp", ["sn.title"]) + .config([ + "snTitleProvider", + function(snTitleProvider){ + snTitleProvider.setSiteTitle("My Site Name"); + } + ]) + .controller("myCtrl",[ + "snTitle", + function (snTitle){ + snTitle.setPageTitle("My Page"); + } + ]) + * @class snTitle + * @module sn.title + * @author SOON_ + */ +.provider("snTitle", function() { + /** + * @property siteTitle + * @type {String} + */ + var siteTitle = null; + /** + * @method setSiteTitle + * @param {String} value Value to set the site title to + */ + this.setSiteTitle = function setSiteTitle(value) { + siteTitle = value; + }; + /** + * @property $get + * @param {Array} + */ + this.$get = [ + "$rootScope", + "EVENTS", + function ($rootScope, EVENTS) { + return { + /** + * @method getSiteTitle + * @return {String} Value of the site title + */ + getSiteTitle: function getSiteTitle(){ + return siteTitle; + }, + /** + * Set the page title of title directive. + * Broadcasts an event which is being listen + * to by title directive + * @method setPageTitle + * @param {String} value Value to set the current page title to + */ + setPageTitle: function setPageTitle(value){ + $rootScope.$broadcast(EVENTS.SET_TITLE, value); + } + }; + } + ]; +}); diff --git a/pool/shard000/JavaScript/0004973_token.js b/pool/shard000/JavaScript/0004973_token.js new file mode 100644 index 0000000000000000000000000000000000000000..ede185aed0d0e66b909d773598f428f4f2281a17 --- /dev/null +++ b/pool/shard000/JavaScript/0004973_token.js @@ -0,0 +1,18 @@ +import Ember from 'ember'; +import ApplicationSerializer from './application'; + +const { copy } = Ember; + +export default ApplicationSerializer.extend({ + primaryKey: 'AccessorID', + + attrs: { + secret: 'SecretID', + }, + + normalize(typeHash, hash) { + hash.PolicyIDs = hash.Policies; + hash.PolicyNames = copy(hash.Policies); + return this._super(typeHash, hash); + }, +}); diff --git a/pool/shard000/JavaScript/0004980_angular-mew.constants.js b/pool/shard000/JavaScript/0004980_angular-mew.constants.js new file mode 100644 index 0000000000000000000000000000000000000000..b791a3c0ff16602ef8e551d73e1132878e3721f9 --- /dev/null +++ b/pool/shard000/JavaScript/0004980_angular-mew.constants.js @@ -0,0 +1,22 @@ +(function (hawkLib) { + 'use strict'; + var algorithms = ['sha256']; + /* istanbul ignore else */ + if (typeof hawkLib === 'object' && hawkLib.hasOwnProperty('crypto')){ + algorithms = hawkLib.crypto.algorithms; + } + angular + .module('angular-mew') + .constant('Hawk', hawkLib) + .constant('HawkAlgorithms', algorithms) + .constant('HawkErrors', { + ALGORITHM: "Unsupported algorithm, please use the 'HawkAlgorithms' constant to get a valid algorithm.", + MISSING_CREDENTIALS: "Hawk authentication is enabled but credentials are missing.", + MISSING_ALGORITHM: "Hawk authentication is enabled but algorithm is missing.", + HEADER_GENERATION: "Hawk header generation failed", + RESPONSE_VALIDATION: "Hawk server response validation failed", + HAWK_UNAVAILABLE: "Hawk library isn't available", + HAWK_AUTHENTICATION_REQUIRED: "Hawk authentication is required for the given url" + }); + +})(hawk); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004981_user.service.js b/pool/shard000/JavaScript/0004981_user.service.js new file mode 100644 index 0000000000000000000000000000000000000000..6255bf60b91a5371bfac96e94361241f3e281227 --- /dev/null +++ b/pool/shard000/JavaScript/0004981_user.service.js @@ -0,0 +1,78 @@ +import ImageService from './image.service'; +import UserRepository from '../../dal/repositories/user.repository'; +import log from '../../log'; + +const projection = { + _id: 1, + username: 1, + name: 1, + email: 1, + joinedDate: 1, + profilePicture: 1 +}; + +const UserService = { + retrieveAuthor: post => new Promise((resolve, reject) => { + UserRepository.getAll({ username: post.author }, { name: 1, username: 1 }) + .limit(1) + .exec((err, author) => { + if (err || author.length < 1) { + reject(err || 'No authors found'); + } + const postObject = post.toObject(); + postObject.author = author.pop(); + resolve(postObject); + }); + }), + getUser: username => UserRepository.get({ username }, projection), + updateProfilePicture: (username, file) => new Promise((resolve, reject) => UserRepository.get({ username }, projection).then((user) => { + if (file) { + const path = `profile_pictures/profile_${user.username}`; + ImageService.updateImage(file, path, user.profilePicture.toObject()) + .then((result) => { + const picture = { + small: result[0].url, + medium: result[1].url, + large: result[2].url + }; + const updatedUser = { + ...user.toObject(), + profilePicture: picture + }; + return UserService.updateUser(username, updatedUser); + }) + .then(resolve) + .catch(reject); + } else { + resolve(''); + } + }).catch((err) => { + reject(err); + })), + updateUser: (username, updatedUser) => new Promise((resolve, reject) => { + UserRepository.update(username, updatedUser).then((user) => { + if (user) { + resolve(user); + } else { + reject(new Error(`The user with the username ${username} does not exist`)); + } + }).catch((error) => { + log.error('Error occured while updating an user: ', error); + reject(error); + }); + }), + deleteUser: username => new Promise((resolve, reject) => { + UserRepository.remove(username).then((deletedUser) => { + if (deletedUser) { + resolve(`The user with the username ${username} was removed`); + } else { + reject(new Error(`The user with the username ${username} does not exist`)); + } + }).catch((error) => { + log.error('Error occured while deleting an user: ', error); + reject(error); + }); + }) +}; + +export default UserService; diff --git a/pool/shard000/JavaScript/0004982_helpers.js b/pool/shard000/JavaScript/0004982_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..c5ecd45187a5c8728af0f349afa6a9cb0ccd3717 --- /dev/null +++ b/pool/shard000/JavaScript/0004982_helpers.js @@ -0,0 +1,40 @@ +function wrap(text, length, center) { + center = center || false + ind = 0 + text.each(function() { + if (length instanceof Array) { + w = length[ind]-25 + } else { + w = length + } + var text = d3.select(this), + s = text.text().replace(/-/g, '- '), + s = s.replace(/\//g, "/ "), + words = s.split(/[\s]+/).reverse(), + word, + line = [], + lineNumber = 0, + lineHeight = 1.0, // ems + y = text.attr("y"), + dy = parseFloat(text.attr("dy")), + tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); + if (center) { + tspan.attr("text-anchor", "middle") + } + while (word = words.pop()) { + line.push(word); + tspan.text(line.join(" ")); + if (tspan.node().getComputedTextLength() > w) { + line.pop(); + tspan.text(line.join(" ")); + line = [word]; + tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word) + if (center) { + tspan.attr("text-anchor", "middle") + } + } + } + text.attr("numlines", lineNumber+1).attr("class", "wrapped_text") + ind += 1 + }); +} diff --git a/pool/shard000/JavaScript/0004983_main.js b/pool/shard000/JavaScript/0004983_main.js new file mode 100644 index 0000000000000000000000000000000000000000..73ceabec125cce6dde31434a124b1425f9068c3f --- /dev/null +++ b/pool/shard000/JavaScript/0004983_main.js @@ -0,0 +1,318 @@ +"use strict"; + +var electron = require('electron'); +var app = electron.app; +var ipcMain = electron.ipcMain; +var dialog = electron.dialog; + +var BrowserWindow = electron.BrowserWindow; +var Menu = electron.Menu; +var crashReporter = electron.crashReporter; + +var path = require('path'); +var isAccelerator = require("electron-is-accelerator"); + +var updater = require('./updater'); + +var isDevelopment = process.env.NODE_ENV === 'development'; + +var mainWindow = null; + +console.log("isDevelopment:",isDevelopment); + +// Electron 4, check only one app can run at a time +app.requestSingleInstanceLock() +app.on('second-instance', function (event, argv, cwd) { + if(mainWindow) { + if(mainWindow.isMinimized()) { + mainWindow.restore(); + } + mainWindow.show(); + mainWindow.focus(); + } +}) +// Pre Electron-4 +// // If someone tried to run a second instance, we should focus our window. +// // Really only applicable on Windows, maybe Linux +// var shouldQuitMultiInstance = app.makeSingleInstance((argv, workingDirectory) => { +// if(mainWindow) { +// if(mainWindow.isMinimized()) { +// mainWindow.restore(); +// } +// mainWindow.show(); +// mainWindow.focus(); +// } +// }); +// if(shouldQuitMultiInstance) { +// app.exit(); // was app.quit(), but that doesn't exit early enough any more +// } + + +// +// now that we're ready to go, let's get started for real... +// +var pkg = require('./package.json'); +var config = require('./configuration'); + +crashReporter.start({ + productName: pkg.productName, + companyName: pkg.companyName, + submitURL: 'http://thingm.com/blink1/blink1control2-crash-reporter', // FIXME: + autoSubmit: true +}); + +// turn off 'app-suspension' because it was causing bad timing in renderer +// FIXME: check if this is still the case in Electron +// update: 18 Sep 2017, this seems to not be an issue, so make it a configurable +var preventAppSuspension = config.readSettings('startup:preventAppSuspension'); +if( preventAppSuspension ) { + var powerSaveBlocker= require('electron').powerSaveBlocker; + var id = powerSaveBlocker.start('prevent-app-suspension'); + console.log("powerSaveBlocker id:",id); +} + +// Linux 3d acceleration sometimes causes black screen for Electron-based apps, so turn it off +var disablegpu = config.readSettings('startup:disableHardwareAcceleration'); +if( disablegpu || (disablegpu === undefined && process.platform === 'linux') ) { + console.log("disabling hardware acceleration"); + app.disableHardwareAcceleration(); +} +//// ignore-gpu-blacklist o maybe fix bad performance issue in Mac Sierra beta +//app.commandLine.appendSwitch('ignore-gpu-blacklist'); +// app.commandLine.appendSwitch('disable-renderer-backgrounding'); + +// Fix Windows Electron throttling down the timers +app.commandLine.appendSwitch('disable-background-timer-throttling'); + + +var isQuitting = false; + +var quit = function() { + console.log("Blink1Control2: quit. quitting...",isQuitting); + if( !isQuitting ) { + mainWindow.webContents.send('quitting', 'blink1control2'); + } + isQuitting = true; + app.quit(); +}; + +app.on('window-all-closed', function () { + console.log("Blink1Control2: app.window-all-closed"); + if (process.platform !== 'darwin') { + quit(); + } +}); + +var handleUrl = function(e,url) { + if( url.startsWith("chrome://") ) { return; } + else if(url != mainWindow.webContents.getURL()) { + e.preventDefault(); + electron.shell.openExternal(url); + } +} + +// stolen from https://github.com/twolfson/google-music-electron/blob/master/lib/google-music-electron.js +var openAboutWindow = function () { + // DEV: aboutWindow will be garbage collection automatically + var aboutWindow = new BrowserWindow({ + icon: path.join(__dirname, 'images/icons/blink1mk2-icon2-128px.png'), + title: "About Blink1Control2", + alwaysOnTop: true, + autoHideMenuBar: true, + height: 375, + width: 500, + webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true } + }); + aboutWindow.webContents.on('new-window', function(e,url) { handleUrl(e,url); } ); + aboutWindow.webContents.on('will-navigate', function(e,url) { handleUrl(e,url); } ); + aboutWindow.loadURL( 'file://' + __dirname + '/about.html') //+autoUpdateMsg ); + return aboutWindow; +}; + +var openMainWindow = function() { + mainWindow.show(); +}; +var openDevTools = function() { + mainWindow.show(); + mainWindow.webContents.openDevTools({mode:'detach'}); +}; +var openPreferences = function() { + mainWindow.show(); + mainWindow.webContents.send('showPreferences'); +}; + +// called via ipcMain below +var openHelpWindow = function() { + var helpWindow = new BrowserWindow({ + title: "Blink1Control2 Help", + // alwaysOnTop: true, + autoHideMenuBar: true, + center: true, + height: 700, + width: 800, + webPreferences: { nodeIntegration: true } + }); + helpWindow.webContents.on('new-window', function(e,url) { handleUrl(e,url); } ); + helpWindow.webContents.on('will-navigate', function(e,url) { handleUrl(e,url); } ); + helpWindow.on("closed", function() { + // helpWindow = null; + }); + + helpWindow.loadURL( 'file://' + __dirname + '/help/index.html' ); +}; + +// autoUpdater.on('checking-for-update', () => { +// console.log('Checking for update...'); +// }); +// autoUpdater.on('update-available', (info) => { +// console.log('Update available.'); +// }); +// autoUpdater.on('update-not-available', (info) => { +// console.log('Update not available.'); +// }); +// autoUpdater.on('error', (err) => { +// console.log('Error in auto-updater.'); +// }); + + +// ------------------------------------------------------------------------ +// +// the main deal +// +app.on('ready', function () { + + // autoUpdater.autoDownload = false; + // autoUpdater.checkForUpdates(); + + // if (!isDevelopment) { + // launchAtStartup(); + // } + + var hideDockIcon = config.readSettings('startup:hideDockIcon'); + if( hideDockIcon && process.platform === 'darwin' ) { + app.dock.hide(); + } + + var startMinimized = config.readSettings('startup:startMinimized'); + if( !startMinimized ) { + var splash = openAboutWindow(); + setTimeout( function() { + splash.close(); + mainWindow.show(); + }, 3000 ); + } + var showDebug = config.readSettings('logger.showDebug') || false; + + // Install global shortcut key (see also MenuMaker) + var globalShortcut = electron.globalShortcut; + // var ret = globalShortcut.register('CommandOrControl+3', function() { + // mainWindow.webContents.send('playBigButtonUser', 3); + // }); + var globalShortcutPrefix = config.readSettings('startup:shortcutPrefix') || 'CommandOrControl+Shift'; + var resetKey = config.readSettings('startup:shortcutResetKey') || 'R'; + var resetShortcut = globalShortcutPrefix + '+' + resetKey; + console.log("global shortcut:", resetShortcut); + + if( isAccelerator( resetShortcut)) { + var ret = globalShortcut.register(resetShortcut, function() { + // console.log('resetShortcut is pressed'); + mainWindow.webContents.send('resetAlerts'); + }); + if (!ret) { console.log('globalShortcut registration failed'); } + // Check whether a shortcut is registered. + console.log("globalShortcut key registered:", globalShortcut.isRegistered(resetShortcut)); + } + else { + console.log("ignoring bad globalShortcutkey: ",resetShortcut); + } + + var loadurl = 'file://' + __dirname + '/index-prod.html'; + if( isDevelopment ) { + loadurl = 'file://' + __dirname + '/index-dev.html'; + } + console.log("loadurl:"+loadurl); + + mainWindow = new BrowserWindow({ + icon: path.join(__dirname, 'images/icons/blink1mk2-icon2-128px.png'), + title: "Blink1Control2", + maximizable: false, + width: 1040, + height: 700 + ((process.platform !== 'darwin') ? 20 : 0), + resizable: isDevelopment && showDebug, + show: false, // show later based on config + webPreferences: { + nodeIntegration: true, + contextIsolation: false, + enableRemoteModule: true, + backgroundThrottling: false + } + }); + mainWindow.loadURL(loadurl); + if(isDevelopment) { + mainWindow.webContents.openDevTools({mode:'detach'}); + } + + // mainWindow.setMenu(null); // remove default menu + mainWindow.on('close', function (e) { + console.log("Blink1Control2: mainWindow.close:"); + if( !isQuitting ) { + mainWindow.hide(); + return e.preventDefault(); + } + }); + + mainWindow.on('closed', function () { + console.log("Blink1Control2: mainWindow.closed"); + quit(); + mainWindow = null; + }); + + mainWindow.on('minimize', function() { + console.log("Blink1Control2: mainWindow.minimize"); + mainWindow.hide(); + }); + + mainWindow.webContents.on('new-window', function(e, url) { + console.log("Blink1Control2: mainWindow.new-window"); + e.preventDefault(); + electron.shell.openExternal(url); + }); + + app.on('will-quit', function() { + console.log("Blink1Control2: app will-quit"); + }); + app.on('activate', function() { + mainWindow.show(); + }); + + // https://discuss.atom.io/t/how-to-catch-the-event-of-clicking-the-app-windows-close-button-in-electron-app/21425/8 + /* 'before-quit' is emitted when Electron receives + * the signal to exit and wants to start closing windows */ + app.on('before-quit', function() { + console.log("Blink1Control2: mainWindow.before-quit"); + isQuitting = true; + }); + + ipcMain.on('openMainWindow', function() { + openMainWindow(); + }); + ipcMain.on('openAboutWindow', function() { + openAboutWindow(); + }); + ipcMain.on('openPreferences', function() { + openPreferences(); + }); + ipcMain.on('openDevTools', function() { + openDevTools(); + }); + ipcMain.on('openHelpWindow', function() { + openHelpWindow(); + }); + ipcMain.on('quitnow', function() { + quit(); + }); + ipcMain.on('checkForUpdates', function() { + updater.checkForUpdates(); + }) + +}); diff --git a/pool/shard000/JavaScript/0004984_Main.js b/pool/shard000/JavaScript/0004984_Main.js new file mode 100644 index 0000000000000000000000000000000000000000..1b1c4b5ff5e25e97a683b30ae4b9c72bebe4e3cc --- /dev/null +++ b/pool/shard000/JavaScript/0004984_Main.js @@ -0,0 +1,138 @@ +/** + * @class EvaluateIt.controller.phone.Main + * @extends EvaluateIt.controller.Main + * + * This is the Main controller subclass for the 'phone' profile. Most of the functionality required for this controller + * is provided by the EvaluateIt.controller.Main superclass, but we do need to add a couple of refs and control + * statements to provide a slightly different behavior for the phone. + * + * The Main superclass provides a couple of capabilities that we use here. Firstly it sets up a listener on the main + * navigation NestedList and redirects to the appropriate url for each view. For example, tapping on the 'Forms' item + * in the list will redirect to the url 'options/forms'. + * + * Secondly, it sets up a route that listens for urls in the form above and calls the controller's showView function + * whenever one is detected. The showView function then just shows the appropriate view on the screen. + * + */ +Ext.define('EvaluateIt.controller.phone.Main', { + extend: 'EvaluateIt.controller.Main', + + config: { + refs: { + touchEvents: 'touchevents', + consoleButton: 'button[action=showConsole]' + }, + + control: { + nav: { + back: 'onBackTap' + }, + consoleButton: { + tap: 'showTouchEventConsole' + } + } + }, + + /** + * This is called whenever the user taps on an item in the main navigation NestedList + */ + onNavTap: function(nestedList, list, index) { + var record = list.getStore().getAt(index); + + if (EvaluateIt.config.mode === 'test') { + console.log('bbb ' + record); + } + + if (record.isLeaf()) { + // append category parameter for use in selection of proper view to render in route through use of filter + if (EvaluateIt.config.mode === 'test') { + console.log('url to route: ' + ' ' + record.toUrl() + '\/' + record.get('category')); + } + record = record.toUrl() + '\/' + record.get('category'); + this.redirectTo(record); + + } else { + this.getApplication().getHistory().add(Ext.create('Ext.app.Action', { + url: 'menu/' + record.get('id') + })); + } + }, + + /** + * In the Phone Profile only we support routing through to a menu page (urls like "menu/ui"). This function + * just sets everything up to show that menu + */ + showMenuById: function(id) { + var nav = this.getNav(), + store = nav.getStore(), + item = id == 'root' ? store.getRoot() : store.getNodeById(id); + + if (item) { + nav.goToNode(item); + this.getToolbar().setTitle(item.get('text')); + + //this.getSourceOverlay().setHidden(true); commented out!! + this.hideSheets(); + } + }, + + /** + * For a given Option model instance, shows the appropriate view. This is the endpoint for all routes matching + * 'option/:id', so is called automatically whenever the user navigates back or forward between options. + * @param {EvaluateIt.model.Option} item The Option model instance for which we want to show a view + */ + showView: function(item) { + var nav = this.getNav(), + title = item.get('text'), + view = this.createView(item), + layout = nav.getLayout(), + anim = item.get('animation'), + initialAnim = layout.getAnimation(), + newAnim; + + if (EvaluateIt.config.mode === 'test') { + console.log('title: ' + title); + } + + if (anim) { + layout.setAnimation(anim); + newAnim = layout.getAnimation(); + } + + nav.setDetailCard(view); + nav.goToNode(item.parentNode); + nav.goToLeaf(item); + + if (newAnim) { + newAnim.on('animationend', function() { + layout.setAnimation(initialAnim); + }, this, { single: true }); + } + + this.getToolbar().setTitle(title); + //this.getSourceButton().setHidden(false); + }, + + /** + * This is called whenever the user hits the Back button on the main navigation NestedList. It hides the + * "View Source" button as we do no want to see that when we are in the NestedList itself + */ + onBackTap: function(nestedList, node) { + + if (EvaluateIt.config.mode === 'test') { + console.log('We are back tappin!'); + } + + this.getApplication().getHistory().add(Ext.create('Ext.app.Action', { + url: 'menu/' + node.parentNode.get('id') + }), true); + }, + + /** + * This is called whenever the user hits the 'Console' button on the TouchEvents view. It just makes sure + * that the view is showing the console card. + */ + showTouchEventConsole: function(button) { + this.getTouchEvents().showConsole(); + } +}); diff --git a/pool/shard000/JavaScript/0004986_obj.js b/pool/shard000/JavaScript/0004986_obj.js new file mode 100644 index 0000000000000000000000000000000000000000..bb89ed2d371cf9c01f7be3db8ae2a21012e2217c --- /dev/null +++ b/pool/shard000/JavaScript/0004986_obj.js @@ -0,0 +1,36 @@ +var me = { + name: 'Vladislav', + age: 21, + color: 'white', + profesion: 'JS Developer', + state: 'hungry', + + eat: function (food){ + + if(food == pizza){ + state : 'full'; + alert('Я съел '+food.name + ' и ссыт'); + }else if(food == apple){ + alert('Я съел '+food.name + ' и голоден'); + }else + alert('Я съел '+ food + ' и голоден'); + + + }, + + move : function () { + alert('Go go go'); + } +} + +var apple = { + name: 'apple', + size: 'small', + color: 'green' +} + +var pizza = { + name: 'pizza', + size: 'big' + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0004987_status.js b/pool/shard000/JavaScript/0004987_status.js new file mode 100644 index 0000000000000000000000000000000000000000..2b16866390bcf8c2149b3e85bf0b9d074e220066 --- /dev/null +++ b/pool/shard000/JavaScript/0004987_status.js @@ -0,0 +1,19 @@ +var colors = require('colors'); + +module.exports = { + log : function(msg) { + console.log(msg); + }, + warn : function(msg) { + return this.log(msg.yellow); + }, + + success : function(msg) { + return this.log(msg.green); + }, + + error : function(msg) { + this.log(msg.red); + throw new ReferenceError(msg); + }, +}; diff --git a/pool/shard000/JavaScript/0004990_paradasTranvia.js b/pool/shard000/JavaScript/0004990_paradasTranvia.js new file mode 100644 index 0000000000000000000000000000000000000000..b03830614167d3b400acce68b6f955b62b6aa461 --- /dev/null +++ b/pool/shard000/JavaScript/0004990_paradasTranvia.js @@ -0,0 +1,19 @@ +WorkerScript.onMessage = function(msg){ + var xmlHttp = new XMLHttpRequest(); + var url = "http://www.zaragoza.es/api/recurso/urbanismo-infraestructuras/tranvia.json?rf=html&results_only=false&srsname=wgs84"; + xmlHttp.open("GET", url, true); + xmlHttp.send(null); + xmlHttp.onreadystatechange = function() { + console.log(xmlHttp.readyState+"-"+xmlHttp.status); + if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { + console.log("vamos"); + var msg = xmlHttp.responseText; + console.log(msg); + var stations = JSON.parse(msg); + console.log(stations); + if (typeof stations != "undefined") { + WorkerScript.sendMessage({'stations': stations.result}); + } + } + } +} diff --git a/pool/shard000/JavaScript/0004992_nav.test.js b/pool/shard000/JavaScript/0004992_nav.test.js new file mode 100644 index 0000000000000000000000000000000000000000..96ef56a634f2d09abf4d4aa6f586b5c072b68a29 --- /dev/null +++ b/pool/shard000/JavaScript/0004992_nav.test.js @@ -0,0 +1,92 @@ +import { collapseDocsOnlyStories, collapseAllStories } from './nav'; + +const docsOnly = { parameters: { docsOnly: true } }; +const root = { id: 'root', parent: false, children: ['a', 'b'] }; +const a = { id: 'a', isComponent: true, parent: 'root', children: ['a1'] }; +const a1 = { id: 'a1', isLeaf: true, parent: 'a' }; +const b = { id: 'b', isComponent: true, parent: 'root', children: ['b1', 'b2'] }; +const b1 = { id: 'b1', isLeaf: true, parent: 'b' }; +const b2 = { id: 'b2', isLeaf: true, parent: 'b' }; +const stories = { root, a, a1, b, b1, b2 }; + +describe('collapse docs-only stories', () => { + it('ignores normal stories', () => { + const filtered = collapseDocsOnlyStories(stories); + expect(filtered).toEqual(stories); + }); + + it('filters out docs-only stories', () => { + const hasDocsOnly = { + ...stories, + a1: { ...a1, ...docsOnly }, + }; + const filtered = collapseDocsOnlyStories(hasDocsOnly); + expect(filtered.a1).toEqual({ + id: 'a1', + isComponent: true, + isLeaf: true, + parent: 'root', + }); + }); +}); + +describe('collapse all stories', () => { + it('collapses normal stories', () => { + const collapsed = collapseAllStories(stories); + expect(collapsed).toEqual({ + a1: { + id: 'a1', + isComponent: true, + isLeaf: true, + parent: 'root', + }, + b1: { + id: 'b1', + isComponent: true, + isLeaf: true, + parent: 'root', + }, + root: { + children: ['a1', 'b1'], + id: 'root', + parent: false, + }, + }); + }); + it('collapses docs-only stories', () => { + const hasDocsOnly = { + ...stories, + a1: { ...a1, ...docsOnly }, + }; + const collapsed = collapseAllStories(hasDocsOnly); + expect(collapsed.a1).toEqual({ + id: 'a1', + isComponent: true, + isLeaf: true, + parent: 'root', + }); + }); + it('collapses mixtures of leaf and non-leaf children', () => { + const mixedRoot = { id: 'root', parent: false, children: ['a', 'b1'] }; + const mixed = { root: mixedRoot, a, a1, b1: { ...b1, parent: 'root' } }; + const collapsed = collapseAllStories(mixed); + expect(collapsed).toEqual({ + a1: { + id: 'a1', + isComponent: true, + isLeaf: true, + parent: 'root', + }, + b1: { + id: 'b1', + isLeaf: true, + parent: 'root', + }, + root: { + children: ['a1', 'b1'], + id: 'root', + parent: false, + }, + }); + }); +}); diff --git a/pool/shard000/JavaScript/0004993_class.js b/pool/shard000/JavaScript/0004993_class.js new file mode 100644 index 0000000000000000000000000000000000000000..0630a573b3674d4776e52f07a9f3c41ba3cc7d73 --- /dev/null +++ b/pool/shard000/JavaScript/0004993_class.js @@ -0,0 +1,186 @@ +/** + * @author NHN Ent. FE Development Team <dl_javascript@nhnent.com> + * @fileoverview Base class + */ +'use strict'; + +tui = tui || {}; + +(function (ns) { + /** + * Create Base instance + * @class tui.component.Base + * @param {object} data - data + * @param {object} data.foo - foo + * @param {string} data.bar - 'bar' + */ + var Base = function (data) { + /** + * Base data + * @type {object} + */ + this.data = data || {}; + }; + + /** + * @alias tui.component.Base.staticMethod + */ + Base.staticMethod = function() {} + + Object.assign(Base.prototype, /** @lends tui.component.Base.prototype */ { + + /** + * Private method + * @private + */ + _privateMethod: function() { + // ...code + }, + + /** + * Base log2 + * @param {string} str - string for log + * @example + * base.log('hello world'); // "LOG1: hello world" + */ + log: function(str) { + console.log('LOG1: ' + str); + }, + + /** + * Base log2 + * @example + * base.log2(); // "LOG2" + */ + log2: function() { + console.log('LOG2') + }, + + /** + * Set datum + * @param {string} id - Id for datum + * @param {*} datum - Datum + * @example + * base.setDatum('a', 'hello world'); + */ + setDatum: function(id, datum) { + this.data[id] = datum; + }, + + /** + * Base get + * @param {string} id - Id for datum + * @returns {?object} datum + * @example + * base.setDatum('a', 'hello world'); + * console.log(base.getDatum('a')); // "hello world"; + */ + getDatum: function(id) { + return data[id]; + } + }); + + /** + * BaseChild Class + * @extends tui.component.Base + * @class tui.component.BaseChild + */ + var BaseChild = function() { + Base.call(this); + + /** + * BaseChild data + * @type {{name: string, a: string}} + */ + this.data = { + name: 'BaseChild', + a: 'b' + }; + + /** + * Private data + * @type {object} + * @private + */ + this._privateData = {} + }; + BaseChild.prototype = Object.create(Base.prototype); + Object.assign(BaseChild.prototype, /** @lends tui.component.BaseChild.prototype */ { + constructor: BaseChild, + + /** + * BaseChild log2 + * @param {string} str - string for log + * @example + * base.log('hello world'); // "BaseChild - LOG1: hello world" + */ + log: function(str) { + console.log('BaseChild - LOG1: ' + str); + }, + + /** + * Returns the sum of a and b + * @param {Number} a + * @param {Number} b + * @param {Boolean} retArr If set to true, the function will return an array + * @returns {Number|Array} Sum of a and b or an array that contains a, b and the sum of a and b. + */ + sum: function(a, b, retArr) { + if (retArr) { + return [a, b, a + b]; + } + return a + b; + } + }); + + /** + * @event tui.component.BaseChild#foo + * @example + * baseChild.on('foo', function() { + * console.log('fire "foo"'); + * }); + */ + + ns.Base = Base; + ns.BaseChild = BaseChild; +})(tui.component || (tui.component = {})); + + +/** + * @classdesc Toaster singleton. + * @class + * @hideconstructor + */ +var Toaster = (function() { + var instance = null; + + function Toaster() {} + + /** + * Toast an item. + * + * @alias toast + * @memberof Toaster + * @instance + * @param {BreadyThing} item - The item to toast. + * @return {Toast} A toasted bready thing. + */ + Toaster.prototype.toast = function(item) {}; + + return { + /** + * Get the Toaster instance. + * + * @alias Toaster.getInstance + * @returns {Toaster} The Toaster instance. + */ + getInstance: function() { + if (instance === null) { + instance = new Toaster(); + delete instance.constructor; + } + + return instance; + } + }; +})(); diff --git a/pool/shard000/JavaScript/0004994_indexing.js b/pool/shard000/JavaScript/0004994_indexing.js new file mode 100644 index 0000000000000000000000000000000000000000..ab880d703cad01188f1023b268026316ade9be4e --- /dev/null +++ b/pool/shard000/JavaScript/0004994_indexing.js @@ -0,0 +1,79 @@ +/** + * Created by azu on 2014/02/21. + * LICENSE : MIT + */ +"use strict"; +var fs = require("fs"); +var pather = require("path"); +var FS = require("q-io/fs"); +var Promise = require("q"); +var getTitle = require("get-html-title"); +var Handlebars = require("handlebars"); +function pLoadFileList(fileList) { + return Promise.all(fileList.map(function (filePath) { + return FS.read(pather.resolve(filePath)).then(JSON.parse).catch(function (error) { + console.log(error); + }); + })); +} +var rootDir = pather.join(__dirname, ".."); +var concatPromise = FS.listTree(rootDir, function isIndexHTML(filePath, stat) { + if (stat.isDirectory()) { + return false; + } + // root 直下は除外 + if (pather.dirname(pather.resolve(rootDir, filePath)) === rootDir) { + return false; + } + // ignore rule + var ignoreRule = /(\/theme\/|reveal\.js|landslide-theme|node_modules)/; + if (ignoreRule.test(filePath)) { + return false; + } + + return pather.extname(filePath) === ".html"; +}); + +function getTitleFromHTMLPath(filePath) { + var content = fs.readFileSync(filePath, "utf-8"); + return getTitle(content); +} +// ディレクトリレベルでグルーピングする +/* + "dir" : [ + file... + ] + */ +function groupingFileList(fileList) { + var listObject = {}; + fileList.forEach(function (filePath) { + var keyName = pather.dirname(filePath).split(pather.sep).pop(); + if (listObject[keyName] == null) { + listObject[keyName] = []; + } + var title = getTitleFromHTMLPath(filePath); + if (title != null) { + listObject[keyName].push({ + filePath: pather.relative(rootDir, filePath), + title: title + }); + } + }); + + return listObject +} +Handlebars.registerHelper('link_to', function () { + return new Handlebars.SafeString("<a href='" + Handlebars.Utils.escapeExpression(this.filePath) + "'>" + Handlebars.Utils.escapeExpression(this.title) + "</a>"); +}); +function compileToHTML(fileListObject) { + var context = { object: fileListObject }; + var source = fs.readFileSync(__dirname + "/index-template.hbs", "utf-8"); + var template = Handlebars.compile(source); + return template(context); +} +var fileListObject = concatPromise.then(groupingFileList); +fileListObject.then(function (result) { + var generatedHTML = compileToHTML(result); + + return fs.writeFileSync(pather.resolve(rootDir, "./index.html"), generatedHTML); +}).catch(console.error.bind(console)); diff --git a/pool/shard000/JavaScript/0004995_index.js b/pool/shard000/JavaScript/0004995_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e1381d7269261bf382fb1d99a9163ed8355bfac --- /dev/null +++ b/pool/shard000/JavaScript/0004995_index.js @@ -0,0 +1,127 @@ +import React, { Component } from 'react'; +import fetchJsonp from 'fetch-jsonp'; +import { SortingState, LocalSorting, TableColumnResizing, + FilteringState, LocalFiltering, RowDetailState } from '@devexpress/dx-react-grid'; +import { Grid, TableView, TableHeaderRow, TableFilterRow, VirtualTableView +} from '@devexpress/dx-react-grid-bootstrap3'; +import $ from 'jquery'; import { Icon } from 'react-fa'; +import { FormattedMessage } from 'react-intl'; +import BooleanTypeProvider from './boolean'; import ImgTypeProvider from './img'; +import DeezerTypeProvider from './deezer'; import PlayerTypeProvider from './player'; +import ApiTypeProvider from './api'; import './index.css'; + +class DataGrid extends Component { + constructor(props) { + super(props); + + this.search = this.search.bind(this); + + this.tracks = []; + this.songs = this.search(''); + + this.state = { + columns: [ + { name: 'title', title: 'Titre' }, { name: 'artist', title: 'Artiste' }, + { name: 'album_name', title: 'Album' }, { name: 'deezer_link', title: 'Deezer', dataType: 'deezer' }, + { name: 'extract', title: 'Extrait', dataType: 'player' }, { name: 'lyrics', title: 'Lyrics', dataType: 'boolean'}, + { name: 'artist_cover', title: 'Artiste Cover', dataType: 'img' }, { name: 'playlist', title: 'Playlist de l\'artist', dataType:'api' }, + { name: 'album_playlist', title: 'Album', dataType:'api' }, { name: 'album_cover', title: 'Album Cover', dataType: 'img' } + ], + rows: [], + sorting: [{ columnName: 'title', direction: 'asc' }], + columnWidths: { + title: 150, artist: 120, album_name: 150, + deezer_link: 150, extract: 150, lyrics: 100, + artist_cover:150, playlist: 150, album_playlist: 150, + album_cover: 150 + } + }; + + this.changeSorting = sorting => this.setState({ sorting }); + this.changeColumnWidths = (columnWidths) => { this.setState({ columnWidths }); }; + } + + queryString(string) { + let url = 'http://api.deezer.com/search/track?q=', query; + query = string; + + if(query === '') { query = 'Take a bow'; } + + let formatted_query = query.split(' ').join('-'); + let request = url + formatted_query + '&output=jsonp'; + + return request; + } + + search(event) { + let request; + if(event !== ''){ request = this.queryString(event.target.value); + } else { request = this.queryString(''); } + this.tracks = []; + + fetchJsonp(request, { timeout: 3000 }) + .then((result) => { + let lists = result.json(); + + lists + .then((songs) => { + for(let i = 0; i < songs.total; i++) { + let song = songs.data[i]; + + this.tracks.push({ + title: song.title, artist: song.artist.name, + album_name: song.album.title, deezer_link: song.link, + extract: song.preview, lyrics: song.explicit_lyrics, + artist_cover: song.artist.picture, playlist: song.artist.tracklist, + album_playlist: song.album.tracklist, album_cover: song.album.cover + }); + } + + this.setState({rows:this.tracks}); this.lastQuery = request; + return this.tracks; + }); + }) + .catch(function(erreur) { + console.log(erreur); + return; + }); + return this.tracks; + } + + displayFilter() { $('#deezer_search').removeClass('hide_filter').addClass('show_filter'); } + + hideFilter() { $('#deezer_search').removeClass('show_filter').addClass('hide_filter'); } + + render() { + let { rows, columns, columnWidths, sorting } = this.state; + return ( + <div id="deezer_search" className='hide_filter'> + <input id="search-engine" type="text" placeholder="Rechercher une musique, un album, un artiste.." onChange={this.search} /> + <div id='filter'> + <a onClick={this.displayFilter}> <FormattedMessage id="deezer.filter" /> <Icon name='chevron-up' /> </a> + </div> + + <div id='hideFilter'> + <a onClick={this.hideFilter}> <FormattedMessage id="deezer.hideFilter" /> <Icon name='chevron-down' /> </a> + </div> + + <Grid rows={rows} columns={columns} > + <FilteringState defaultFilters={[]}/> + <SortingState sorting={sorting} onSortingChange={this.changeSorting} /> + <RowDetailState /> <LocalFiltering /> <LocalSorting /> + + <BooleanTypeProvider /> <ImgTypeProvider /> <DeezerTypeProvider /> + <PlayerTypeProvider /> <ApiTypeProvider /> + + <TableView /> <VirtualTableView /> + <TableColumnResizing columnWidths={columnWidths} + onColumnWidthsChange={this.changeColumnWidths} /> + <TableHeaderRow allowResizing allowSorting /> + <TableFilterRow rowHeight={50} /> + </Grid> + </div> + ) + } +} + +export default DataGrid; diff --git a/pool/shard000/JavaScript/0004996_EasyAdd.js b/pool/shard000/JavaScript/0004996_EasyAdd.js new file mode 100644 index 0000000000000000000000000000000000000000..5e8c0dd299609212ed3b4f3235615ce9fd6adc6e --- /dev/null +++ b/pool/shard000/JavaScript/0004996_EasyAdd.js @@ -0,0 +1,190 @@ +/*! + * ${copyright} + */ + +// Provides class sap.ui.rta.plugin.EasyAdd. +sap.ui.define([ + 'sap/ui/rta/plugin/additionalElements/AdditionalElementsPlugin', + 'sap/ui/dt/OverlayRegistry' +], function(AdditionalElementsPlugin, OverlayRegistry) { + "use strict"; + + /** + * Constructor for a new EasyAdd Plugin. + * + * @param {string} [sId] id for the new object, generated automatically if no id is given + * @param {object} [mSettings] initial settings for the new object + * @class The EasyAdd Plugin adds an Icon to an Overlay, which allows to trigger add operations directly + * @extends sap.ui.rta.plugin.additionalElements.AdditionalElementsPlugin + * @author SAP SE + * @version ${version} + * @constructor + * @private + * @since 1.48 + * @alias sap.ui.rta.plugin.EasyAdd + * @experimental Since 1.48. This class is experimental and provides only limited functionality. Also the API might be changed in future. + */ + var EasyAdd = AdditionalElementsPlugin.extend("sap.ui.rta.plugin.EasyAdd", /** @lends sap.ui.rta.plugin.EasyAdd.prototype */ + { + metadata: { + // ---- object ---- + + // ---- control specific ---- + library: "sap.ui.rta", + properties: {}, + associations: {}, + events: {} + } + }); + + /** + * Register browser event for an overlay + * + * @param {sap.ui.dt.ElementOverlay} oOverlay overlay object + * @override + */ + EasyAdd.prototype.registerElementOverlay = function(oOverlay) { + this._oDelegate = { + "onAfterRendering" : function() { + var onAddPressed = function(bOverlayIsSibling, oOverlay, iIndex) { + var sControlName; + if (bOverlayIsSibling) { + sControlName = oOverlay.getDesignTimeMetadata().getName().plural; + } else { + sControlName = oOverlay.getDesignTimeMetadata().getAggregation("sections").childNames.plural(); + } + this.showAvailableElements(bOverlayIsSibling, [oOverlay], iIndex, sControlName); + }.bind(this); + + var fnAddButton = function(oOverlay, oOverlayDom, bSibling, vControlName, iIndex) { + var fnCallback = function(oEvent) { + var oOverlay = sap.ui.getCore().byId(oEvent.getSource().getId().replace("-AddButton", "")); + onAddPressed(bSibling, oOverlay, iIndex); + oEvent.cancelBubble(); + }; + var sControlName = typeof vControlName === "function" ? vControlName() : vControlName; + this._addButton(oOverlay, fnCallback, oOverlayDom, sControlName, bSibling); + }.bind(this); + + if (oOverlay.$().hasClass("sapUiRtaPersAdd")) { + var bAddButton = oOverlay.$().hasClass("sapUiRtaPersAdd") && oOverlay.$().children(".sapUiRtaPersAddIconOuter").length <= 0; + var oParentControl = oOverlay.getElementInstance().getParent(); + var oParentOverlay = OverlayRegistry.getOverlay(oParentControl); + if (oParentControl.getMetadata().getName() === "sap.uxap.ObjectPageLayout") { + if (oParentOverlay.$().hasClass("sapUiRtaPersAddTop") && oParentOverlay.getAggregationOverlay("sections").$().children(".sapUiRtaPersAddIconOuter").length > -1) { + oParentControl.$("sectionsContainer").addClass("sapUiRtaPaddingTop"); + } + } + if (bAddButton) { + fnAddButton(oOverlay, oOverlay.$(), true, oOverlay.getDesignTimeMetadata().getName().singular); + } + } else if (oOverlay.$().hasClass("sapUiRtaPersAddTop")) { + if (oOverlay.getAggregationOverlay("sections").$().children(".sapUiRtaPersAddIconOuter").length <= 0) { + var $sectionsOverlay = oOverlay.getAggregationOverlay("sections").$(); + fnAddButton(oOverlay, $sectionsOverlay, false, oOverlay.getDesignTimeMetadata().getAggregation("sections").childNames.singular, 0); + } + } + + oOverlay.removeEventDelegate(this._oDelegate, this); + } + }; + + var oControl = oOverlay.getElementInstance(); + if (oControl.getMetadata().getName() === "sap.uxap.ObjectPageSection" && this.hasStableId(oOverlay)) { + oOverlay.addStyleClass("sapUiRtaPersAdd"); + oControl.addStyleClass("sapUiRtaMarginBottom"); + } else if (oControl.getMetadata().getName() === "sap.uxap.ObjectPageLayout" && this.hasStableId(oOverlay)) { + oOverlay.addStyleClass("sapUiRtaPersAddTop"); + oControl.$("sectionsContainer").addClass("sapUiRtaPaddingTop"); + } + + oOverlay.addEventDelegate(this._oDelegate, this); + AdditionalElementsPlugin.prototype.registerElementOverlay.apply(this, arguments); + }; + + /** + * Deregister browser event for an overlay + * + * @param {sap.ui.dt.ElementOverlay} oOverlay overlay object + * @override + */ + EasyAdd.prototype.deregisterElementOverlay = function(oOverlay) { + var oControl = oOverlay.getElementInstance(); + if (oOverlay._oAddButton) { + oOverlay._oAddButton.destroy(); + } + if (oControl.getMetadata().getName() === "sap.uxap.ObjectPageSection") { + oOverlay.removeStyleClass("sapUiRtaPersAdd"); + oControl.removeStyleClass("sapUiRtaMarginBottom"); + oOverlay.removeEventDelegate(this._oDelegate, this); + } else if (oControl.getMetadata().getName() === "sap.uxap.ObjectPageLayout") { + oOverlay.removeStyleClass("sapUiRtaPersAddTop"); + oControl.$("sectionsContainer").removeClass("sapUiRtaPaddingTop"); + } + }; + + /** + * On Editable Change the enablement of the Button has to be adapted + * + * @param {sap.ui.dt.Overlay} oOverlay overlay object + * @override + */ + EasyAdd.prototype._isEditable = function(oOverlay) { + var bIsEditable = AdditionalElementsPlugin.prototype._isEditable.apply(this, arguments); + if (oOverlay._oAddButton) { + var sOverlayIsSibling = oOverlay.hasStyleClass("sapUiRtaPersAddTop") ? "asChild" : "asSibling"; + oOverlay._oAddButton.setEnabled(bIsEditable[sOverlayIsSibling]); + } + return bIsEditable; + }; + + /** + * @param {sap.ui.dt.ElementOverlay} oOverlay - overlay object + * @param {function} fnCallback - callback function will be passed to the new button as on press event function + * @param {object} oOverlayDom - dom object of the overlay + * @param {string} sControlName - name of the control. This name will be displayed on the Add-Button + * @param {boolean} bOverlayIsSibling - defines if the button is added on a sibling or not + * @private + */ + EasyAdd.prototype._addButton = function(oOverlay, fnCallback, oOverlayDom, sControlName, bOverlayIsSibling) { + var bIsEditable = oOverlay.getEditableByPlugins().indexOf(this._retrievePluginName(bOverlayIsSibling)) > -1; + var oTextResources = sap.ui.getCore().getLibraryResourceBundle("sap.ui.rta"); + + var sId = oOverlay.getId() + "-AddButton"; + var oHtmlButtonOuter = jQuery("<div class='sapUiRtaPersAddIconOuter' draggable='true'> </div>"); + oOverlay._oAddButton = new sap.m.Button(sId, { + text: oTextResources.getText("CTX_ADD_ELEMENTS", sControlName), + icon: "sap-icon://add", + press: fnCallback, + enabled: bIsEditable + }).placeAt(oHtmlButtonOuter.get(0)); + oOverlayDom.append(oHtmlButtonOuter); + + oHtmlButtonOuter[0].addEventListener("mouseover", function(oEvent) { + oEvent.stopPropagation(); + var oOverlay = oEvent.fromElement ? sap.ui.getCore().byId(oEvent.fromElement.id) : null; + if (oOverlay && oOverlay.getMetadata().getName() === "sap.ui.dt.ElementOverlay") { + var oParentContainer = oOverlay.getParentElementOverlay(); + oParentContainer.$().removeClass("sapUiRtaOverlayHover"); + } + }); + + oHtmlButtonOuter[0].addEventListener("mouseleave", function(oEvent) { + oEvent.stopPropagation(); + var oOverlay = oEvent.toElement ? sap.ui.getCore().byId(oEvent.toElement.id) : null; + if (oOverlay && oOverlay.getMetadata().getName() === "sap.ui.dt.ElementOverlay") { + var oParentContainer = oOverlay.getParentElementOverlay(); + if (oParentContainer.getMovable()) { + oParentContainer.$().addClass("sapUiRtaOverlayHover"); + } + } + }); + + oHtmlButtonOuter[0].addEventListener("dragstart", function(oEvent) { + oEvent.stopPropagation(); + oEvent.preventDefault(); + }); + }; + + return EasyAdd; +}, /* bExport= */true); diff --git a/pool/shard000/JavaScript/0005001_inabox-host.js b/pool/shard000/JavaScript/0005001_inabox-host.js new file mode 100644 index 0000000000000000000000000000000000000000..5eb2a922ff6cce0bc91eaf071ee0186f028f13f0 --- /dev/null +++ b/pool/shard000/JavaScript/0005001_inabox-host.js @@ -0,0 +1,90 @@ +/** + * Copyright 2016 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS-IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Inabox host script is installed on a non-AMP host page to provide APIs for + * its embed AMP content (such as an ad created in AMP). + */ + +import {InaboxMessagingHost} from './inabox-messaging-host'; +import {dev, initLogConstructor, setReportError} from '../../src/log'; +import {reportError} from '../../src/error'; + +/** @const {string} */ +const TAG = 'inabox-host'; +/** @const {string} */ +const AMP_INABOX_INITIALIZED = 'ampInaboxInitialized'; +/** @const {string} */ +const PENDING_MESSAGES = 'ampInaboxPendingMessages'; +/** @const {string} */ +const INABOX_IFRAMES = 'ampInaboxIframes'; +/** @const {string} */ +const INABOX_UNREGISTER_IFRAME = 'inaboxUnregisterIframe'; + +/** + * Class for initializing host script and consuming queued messages. + * @visibleForTesting + */ +export class InaboxHost { + /** @param win {!Window} */ + constructor(win) { + // Prevent double initialization + if (win[AMP_INABOX_INITIALIZED]) { + dev().info(TAG, 'Skip a 2nd attempt of initializing AMP inabox host.'); + return; + } + + // Assume we cannot recover from state initialization errors. + win[AMP_INABOX_INITIALIZED] = true; + initLogConstructor(); + setReportError(reportError); + + if (win[INABOX_IFRAMES] && !Array.isArray(win[INABOX_IFRAMES])) { + dev().info(TAG, `Invalid ${INABOX_IFRAMES}`, + win[INABOX_IFRAMES]); + win[INABOX_IFRAMES] = []; + } + const host = new InaboxMessagingHost(win, win[INABOX_IFRAMES]); + win.AMP = win.AMP || {}; + if (win.AMP[INABOX_UNREGISTER_IFRAME]) { + // It's already defined; log a debug message and assume the existing + // implmentation is good. + dev().info(TAG, `win.AMP[${INABOX_UNREGISTER_IFRAME}] already defined}`); + } else { + win.AMP[INABOX_UNREGISTER_IFRAME] = host.unregisterIframe.bind(host); + } + const queuedMsgs = win[PENDING_MESSAGES]; + if (queuedMsgs) { + if (Array.isArray(queuedMsgs)) { + queuedMsgs.forEach(message => { + try { + host.processMessage(message); + } catch (err) { + dev().error(TAG, 'Error processing inabox message', message, err); + } + }); + } else { + dev().info(TAG, `Invalid ${PENDING_MESSAGES}`, queuedMsgs); + } + } + // Empty and ensure that future messages are no longer stored in the array. + win[PENDING_MESSAGES] = []; + win[PENDING_MESSAGES]['push'] = () => {}; + win.addEventListener('message', host.processMessage.bind(host)); + } +} + +new InaboxHost(self); diff --git a/pool/shard000/JavaScript/0005004_role-supports-aria-props.js b/pool/shard000/JavaScript/0005004_role-supports-aria-props.js new file mode 100644 index 0000000000000000000000000000000000000000..250b5887d16b111087e98261e0117a29ed803856 --- /dev/null +++ b/pool/shard000/JavaScript/0005004_role-supports-aria-props.js @@ -0,0 +1,84 @@ +'use strict'; + +var _role = require('../util/attributes/role'); + +var _role2 = _interopRequireDefault(_role); + +var _ARIA = require('../util/attributes/ARIA'); + +var _ARIA2 = _interopRequireDefault(_ARIA); + +var _getImplicitRole = require('../util/getImplicitRole'); + +var _getImplicitRole2 = _interopRequireDefault(_getImplicitRole); + +var _jsxAstUtils = require('jsx-ast-utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @fileoverview Enforce that elements with explicit or implicit roles defined contain only + * `aria-*` properties supported by that `role`. + * @author Ethan Cohen + */ + +// ---------------------------------------------------------------------------- +// Rule Definition +// ---------------------------------------------------------------------------- + +var errorMessage = function errorMessage(attr, role, tag, isImplicit) { + if (isImplicit) { + return 'The attribute ' + attr + ' is not supported by the role ' + role + '. This role is implicit on the element ' + tag + '.'; + } + + return 'The attribute ' + attr + ' is not supported by the role ' + role + '.'; +}; + +module.exports = { + meta: { + docs: {}, + + schema: [{ type: 'object' }] + }, + + create: function create(context) { + return { + JSXOpeningElement: function JSXOpeningElement(node) { + // If role is not explicitly defined, then try and get its implicit role. + var type = (0, _jsxAstUtils.elementType)(node); + var role = (0, _jsxAstUtils.getProp)(node.attributes, 'role'); + var roleValue = role ? (0, _jsxAstUtils.getLiteralPropValue)(role) : (0, _getImplicitRole2.default)(type, node.attributes); + var isImplicit = roleValue && role === undefined; + + // If there is no explicit or implicit role, then assume that the element + // can handle the global set of aria-* properties. + // This actually isn't true - should fix in future release. + if (typeof roleValue !== 'string' || _role2.default[roleValue.toUpperCase()] === undefined) { + return; + } + + // Make sure it has no aria-* properties defined outside of its property set. + var propertySet = _role2.default[roleValue.toUpperCase()].props; + var invalidAriaPropsForRole = Object.keys(_ARIA2.default).filter(function (attribute) { + return propertySet.indexOf(attribute) === -1; + }); + + node.attributes.forEach(function (prop) { + if (prop.type === 'JSXSpreadAttribute') { + return; + } + + var name = (0, _jsxAstUtils.propName)(prop); + var normalizedName = name ? name.toUpperCase() : ''; + + if (invalidAriaPropsForRole.indexOf(normalizedName) > -1) { + context.report({ + node: node, + message: errorMessage(name, roleValue, type, isImplicit) + }); + } + }); + } + }; + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005005_GeneralConfiguration.js b/pool/shard000/JavaScript/0005005_GeneralConfiguration.js new file mode 100644 index 0000000000000000000000000000000000000000..91948ca868cb38cbb84c02208f662cd1ee51651f --- /dev/null +++ b/pool/shard000/JavaScript/0005005_GeneralConfiguration.js @@ -0,0 +1,43 @@ +'use strict'; + +let handlebars = require('handlebars'), + config = require('./config.json'), + fs = require('fs'); + +let carousel = fs.readFileSync('back/templates/site/partials/carousel.html', "utf-8"), + who = fs.readFileSync('back/templates/site/partials/who.html', "utf-8"), + header = fs.readFileSync('back/templates/site/partials/header.html', "utf-8"), + search = fs.readFileSync('back/templates/site/partials/search.html', "utf-8"), + menu = fs.readFileSync('back/templates/site/partials/menu.html', "utf-8"), + othermenus = fs.readFileSync('back/templates/site/partials/othermenus.html', "utf-8"), + layout = fs.readFileSync('back/templates/site/layout.html', "utf-8"), + numeral = require('../front/js/Common/NumeralInstance'); + +class InitialConfiguration { + + getBaseUrl() { + return config.baseUrl; + } + + currency(value) { + return numeral(value).format('$ 0,0.00'); + } + + constructor() { + // static partials + handlebars.registerPartial('carousel', carousel); + handlebars.registerPartial('who', who); + handlebars.registerPartial('header', header); + handlebars.registerPartial('search', search); + handlebars.registerPartial('menu', menu); + handlebars.registerPartial('othermenus', othermenus); + + // layout + handlebars.registerPartial('layout', layout); + + handlebars.registerHelper('baseUrl', this.getBaseUrl); + handlebars.registerHelper('currency', this.currency); + } +} + +module.exports = new InitialConfiguration(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005009_Image.js b/pool/shard000/JavaScript/0005009_Image.js new file mode 100644 index 0000000000000000000000000000000000000000..dbc1f8bad4c2384df810b0959c7334908e0b2a12 --- /dev/null +++ b/pool/shard000/JavaScript/0005009_Image.js @@ -0,0 +1,145 @@ +MWF.xApplication.process.FormDesigner.Module = MWF.xApplication.process.FormDesigner.Module || {}; +MWF.xDesktop.requireApp("process.FormDesigner", "Module.$Element", null, false); +MWF.xApplication.process.FormDesigner.Module.Image = MWF.FCImage = new Class({ + Extends: MWF.FC$Element, + Implements: [Options, Events], + options: { + "style": "default", + "propertyPath": "../x_component_process_FormDesigner/Module/Image/image.html" + }, + + initialize: function(form, options){ + this.setOptions(options); + + this.path = "../x_component_process_FormDesigner/Module/Image/"; + this.cssPath = "../x_component_process_FormDesigner/Module/Image/"+this.options.style+"/css.wcss"; + + this._loadCss(); + this.moduleType = "element"; + this.moduleName = "image"; + + this.form = form; + this.container = null; + this.containerNode = null; + }, + + _createMoveNode: function(){ + this.moveNode = new Element("img", { + "MWFType": "image", + "id": this.json.id, + "src": this.json.src || this.path+this.options.style+"/icon/image1.png", + "styles": this.css.moduleNodeMove, + "events": { + "selectstart": function(){ + return false; + } + } + }).inject(this.form.container); + }, + + _getCopyNode: function(){ + if (!this.copyNode) this._createCopyNode(); + this.copyNode.setStyle("display", "inline-block"); + return this.copyNode; + }, + + _setEditStyle_custom: function(name){ + if (name=="src"){ + if (this.json.src){ + var src = this.json.src.imageSrc; + this.node.src = src; + this.setPropertiesOrStyles("styles"); + }else{ + this.node.set("src", this.path +this.options.style+"/icon/image1.png"); + } + } + if (name=="srcfile"){ + var value = this.json.srcfile; + if (value==="none"){ + this.json.srcfile = ""; + value = ""; + } + if (value){ + if (typeOf(value)==="object"){ + var url = MWF.xDesktop.getProcessFileUr(value.id, value.application); + try{ + this.node.set("src", url); + }catch(e){} + }else{ + var host = MWF.Actions.getHost("x_processplatform_assemble_surface"); + var action = MWF.Actions.get("x_processplatform_assemble_surface"); + var uri = action.action.actions.readFile.uri; + uri = uri.replace("{flag}", value); + uri = uri.replace("{applicationFlag}", this.form.json.application); + value = host+"/x_processplatform_assemble_surface"+uri; + + try{ + this.node.set("src", value); + }catch(e){} + } + }else{ + if (this.json.properties.src) { + this._setEditStyle_custom("properties"); + }else if (this.json.src){ + this._setEditStyle_custom("src"); + }else{ + this.node.set("src", this.path +this.options.style+"/icon/image1.png"); + } + } + } + if (name=="properties"){ + this._setNodeProperty(); + } + }, + _setNodeProperty: function(){ + if (this.form.moduleList.indexOf(this)==-1) this.form.moduleList.push(this); + if (this.form.moduleNodeList.indexOf(this.node)==-1) this.form.moduleNodeList.push(this.node); + if (this.form.moduleElementNodeList.indexOf(this.node)==-1) this.form.moduleElementNodeList.push(this.node); + this.node.store("module", this); + + if (typeOf(this.json.src)==="object"){ + var src = MWF.xDesktop.getImageSrc( this.json.src.imageId ); + this.node.set("src", src); + } + if (this.json.properties && this.json.properties["src"]){ + var value = this.json.properties["src"]; + if ((value.indexOf("x_processplatform_assemble_surface")!=-1 || value.indexOf("x_portal_assemble_surface")!=-1)){ + var host1 = MWF.Actions.getHost("x_processplatform_assemble_surface"); + var host2 = MWF.Actions.getHost("x_portal_assemble_surface"); + if (value.indexOf("/x_processplatform_assemble_surface")!==-1){ + value = value.replace("/x_processplatform_assemble_surface", host1+"/x_processplatform_assemble_surface"); + }else if (value.indexOf("x_processplatform_assemble_surface")!==-1){ + value = value.replace("x_processplatform_assemble_surface", host1+"/x_processplatform_assemble_surface"); + } + if (value.indexOf("/x_portal_assemble_surface")!==-1){ + value = value.replace("/x_portal_assemble_surface", host2+"/x_portal_assemble_surface"); + }else if (value.indexOf("x_portal_assemble_surface")!==-1){ + value = value.replace("x_portal_assemble_surface", host2+"/x_portal_assemble_surface"); + } + value = o2.filterUrl(value); + } + if (value){ + this.node.set("src", value); + }else{ + if (this.json.srcfile && this.json.srcfile!="none") { + this._setEditStyle_custom("srcfile"); + }else if (this.json.src){ + this._setEditStyle_custom("src"); + }else{ + this.node.set("src", this.path +this.options.style+"/icon/image1.png"); + } + } + }else{ + if (this.json.srcfile && this.json.srcfile!="none") { + this._setEditStyle_custom("srcfile"); + }else if (this.json.src){ + this._setEditStyle_custom("src"); + }else{ + this.node.set("src", this.path +this.options.style+"/icon/image1.png"); + } + } + + } + + +}); diff --git a/pool/shard000/JavaScript/0005013_getScale9Grid.js b/pool/shard000/JavaScript/0005013_getScale9Grid.js new file mode 100644 index 0000000000000000000000000000000000000000..ffd45a0e826225f70b39a3bee5bdc34ef9edfe98 --- /dev/null +++ b/pool/shard000/JavaScript/0005013_getScale9Grid.js @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2014,Egret-Labs.org + * 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 the Egret-Labs.org 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 EGRET-LABS.ORG 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 EGRET-LABS.ORG AND 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. + */ +var egret; +(function (egret) { + var gui; + (function (gui) { + var rectangleCache = {}; + /** + * 返回字符串所对应的全局唯一Rectangle对象。此方法主要为了减少scale9Grid属性的实例个数。 + * 参数的相同的九宫格数据使用此方法可以全局共享同一个Rectangle对象。 + * @param value {string} 以字符串形式表示Rectangle构造函数的四个参数:x,y,width,height。例如:"7,7,46,46"。 + * @returns {string} 字符串对应的Rectangle实例。 + */ + function getScale9Grid(value) { + if (rectangleCache[value]) { + return rectangleCache[value]; + } + if (!value) { + return null; + } + var arr = value.split(","); + var rect = new egret.Rectangle(parseInt(arr[0]), parseInt(arr[1]), parseInt(arr[2]), parseInt(arr[3])); + rectangleCache[value] = rect; + return rect; + } + gui.getScale9Grid = getScale9Grid; + })(gui = egret.gui || (egret.gui = {})); +})(egret || (egret = {})); diff --git a/pool/shard000/JavaScript/0005014_Step.js b/pool/shard000/JavaScript/0005014_Step.js new file mode 100644 index 0000000000000000000000000000000000000000..43121d3074a2223295c6f01f31487f296e0085ed --- /dev/null +++ b/pool/shard000/JavaScript/0005014_Step.js @@ -0,0 +1,121 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import cx from 'classnames'; + +import LeftRight from '../LeftRight/LeftRight'; +import Circle from '../Animate/Circle'; +import Icon from '../Icon/Icon'; +import m from '../../globals/modifiers.css'; +import defaultCss from './ProgressSteps.css'; + +const Step = (props) => { + const { + step, + completed, + title, + children, + css, + icon, + ...rest, + } = props; + + const leftClassName = cx( + m.valignt, + defaultCss.stepIconContainer, + css.stepIconContainer, + completed ? defaultCss.stepIconContainerCompleted : null, + completed ? css.stepIconContainerCompleted : null, + ); + + const rightClassName = cx( + m.valignt, + defaultCss.stepContent, + css.stepContent, + completed ? defaultCss.stepContentCompleted : null, + completed ? css.stepContentCompleted : null, + ); + + const stepIconClassName = cx( + defaultCss.stepIcon, + css.stepIcon, + completed ? defaultCss.stepIconCompleted : null, + completed ? css.stepIconCompleted : null, + ); + + const stepTitleClassName = cx( + defaultCss.stepTitle, + css.stepTitle, + completed ? defaultCss.stepTitleCompleted : null, + completed ? css.stepTitleCompleted : null, + ); + + const stepBodyClassName = cx( + defaultCss.stepBody, + css.stepBody, + completed ? defaultCss.stepBodyCompleted : null, + completed ? css.stepBodyCompleted : null, + ); + + return ( + <LeftRight + { ...rest } + className={ cx(defaultCss.step, css.step) } + leftClassName={ leftClassName } + rightClassName={ rightClassName } + leftChildren={ icon ? ( + <Icon + className={ defaultCss.icon } + name={ icon } + /> + ) : ( + <Circle + circleClassName={ css.stepIconCircle } + className={ stepIconClassName } + completed={ completed } + > + { step } + </Circle> + ) } + rightChildren={ + <div> + <dt className={ stepTitleClassName }>{ title }</dt> + <dd className={ stepBodyClassName }>{ children }</dd> + </div> + } + primarySide="right" + /> + ); +}; + +Step.propTypes = { + completed: PropTypes.bool, + title: PropTypes.node, + children: PropTypes.node, + css: PropTypes.shape({ + stepIconContainer: PropTypes.string, + stepIconContainerCompleted: PropTypes.string, + stepIcon: PropTypes.string, + stepIconCompleted: PropTypes.string, + stepTitle: PropTypes.string, + stepTitleCompleted: PropTypes.string, + stepBody: PropTypes.string, + stepBodyCompleted: PropTypes.string, + }), + step: PropTypes.node, + icon: PropTypes.string, +}; + +Step.defaultProps = { + css: { + stepIconContainer: '', + stepIconContainerCompleted: '', + stepIcon: '', + stepIconCompleted: '', + stepTitle: '', + stepTitleCompleted: '', + stepBody: '', + stepBodyCompleted: '', + }, +}; + +export default Step; diff --git a/pool/shard000/JavaScript/0005017_mura.cache.js b/pool/shard000/JavaScript/0005017_mura.cache.js new file mode 100644 index 0000000000000000000000000000000000000000..16ae04d9fd6f0f6bb4fcebfce531a2be5b56bd3a --- /dev/null +++ b/pool/shard000/JavaScript/0005017_mura.cache.js @@ -0,0 +1,166 @@ +/* This file is part of Mura CMS. + + Mura CMS 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, Version 2 of the License. + + Mura CMS 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 Mura CMS. If not, see <http://www.gnu.org/licenses/>. + + Linking Mura CMS statically or dynamically with other modules constitutes the preparation of a derivative work based on + Mura CMS. Thus, the terms and conditions of the GNU General Public License version 2 ("GPL") cover the entire combined work. + + However, as a special exception, the copyright holders of Mura CMS grant you permission to combine Mura CMS with programs + or libraries that are released under the GNU Lesser General Public License version 2.1. + + In addition, as a special exception, the copyright holders of Mura CMS grant you permission to combine Mura CMS with + independent software modules (plugins, themes and bundles), and to distribute these plugins, themes and bundles without + Mura CMS under the license of your choice, provided that you follow these specific guidelines: + + Your custom code + + • Must not alter any default objects in the Mura CMS database and + • May not alter the default display of the Mura CMS logo within Mura CMS and + • Must not alter any files in the following directories. + + /admin/ + /tasks/ + /config/ + /requirements/mura/ + /Application.cfc + /index.cfm + /MuraProxy.cfc + + You may copy and distribute Mura CMS with a plug-in, theme or bundle that meets the above guidelines as a combined work + under the terms of GPL for Mura CMS, provided that you include the source code of that other code when and as the GNU GPL + requires distribution of source code. + + For clarity, if you create a modified version of Mura CMS, you are not obligated to grant this special exception for your + modified version; it is your choice whether to do so, or to make such modified version available under the GNU General Public License + version 2 without this exception. You may, if you choose, apply this exception to your own modified versions of Mura CMS. */ + +;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['Mura'], factory); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + factory(require('Mura')); + } else { + // Browser globals (root is window) + factory(root.Mura); + } +}(this, function (Mura) { + /** + * Creates a new Mura.Cache + * @class {class} Mura.Cache + */ + Mura.Cache=Mura.Core.extend( + /** @lends Mura.Cache.prototype */ + { + + /** + * init - Initialiazes cache + * + * @return {void} + */ + init:function(){ + this.cache={}; + }, + + /** + * getKey - Returns Key value associated with key Name + * + * @param {string} keyName Key Name + * @return {*} Key Value + */ + getKey:function(keyName){ + return Mura.hashCode(keyName); + }, + + /** + * get - Returns the value associated with key name + * + * @param {string} keyName description + * @param {*} keyValue Default Value + * @return {*} + */ + get:function(keyName,keyValue){ + var key=this.getKey(keyName); + + if(typeof this.cache[key] != 'undefined'){ + return this.cache[key].keyValue; + } else if (typeof keyValue != 'undefined') { + this.set(keyName,keyValue,key); + return this.cache[key].keyValue; + } else { + return; + } + }, + + /** + * set - Sets and returns key value + * + * @param {string} keyName Key Name + * @param {*} keyValue Key Value + * @param {string} key Key + * @return {*} + */ + set:function(keyName,keyValue,key){ + key=key || this.getKey(keyName); + this.cache[key]={name:keyName,value:keyValue}; + return keyValue; + }, + + /** + * has - Returns if the key name has a value in the cache + * + * @param {string} keyName Key Name + * @return {boolean} + */ + has:function(keyName){ + return typeof this.cache[getKey(keyName)] != 'undefined'; + }, + + /** + * getAll - Returns object containing all key and key values + * + * @return {object} + */ + getAll:function(){ + return this.cache; + }, + + /** + * purgeAll - Purges all key/value pairs from cache + * + * @return {object} Self + */ + purgeAll:function(){ + this.cache={}; + return this; + }, + + /** + * purge - Purges specific key name from cache + * + * @param {string} keyName Key Name + * @return {object} Self + */ + purge:function(keyName){ + var key=this.getKey(keyName) + if( typeof this.cache[key] != 'undefined') + delete this.cache[key]; + return this; + } + + }); + +})); diff --git a/pool/shard000/JavaScript/0005019_test.js b/pool/shard000/JavaScript/0005019_test.js new file mode 100644 index 0000000000000000000000000000000000000000..7286c0aab5a48a279d9617baa5cb2bf780673259 --- /dev/null +++ b/pool/shard000/JavaScript/0005019_test.js @@ -0,0 +1,43 @@ +import Ember from 'ember'; + +export default Ember.Controller.extend({ + url: 'assets/images/a2.png', + url1: 'assets/images/a2.png', + url2: 'assets/images/a1.png', + name1: 'Jeremy', + store: '', + empty: '', + state: true, + clean: true, + + actions: { + selected: function() { + this.set('state', false); + var temp= this.get('url2'); + this.set('url',temp); + }, + + unselected: function() { + this.set('state', true); + var temp= this.get('url1'); + this.set('url',temp); + }, + + clean: function() { + this.set('clean', false); + var current= this.get('url'); + this.set('store',current); + var empty = this.get('empty'); + this.set('url',empty); + //console.log('store:'+this.get('store')); + }, + + get: function() { + this.set('clean', true); + var current= this.get('store'); + this.set('url',current); + //console.log('Url:'+this.get('url')); + }, + }, + +}); diff --git a/pool/shard000/JavaScript/0005021_index.js b/pool/shard000/JavaScript/0005021_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8c138cae47393fc4b6d93be5a0dc42e6d2adbb51 --- /dev/null +++ b/pool/shard000/JavaScript/0005021_index.js @@ -0,0 +1,96 @@ +'use strict'; + +const md5 = require('md5'); + +/** + * includes general functions for the work with patterns + */ +class PatternHelper { + /** + * Gets a hash or an array of hashes from the first characters of a pattern/user agent, that can + * be used for a fast comparison, by comparing only the hashes, without having to match the + * complete pattern against the user agent. + * + * With the variants options, all variants from the maximum number of pattern characters to one + * character will be returned. This is required in some cases, the a placeholder is used very + * early in the pattern. + * + * Example: + * + * Pattern: "Mozilla/* (Nintendo 3DS; *) Version/*" + * User agent: "Mozilla/5.0 (Nintendo 3DS; U; ; en) Version/1.7567.US" + * + * In this case the has for the pattern is created for "Mozilla/" while the pattern + * for the hash for user agent is created for "Mozilla/5.0". The variants option + * results in an array with hashes for "Mozilla/5.0", "Mozilla/5.", "Mozilla/5", + * "Mozilla/" ... "M", so that the pattern hash is included. + * + * @return {string|Array} + * @param {string} pattern + * @param {boolean} variants + */ + static getHashForPattern(pattern, variants = false) { + const regex = new RegExp('^([^\\.\\*\\?\\s\\r\\n\\\\]+).*$'); + pattern = pattern.substring(0, 32); + + if (typeof variants === 'undefined') { + variants = false; + } + + if (!regex.test(pattern)) { + return variants ? [md5('')] : md5(''); + } + + const matches = pattern.match(regex); + + if (typeof matches[1] === 'undefined') { + return variants ? [md5('')] : md5(''); + } + + let string = matches[1]; + + if (variants) { + let patternStarts = []; + + for (let i = string.length; i >= 1; i--) { + string = string.substring(0, i); + patternStarts.push(md5(string)); + } + + // Add empty pattern start to include patterns that start with "*", + // e.g. "*FAST Enterprise Crawler*" + patternStarts.push(md5('')); + + // add special key to fall back to the default browser + patternStarts.push('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); + + return patternStarts; + } + + return md5(string); + } + + /** + * returns a hash for one pattern + * + * @param {string} pattern + * + * @return {string} + */ + static getHashForParts(pattern) { + return md5(pattern); + } + + /** + * Gets the minimum length of the patern (used in the getPatterns() method to + * check against the user agent length) + * + * @param {string} pattern + * @return {int} + */ + static getPatternLength(pattern) { + return pattern.replace('*', '').length; + } +} + +module.exports = PatternHelper; diff --git a/pool/shard000/JavaScript/0005023_smb2-connection.js b/pool/shard000/JavaScript/0005023_smb2-connection.js new file mode 100644 index 0000000000000000000000000000000000000000..f4488eb28a1d2b83f6cfaff421118dbb91f6c964 --- /dev/null +++ b/pool/shard000/JavaScript/0005023_smb2-connection.js @@ -0,0 +1,155 @@ + +/* + * DEPENDENCIES + */ +var net = require('net') + , SMB2Forge = require('./smb2-forge') + , SMB2Request = SMB2Forge.request + ; + + + +/* + * CONNECTION MANAGER + */ +var SMB2Connection = module.exports = {}; + + + +/* + * CLOSE CONNECTION + */ +SMB2Connection.close = function(connection){ + clearAutoCloseTimeout(connection); + if(connection.connected){ + connection.connected = false; + connection.socket.end(); + } +} + + +/* + * OPEN CONNECTION + */ +SMB2Connection.requireConnect = function(method){ + return function(){ + var connection = this; + var args = Array.prototype.slice.call(arguments); + connect(connection, function(err){ + // process the cb + var cb = args.pop(); + cb = scheduleAutoClose(connection, cb); + args.push(cb); + + // manage the connection error + if(err) cb(err); + else method.apply(connection, args); + }); + } +} + + +/* + * INIT CONNECTION + */ +SMB2Connection.init = function(connection){ + // create a socket + connection.connected = false; + connection.socket = new net.Socket({ + allowHalfOpen:true + }); + + // attach data events to socket + connection.socket.on('data', SMB2Forge.response(connection)); + connection.errorHandler = []; + connection.socket.on('error', function(err){ + if(connection.errorHandler.length > 0){ + connection.errorHandler[0].call(null, err) + } + if(connection.debug){ + console.log('-- error'); + console.log(arguments); + } + }); +} + + + + +/* + * PRIVATE FUNCTION TO HANDLE CONNECTION + */ +function connect(connection, cb){ + + if(connection.connected){ + cb && cb(null); + return; + } + + cb = scheduleAutoClose(connection, cb); + + // open TCP socket + connection.socket.connect(connection.port, connection.ip); + + // SMB2 negotiate connection + SMB2Request('negotiate', {}, connection, function(err){ + if(err) cb && cb(err); + // SMB2 setup session / negotiate ntlm + else SMB2Request('session_setup_step1', {}, connection, function(err){ + if(err) cb && cb(err); + // SMB2 setup session / autheticate with ntlm + else SMB2Request('session_setup_step2', {}, connection, function(err){ + if(err) cb && cb(err); + // SMB2 tree connect + else SMB2Request('tree_connect', {}, connection, function(err){ + if(err) cb && cb(err); + else { + connection.connected = true; + cb && cb(null); + } + }); + }); + }); + }); +} + + +/* + * PRIVATE FUNCTION TO HANDLE CLOSING THE CONNECTION + */ +function clearAutoCloseTimeout(connection){ + if(connection.scheduledAutoClose){ + clearTimeout(connection.scheduledAutoClose); + connection.scheduledAutoClose = null; + } +} +function setAutoCloseTimeout(connection){ + clearAutoCloseTimeout(connection); + if(connection.autoCloseTimeout != 0){ + connection.scheduledAutoClose = setTimeout(function(){ + connection.close(); + }, connection.autoCloseTimeout); + } +} +function scheduleAutoClose(connection, cb){ + addErrorListener(connection, cb); + clearAutoCloseTimeout(connection); + return function(){ + removeErrorListener(connection); + setAutoCloseTimeout(connection); + cb.apply(null, arguments); + } +} + + +/* + * PRIVATE FUNCTIONS TO HANDLE ERRORS + */ +function addErrorListener(connection, callback){ + connection.errorHandler.unshift(callback); +} +function removeErrorListener(connection){ + connection.errorHandler.shift(); +} + + diff --git a/pool/shard000/JavaScript/0005024_commitment.js b/pool/shard000/JavaScript/0005024_commitment.js new file mode 100644 index 0000000000000000000000000000000000000000..e2202bfdf4c9c3d42c6615aa2862850ec16b04fb --- /dev/null +++ b/pool/shard000/JavaScript/0005024_commitment.js @@ -0,0 +1,93 @@ +'use strict'; + +const db = require('../db'); +const dbConnectionHandling = require('./dbConnectionHandling'); + +const createCommitment = function (commitmentId, data) { + data.title = data.title || `commitment${commitmentId}Title`; + data.description = data.description || `commitment${commitmentId}Description`; + data.website = data.website || null; + data.modified = data.modified || null; + data.modifiedAddress = data.modifiedAddress || data.created; + data.importTC = data.importTC ? ':ImportTC' : ''; + data.regions = data.regions || null; + dbConnectionHandling.getCommands().push(db.cypher().match("(user:User {userId: {adminId}})") + .create(`(user)-[:IS_ADMIN]->(commitment:Commitment${data.importTC} {title: {title}, language: {language}, description: {description}, modified: {modified}, modifiedAddress: {modifiedAddress}, + created: {created}, commitmentId: {commitmentId}, website: {website}})`) + .with(`commitment, user`) + .merge(`(user)-[:IS_CREATOR]->(commitment)`) + .with(`commitment`) + .match(`(topic:Topic)`) + .where(`topic.topicId IN {topics}`) + .merge(`(topic)-[:TOPIC]->(commitment)`) + .with(`commitment`) + .match(`(region:Region)`) + .where(`region.regionId IN {regions}`) + .merge(`(region)<-[:BELONGS_TO_REGION]-(commitment)`) + .end({ + commitmentId: commitmentId, + adminId: data.adminId, + title: data.title, + description: data.description, + language: data.language, + topics: data.topics, + created: data.created, + modified: data.modified, + modifiedAddress: data.modifiedAddress, + website: data.website, + regions: data.regions + }).getCommand()); +}; + +const createEvent = function (data) { + data.title = data.title || `event${data.eventId}Title`; + data.description = data.description || `event${data.eventId}Description`; + data.location = data.location || `event${data.eventId}Location`; + data.linkDescription = data.linkDescription || `https://example.org/${data.eventId}`; + data.uid = data.description || `${data.eventId}@dumonda.me`; + data.created = data.created || 500; + data.modified = data.modified || null; + + dbConnectionHandling.getCommands().push(db.cypher().match(`(commitment:Commitment {commitmentId: {commitmentId}})`) + .create(`(commitment)-[:EVENT]->(event:Event {eventId: {eventId}, uid: {uid}, title: {title}, description: {description}, + location: {location}, startDate: {startDate}, endDate: {endDate}, created: {created}, modified: {modified}, + linkDescription: {linkDescription}})`) + .with(`event`) + .match(`(region:Region {regionId: {regionId}})`) + .merge(`(event)-[:BELONGS_TO_REGION]->(region)`) + .end({ + commitmentId: data.commitmentId, eventId: data.eventId, uid: data.uid, title: data.title, + description: data.description, startDate: data.startDate, endDate: data.endDate, created: data.created, + modified: data.modified, regionId: data.regionId, location: data.location, linkDescription: data.linkDescription + }).getCommand()); +}; + +const showQuestionOnCommitment = function (data) { + dbConnectionHandling.getCommands().push(db.cypher() + .match(`(c:Commitment {commitmentId: {commitmentId}}), (q:Question {questionId: {questionId}})`) + .merge(`(q)<-[:SHOW_QUESTION]-(c)`) + .end({commitmentId: data.commitmentId, questionId: data.questionId}).getCommand()); +}; + +const watchCommitment = function (data) { + data.created = data.created || 555; + dbConnectionHandling.getCommands().push(db.cypher() + .match(`(c:Commitment {commitmentId: {commitmentId}}), (u:User {userId: {userId}})`) + .merge(`(c)<-[:WATCH {created: {created}}]-(u)`) + .end({commitmentId: data.commitmentId, userId: data.userId, created: data.created}).getCommand()); +}; + +const addAdminToCommitment = function (data) { + dbConnectionHandling.getCommands().push(db.cypher() + .match(`(c:Commitment {commitmentId: {commitmentId}}), (u:User {userId: {userId}})`) + .merge(`(c)<-[:IS_ADMIN]-(u)`) + .end({commitmentId: data.commitmentId, userId: data.userId}).getCommand()); +}; + +module.exports = { + createCommitment, + createEvent, + showQuestionOnCommitment, + watchCommitment, + addAdminToCommitment +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005026_transition.js b/pool/shard000/JavaScript/0005026_transition.js new file mode 100644 index 0000000000000000000000000000000000000000..04f70d18e0ea40528d407b6e677522b7ed3acdba --- /dev/null +++ b/pool/shard000/JavaScript/0005026_transition.js @@ -0,0 +1,95 @@ +var __extends = (this && this.__extends) || (function () { + var 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 function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "../animations/animation"], factory); + } +})(function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var animation_1 = require("../animations/animation"); + /** + * @hidden + * + * - play + * - Add before classes - DOM WRITE + * - Remove before classes - DOM WRITE + * - Add before inline styles - DOM WRITE + * - set inline FROM styles - DOM WRITE + * - RAF + * - read toolbar dimensions - DOM READ + * - write content top/bottom padding - DOM WRITE + * - set css transition duration/easing - DOM WRITE + * - RAF + * - set inline TO styles - DOM WRITE + */ + var Transition = (function (_super) { + __extends(Transition, _super); + /** + * @param {?} plt + * @param {?} enteringView + * @param {?} leavingView + * @param {?} opts + */ + function Transition(plt, enteringView, leavingView, opts) { + var _this = _super.call(this, plt, null, opts) || this; + _this.enteringView = enteringView; + _this.leavingView = leavingView; + return _this; + } + /** + * @return {?} + */ + Transition.prototype.init = function () { }; + /** + * @param {?} trnsStart + * @return {?} + */ + Transition.prototype.registerStart = function (trnsStart) { + this._trnsStart = trnsStart; + }; + /** + * @return {?} + */ + Transition.prototype.start = function () { + this._trnsStart && this._trnsStart(); + this._trnsStart = null; + // bubble up start + this.parent && this.parent.start(); + }; + /** + * @return {?} + */ + Transition.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.parent = this.enteringView = this.leavingView = this._trnsStart = null; + }; + return Transition; + }(animation_1.Animation)); + exports.Transition = Transition; + function Transition_tsickle_Closure_declarations() { + /** @type {?} */ + Transition.prototype._trnsStart; + /** @type {?} */ + Transition.prototype.parent; + /** @type {?} */ + Transition.prototype.trnsId; + /** @type {?} */ + Transition.prototype.enteringView; + /** @type {?} */ + Transition.prototype.leavingView; + } +}); +//# sourceMappingURL=transition.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005027_amp_components.js b/pool/shard000/JavaScript/0005027_amp_components.js new file mode 100644 index 0000000000000000000000000000000000000000..19fc43bd319f31d5796b59c77d8f7c26e22b8186 --- /dev/null +++ b/pool/shard000/JavaScript/0005027_amp_components.js @@ -0,0 +1,37 @@ +// # Amp Components Helper +// Usage: `{{amp_components}}` +// +// Reads through the AMP HTML and adds neccessary scripts +// for each extended component +// If more components need to be added, we can add more scripts. +// Here's the list of all supported extended components: https://www.ampproject.org/docs/reference/extended.html +// By default supported AMP HTML tags (no additional script tag necessary): +// amp-img, amp-ad, amp-embed, amp-video and amp-pixel. +// (less) dirty requires +var proxy = require('../../../../helpers/proxy'), + SafeString = proxy.SafeString; + +function ampComponents() { + var components = [], + html = this.post.html || this.html; + + if (!html) { + return; + } + + if (html.indexOf('.gif') !== -1) { + components.push('<script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script>'); + } + + if (html.indexOf('<iframe') !== -1) { + components.push('<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>'); + } + + if (html.indexOf('<audio') !== -1) { + components.push('<script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>'); + } + + return new SafeString(components.join('\n')); +} + +module.exports = ampComponents; diff --git a/pool/shard000/JavaScript/0005028_chimp_test.js b/pool/shard000/JavaScript/0005028_chimp_test.js new file mode 100644 index 0000000000000000000000000000000000000000..74b5eacb0974e57339212d4128ac9d315682c2d7 --- /dev/null +++ b/pool/shard000/JavaScript/0005028_chimp_test.js @@ -0,0 +1,48 @@ +'use strict'; + +var grunt = require('grunt'); + +/* + ======== A Handy Little Nodeunit Reference ======== + https://github.com/caolan/nodeunit + + Test methods: + test.expect(numAssertions) + test.done() + Test assertions: + test.ok(value, [message]) + test.equal(actual, expected, [message]) + test.notEqual(actual, expected, [message]) + test.deepEqual(actual, expected, [message]) + test.notDeepEqual(actual, expected, [message]) + test.strictEqual(actual, expected, [message]) + test.notStrictEqual(actual, expected, [message]) + test.throws(block, [error], [message]) + test.doesNotThrow(block, [error], [message]) + test.ifError(value) +*/ + +exports.chimp = { + setUp: function(done) { + // setup here if necessary + done(); + }, + default_options: function(test) { + test.expect(1); + + var actual = grunt.file.read('tmp/default_options'); + var expected = grunt.file.read('test/expected/default_options'); + test.equal(actual, expected, 'should describe what the default behavior is.'); + + test.done(); + }, + custom_options: function(test) { + test.expect(1); + + var actual = grunt.file.read('tmp/custom_options'); + var expected = grunt.file.read('test/expected/custom_options'); + test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); + + test.done(); + }, +}; diff --git a/pool/shard000/JavaScript/0005029_physics-util.js b/pool/shard000/JavaScript/0005029_physics-util.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc68f837b471aa2b3a9ad881e66412498390fbc --- /dev/null +++ b/pool/shard000/JavaScript/0005029_physics-util.js @@ -0,0 +1,101 @@ +define(function (require) { + + 'use strict'; + + /** + * Constants + */ + + // Planck's constant J-s + var PLANCK = 6.626E-34; + // Speed of light - m/s + var LIGHT_SPEED = 2.9979E8; + // Electron rest mass - kg + var ELECTRON_MASS = 9.109E-31; + // Joules per EV, EV per Joule + var JOULES_PER_EV = 1.6022E-19; + var EV_PER_JOULE = 1 / JOULES_PER_EV; + // nanometers per meter + var NM_PER_M = 1E9; + // Avogadro's number + var AVOGADRO = 6.022E23; + + + /** + * A collection of utilities having to do with physical constants and phenomena + */ + var PhysicsUtil = { + + PLANCK: PLANCK, + LIGHT_SPEED: LIGHT_SPEED, + ELECTRON_MASS: ELECTRON_MASS, + JOULES_PER_EV: JOULES_PER_EV, + EV_PER_JOULE: EV_PER_JOULE, + NM_PER_M: NM_PER_M, + AVOGADRO: AVOGADRO, + + /** + * Determines the energy, in EV, of radiation with a specified wavelength + * + * @param wavelength in nm + * @return energy in EV + */ + wavelengthToEnergy: function(wavelength) { + return PLANCK * LIGHT_SPEED / wavelength / JOULES_PER_EV * NM_PER_M; + }, + + /** + * Determines the wavelength, in nm, of radiation with a specified energy + * + * @param ev energy of the radiation, in ev + * @return wavelength in nm + */ + energyToWavelength: function(ev) { + return (PLANCK * LIGHT_SPEED / ev) * EV_PER_JOULE * NM_PER_M; + }, + + /** + * Returns the frequency of EM radiation of a specified wavelength + * + * @param wavelength Wavelength, in nm + * @return frequency in Hz + */ + wavelengthToFrequency: function(wavelength) { + return LIGHT_SPEED * NM_PER_M / wavelength; + }, + + /** + * Returns the wavelength, in nm, of EM radiation of a specified + * frequency + * + * @param frequency in Hz + * @return wavelength in nm + */ + frequencyToWavelength: function(frequency) { + return LIGHT_SPEED * NM_PER_M / frequency; + }, + + /** + * Returns the energy, in EV, of EM radiation of a specified frequency + * + * @param frequency in Hz + * @return energy in EV + */ + frequencyToEnergy: function(frequency) { + return this.wavelengthToEnergy(this.frequencyToWavelength(frequency)); + }, + + /** + * Returns the frequency, in Hz, of EM radiation of a specified energy + * + * @param energy + * @return frequency in Hz + */ + energyToFrequency: function(energy) { + return this.wavelengthToFrequency(this.energyToWavelength(energy)); + } + + }; + + return PhysicsUtil; +}); diff --git a/pool/shard000/JavaScript/0005031_index.js b/pool/shard000/JavaScript/0005031_index.js new file mode 100644 index 0000000000000000000000000000000000000000..93dfd4dbb2447d3435571996e1ff7412863d022d --- /dev/null +++ b/pool/shard000/JavaScript/0005031_index.js @@ -0,0 +1,47 @@ +'use strict'; + +import React, {Component} from 'react'; +import Table from '~/views/lib/material/Table'; +import {Link} from 'react-router'; +import './SearchedJobs.less'; + +export default class SearchJobs extends Component { + static propTypes = { + project: React.PropTypes.object.isRequired + } + + render() { + console.log(this.props.project); + let jobs = {}; + + for (let j of this.props.project.requiredJobs){ + if (jobs[j.name]){ + jobs[j.name]++; + } else { + jobs[j.name] = 1; + } + } + return ( + <div className="searchedJobs"> + <h4>Métiers recherchés :</h4> + <Table> + <tbody> + {Object.keys(jobs).map((key) => { + return ( + <tr key={key}> + <td>{jobs[key]}</td> + <td>{key}</td> + <td className="centered"> + <Link className="btn btn-raised btn-xs btn-primary postulateButton" to="/"> + Postuler + </Link> + </td> + </tr> + ); + })} + </tbody> + </Table> + </div> + ); + } +} diff --git a/pool/shard000/JavaScript/0005032_defaults.js b/pool/shard000/JavaScript/0005032_defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..d286a9ce3fd0409797dc68072f17292e5482f0ec --- /dev/null +++ b/pool/shard000/JavaScript/0005032_defaults.js @@ -0,0 +1,82 @@ +'use strict'; +var utils = require('./utils'); +var _ = require('lodash'); +var TypeScriptDefaults = { + allowBool: false, + allowImportModule: false, + allowSyntheticDefaultImports: null, + amdloader: null, + compile: true, + declaration: false, + emitDecoratorMetadata: false, + experimentalDecorators: false, + mapRoot: '', + module: null, + noImplicitAny: false, + noResolve: false, + comments: null, + removeComments: null, + sourceMap: true, + sourceRoot: '', + target: null, + verbose: false, + fast: null, + watch: null, + compiler: '', + html: null, + htmlModuleTemplate: null, + htmlVarTemplate: null, + htmlOutputTemplate: null, + htmlOutDir: null, + htmlOutDirFlatten: null, + failOnTypeErrors: null, + emitGruntEvents: null, + noEmitOnError: false, + preserveConstEnums: false, + suppressExcessPropertyErrors: false, + suppressImplicitAnyIndexErrors: false, + stripInternal: false, + noEmit: false, + noLib: false, + emitBOM: false, + inlineSources: false, + inlineSourceMap: false, + newLine: utils.eol, + isolatedModules: false, + noEmitHelpers: false, + additionalFlags: '', + templateCache: null, + targetName: '', + locale: null, + jsx: null, + moduleResolution: null, + experimentalAsyncFunctions: null, + reactNamespace: null, + skipDefaultLibCheck: null, + pretty: false, + allowUnusedLabels: false, + noImplicitReturns: false, + noFallthroughCasesInSwitch: false, + allowUnreachableCode: false, + forceConsistentCasingInFileNames: false, + allowJs: false, + noImplicitUseStrict: false, + rootDir: null, + warnings: [], + errors: [] +}; +exports.GruntTSDefaults = applyGruntTSDefaults(_.clone(TypeScriptDefaults)); +function applyGruntTSDefaults(options) { + // this function applies defaults where grunt-ts differs from TypeScript + options.sourceMap = true; + options.target = 'es5'; + options.htmlModuleTemplate = '<%= filename %>'; + options.htmlVarTemplate = '<%= ext %>'; + options.htmlOutDirFlatten = false; + options.fast = 'watch'; + options.removeComments = true; + options.failOnTypeErrors = true; + options.emitGruntEvents = false; + return options; +} +//# sourceMappingURL=defaults.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005036_data.js b/pool/shard000/JavaScript/0005036_data.js new file mode 100644 index 0000000000000000000000000000000000000000..3c89fcb0065e8ae2a84cbad5a40988dad7521477 --- /dev/null +++ b/pool/shard000/JavaScript/0005036_data.js @@ -0,0 +1,53 @@ +const util = require('util'); + +module.exports = function (req, res, utils) { + + var deferred = Promise.defer(); + + utils.request({ + url: 'open/get_posts_by_category', + method: 'POST', + qs: { + siteId: req.site.id, + categoryId: 'pwlualmmdlhneunpwyxssg', + pageSize: 6 + } + }, function (result) { + + var data = { + category: {}, + list: [], + first: undefined + }; + + if (result.code != 200) { + + deferred.resolve(data); + return; + }; + + result.body = JSON.parse(result.body); + + data.category = { + href: util.format('category?id=%s', result.body.category.id), + title: result.body.category.title + }; + result.body.data.forEach(function (e) { + + data.list.push({ + ori_title: e.title, + title: utils.subString(e.title, 30), + date: e.date_published, + summary: e.summary, + href: util.format('detail?id=%s', e.id) + }); + + }, this); + + deferred.resolve({ + data: data + }); + },deferred); + + return deferred.promise; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005038_display.js b/pool/shard000/JavaScript/0005038_display.js new file mode 100644 index 0000000000000000000000000000000000000000..229ab3313a1bb1325e8357d8492160ffabad8046 --- /dev/null +++ b/pool/shard000/JavaScript/0005038_display.js @@ -0,0 +1,60 @@ +'use strict' + +var chalk = require('chalk') +var figures = require('figures') + +var Spinner = require('cli-spinner').Spinner + +module.exports = { + /** + * Display an error message. + * @param {string} title title of the message + * @param {string} message the message + */ + error: function (title, message) { + console.log(' ' + chalk.red(title) + ' ' + message) + }, + + /** + * Display a title. + * @param {string} title the title + */ + title: function (title) { + console.log(chalk.green(title)) + }, + + /** + * Display the message + * @param {string} message the message to display + */ + message: function (message) { + console.log(' ' + message) + }, + + /** + * Display a carriage return. + */ + carriageReturn: function () { + console.log('') + }, + + /** + * Get a warning message. + * @param {string} message a message + * @returns {string} formatted message + */ + getWarning: function (message) { + return chalk.yellow(figures.warning + ' ' + message) + }, + + /** + * Get a spinner + * @param {string} message the message that will be display next to the spinner + * @returns {Spinner} a spinner + */ + getSpinner: function (message) { + var spinner = new Spinner(message) + spinner.setSpinnerString(18) + return spinner + } +} diff --git a/pool/shard000/JavaScript/0005041_submit.test.js b/pool/shard000/JavaScript/0005041_submit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7ca3e78bf4500ff9482c0d82b23f0d899bd3574b --- /dev/null +++ b/pool/shard000/JavaScript/0005041_submit.test.js @@ -0,0 +1,61 @@ +import {addonSubmitReducer, addonSubmitVersionReducer} from '../submit'; +import * as submitActions from '../../actions/submit'; +import * as submitVersionActions from '../../actions/submitVersion'; + + +describe('submitReducer', () => { + it('handles message change', () => { + const newState = addonSubmitReducer( + { + message: '', + }, + { + type: submitActions.MESSAGE_CHANGE, + payload: 'help me please' + } + ); + assert.equal(newState.message, 'help me please'); + }); + + it('handles validation begin', () => { + const newState = addonSubmitReducer( + { + message: 'help', + }, + { + type: submitActions.VALIDATION_BEGIN, + } + ); + assert.equal(newState.message, 'help'); + assert.ok(newState.isSubmitting); + }); +}); + + +describe('submitVersionReducer', () => { + it('handles message change', () => { + const newState = addonSubmitVersionReducer( + { + message: '', + }, + { + type: submitVersionActions.MESSAGE_CHANGE, + payload: 'help me please' + } + ); + assert.equal(newState.message, 'help me please'); + }); + + it('handles validation begin', () => { + const newState = addonSubmitVersionReducer( + { + message: 'help', + }, + { + type: submitVersionActions.VALIDATION_BEGIN, + } + ); + assert.equal(newState.message, 'help'); + assert.ok(newState.isSubmitting); + }); +}); diff --git a/pool/shard000/JavaScript/0005042_exit.js b/pool/shard000/JavaScript/0005042_exit.js new file mode 100644 index 0000000000000000000000000000000000000000..48eb415866774c5c821a9eb6a3b10b126b844d99 --- /dev/null +++ b/pool/shard000/JavaScript/0005042_exit.js @@ -0,0 +1,13 @@ +const { TIME_COLOR, WS } = require("../constants"); +const { error, ok } = require("../core"); + +function exit(reason) { + const hasReason = Boolean(reason); + if (hasReason) error(`${reason}${WS}`); + else ok(`Success${WS}`); + // eslint-disable-next-line no-console + console.timeEnd(TIME_COLOR); + process.exit(hasReason); +} + +module.exports = exit; diff --git a/pool/shard000/JavaScript/0005043_ManageOrderItem.js b/pool/shard000/JavaScript/0005043_ManageOrderItem.js new file mode 100644 index 0000000000000000000000000000000000000000..6053d713ea3c50d7753df0baf37c98a9d2c40012 --- /dev/null +++ b/pool/shard000/JavaScript/0005043_ManageOrderItem.js @@ -0,0 +1,53 @@ +import React, {PropTypes} from 'react'; +import {connect} from 'react-redux'; +import OrderItemActions from '../../actions/orderItemActions'; +import OrderItemForm from './orderItemForm'; +import ManageEntityBase from '../common/ManageEntityBase'; +import constants from '../../constants'; +import OrderItemViewModel from '../../viewModels/orderItemViewModel'; + +let orderItemActions = new OrderItemActions(); + +class ManageOrderItem extends ManageEntityBase { + + _saveAction(viewModel) { + return orderItemActions.save(viewModel.entity); + } + + _redirectUri(savedEntity) { + var currentOrder = savedEntity || this.props.viewModel.entity; + return constants.routes.ORDERS + '/' + currentOrder.orderId; + } + + render() { + return ( + <div> + <h1>Manage Order Item</h1> + <OrderItemForm + onCancel={this.cancel} + onChange={this.change} + onSave={this.save} + viewModel={this.state.viewModel} + errors={this.state.errors} + saving={this.state.saving} /> + </div> + ); + } +} + +function mapStateToProps(state, ownProps) { + var orderId = ownProps.match.params.id; + var orderItemId = ownProps.match.params.itemid; + return { + viewModel: new OrderItemViewModel( + orderId, + orderItemId, + state.orderItems, + state.categories, + state.products, + state.inventoryItems + ) + } +} + +export default connect(mapStateToProps)(ManageOrderItem); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005046_editRecipeController.js b/pool/shard000/JavaScript/0005046_editRecipeController.js new file mode 100644 index 0000000000000000000000000000000000000000..3d49ae56e8f169a0c0b88e1240557153f05e6567 --- /dev/null +++ b/pool/shard000/JavaScript/0005046_editRecipeController.js @@ -0,0 +1,92 @@ +//Can refactor to eliminate redundancy between this and the add recipe controller. +(function() { + 'use strict'; + + angular.module('brewApp.controllers') + .controller('EditRecipeCtrl', ['$modalInstance', 'BrewMaster', 'logger', 'notifications', 'UserStore', '$modalParams', editRecipeController]); + + function editRecipeController($modalInstance, BrewMaster, logger, notifications, UserStore, $modalParams) { + /* jshint validthis: true */ + var self = this; + + self.INGREDIENT_TYPE = { HOPS: 'hops', MALT: 'malt', YEAST: 'yeast' }; + + self.isIngredientsCollapsed = true; + + UserStore.getCurrentUserRecipeById($modalParams.id).then(function(recipe) { + self.recipe = angular.copy(recipe); + + UserStore.getRecipeIngredientsByRecipeId($modalParams.id).then(function(ingredients) { + //Break out ingredients by type for UI. + if (ingredients && ingredients.length > 0) { + self.ingredients = []; + + for (var i = 0; i < ingredients.length; i++) + (self.ingredients[ingredients[i].type] = self.ingredients[ingredients[i].type] || []).push(ingredients[i]); + } + }); + }); + + BrewMaster.getDefinitions().then(function(definitions) { + self.units = definitions.units.volume.map(function(def) { return def.name; }); + + if (BrewMaster.hasIngredient(definitions, 'yeast')) + self.yeasts = definitions.ingredient.yeast.map(function(def) { return def.name; }); + }); + + self.addIngredient = function(type, ingredient) { + (self.ingredients[type] = self.ingredients[type] || []).push(ingredient); + + //This is pretty brittle. + self.current[type] = null; + }; + + self.deleteIngredient = function(type, ingredient) { + var index = self.ingredients[type] + .map(function(i) { return i.name; }) + .indexOf(ingredient.name); + + self.ingredients[type].splice(index, 1); + }; + + self.isIngredientValid = function(ingredient) { + return !(ingredient == null || ingredient.name == null || ingredient.name.trim() == '' || + (ingredient.volume != null && ingredient.units == null)); + }; + + self.update = function(isValid) { + //Make notification more useful. + if (!isValid) { notifications.error('Submission is not valid.'); return; } + + self.recipe.ingredients = self.recipe.ingredients || []; + + for (var key in self.INGREDIENT_TYPE) { + if (!self.INGREDIENT_TYPE.hasOwnProperty(key)) continue; + + var type = self.INGREDIENT_TYPE[key]; + + if (self.ingredients[type] && self.ingredients[type].length > 0) + for (var i = 0; i < self.ingredients[type].length; i++) { + var ingredient = self.ingredients[type][i]; + ingredient.type = type; + + self.recipe.ingredients.push(ingredient); + } + } + + //Need a spinner on this? + UserStore.updateRecipe(self.recipe).then(function() { + notifications.success('Recipe ' + self.recipe.name + ' updated.'); + logger.info('Recipe ' + self.recipe.recipeId + ' updated.'); + + $modalInstance.close(); + }); + }; + + self.cancel = $modalInstance.dismiss; + + self.ingredientsCollapse = function() { + self.isIngredientsCollapsed = !self.isIngredientsCollapsed; + }; + } +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005048_enquiries.js b/pool/shard000/JavaScript/0005048_enquiries.js new file mode 100644 index 0000000000000000000000000000000000000000..a69ef318631fe66920ec0c123142e596fe99ab5e --- /dev/null +++ b/pool/shard000/JavaScript/0005048_enquiries.js @@ -0,0 +1,135 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +import { Component } from '@angular/core'; +import { NavController, NavParams, LoadingController } from 'ionic-angular'; +import { EnquiryDetailsPage } from '../enquiry-details/enquiry-details'; +import { Storage } from '@ionic/storage'; +import firebase from 'firebase'; +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/observable/of'; +/* + Generated class for the Enquiries page. + + See http://ionicframework.com/docs/v2/components/#navigation for more info on + Ionic pages and navigation. +*/ +var EnquiriesPage = (function () { + function EnquiriesPage(navCtrl, navParams, storage, loadingCtrl) { + //storage.ready().then(() => { + //storage.get('currentuser').then((val) => { + this.navCtrl = navCtrl; + this.navParams = navParams; + this.storage = storage; + this.loadingCtrl = loadingCtrl; + this.currentuser = firebase.auth().currentUser; + //this.currentuserid = this.currentuser.uid; + this.segment = "received"; + //setTimeout(() => { + this.setData(); + //},3000); + //this.enquiryList = af.database.list('/users/' + this.currentuser.uid + '/enquiries'); + //}) + // .catch((err) => + // console.log(err)); + //}).catch((err) => + // console.log(err)); + } + EnquiriesPage.prototype.ionViewDidLoad = function () { + console.log('ionViewDidLoad EnquiriesPage'); + this.segment = "received"; + var loading = this.loadingCtrl.create({ + content: 'Updating...' + }); + loading.present(); + setTimeout(function () { + loading.dismiss(); + }, 1500); + }; + EnquiriesPage.prototype.setData = function () { + var _this = this; + this.enquiryListref = firebase.database().ref('/users/' + this.currentuser.uid + '/enquiries').orderByChild("type").equalTo("received"); + //this.enquiryList = this.af.database.list('/users/' + this.currentuserid + '/enquiries', { + // query: { + // orderByChild: "type", + // equalTo: this.segment + // } + //}); + this.enquiryListref.on('value', function (snapshot) { + //this.enquiryList = this.af.database.list('/users/' + this.currentuserid + '/enquiries', { + //query: { + // orderByChild: "type", + // equalTo: this.segment + // } + //}); + //console.log("received"); + //this.enqListRev = []; + _this.enquiryList = []; + _this.keys = []; + snapshot.forEach(function (country) { + _this.enquiryList.push(country.val()); + _this.keys.push(country.key); + }); + for (var i in _this.enquiryList) { + _this.enquiryList[i].key = _this.keys[i]; + } + //this.enqListRev = this.enquiryList.reverse(); + _this.enqListRev = Observable.of(_this.enquiryList.reverse()); + console.log(_this.enqListRev); + _this.flag = true; + }); + this.sentListref = firebase.database().ref('/users/' + this.currentuser.uid + '/enquiries').orderByChild("type").equalTo("sent"); + //this.enquiryList = this.af.database.list('/users/' + this.currentuserid + '/enquiries', { + // query: { + // orderByChild: "type", + // equalTo: this.segment + // } + //}); + this.sentListref.on('value', function (snapshot) { + //this.sentListRev = []; + _this.sentList = []; + _this.keys2 = []; + snapshot.forEach(function (country) { + //console.log(country.key); + _this.sentList.push(country.val()); + _this.keys2.push(country.key); + }); + for (var i in _this.sentList) { + _this.sentList[i].key = _this.keys2[i]; + } + //this.updateEnquiryList(2); + _this.sentListRev = Observable.of(_this.sentList.reverse()); + }); + }; + EnquiriesPage.prototype.ionViewDidEnter = function () { + }; + EnquiriesPage.prototype.openenquirypage = function (enquiry) { + this.navCtrl.push(EnquiryDetailsPage, { enquiry: enquiry }); + }; + EnquiriesPage.prototype.updateEnquiryList = function (type) { + if (type == 1) { + this.enqListRev = this.enquiryList.reverse(); + this.enqListRev = Observable.of(this.enqListRev); + } + else if (type == 2) { + this.sentListRev = this.sentList.reverse(); + this.sentListRev = Observable.of(this.sentList.reverse()); + } + }; + return EnquiriesPage; +}()); +EnquiriesPage = __decorate([ + Component({ + selector: 'page-enquiries', + templateUrl: 'enquiries.html' + }), + __metadata("design:paramtypes", [NavController, NavParams, Storage, LoadingController]) +], EnquiriesPage); +export { EnquiriesPage }; +//# sourceMappingURL=enquiries.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005053_marloBulk.js b/pool/shard000/JavaScript/0005053_marloBulk.js new file mode 100644 index 0000000000000000000000000000000000000000..12bcf889bdd8fc6e77c7c4ec5513b32d341cf3ea --- /dev/null +++ b/pool/shard000/JavaScript/0005053_marloBulk.js @@ -0,0 +1,138 @@ +var $globalUnitSelect, $phasesSelect, $deliverablesList; +$(document).ready(init); + +function init() { + $entitySelect = $('#entityID'); + $globalUnitSelect = $('#globalUnitID'); + $phasesSelect = $('#phaseID'); + $deliverablesList = $('#deliverables-checkbox table tbody'); + // Events + attachEvents(); +} + +function attachEvents() { + $entitySelect.on('change', updateEntity); + $globalUnitSelect.on('change', updatePhases); + $phasesSelect.on('change', updateDeliverables); + + $('#toggleSelectAll').on('change', function() { + $deliverablesList.find('tr:visible').find('.deliverableCheck').prop("checked", this.checked); + updateCheckedCount(); + }); + + $('.deliverableCheck').on('change', function() { + updateCheckedCount(); + }); + + $('#filterButton').on('click', function() { + var fiterText = $.trim($('#filterText').val()); + if(fiterText) { + $deliverablesList.find('tr').hide(); + $('.deliverableCheck').prop("checked", false); + $.each(fiterText.split(','), function(i,id) { + var id = $.trim(id); + if(id) { + $('tr#' + id).show(); + $('tr#' + id).find('.deliverableCheck').prop("checked", true); + } + }); + } else { + $deliverablesList.find('tr').show(); + $('.deliverableCheck').prop("checked", true); + } + updateCheckedCount(); + }); +} + +function updateEntity() { + var entityName = $(this).find(":selected").text(); + var entityAction = $(this).find(":selected").classParam('action'); + $('th.entityName').text(entityName); + $("#bulkReplicationForm").attr("action", "./" + entityAction + ".do"); + + $globalUnitSelect.val(-1); + $phasesSelect.empty(); + $deliverablesList.empty(); + $('.count').text(0); +} + +function updatePhases() { + var globalUnitID = this.value; + + if(globalUnitID == "-1") { + return; + } + + $.ajax({ + url: baseURL + "/getPhasesByGlobalUnit.do", + data: { + selectedGlobalUnitID: globalUnitID + }, + beforeSend: function() { + $('.loading').fadeIn(); + $phasesSelect.empty(); + $deliverablesList.empty(); + $('.count').text(0); + }, + success: function(data) { + $phasesSelect.addOption('-1', 'Select an option...'); + $.each(data.phasesbyGlobalUnit, function(i,e) { + $phasesSelect.addOption(e.id, e.name + ' ' + e.year); + }); + }, + complete: function() { + $('.loading').fadeOut(); + updateCheckedCount(); + } + }); +} + +function updateDeliverables() { + var phaseID = this.value; + if(phaseID == "-1") { + return; + } + + $.ajax({ + url: baseURL + "/" + $('select#entityID').val() + ".do", + data: { + selectedPhaseID: phaseID + }, + beforeSend: function() { + $('.loading').fadeIn(); + $deliverablesList.empty(); + + }, + success: function(data) { + var dataArray = (data.entityByPhaseList); + + $.each(dataArray, function(i,e) { + var $checkmarkRow = $('.check-template tr').clone(true).removeAttr('id'); + $checkmarkRow.attr('id', e.id); + $checkmarkRow.find('input').addClass('deliverableCheckAdded'); + $checkmarkRow.find('input').val(e.id); + $checkmarkRow.find('.id').text(e.id); + $checkmarkRow.find('.labelText').text(e.composedName); + + // console.log($checkmarkRow); + $deliverablesList.append($checkmarkRow); + + }); + }, + complete: function() { + $('.loading').fadeOut(); + updateCheckedCount(); + } + }); +} + +function updateCheckedCount() { + var checkedCounted = $('.deliverableCheckAdded:checked').length; + $('.count').text(checkedCounted); + + if(checkedCounted) { + // $('.controls-block').fadeIn(); + } else { + // $('.controls-block').fadeOut(); + } +} diff --git a/pool/shard000/JavaScript/0005054_provider.js b/pool/shard000/JavaScript/0005054_provider.js new file mode 100644 index 0000000000000000000000000000000000000000..60d8e96b6982e404d6b199ee803d07195dbffb4a --- /dev/null +++ b/pool/shard000/JavaScript/0005054_provider.js @@ -0,0 +1,95 @@ +import { logDebug } from "./logger"; +import providers from "./providers"; + + +/** @type {Map<string,NotificationProvider>} */ +const instanceMap = new Map(); +/** @type {Map<string,Promise>} */ +const setupMap = new Map(); + + +/** + * Check whether a NotificationProvider is supported on the current platform + * @param {string} provider + * @returns {boolean} + */ +export function isSupported( provider ) { + return providers.hasOwnProperty( provider ) + ? providers[ provider ].isSupported() + : false; +} + + +/** + * Finds a NotificationProvider given by name, sets it up and displays a notification. + * Falls back to the next provider if its setup or showing the notification fails. + * @param {string} provider + * @param {NotificationData} data + * @param {boolean} newInst + * @returns {Promise} + */ +export async function showNotification( provider, data, newInst ) { + if ( !providers.hasOwnProperty( provider ) ) { + throw new Error( "Invalid notification provider" ); + } + + const useFallbacks = provider === "auto"; + let foundProvider = false; + + for ( const [ current, Provider ] of Object.entries( providers ) ) { + // start at the requested provider and continue from there if using fallbacks + if ( !foundProvider && current !== provider ) { + continue; + } + foundProvider = true; + + // the provider needs to be supported + if ( !Provider.isSupported() ) { + if ( useFallbacks ) { + continue; + } else { + throw new Error( "The notification provider is not supported" ); + } + } + + try { + let instance; + // create a provider instance if it doesn't exist yet + if ( newInst || !instanceMap.has( current ) ) { + /** @type {NotificationProvider} */ + instance = new Provider(); + instanceMap.set( current, instance ); + + // set up provider instance + try { + const setup = instance.setup(); + setupMap.set( current, setup ); + // wait for setup to finish + await setup; + } catch ( err ) { + // unregister if setup has failed + instanceMap.delete( current ); + throw err; + } + + } else { + instance = instanceMap.get( current ); + // wait for setup to finish + await setupMap.get( current ); + } + + // show the notification + await logDebug( "Showing notification", { provider, current, data } ); + await instance.notify( data ); + return; + + } catch ( err ) { + // provider is not working... try the next one + if ( !useFallbacks ) { + throw err; + } + } + } + + throw new Error( "Couldn't find a notification provider" ); +} diff --git a/pool/shard000/JavaScript/0005055_bookingCost.js b/pool/shard000/JavaScript/0005055_bookingCost.js new file mode 100644 index 0000000000000000000000000000000000000000..c52fe8dadaea162dd1ab129a5546816235723451 --- /dev/null +++ b/pool/shard000/JavaScript/0005055_bookingCost.js @@ -0,0 +1,24 @@ +'use strict' + +var _ = require('lodash'); + +module.exports = function bookingCost(booking, uid) { + var cost = booking.getCost(); + var playInfo = booking.getPlayer(uid); + + // Joined players + var players = Object.keys(booking.getPlayers()).length; + // Sum of join players' guests + var guests = _.reduce(booking.getPlayers(), function (result, player) { + result += (player.guests || 0); + return result; + }, 0); + + var costPerPlayer = cost / (players + guests); + + var playerGuests = playInfo.guests || 0; + + var playerCost = costPerPlayer * (1 + playerGuests); + + return playerCost; +}; diff --git a/pool/shard000/JavaScript/0005058_inter.js b/pool/shard000/JavaScript/0005058_inter.js new file mode 100644 index 0000000000000000000000000000000000000000..e1c2151bc823785c9350b6c3c0d63a5f1ab1c230 --- /dev/null +++ b/pool/shard000/JavaScript/0005058_inter.js @@ -0,0 +1,70 @@ +var async = require('interleavings') +var assert = require('assert') +var pull = require('pull-stream') + +var creditor = require('../creditor') +var debtor = require('../debtor') + + +var crypto = require('crypto') +var pull = require('pull-stream') +var tape = require('tape') +var randomsp = require('pull-randomly-split') +var property = require('pull-property') + + +function streamTest (async) { + var totalRead = 0 + var totalGiven = 0, totalReceived = 0 + + var dr = debtor(128) + var creditSource = property() + + var cr = creditor(128, function (_, data){ + console.log('totalGiven ', totalGiven += data) + creditSource.update(data | 0) + }) + + var creditSink = pull.drain(function (data) { + console.log('totalReceived', totalReceived += data) + dr.credit(data) + }) + + var buffer = crypto.randomBytes(1024) + + function interleave () { + return function (read) { + return function (abort, cb) { + read(abort, async(cb)) + } + } + } + + pull( + pull.values([buffer]), + interleave(), + dr, + pull.through(function (data) { + if(data.length > 128) { + throw new Error('too much data') + } + }), + interleave(), + cr, + interleave(), + pull.collect(function (err, ary) { + console.log(ary.length) + var avg = 1024 / ary.length + assert.ok(avg > 64, 'average chunk should be > 64, was:' + avg) + assert.deepEqual(Buffer.concat(ary), buffer) + async.done(null, Buffer.concat(ary)) + }) + ) + + pull(creditSource, interleave() , creditSink) +} + +async.test(streamTest, function (err, result, stats) { + console.log(result) + console.log(stats) +}) diff --git a/pool/shard000/JavaScript/0005062_build.js b/pool/shard000/JavaScript/0005062_build.js new file mode 100644 index 0000000000000000000000000000000000000000..cf7c6abd955eef4fb9366bd34e85990babb1310f --- /dev/null +++ b/pool/shard000/JavaScript/0005062_build.js @@ -0,0 +1,56 @@ +var gulp = require('gulp'); +var $ = require('./shared').plugins; +var del = require('del'); +var babelify = require('babelify'); +var browserify = require('browserify'); +var source = require('vinyl-source-stream'); + +gulp.task('build-clean', function(cb) { + del('build/*', cb) +}); + +gulp.task('eslint', function() { + gulp.src('./src/app/**/*.es6') + .pipe($.eslint()) + .pipe($.eslint.formatEach()); +}); + +gulp.task('sass', function () { + gulp.src('./src/app/styles/app.scss', {"base": "./src/app"}) + .pipe($.sass()) + .on("error", function(error){ + $.util.log($.util.colors.red(error.fileName)); + del('./build/app/styles/app.css'); + this.emit('end'); + }) + .pipe($.csslint('.csslintrc')) + .pipe($.csslint.reporter()) + .pipe($.autoprefixer()) + .pipe(gulp.dest('./build/app')); +}); + +gulp.task('browserify', function() { + return browserify({ + entries: './src/app/app.es6', + transform: [babelify.configure({ + optional: ["es7.decorators", "es7.classProperties"] + })], + extensions: ['.es6', '.js'] + }) + .bundle() + .on("error", $.notify.onError(function(error){ + return error.message; + })) + .on("error", function(){ + del('./build/app/app.js'); + this.emit('end'); + }) + .pipe(source('app.js')) + .pipe(gulp.dest('./build/app')) + ; +}); + + +gulp.task('build', ['build-clean'], function() { + gulp.start('eslint', 'sass', 'browserify'); +}); diff --git a/pool/shard000/JavaScript/0005065_warning.js b/pool/shard000/JavaScript/0005065_warning.js new file mode 100644 index 0000000000000000000000000000000000000000..3ab3af1bd3e0bb4cc3be39f3f1d042114e003709 --- /dev/null +++ b/pool/shard000/JavaScript/0005065_warning.js @@ -0,0 +1,74 @@ +import Ember from 'ember'; +import QUnit from 'qunit'; +import { checkMatcher } from '../-private/utils'; + + +export default function() { + let warnings; + + QUnit.testStart(function() { + warnings = []; + }); + + Ember.Debug.registerWarnHandler(function(message, options, next) { + // It's possible for warnings to trigger before the test has started. + if (warnings) { + warnings.push({ message, options }); + } + next(message, options); + }); + + function assertWarnings(qunitAssert, matcher) { + let matchedWarnings = warnings.filter(warning => { + return checkMatcher(warning.message, matcher); + }); + qunitAssert.pushResult({ + result: matchedWarnings.length !== 0, + actual: matchedWarnings, + expected: null, + message: 'Expected warnings during test, but no warnings were found.' + }); + } + + function assertNoWarnings(qunitAssert) { + let warningStr = warnings.reduce((a, b) => { + return `${b}${a.message}\n`; + }, ''); + + qunitAssert.pushResult({ + result: warnings.length === 0, + actual: warnings, + expected: [], + message: `Expected no warnings during test, but warnings were found.\n${warningStr}` + }); + } + + QUnit.assert.expectWarning = function(cb, matcher) { + let originalWarnings = warnings; + + if (typeof cb !== 'function') { + matcher = cb; + cb = null; + } + + if (cb) { + warnings = []; + cb(); + } + + assertWarnings(this, matcher); + warnings = originalWarnings; + }; + + QUnit.assert.expectNoWarning = function(cb) { + let originalWarnings = warnings; + + if (cb) { + warnings = []; + cb(); + } + + assertNoWarnings(this); + warnings = originalWarnings; + }; +} diff --git a/pool/shard000/JavaScript/0005070_docker_terminal.js b/pool/shard000/JavaScript/0005070_docker_terminal.js new file mode 100644 index 0000000000000000000000000000000000000000..c4a838884cfc22e199f26fb1ab185920db17a867 --- /dev/null +++ b/pool/shard000/JavaScript/0005070_docker_terminal.js @@ -0,0 +1,49 @@ +window.docker = (function(docker) { + docker.terminal = { + startTerminalForContainer: function(host, container) { + var term = new Terminal(); + term.open(); + + var wsUri = "ws://" + + host + + "/v1.8/containers/" + + container + + "/attach/ws?logs=1&stderr=1&stdout=1&stream=1&stdin=1"; + + var websocket = new WebSocket(wsUri); + websocket.onopen = function(evt) { onOpen(evt) }; + websocket.onclose = function(evt) { onClose(evt) }; + websocket.onmessage = function(evt) { onMessage(evt) }; + websocket.onerror = function(evt) { onError(evt) }; + + term.on('data', function(data) { + websocket.send(data); + }); + + function onOpen(evt) { + term.write("Session started"); + } + + function onClose(evt) { + term.write("Session terminated"); + } + + function onMessage(evt) { + term.write(evt.data); + } + + function onError(evt) { + } + } + }; + + return docker; +})(window.docker || {}); + +$(function() { + $("[data-docker-terminal-container]").each(function(i, el) { + var container = $(el).data('docker-terminal-container'); + var host = $(el).data('docker-terminal-host'); + docker.terminal.startTerminalForContainer(host, container); + }); +}); diff --git a/pool/shard000/JavaScript/0005071_crm.schema-mapped.js b/pool/shard000/JavaScript/0005071_crm.schema-mapped.js new file mode 100644 index 0000000000000000000000000000000000000000..c9601085f621b8e90499c0bd5ff9ddb0d50a7a16 --- /dev/null +++ b/pool/shard000/JavaScript/0005071_crm.schema-mapped.js @@ -0,0 +1,47 @@ +/** + * Dynamically-generated alternative to civi.core.js + */ +(function($, _) { + if (!CRM.Schema) CRM.Schema = {}; + + /** + * Data models used by the Civi form designer require more attributes than basic Backbone models: + * - sections: array of field-groupings + * - schema: array of fields, keyed by field name, per backbone-forms; extra attributes: + * + section: string, index to the 'sections' array + * + civiFieldType: string + * + * @see https://github.com/powmedia/backbone-forms + */ + + CRM.Schema.BaseModel = CRM.Backbone.Model.extend({ + initialize: function() { + } + }); + + CRM.Schema.loadModels = function(civiSchema) { + _.each(civiSchema, function(value, key, list) { + CRM.Schema[key] = CRM.Schema.BaseModel.extend(value); + }); + }; + + CRM.Schema.reloadModels = function(options) { + return $ + .ajax({ + url: CRM.url("civicrm/profile-editor/schema"), + data: { + 'entityTypes': _.keys(CRM.civiSchema).join(',') + }, + type: 'POST', + dataType: 'json', + success: function(data) { + if (data) { + CRM.civiSchema = data; + CRM.Schema.loadModels(CRM.civiSchema); + } + } + }); + }; + + CRM.Schema.loadModels(CRM.civiSchema); +})(CRM.$, CRM._); diff --git a/pool/shard000/JavaScript/0005073_dropdown.js b/pool/shard000/JavaScript/0005073_dropdown.js new file mode 100644 index 0000000000000000000000000000000000000000..a14963426b97c62679953ca4c3059f85cc81985d --- /dev/null +++ b/pool/shard000/JavaScript/0005073_dropdown.js @@ -0,0 +1,108 @@ +angular.module('ui.bootstrap.dropdown', []) + +.constant('dropdownConfig', { + openClass: 'open' +}) + +.service('dropdownService', ['$document', function($document) { + var self = this, openScope = null; + + this.open = function( dropdownScope ) { + if ( !openScope ) { + $document.bind('click', closeDropdown); + $document.bind('keydown', escapeKeyBind); + } + + if ( openScope && openScope !== dropdownScope ) { + openScope.isOpen = false; + } + + openScope = dropdownScope; + }; + + this.close = function( dropdownScope ) { + if ( openScope === dropdownScope ) { + openScope = null; + $document.unbind('click', closeDropdown); + $document.unbind('keydown', escapeKeyBind); + } + }; + + var closeDropdown = function() { + openScope.$apply(function() { + openScope.isOpen = false; + }); + }; + + var escapeKeyBind = function( evt ) { + if ( evt.which === 27 ) { + closeDropdown(); + } + }; +}]) + +.controller('DropdownController', ['$scope', '$attrs', 'dropdownConfig', 'dropdownService', function($scope, $attrs, dropdownConfig, dropdownService) { + var self = this, openClass = dropdownConfig.openClass; + + this.init = function( element ) { + self.$element = element; + $scope.isOpen = angular.isDefined($attrs.isOpen) ? $scope.$parent.$eval($attrs.isOpen) : false; + }; + + this.toggle = function( open ) { + return $scope.isOpen = arguments.length ? !!open : !$scope.isOpen; + }; + + $scope.$watch('isOpen', function( value ) { + self.$element.toggleClass( openClass, value ); + + if ( value ) { + dropdownService.open( $scope ); + } else { + dropdownService.close( $scope ); + } + + $scope.onToggle({ open: !!value }); + }); + + $scope.$on('$locationChangeSuccess', function() { + $scope.isOpen = false; + }); +}]) + +.directive('dropdown', function() { + return { + restrict: 'CA', + controller: 'DropdownController', + scope: { + isOpen: '=?', + onToggle: '&' + }, + link: function(scope, element, attrs, dropdownCtrl) { + dropdownCtrl.init( element ); + } + }; +}) + +.directive('dropdownToggle', function() { + return { + restrict: 'CA', + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if ( !dropdownCtrl ) { + return; + } + + element.bind('click', function(event) { + event.preventDefault(); + event.stopPropagation(); + + if ( !element.hasClass('disabled') && !element.prop('disabled') ) { + scope.$apply(function() { + dropdownCtrl.toggle(); + }); + } + }); + } + }; +}); diff --git a/pool/shard000/JavaScript/0005075_PublishDate.js b/pool/shard000/JavaScript/0005075_PublishDate.js new file mode 100644 index 0000000000000000000000000000000000000000..edd53a07e155e0aee5185f174818e38577f4e946 --- /dev/null +++ b/pool/shard000/JavaScript/0005075_PublishDate.js @@ -0,0 +1,38 @@ +/*eslint no-unused-vars:0*/ +'use strict' +import { date2yyyymmdd } from '../../utils/index' +import { FormattedDate } from 'react-intl' +import React, { Component } from 'react' +import commonStyles from './Common.scss' +import classNames from 'classnames' +import styles from './PublishDate.scss' + +export class PublishDate extends Component { + constructor(props) { + super(props) + this.state = { + isMounted: false + } + } + + componentDidMount() { + this.setState({ isMounted: true }) + } + + render() { + const { date } = this.props + const dateTime = new Date(date) + let fDate = date2yyyymmdd(date, '-') + + // avoid the server-side rendered date being inconsistent with the client-side results rendered by react-intl + if(this.state.isMounted) { + fDate = <FormattedDate value={ dateTime } day="numeric" month="numeric" year="numeric" /> + } + + return ( + <span itemProp="datePublished" className={classNames(styles['publish-date'], commonStyles['desc-text-color'])}> + {fDate} + </span> + ) + } +} diff --git a/pool/shard000/JavaScript/0005076_simpletimezone.js b/pool/shard000/JavaScript/0005076_simpletimezone.js new file mode 100644 index 0000000000000000000000000000000000000000..22502a18f8d27a260dc80a136a8302600f228a75 --- /dev/null +++ b/pool/shard000/JavaScript/0005076_simpletimezone.js @@ -0,0 +1,53 @@ +(function() { + "use strict"; + var OffsetGetter = (function() { + function OffsetGetter() { + // Nothing to see here; move along. + } + + OffsetGetter.prototype.get = function() { + // Get the JSON time zone offset data + var xhr = new XMLHttpRequest(); + xhr.open("GET", "time-zone-offsets.json", false); + xhr.send(); + if( xhr.status === 200 ) { + return JSON.parse(xhr.responseText); + } else { + alert("There was an error loading the time zone data; sorry!"); + return {}; + } + }; + + return OffsetGetter; + })(); + + var SimpleTimezone = (function() { + function SimpleTimezone(offsets) { + this._offsets = offsets; + } + + SimpleTimezone.prototype.matching_time_zones = function(str) { + var out = {}; + var find = str.toLowerCase(); + for( var tz_id in this._offsets ) { + var tz_record = this._offsets[tz_id]; + for( var property in tz_record ) { + if( typeof(tz_record[property]) === 'string' && + tz_record[property].toLowerCase().indexOf(find) !== -1 ) { + out[tz_id] = tz_record; + break; // no need to search further within this zone + } + } + } + return out; + }; + + SimpleTimezone.prototype.local_to_utc = function(tz, hour) { + return hour - this._offsets[tz].offset; + }; + + return SimpleTimezone; + })(); + + this['SimpleTimezone'] = new SimpleTimezone(new OffsetGetter().get()); +}).call(this); diff --git a/pool/shard000/JavaScript/0005079_application.js b/pool/shard000/JavaScript/0005079_application.js new file mode 100644 index 0000000000000000000000000000000000000000..36c1482343342e0af9386b250db4520782a07e11 --- /dev/null +++ b/pool/shard000/JavaScript/0005079_application.js @@ -0,0 +1,18 @@ +$(function() { + var map = L.map('map').setView([55, -70], 4), + graticule = L.graticule({ interval: 10 }); + + L.tileLayer('http://localhost:8888/{z}/{x}/{y}.png', { + minZoom: 1, + maxZoom: 9 + }).addTo(map); + + $('#graticules').on("click", function() { + if ($(this).prop("checked")) { + map.addLayer(graticule); + } else { + map.removeLayer(graticule); + } + }); + +}); diff --git a/pool/shard000/JavaScript/0005081_adminUsers.js b/pool/shard000/JavaScript/0005081_adminUsers.js new file mode 100644 index 0000000000000000000000000000000000000000..97d3044db69824d23b695204642d86f3b1208718 --- /dev/null +++ b/pool/shard000/JavaScript/0005081_adminUsers.js @@ -0,0 +1,220 @@ +var ref = firebase.database().ref('/Companies'); +var deptRef = firebase.database().ref('/Departments'); +var companies = {}; +var companyList = []; +var reverseCompanyMapping = {}; +var reverseDeptMapping = {}; +var reverseMassInput = {}; + + +var departments = {}; +//var departmentList = []; + +var secondaryApp = firebase.initializeApp(config, "Secondary"); + +var data = []; + +var toDoubleDigit = function(date) { + if (date < 10) { + return "0" + date; + } else { + return date; + } +} + +var upload = function() { + console.log("Running Upload"); + var file = $("#file")[0].files[0]; + var company = $('#company').val(); +/* if (company == "") { + alert("Please enter the company name to add csv file to"); + $('#file').val(''); + return false; + }*/ + console.log("Company present"); + if (file && file.name.substring(file.name.length - 4) == ".csv") { + console.log("Is valid file"); + Papa.parse(file, { + complete: function(results) { + data = results.data; + console.log(data); + massCreate(); + } + }) + } +} + +var massCreate = function(){firebase.auth().onAuthStateChanged(function(user) { + // redirect if the user is signed in + var emailToIdMapping = {}; + for(var i = 0; i < data.length; i++) { + emailToIdMapping[data[i][0]] = i; + if(data[i].length == 6){ + secondaryApp.auth().createUserWithEmailAndPassword(data[i][0],data[i][1]).then(function(firebaseUser) { + var index = emailToIdMapping[firebaseUser.email]; + + console.log("User " + firebaseUser.uid + " created successfully!"); + console.log(i); + date = new Date(); + time = date.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"); + created = toDoubleDigit(date.getMonth() + 1) + "/" + toDoubleDigit(date.getDate()) + "/" + date.getFullYear() + " " + time; + obj = { + companyId: reverseCompanyMapping[data[index][4]], + companyName: data[index][4], + createdAt: created, + departmentId: reverseDeptMapping[data[index][5]], + departmentName: data[index][5], + email: data[index][0], + title: data[index][2], + userName: data[index][3] + } + + firebase.database().ref("/Users/" + firebaseUser.uid).set(obj).catch(function(error) { + console.log(error.message) + }); + + secondaryApp.auth().signOut(); + }) + } + } + alert("Users have been added!"); + }) + } + + +var deptComplete = function(ui) { + console.log(typeof departments[reverseCompanyMapping[ui]] ); + console.log(departments); + console.log(reverseCompanyMapping ); + console.log(ui); + if (typeof departments[reverseCompanyMapping[ui]] !== 'undefined'){ + departmentList = []; + + for (key in departments[reverseCompanyMapping[ui]]){ + var list = departments[reverseCompanyMapping[ui]]; + //departmentList.push(list[key]); + $("#department").append(new Option(list[key])); + reverseDeptMapping[list[key]] = key; + } + console.log("enabled"); + $("#department").attr("disabled",false); + /*$("#department").autocomplete({ + source: departmentList + })*/ + } +} + +firebase.auth().onAuthStateChanged(function(user) { + // redirect if the user is signed in + + if (user) { + console.log("UserID:"+user.uid); + var userRef = firebase.database().ref('/Users/'+user.uid); + + userRef.once('value', function(snapshot) { + var idtypes = snapshot.val(); + console.log(idtypes); + if(idtypes === null){ + + console.log("An admin"); + //On right page, do nothing + //window.location = "admin.html"; + } + else{ + console.log("Not an admin"); + window.location = "userHome.html"; + } + }) + + $("#signup-btn,#add-btn").click(function(){ + secondaryApp.auth().createUserWithEmailAndPassword($("#email").val(), $("#password").val()).then(function(firebaseUser) { + console.log("User " + firebaseUser.uid + " created successfully!"); + date = new Date(); + time = date.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"); + created = toDoubleDigit(date.getMonth() + 1) + "/" + toDoubleDigit(date.getDate()) + "/" + date.getFullYear() + " " + time; + var departmentName = $("#department option:selected").val(); + obj = { + companyId: reverseCompanyMapping[$("#company").val()], + companyName: $("#company").val(), + createdAt: created, + departmentId: reverseDeptMapping[departmentName], + departmentName: departmentName, + email: $("#email").val(), + title: $("#title").val(), + userName: $("#name").val() + } + firebase.database().ref("/Users/" + firebaseUser.uid).set(obj).catch(function(error) { + console.log(error.message) + }); + //I don't know if the next statement is necessary + secondaryApp.auth().signOut(); + alert("User has been added!"); + }) +}) + + /*firebase.auth().createUserWithEmailAndPassword("email@gmail.com", "Password12").catch(function(error) { + var errorCode = error.code; + var errorMessage = error.message; + })*/ + + } else { + window.location = "/"; + } +}) + + +ref.once('value', function(snapshot) { + companies = snapshot.val(); + console.log("Companies:"); + console.log(companies); + for (key in companies) { + companyList.push(companies[key].companyName); + reverseCompanyMapping[companies[key].companyName] = key; + } + console.log("companyList"); + console.log(companyList); + console.log("reverseCompanyMapping: "); + console.log(reverseCompanyMapping); +}) + + +deptRef.once('value', function(snapshot) { + departments = snapshot.val(); + console.log("Departments: "); + console.log(departments); + uid = snapshot.val(); + +}) + +$(function() { + $("#company").autocomplete({ + source: companyList, + select: function(event, ui){ + deptComplete(ui.item.value); + } + }) +}) + +$('#csv-btn').click(function() { + console.log("csv btn click") + $('#file').click(); +}); + +$($("#company").change(function() { + console.log("Running"); + deptComplete($("#company").val()); + +})) + +$(document).ready(function(){ + $('#file').change(function (e) { + console.log("File changed"); + var file = this.files[0]; + if (!file && file.name.substring(file.name.length - 4) != ".csv") { + alert("Please upload a valid csv file"); + } else { + upload(); + //uploaded = true; + } + }) +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005083_test_date_display.js b/pool/shard000/JavaScript/0005083_test_date_display.js new file mode 100644 index 0000000000000000000000000000000000000000..3e6e4deccf4058d785c9b9d316110055c0654d51 --- /dev/null +++ b/pool/shard000/JavaScript/0005083_test_date_display.js @@ -0,0 +1,23 @@ +jest.dontMock('../components/DateDisplay.js'); +jest.dontMock('moment'); + +describe("DateDisplay", function(){ + it("shows current date", function() { + var React = require("react/addons"); + var DateDisplay = require("../components/DateDisplay"); + var DateGenerator = require("../utils/DateGenerator"); + var TestUtils = React.addons.TestUtils; + + DateGenerator.now.mockReturnValueOnce(new Date("2015-05-04 03:02:01")); + + var display = TestUtils.renderIntoDocument( + <DateDisplay /> + ); + + var timeSpan = TestUtils.findRenderedDOMComponentWithTag(display, "h3"); + var dateSpan = TestUtils.findRenderedDOMComponentWithTag(display, "h4"); + + expect(timeSpan.getDOMNode().textContent).toEqual("03:02:01"); + expect(dateSpan.getDOMNode().textContent).toEqual("4. Mai 2015"); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005085_route.js b/pool/shard000/JavaScript/0005085_route.js new file mode 100644 index 0000000000000000000000000000000000000000..1114546dcc11517edef59415bf0822af4508688a --- /dev/null +++ b/pool/shard000/JavaScript/0005085_route.js @@ -0,0 +1,32 @@ +import Ember from 'ember'; +import SPDRouteMixin from 'diesel/mixins/routes/spd-route'; + +export default Ember.Route.extend(SPDRouteMixin, { + stepName: 'security-controls', + model() { + return this.modelFor('gridiron-setup.security-controls'); + }, + + setupController(controller, model) { + let organizationUrl = this.modelFor('gridiron-organization').get('organization.data.links.self'); + + controller.set('model', model); + controller.set('organizationUrl', organizationUrl); + }, + + actions: { + onNext() { + let transition; + + this.currentModel.forEach((securityControlGroup) => { + if (!securityControlGroup.completed && !transition) { + transition = this.transitionTo('gridiron-setup.security-controls.show', securityControlGroup); + } + }); + + if (!transition) { + transition = this.finish(); + } + } + } +}); diff --git a/pool/shard000/JavaScript/0005087_trace.js b/pool/shard000/JavaScript/0005087_trace.js new file mode 100644 index 0000000000000000000000000000000000000000..daba7f9931861dce63d6a126d674d34466dbd3f5 --- /dev/null +++ b/pool/shard000/JavaScript/0005087_trace.js @@ -0,0 +1,98 @@ +/* + * requireJS trace + * + * Given a configuration object, as would be passed to the optimizer, + * runs a raw build trace on the configuration, returning the traced + * dependency trees. + * + * Loaded as a requirejs module on the server. + * + * eg: + * + * var requirejs = require('requirejs'); + * requirejs.configure({ context: 'server', baseUrl: '__dirname' }); + * requirejs(['trace'], function(trace) { + * trace(buildConfig, function(trees) { + * // where trees is the array of dependency trees from each of the modules. + * }); + * }); + * + */ + +define(function() { + + // the array of module dependency trees + var trees; + + var traceModules = function(build, config, moduleCallback, completeCallback, errback, index) { + if (index === undefined) { + index = 0; + trees = []; + } + + // the dependency tree for the current module + var curTree = trees[index] = {}; + + var resourceLoad = requirejs.onResourceLoad || function(){}; + requirejs.onResourceLoad = function(context, map, depArray) { + resourceLoad(context, map, depArray); + // build up proper normalized moduleID dependency tree + var curId = map.unnormalized ? (map.prefix + '!' + map.name) : map.id; + if (map.prefix != 'require-coffee/cs' && map.prefix != 'cs') { + var deps = []; + for (var i = 0; i < depArray.length; i++) { + if (depArray[i].unnormalized) + deps.push(depArray[i].prefix + '!' + depArray[i].name); + else + deps.push(depArray[i].id); + } + curTree[curId] = deps; + } + else + curTree[curId] = [map.name]; + } + + build.traceDependencies(config.modules[index], config).then(function(layer) { + config.modules[index].layer = layer; + + requirejs.onResourceLoad = resourceLoad; + + if (moduleCallback) + moduleCallback(config.modules[index], trees[index], index); + //requirejs._buildReset(); + + if (config.modules[++index]) + traceModules(build, config, moduleCallback, completeCallback, errback, index); + else + completeCallback(trees); + }, errback).end(); + } + + return function(config, moduleCallback, completeCallback, errback) { + requirejs.tools.useLib(function(req) { + req(['build', 'requirePatch'], function(build, requirePatch) { + requirePatch(); + + // prepare the configuration for the trace dependencies function + config.dir = config.appDir; + config = build.createConfig(config); + + // add the configuration + requirejs(config); + + // prepare the modules for tracing dependencies + var buildContext = require.s.contexts._; + for (var i = 0; i < config.modules.length; i++) { + var module = config.modules[i]; + if (!module.name) + continue; + module._sourcePath = buildContext.nameToUrl(module.name); + } + + // run the trace + traceModules(build, config, moduleCallback, completeCallback, errback); + }); + }); + } + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005088_up.js b/pool/shard000/JavaScript/0005088_up.js new file mode 100644 index 0000000000000000000000000000000000000000..659e1e7c6b7d457594d8aac544fbbd1005c3eb18 --- /dev/null +++ b/pool/shard000/JavaScript/0005088_up.js @@ -0,0 +1,23 @@ +/** + * @class elFinder command "up" + * Go into parent directory + * + * @author Dmitry (dio) Levashov + **/ +elFinder.prototype.commands.up = function () { + this.alwaysEnabled = true; + this.updateOnSelect = false; + + this.shortcuts = [{ + pattern: 'ctrl+up' + }]; + + this.getstate = function () { + return this.fm.cwd().phash ? 0 : -1; + } + + this.exec = function () { + return this.fm.cwd().phash ? this.fm.exec('open', this.fm.cwd().phash) : $.Deferred().reject(); + } + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005090_15.4.4.16-7-7.js b/pool/shard000/JavaScript/0005090_15.4.4.16-7-7.js new file mode 100644 index 0000000000000000000000000000000000000000..a3b156b05a38cee21dc323d440a078e66aea59a2 --- /dev/null +++ b/pool/shard000/JavaScript/0005090_15.4.4.16-7-7.js @@ -0,0 +1,22 @@ +/// Copyright (c) 2012 Ecma International. All rights reserved. +/** + * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-7.js + * @description Array.prototype.every - Deleting the array itself within the callbackfn of Array.prototype.every is successful once Array.prototype.every is called for all elements + */ + + +function testcase() { + var o = new Object(); + o.arr = [1, 2, 3, 4, 5]; + + function callbackfn(val, Idx, obj) { + delete o.arr; + if (val === Idx + 1) + return true; + else + return false; + } + + return o.arr.every(callbackfn) && !o.hasOwnProperty("arr"); + } +runTestCase(testcase); diff --git a/pool/shard000/JavaScript/0005093_custom-dashboard.js b/pool/shard000/JavaScript/0005093_custom-dashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..098cf7899e7cf5926e63ae8ab48571c4d2e2a48a --- /dev/null +++ b/pool/shard000/JavaScript/0005093_custom-dashboard.js @@ -0,0 +1,159 @@ +jQuery(document).ready(function($) { + var list_count = jQuery(".dashboard-lead-lists").length; + if( list_count < 1) { + $("#wp-lead-dashboard-list").hide(); + } + var before_dash = jQuery("#lead-before-dashboard"); + var dashboard_view = $.cookie("dashboard-view-choice"); + jQuery(".wrap h2").after(before_dash); + jQuery("#lead-before-dashboard").fadeIn(800); + + jQuery("body").on('hover', '.widget-block', function () { + jQuery('.db-active').removeClass('db-active'); + jQuery(this).addClass('db-active'); + }); + jQuery("body").on('mouseleave', '.widget-block', function () { + jQuery('.db-active').removeClass('db-active'); + }); + + jQuery(".marketing-widget-header").on("click", function(event){ + + var link = jQuery(this).find(".toggle-lead-list"); + var conversion_log = jQuery(this).parent().find("#lead-ul").toggle(); + + if (jQuery(conversion_log).is(":visible")) { + link.text('-'); + $.cookie("dashboard-view-choice", "show_leads", { path: '/', expires: 7 }); + } else { + link.text('+'); + $.cookie("dashboard-view-choice", "hide_leads", { path: '/', expires: 7 }); + } + }); + if(dashboard_view === "hide_leads") { + jQuery("#lead-ul").hide(); + jQuery(".toggle-lead-list").html('<span>(Click to View)</span> +'); + } + jQuery( '#cd-dropdown' ).dropdown(); + + }); + +jQuery(document).ready(function ($) { + + var dataset = [ + { + label: "Last Month", + data: data2, + xaxis:2, + color: "#D8D8D8", + + points: { fillColor: "#D8D8D8", show: true }, + lines: { show: true } + }, + { + label: "Current Month", + data: data1, + color: "#00769c", + + points: { fillColor: "#00769c", show: true }, + lines: { show: true, fill:true, fillColor:'rgba(216, 216, 216, .3)' } + } +]; + +var dayOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"]; + +var options = { + series: { + shadowSize: 5 + }, + crosshair: { mode: "x", color: "rgba(170, 0, 0, 0.80)", + lineWidth: 1 }, + xaxes: [{ + show: false, + mode: "time", + tickFormatter: function (val, axis) { + return dayOfWeek[new Date(val).getDay()]; + }, + color: 'none', + position: "top", + axisLabel: "Day of week", + axisLabelUseCanvas: false, + axisLabel: "<span class='chart-header'>Lead Growth</span><span class='chart-label-one'>Current Month</span> vs. <span class='chart-label-two'>Last Month</span>", + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 5 + }, + { + mode: "time", + timeformat: "%m/%d", + tickSize: [2, "day"], + color: "D8D8D8", + axisLabel: false, + axisLabelUseCanvas: false, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 10, + alignTicksWithAxis: 10 + }], + yaxis: { + color: "D8D8D8", + tickDecimals: 0, + axisLabel: "Lead Count", + axisLabelUseCanvas: false, + axisLabelFontSizePixels: 12, + axisLabelFontFamily: 'Verdana, Arial', + axisLabelPadding: 5 + }, + legend: { + show: false, + noColumns: 0, + labelFormatter: function (label, series) { + return "<font color=\"white\">" + label + "</font>"; + }, + backgroundColor: "#000", + backgroundOpacity: 0.9, + labelBoxBorderColor: "#000000", + position: "se" + }, + grid: { + hoverable: true, + autoHighlight: false, + borderWidth: 2, + mouseActiveRadius: 60, + backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }, + axisMargin: 20 + } +}; + chartplot = jQuery.plot(jQuery("#flot-placeholder"), dataset, options); + jQuery("#flot-placeholder").UseTooltip_leads(); + var the_data = chartplot.getData(); + + //console.log(the_data); + var today = new Date(); + var dd = today.getDate(); + var date_exists = the_data[1].data[dd]; + if(typeof(date_exists) != "undefined" && date_exists !== null && date_exists !== "") { + var getit = the_data[1].data[dd][0]; // gets the crosshair location + //console.log(getit); + // var today = ture; + // chartplot.lockCrosshair({ x: getit }); + } + + var tourlink = ""; + $("#flot-placeholder").bind("plothover", function (event, pos, item) + { + if (item) { + // Lock the crosshair to the data point being hovered + // chartplot.lockCrosshair({ x: item.datapoint[0] }); + } + else { + // Return normal crosshair operation + // chartplot.unlockCrosshair(); + } + //plot.lockCrosshair({ x: item.dataIndex[5] }); + //chartplot.setCrosshair({x: pos.x}) + // console.log(item); + // console.log(item.series.data[6][0]); // The X coordinate for line in 6th item. WORKS + //console.log(pos.x); + }); + //jQuery("#wp-lead-stats h3 span").text('test'); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005095_selectedUser.js b/pool/shard000/JavaScript/0005095_selectedUser.js new file mode 100644 index 0000000000000000000000000000000000000000..eeaa162e6493f6835c17f1fa711cf4e976981ad7 --- /dev/null +++ b/pool/shard000/JavaScript/0005095_selectedUser.js @@ -0,0 +1,47 @@ +/* eslint-disable react/no-multi-comp */ +import React, { PropTypes } from 'react' +import moment from 'moment' + +import UserAvatar from 'src/components/shared/userAvatar' + +const SelectedUser = ({ selectedUser }) => { + const { + city, + state, + country, + profileImageURL, + timestamp, + } = selectedUser + + let locationString + if (country === 'United States' || country === 'Canada') { + locationString = `${city}, ${state}` + } else { + locationString = `${city}, ${country}` + } + + const location = city ? (<div>{locationString}</div>) : null + + const dateString = moment(timestamp).format('MMM Do, YYYY') + + return ( + <div className="graph-overlay"> + <div className="graph-user-container"> + <div className="graph-user-avatar"> + <UserAvatar size={50} profileImageURL={profileImageURL} /> + </div> + <div className="graph-user-info"> + <div className="graph-user-name">{selectedUser.displayName}</div> + {location} + <div>{dateString}</div> + </div> + </div> + </div> + ) +} + +SelectedUser.propTypes = { + selectedUser: PropTypes.object, +} + +export default SelectedUser diff --git a/pool/shard000/JavaScript/0005096_focusable.js b/pool/shard000/JavaScript/0005096_focusable.js new file mode 100644 index 0000000000000000000000000000000000000000..a50598cd4eaa1539a4d109b2c53f853cf1e2a61e --- /dev/null +++ b/pool/shard000/JavaScript/0005096_focusable.js @@ -0,0 +1,65 @@ +/*! + * jQuery UI Focusable @VERSION + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +//>>label: focusable +//>>group: Core +//>>description: Selects elements which can be focused. +//>>docs: http://api.jqueryui.com/focusable-selector/ + +( function( factory ) { + if ( typeof define === "function" && define.amd ) { + + // AMD. Register as an anonymous module. + define( [ "jquery", "./version" ], factory ); + } else { + + // Browser globals + factory( jQuery ); + } +} ( function( $ ) { + +// Selectors +$.ui.focusable = function( element, hasTabindex ) { + var map, mapName, img, + nodeName = element.nodeName.toLowerCase(); + if ( "area" === nodeName ) { + map = element.parentNode; + mapName = map.name; + if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { + return false; + } + img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; + return !!img && visible( img ); + } + return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ? + !element.disabled : + "a" === nodeName ? + element.href || hasTabindex : + hasTabindex ) && + + // The element and all of its ancestors must be visible + visible( element ); +}; + +function visible( element ) { + return $.expr.filters.visible( element ) && + !$( element ).parents().addBack().filter( function() { + return $.css( this, "visibility" ) === "hidden"; + } ).length; +} + +$.extend( $.expr[ ":" ], { + focusable: function( element ) { + return $.ui.focusable( element, $.attr( element, "tabindex" ) != null ); + } +} ); + +return $.ui.focusable; + +} ) ); diff --git a/pool/shard000/JavaScript/0005099_PhoneController.js b/pool/shard000/JavaScript/0005099_PhoneController.js new file mode 100644 index 0000000000000000000000000000000000000000..c1cd58cda8083cd2290f8b54e97231268a2ae230 --- /dev/null +++ b/pool/shard000/JavaScript/0005099_PhoneController.js @@ -0,0 +1,47 @@ +bController.controller('PhoneController', ['$scope', function ($scope) { + $scope.isDialogVisible = false; + + $scope.editObj = {}; + + + $scope.constants = { + "MEDIA_URL": "Media Link", + "MEDIA_CREDITS": "Credits", + "TITLE": "Title", + "DESCRIPTION": "Descrition", + "SOURCE_URL": "Source Link", + "SOURCE_URL_TEXT": "Source Link Text", + "50_50": "half", + "70_30": "seven-3", + "Full": "full" + }; + + + $scope.dialogTitle = "Default title"; + + $scope.update = function (str, value) { + $scope.isDialogVisible = true; + $scope.dialogTitle = str; + $scope.editObj[str] = value; + }; + + $scope.updateVal = function (str, obj) { + $scope.SelectedDeck.cards[$scope.cardIndex][obj] = $scope.editObj[str]; + $scope.closeDialog(); + }; + + $scope.updateMed = function (str, obj) { + $scope.SelectedDeck.cards[$scope.cardIndex].media[obj] = $scope.editObj[str]; + $scope.closeDialog(); + }; + $scope.closeDialog = function () { + $scope.isDialogVisible = false; + }; + + $scope.getTemplateClass = function (string) { + if (string == undefined) { + return "full"; + } + return $scope.constants[string]; + } +}]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005101_index.js b/pool/shard000/JavaScript/0005101_index.js new file mode 100644 index 0000000000000000000000000000000000000000..caa44121e4d323929b2b6da2be1a5835738b939a --- /dev/null +++ b/pool/shard000/JavaScript/0005101_index.js @@ -0,0 +1,30 @@ +"use strict"; + +const Command = require("@lerna/command"); +const output = require("@lerna/output"); +const envinfo = require("envinfo"); + +module.exports = factory; + +function factory(argv) { + return new InfoCommand(argv); +} + +class InfoCommand extends Command { + // eslint-disable-next-line + initialize() {} + // eslint-disable-next-line + execute() { + output("\n Environment info:"); + envinfo + .run({ + System: ["OS", "CPU"], + Binaries: ["Node", "Yarn", "npm"], + Utilities: ["Git"], + npmPackages: ["lerna"], + }) + .then(output); + } +} + +module.exports.InfoCommand = InfoCommand; diff --git a/pool/shard000/JavaScript/0005103_legend.js b/pool/shard000/JavaScript/0005103_legend.js new file mode 100644 index 0000000000000000000000000000000000000000..f707898f1b8da27046749e2fd3b29a45c1c09aa9 --- /dev/null +++ b/pool/shard000/JavaScript/0005103_legend.js @@ -0,0 +1,71 @@ +"use strict"; + +var d3 = require("d3"); +var _ = require("underscore"); + +// Build a legend in the given div showing the top-level categories. +// Div must be a jQuery selector. The div will be emptied. +exports.makeViz = function(categories, div) { + // Copy skeleton from the template. + div.empty(); + div.append($("#legend_template").children().clone()); + + // V is the visualization object that we will return. + var V = {}; + V.numCols = 4; + + // Build the data for the visualization. + // We display the top-level categories, ordered by their id. + V.topLevelCategs = _.sortBy(categories.root.children, function(category) { + return category.id; + }); + _.each(V.topLevelCategs, function(category, index) { + category.row = Math.floor(index / V.numCols); + category.col = index % V.numCols; + }); + + // Dimensions. + V.div = d3.select(div[0]); + V.width = 730; + V.numRows = Math.ceil(V.topLevelCategs.length / V.numCols); + V.rowHeight = 25; + V.height = V.numRows * V.rowHeight; + + // Scales. + V.x = d3.scale.linear() + .domain([0, V.numCols]) + .range([0, V.width]); + V.y = d3.scale.linear() + .domain([0, V.numRows]) + .range([0, V.height]); + + // Init svg. + V.svg = V.div.select("svg") + .attr("width", V.width) + .attr("height", V.height) + .append("g"); + + // Each category becomes a <g> element. + V.categories = V.svg.selectAll(".category") + .data(V.topLevelCategs) + .enter().append("g") + .attr("class", "category") + .attr("transform", function(d) { + return "translate(" + V.x(d.col) + ", " + V.y(d.row) + ")"; + }); + + // Inside that <g> element we add a colored circle and text. + V.svg.selectAll(".category") + .append("circle") + .attr("cx", V.rowHeight / 2) + .attr("cy", V.rowHeight / 2) + .attr("r", V.rowHeight / 2 - 2) + .attr("fill", function(d) { return d.color; }); + V.svg.selectAll(".category") + .append("text") + .attr("x", V.rowHeight + 5) + .attr("y", V.rowHeight / 2 + 5) + .text(function(d) { return d.name; }); + + return V; +}; diff --git a/pool/shard000/JavaScript/0005107_progressBar.js b/pool/shard000/JavaScript/0005107_progressBar.js new file mode 100644 index 0000000000000000000000000000000000000000..c393bffc7f382388f1f9f48c7d7dbf2ed1445ebe --- /dev/null +++ b/pool/shard000/JavaScript/0005107_progressBar.js @@ -0,0 +1,124 @@ +function progressBar(parentDivId, width, height, backGroundColor, borderWidth, borderColor, lineColor ) +{ + var PROGRESS_BAR_WIDGET_ID = "progressBarWidget"; + var BLOCKS_ID = "blocks"; + var PROGRESS_LINE_ID = "progressLine"; + var _pDivId = parentDivId; + var _width = width; + var _height = height; + var _backGroundColor = backGroundColor; + var _borderWidth = borderWidth; + var _borderColor = borderColor; + var _lineColor = lineColor; + var _progressLine; + var _step; + var _pbWidget; + var _infoLine; + + var parentDiv = document.getElementById(_pDivId); + if( parentDiv ) + { + var infoLine = document.createElement('div'); + infoLine.setAttribute("name","infoLine"); + infoLine.setAttribute("id","infoLine"); + infoLine.setAttribute("innerHTML","..."); + infoLine.style.fontWeight = "normal"; + parentDiv.appendChild(infoLine); + _infoLine = infoLine; + + var pbWidget = document.createElement('div'); + pbWidget.setAttribute('id', PROGRESS_BAR_WIDGET_ID); + pbWidget.style.backgroundColor = "white"; + pbWidget.style.position = 'relative'; + pbWidget.style.overflow = 'hidden'; + pbWidget.style.width = '300px'; + pbWidget.style.height = '15px'; + pbWidget.style.borderColor = 'gray'; + pbWidget.style.borderWidth = '1px'; + pbWidget.style.borderStyle = 'solid'; + pbWidget.style.fontSize = '1px'; + parentDiv.appendChild(pbWidget); + + var blocks = document.createElement('span'); + blocks.setAttribute("id", BLOCKS_ID); + blocks.style.left = "42px"; + blocks.style.position = "absolute"; + blocks.style.fontSize = "1px"; + pbWidget.appendChild(blocks); + + var progressLine = document.createElement('span'); + progressLine.setAttribute("id", PROGRESS_LINE_ID); + progressLine.style.backgroundColor = 'blue'; + progressLine.style.left = "-42px"; + progressLine.style.fontSize = "1px"; + progressLine.style.position = "absolute"; + progressLine.style.width = "0px"; + progressLine.style.height = "20px"; + blocks.appendChild(progressLine); + _progressLine = progressLine; + _pbWidget = pbWidget; + + var step = document.createElement('input'); + step.setAttribute("type", "hidden"); + step.setAttribute("name","stepInterval"); + step.setAttribute("id","stepInterval"); + step.setAttribute("value","1"); + parentDiv.appendChild(step); + _step = step; + + var stepButton = document.createElement('input'); + stepButton.setAttribute("name","stepButton"); + stepButton.setAttribute("id","stepButton"); + stepButton.setAttribute("type", "Button"); + stepButton.setAttribute("value","Step"); + stepButton.onclick = function() {_execute();}; + stepButton.style.display = "none"; + parentDiv.appendChild(stepButton); + + var resetButton = document.createElement('input'); + resetButton.setAttribute("type", "Button"); + resetButton.setAttribute("id","resetButton"); + resetButton.setAttribute("name","resetButton"); + resetButton.setAttribute("value","Reset"); + resetButton.onclick = function() {_reset();}; + resetButton.style.display = "none"; + parentDiv.appendChild(resetButton); + + var showOrHideButton = document.createElement('input'); + showOrHideButton.setAttribute("type", "Button"); + showOrHideButton.setAttribute("id","showHideButton"); + showOrHideButton.setAttribute("name","showHideButton"); + showOrHideButton.setAttribute("value","ShowOrHide"); + showOrHideButton.onclick = function() {_reset();}; + showOrHideButton.style.display = "none"; + parentDiv.appendChild(showOrHideButton); + + } + else + { + alert("Wrong parent div id!"); + } + + this.execute = _execute; + this.reset = _reset; + + function _execute() + { + if( _pbWidget ) + { + var line = _progressLine.style.width; + width = (parseInt(line.substring(0, line.length - 2)) + parseInt(_step.value)).toString()+"px"; + _progressLine.style.width = width; + } + } + + function _reset() + { + if( _pbWidget ) + { + _progressLine.style.width = "0px"; + _infoLine.innerHTML = "..."; + } + } + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005110_get-styles.test.js b/pool/shard000/JavaScript/0005110_get-styles.test.js new file mode 100644 index 0000000000000000000000000000000000000000..cb553ec8bf264aa838db5745fe448ec010da241f --- /dev/null +++ b/pool/shard000/JavaScript/0005110_get-styles.test.js @@ -0,0 +1,26 @@ +/* eslint-env mocha */ +import { expect } from 'chai'; +import getStyles from '../../src/table-header/get-styles'; +import styles from '../../src/table-header/styles'; + +describe('TableHeader.getStyles', () => { + describe('root', () => { + it('should get styles', () => { + const style = getStyles.root(); + + expect(style).to.deep.equal(styles.root); + }); + + it('should combine styles', () => { + const style = getStyles.root(false, { color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + + it('should add theme colors', () => { + const style = getStyles.root('red'); + + expect(style).to.have.property('backgroundColor', 'red'); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005111_gridSimple.js b/pool/shard000/JavaScript/0005111_gridSimple.js new file mode 100644 index 0000000000000000000000000000000000000000..dc0abb3fee4366a2f9c6a40fc6d11b3623caf6f9 --- /dev/null +++ b/pool/shard000/JavaScript/0005111_gridSimple.js @@ -0,0 +1,34 @@ +var echarts = require("../echarts"); + +var zrUtil = require("zrender/lib/core/util"); + +var graphic = require("../util/graphic"); + +require("../coord/cartesian/Grid"); + +require("./axis"); + +// Grid view +echarts.extendComponentView({ + type: 'grid', + render: function (gridModel, ecModel) { + this.group.removeAll(); + + if (gridModel.get('show')) { + this.group.add(new graphic.Rect({ + shape: gridModel.coordinateSystem.getRect(), + style: zrUtil.defaults({ + fill: gridModel.get('backgroundColor') + }, gridModel.getItemStyle()), + silent: true, + z2: -1 + })); + } + } +}); +echarts.registerPreprocessor(function (option) { + // Only create grid when need + if (option.xAxis && option.yAxis && !option.grid) { + option.grid = {}; + } +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005112_layout.js b/pool/shard000/JavaScript/0005112_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..287a612602dd87dbfc376ec4d5120762a5d855ce --- /dev/null +++ b/pool/shard000/JavaScript/0005112_layout.js @@ -0,0 +1,212 @@ +var EditModeItemView = require( 'qazana-regions/panel/edit-mode' ), + PanelLayoutView; + +PanelLayoutView = Marionette.LayoutView.extend( { + template: '#tmpl-qazana-panel', + + id: 'qazana-panel-inner', + + regions: { + content: '#qazana-panel-content', + header: '#qazana-panel-header', + footer: '#qazana-panel-footer', + modeSwitcher: '#qazana-mode-switcher', + }, + + pages: {}, + + childEvents: { + 'click:add': function() { + this.setPage( 'elements' ); + }, + 'editor:destroy': function() { + this.setPage( 'elements', null, { autoFocusSearch: false } ); + }, + }, + + currentPageName: null, + + currentPageView: null, + + _isScrollbarInitialized: false, + + initialize: function() { + this.initPages(); + }, + + buildPages: function() { + var pages = { + elements: { + view: require( 'qazana-panel/pages/elements/elements' ), + title: qazana.config.document.title, + }, + editor: { + view: require( 'qazana-panel/pages/editor' ), + }, + menu: { + view: qazana.modules.layouts.panel.pages.menu.Menu, + title: qazana.config.document.title, + }, + colorScheme: { + view: require( 'qazana-panel/pages/schemes/colors' ), + }, + typographyScheme: { + view: require( 'qazana-panel/pages/schemes/typography' ), + }, + colorPickerScheme: { + view: require( 'qazana-panel/pages/schemes/color-picker' ), + }, + }; + + var schemesTypes = Object.keys( qazana.schemes.getSchemes() ), + disabledSchemes = _.difference( schemesTypes, qazana.schemes.getEnabledSchemesTypes() ); + + _.each( disabledSchemes, function( schemeType ) { + var scheme = qazana.schemes.getScheme( schemeType ); + + pages[ schemeType + 'Scheme' ].view = require( 'qazana-panel/pages/schemes/disabled' ).extend( { + disabledTitle: scheme.disabled_title, + } ); + } ); + + return pages; + }, + + initPages: function() { + var pages; + + this.getPages = function( page ) { + if ( ! pages ) { + pages = this.buildPages(); + } + + return page ? pages[ page ] : pages; + }; + + this.addPage = function( pageName, pageData ) { + if ( ! pages ) { + pages = this.buildPages(); + } + + pages[ pageName ] = pageData; + }; + }, + + getHeaderView: function() { + return this.getChildView( 'header' ); + }, + + getFooterView: function() { + return this.getChildView( 'footer' ); + }, + + getCurrentPageName: function() { + return this.currentPageName; + }, + + getCurrentPageView: function() { + return this.currentPageView; + }, + + setPage: function( page, title, viewOptions ) { + const pages = this.getPages(); + + if ( 'elements' === page && ! qazana.userCan( 'design' ) ) { + if ( pages.page_settings ) { + page = 'page_settings'; + } + } + + const pageData = pages[ page ]; + + if ( ! pageData ) { + throw new ReferenceError( 'Qazana panel doesn\'t have page named \'' + page + '\'' ); + } + + if ( pageData.options ) { + viewOptions = _.extend( pageData.options, viewOptions ); + } + + let View = pageData.view; + + if ( pageData.getView ) { + View = pageData.getView(); + } + + this.currentPageName = page; + + this.currentPageView = new View( viewOptions ); + + this.showChildView( 'content', this.currentPageView ); + + this.getHeaderView().setTitle( title || pageData.title ); + + this + .trigger( 'set:page', this.currentPageView ) + .trigger( 'set:page:' + page, this.currentPageView ); + }, + + openEditor: function( model, view ) { + this.setPage( 'editor', qazana.translate( 'edit_element', [ qazana.getElementData( model ).title ] ), { + model: model, + controls: qazana.getElementControls( model ), + editedElementView: view, + } ); + + const action = 'panel/open_editor/' + model.get( 'elType' ); + + // Example: panel/open_editor/widget + qazana.hooks.doAction( action, this, model, view ); + + // Example: panel/open_editor/widget/heading + qazana.hooks.doAction( action + '/' + model.get( 'widgetType' ), this, model, view ); + }, + + onBeforeShow: function() { + var PanelFooterItemView = require( 'qazana-regions/panel/footer' ), + PanelHeaderItemView = require( 'qazana-regions/panel/header' ); + + // Edit Mode + this.showChildView( 'modeSwitcher', new EditModeItemView() ); + + // Header + this.showChildView( 'header', new PanelHeaderItemView() ); + + // Footer + this.showChildView( 'footer', new PanelFooterItemView() ); + + // Added Editor events + this.updateScrollbar = _.throttle( this.updateScrollbar, 100 ); + + this.getRegion( 'content' ) + .on( 'before:show', this.onEditorBeforeShow.bind( this ) ) + .on( 'empty', this.onEditorEmpty.bind( this ) ) + .on( 'show', this.updateScrollbar.bind( this ) ); + + // Set default page to elements + this.setPage( 'elements' ); + }, + + onEditorBeforeShow: function() { + _.defer( this.updateScrollbar.bind( this ) ); + }, + + onEditorEmpty: function() { + this.updateScrollbar(); + }, + + updateScrollbar: function() { + var $panel = this.content.$el; + + if ( ! this._isScrollbarInitialized ) { + $panel.perfectScrollbar(); + this._isScrollbarInitialized = true; + + return; + } + + $panel.perfectScrollbar( 'update' ); + }, +} ); + +module.exports = PanelLayoutView; diff --git a/pool/shard000/JavaScript/0005114_ping-until-ready.js b/pool/shard000/JavaScript/0005114_ping-until-ready.js new file mode 100644 index 0000000000000000000000000000000000000000..ca5dccc41da3afe1f626c527eecfe0e3f2fc2755 --- /dev/null +++ b/pool/shard000/JavaScript/0005114_ping-until-ready.js @@ -0,0 +1,63 @@ +var async = require('async'); +var http = require('http'); +var urlParse = require('url').parse; + +var PING_INTERVAL = 100; +var TIMEOUT = 10000; + +function ping(url, cb) { + var urlInfo = urlParse(url); + var ended = false; + var end = function(success) { + if (ended) return; + ended = true; + clearTimeout(timeout); + cb(null, success); + }; + var timeout = setTimeout(end.bind(null, false), TIMEOUT); + var req = http.request({ + hostname: urlInfo.hostname, + port: urlInfo.port, + path: urlInfo.pathname + }, function(res) { + end(res.statusCode == 200); + }); + + req.on('error', end.bind(null, false)); + req.end(); +}; + +module.exports = function pingUntilReady(url, timeout, cb) { + var startTime = Date.now(); + var timeElapsed; + var pingSuccess = false; + + async.whilst(function test() { + timeElapsed = Date.now() - startTime; + return timeElapsed < timeout && !pingSuccess; + }, function keepTrying(cb) { + ping(url, function(err, success) { + if (err) return cb(err); + pingSuccess = success; + cb(); + }); + }, function(err) { + if (err) return cb(err); + if (timeElapsed >= timeout) + return cb(new Error("timeout (" + timeout + + "ms) exceeded when pinging " + url)); + cb(); + }); +}; + +if (!module.parent) { + if (process.argv.length < 3) { + console.log("usage: ping-until-ready.js <url>"); + process.exit(1); + } + console.log("Attempting to ping " + process.argv[2]); + module.exports(process.argv[2], 5000, function(err) { + if (err) throw err; + console.log("Success!"); + }); +} diff --git a/pool/shard000/JavaScript/0005116_bootstrap.js b/pool/shard000/JavaScript/0005116_bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..4ffa5de33fd3fb25d234309334c28637b285ce6e --- /dev/null +++ b/pool/shard000/JavaScript/0005116_bootstrap.js @@ -0,0 +1,23 @@ +'use strict'; + +angular.module('angularApp', ['ngTouch']).factory('cordovaReady', function() { + return function (fn) { + + var queue = []; + + var impl = function () { + queue.push(Array.prototype.slice.call(arguments)); + }; + + document.addEventListener('deviceready', function () { + queue.forEach(function (args) { + fn.apply(this, args); + }); + impl = fn; + }, false); + + return function () { + return impl.apply(this, arguments); + }; + }; +}); diff --git a/pool/shard000/JavaScript/0005119_jquery.aljs-tabs.js b/pool/shard000/JavaScript/0005119_jquery.aljs-tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..31055d611a37487d56cc3d167e6761cfb1cf0141 --- /dev/null +++ b/pool/shard000/JavaScript/0005119_jquery.aljs-tabs.js @@ -0,0 +1,122 @@ +/* ------------------------------------------------------------ +ALJS Tab +------------------------------------------------------------ */ +if (typeof jQuery.aljs === "undefined") { throw new Error("Please include the ALJS initializer file") } + +(function($) { + var Tabs = function(el, settings) { + this.$el = $(el); + this.settings = settings; + this.initTabs(); + }; + + Tabs.prototype = { + constructor: Tabs, + initTabs: function() { + // Bind buttons + var self = this; + var $tabButtons = this.$el.find('> .slds-tabs--default__nav > .slds-tabs--default__item > .slds-tabs--default__link, > .slds-tabs--scoped__nav > .slds-tabs--scoped__item > .slds-tabs--scoped__link'); + var children = this.$el.find('> .slds-tabs--default__nav > .slds-tabs--default__item, > .slds-tabs--scoped__nav > .slds-tabs--scoped__item'); + var tabsObj = { + self: self, + children: children + } + + $tabButtons.on('click', function(e) { + e.stopPropagation(); + self.selectTab($(e.target).data('aljs-show')); + $(this).trigger('selected.aljs.tab'); // Custom aljs event + return false; + }); + + // Show first tab + if (this.settings.defaultTabId === '' || $('#' + this.settings.defaultTabId).length === 0) { + this.selectTab($tabButtons.first().data('aljs-show')); + } else { + this.selectTab(this.settings.defaultTabId); + } + + children.keyup(tabsObj, this.processKeypress); + }, + selectTab: function(tabId) { + this.$el.find('> .slds-tabs--default__nav > .slds-tabs--default__item, > .slds-tabs--scoped__nav > .slds-tabs--scoped__item') + .removeClass('slds-active') + .blur() + .find('> .slds-tabs--default__link, > .slds-tabs--scoped__link') + .attr('tabindex', '-1') + .attr('aria-selected', 'false'); + this.$el.find('> .slds-tabs--default__content, > .slds-tabs--scoped__content') + .hide(); + this.$el.find('[data-aljs-show="' + tabId + '"]') + .focus() + .closest('li') + .addClass('slds-active') + .find('> .slds-tabs--default__link, > .slds-tabs--scoped__link') + .attr('tabindex', '0') + .attr('aria-selected', 'true'); + this.$el.find('#' + tabId).show() + .trigger('shown.aljs.tabcontent'); // Custom aljs event + + this.id = tabId; + this.settings.onChange(this); + }, + processKeypress: function(e) { + var children = e.data.children; + var length = $(children).length - 1; + var selectedPos = $('.slds-active', $(children).parent()).index(); + var tabId; + + if (e.which == 37) { // Left arrow + if (selectedPos == 0) { + tabId = $(children).eq(length).find('[data-aljs-show]').data('aljs-show'); + } else { + tabId = $(children).eq((selectedPos - 1)).find('[data-aljs-show]').data('aljs-show'); + } + e.data.self.selectTab(tabId); + } else if (e.which == 39) { // Right arrow + if (selectedPos == length) { + tabId = $(children).eq(0).find('[data-aljs-show]').data('aljs-show'); + } else { + tabId = $(children).eq((selectedPos + 1)).find('[data-aljs-show]').data('aljs-show'); + } + e.data.self.selectTab(tabId); + } + } + }; + + $.fn.tabs = function(options) { + var tabsArguments = arguments; + var internalReturn; + + var settings = $.extend({ + // These are the defaults + defaultTabId: '', + onChange: function(obj) {}, + assetsLocation: $.aljs.assetsLocation + }, typeof options === 'object' ? options : {}); + + this.each(function() { + var $this = $(this); + var data = $this.data('aljs-tabs'); + + if (!data) { + var tabsData = new Tabs(this, settings); + $this.data('aljs-tabs', (data = tabsData)); + } + + if (typeof options === 'string') { + internalReturn = data[options](tabsArguments[1], tabsArguments[2]); + } + }); + + if (internalReturn === undefined || internalReturn instanceof Tabs) { + return this; + } + + if (this.length > 1) { + throw new Error('Using only allowed for the collection of a single element (' + option + ' function)'); + } else { + return internalReturn; + } + } +}(jQuery)); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005120_search.js b/pool/shard000/JavaScript/0005120_search.js new file mode 100644 index 0000000000000000000000000000000000000000..62df79696c01387f8afb7a6ac8d2205876cb001f --- /dev/null +++ b/pool/shard000/JavaScript/0005120_search.js @@ -0,0 +1,131 @@ +'use strict'; + +var async = require('async'); + +var user = require('../user'); +var db = require('./../database'); + + +module.exports = function (Groups) { + Groups.search = function (query, options, callback) { + if (!query) { + return callback(null, []); + } + query = query.toLowerCase(); + async.waterfall([ + async.apply(db.getObjectValues, 'groupslug:groupname'), + function (groupNames, next) { + // Ephemeral groups and the registered-users groups are searchable + groupNames = Groups.ephemeralGroups.concat(groupNames).concat('registered-users'); + groupNames = groupNames.filter(function (name) { + return name.toLowerCase().indexOf(query) !== -1 && name !== 'administrators' && !Groups.isPrivilegeGroup(name); + }); + groupNames = groupNames.slice(0, 100); + Groups.getGroupsData(groupNames, next); + }, + function (groupsData, next) { + groupsData = groupsData.filter(Boolean); + if (options.filterHidden) { + groupsData = groupsData.filter(function (group) { + return !group.hidden; + }); + } + + Groups.sort(options.sort, groupsData, next); + }, + ], callback); + }; + + Groups.sort = function (strategy, groups, next) { + switch (strategy) { + case 'count': + groups = groups.sort(function (a, b) { + return a.slug > b.slug; + }).sort(function (a, b) { + return b.memberCount - a.memberCount; + }); + break; + + case 'date': + groups = groups.sort(function (a, b) { + return b.createtime - a.createtime; + }); + break; + + case 'alpha': // intentional fall-through + default: + groups = groups.sort(function (a, b) { + return a.slug > b.slug ? 1 : -1; + }); + } + + next(null, groups); + }; + + Groups.searchMembers = function (data, callback) { + function findUids(query, searchBy, callback) { + query = query.toLowerCase(); + + async.waterfall([ + function (next) { + Groups.getMembers(data.groupName, 0, -1, next); + }, + function (members, next) { + user.getUsersFields(members, ['uid'].concat([searchBy]), next); + }, + function (users, next) { + var uids = []; + for (var i = 0; i < users.length; i += 1) { + var field = users[i][searchBy]; + if (field.toLowerCase().startsWith(query)) { + uids.push(users[i].uid); + } + } + next(null, uids); + }, + ], callback); + } + + if (!data.query) { + Groups.getOwnersAndMembers(data.groupName, data.uid, 0, 19, function (err, users) { + if (err) { + return callback(err); + } + callback(null, { users: users }); + }); + return; + } + + data.findUids = findUids; + var results; + async.waterfall([ + function (next) { + user.search(data, next); + }, + function (_results, next) { + results = _results; + var uids = results.users.map(function (user) { + return user && user.uid; + }); + Groups.ownership.isOwners(uids, data.groupName, next); + }, + function (isOwners, next) { + results.users.forEach(function (user, index) { + if (user) { + user.isOwner = isOwners[index]; + } + }); + + results.users.sort(function (a, b) { + if (a.isOwner && !b.isOwner) { + return -1; + } else if (!a.isOwner && b.isOwner) { + return 1; + } + return 0; + }); + next(null, results); + }, + ], callback); + }; +}; diff --git a/pool/shard000/JavaScript/0005121_deviceorientation.js b/pool/shard000/JavaScript/0005121_deviceorientation.js new file mode 100644 index 0000000000000000000000000000000000000000..be0caf002a728ca3895430bf633c8f1cb3098e71 --- /dev/null +++ b/pool/shard000/JavaScript/0005121_deviceorientation.js @@ -0,0 +1,228 @@ +goog.provide('ol.DeviceOrientation'); + +goog.require('ol.events'); +goog.require('ol'); +goog.require('ol.Object'); +goog.require('ol.has'); +goog.require('ol.math'); + + +/** + * @enum {string} + */ +ol.DeviceOrientationProperty = { + ALPHA: 'alpha', + BETA: 'beta', + GAMMA: 'gamma', + HEADING: 'heading', + TRACKING: 'tracking' +}; + + +/** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ +ol.DeviceOrientation = function(opt_options) { + + ol.Object.call(this); + + var options = opt_options ? opt_options : {}; + + /** + * @private + * @type {?ol.EventsKey} + */ + this.listenerKey_ = null; + + ol.events.listen(this, + ol.Object.getChangeEventType(ol.DeviceOrientationProperty.TRACKING), + this.handleTrackingChanged_, this); + + this.setTracking(options.tracking !== undefined ? options.tracking : false); + +}; +ol.inherits(ol.DeviceOrientation, ol.Object); + + +/** + * @inheritDoc + */ +ol.DeviceOrientation.prototype.disposeInternal = function() { + this.setTracking(false); + ol.Object.prototype.disposeInternal.call(this); +}; + + +/** + * @private + * @param {Event} originalEvent Event. + */ +ol.DeviceOrientation.prototype.orientationChange_ = function(originalEvent) { + var event = /** @type {DeviceOrientationEvent} */ (originalEvent); + if (event.alpha !== null) { + var alpha = ol.math.toRadians(event.alpha); + this.set(ol.DeviceOrientationProperty.ALPHA, alpha); + // event.absolute is undefined in iOS. + if (typeof event.absolute === 'boolean' && event.absolute) { + this.set(ol.DeviceOrientationProperty.HEADING, alpha); + } else if (typeof event.webkitCompassHeading === 'number' && + event.webkitCompassAccuracy != -1) { + var heading = ol.math.toRadians(event.webkitCompassHeading); + this.set(ol.DeviceOrientationProperty.HEADING, heading); + } + } + if (event.beta !== null) { + this.set(ol.DeviceOrientationProperty.BETA, + ol.math.toRadians(event.beta)); + } + if (event.gamma !== null) { + this.set(ol.DeviceOrientationProperty.GAMMA, + ol.math.toRadians(event.gamma)); + } + this.changed(); +}; + + +/** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.getAlpha = function() { + return /** @type {number|undefined} */ ( + this.get(ol.DeviceOrientationProperty.ALPHA)); +}; + + +/** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.getBeta = function() { + return /** @type {number|undefined} */ ( + this.get(ol.DeviceOrientationProperty.BETA)); +}; + + +/** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.getGamma = function() { + return /** @type {number|undefined} */ ( + this.get(ol.DeviceOrientationProperty.GAMMA)); +}; + + +/** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.getHeading = function() { + return /** @type {number|undefined} */ ( + this.get(ol.DeviceOrientationProperty.HEADING)); +}; + + +/** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.getTracking = function() { + return /** @type {boolean} */ ( + this.get(ol.DeviceOrientationProperty.TRACKING)); +}; + + +/** + * @private + */ +ol.DeviceOrientation.prototype.handleTrackingChanged_ = function() { + if (ol.has.DEVICE_ORIENTATION) { + var tracking = this.getTracking(); + if (tracking && !this.listenerKey_) { + this.listenerKey_ = ol.events.listen(ol.global, 'deviceorientation', + this.orientationChange_, this); + } else if (!tracking && this.listenerKey_ !== null) { + ol.events.unlistenByKey(this.listenerKey_); + this.listenerKey_ = null; + } + } +}; + + +/** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ +ol.DeviceOrientation.prototype.setTracking = function(tracking) { + this.set(ol.DeviceOrientationProperty.TRACKING, tracking); +}; diff --git a/pool/shard000/JavaScript/0005126_memstore.js b/pool/shard000/JavaScript/0005126_memstore.js new file mode 100644 index 0000000000000000000000000000000000000000..508494e0b1dbe69cf10e910b80dd4a76bfbfca52 --- /dev/null +++ b/pool/shard000/JavaScript/0005126_memstore.js @@ -0,0 +1,76 @@ +var tough = require('./cookie'); +var permuteDomain = tough.permuteDomain; +var permutePath = tough.permutePath; +var util = require('util'); + +function MemoryCookieStore() { + this.idx = {}; +} +module.exports.MemoryCookieStore = MemoryCookieStore; +MemoryCookieStore.prototype.idx = null; + +// force a default depth: +MemoryCookieStore.prototype.inspect = function inspect() { + return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; +}; + +MemoryCookieStore.prototype.findCookie = function findCookie(domain, path, key, cb) { + if (!this.idx[domain]) return cb(null,undefined); + if (!this.idx[domain][path]) return cb(null,undefined); + return cb(null,this.idx[domain][path][key]||null); +}; + +MemoryCookieStore.prototype.findCookies = function findCookies(domain, path, cb) { + var results = []; + if (!domain || !path) return cb(null,[]); + + var domains = permuteDomain(domain)||[domain], dlen = domains.length; + var paths = permutePath(path), plen = paths.length; + + for (var i=0; i<dlen; i++) { + var curDomain = domains[i]; + var domainIndex = this.idx[curDomain]; + if (!domainIndex) continue; + for (var j=0; j<plen; j++) { + var curPath = paths[j]; + var pathIndex = domainIndex[curPath]; + if (!pathIndex) continue; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + } + cb(null,results); +}; + +MemoryCookieStore.prototype.putCookie = function putCookie(cookie, cb) { + if (!this.idx[cookie.domain]) this.idx[cookie.domain] = {}; + if (!this.idx[cookie.domain][cookie.path]) this.idx[cookie.domain][cookie.path] = {}; + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); +}; + +MemoryCookieStore.prototype.updateCookie = function updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie,cb); +}; + +MemoryCookieStore.prototype.removeCookie = function removeCookie(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); +}; + +MemoryCookieStore.prototype.removeCookies = function removeCookies(domain, path, cb) { + if (!this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); +}; diff --git a/pool/shard000/JavaScript/0005128_appearance_page.js b/pool/shard000/JavaScript/0005128_appearance_page.js new file mode 100644 index 0000000000000000000000000000000000000000..b6697eb7f8e192241e0381ee0812218cc23b8bf2 --- /dev/null +++ b/pool/shard000/JavaScript/0005128_appearance_page.js @@ -0,0 +1,326 @@ +// Copyright 2015 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. + +import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; +import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.m.js'; +import 'chrome://resources/cr_elements/shared_style_css.m.js'; +import 'chrome://resources/cr_elements/md_select_css.m.js'; +import '../controls/controlled_radio_button.m.js'; +import '../controls/extension_controlled_indicator.m.js'; +import '../controls/settings_radio_group.m.js'; +import '../controls/settings_toggle_button.m.js'; +import '../settings_page/settings_animated_pages.m.js'; +import '../settings_page/settings_subpage.m.js'; +import '../settings_shared_css.m.js'; +import '../settings_vars_css.m.js'; +import './home_url_input.js'; + +import {assert} from 'chrome://resources/js/assert.m.js'; +import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js'; +import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {DropdownMenuOptionList} from '../controls/settings_dropdown_menu.m.js'; +import {loadTimeData} from '../i18n_setup.js'; +import {AppearancePageVisibility} from '../page_visibility.js'; +import {routes} from '../route.js'; +import {Router} from '../router.m.js'; + +import {AppearanceBrowserProxy, AppearanceBrowserProxyImpl} from './appearance_browser_proxy.js'; + + +/** + * This is the absolute difference maintained between standard and + * fixed-width font sizes. http://crbug.com/91922. + * @type {number} + */ +const SIZE_DIFFERENCE_FIXED_STANDARD = 3; + +/** + * ID for autogenerated themes. Should match + * |ThemeService::kAutogeneratedThemeID|. + */ +const AUTOGENERATED_THEME_ID = 'autogenerated_theme_id'; + +/** + * 'settings-appearance-page' is the settings page containing appearance + * settings. + */ +Polymer({ + is: 'settings-appearance-page', + + _template: html`{__html_template__}`, + + behaviors: [I18nBehavior], + + properties: { + /** + * Dictionary defining page visibility. + * @type {!AppearancePageVisibility} + */ + pageVisibility: Object, + + prefs: { + type: Object, + notify: true, + }, + + /** @private */ + defaultZoom_: Number, + + /** @private */ + isWallpaperPolicyControlled_: {type: Boolean, value: true}, + + /** + * List of options for the font size drop-down menu. + * @type {!DropdownMenuOptionList} + */ + fontSizeOptions_: { + readOnly: true, + type: Array, + value() { + return [ + {value: 9, name: loadTimeData.getString('verySmall')}, + {value: 12, name: loadTimeData.getString('small')}, + {value: 16, name: loadTimeData.getString('medium')}, + {value: 20, name: loadTimeData.getString('large')}, + {value: 24, name: loadTimeData.getString('veryLarge')}, + ]; + }, + }, + + /** + * Predefined zoom factors to be used when zooming in/out. These are in + * ascending order. Values are displayed in the page zoom drop-down menu + * as percentages. + * @private {!Array<number>} + */ + pageZoomLevels_: Array, + + /** @private */ + themeSublabel_: String, + + /** @private */ + themeUrl_: String, + + /** @private */ + useSystemTheme_: { + type: Boolean, + value: false, // Can only be true on Linux, but value exists everywhere. + }, + + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value() { + const map = new Map(); + if (routes.FONTS) { + map.set(routes.FONTS.path, '#customize-fonts-subpage-trigger'); + } + return map; + }, + }, + + /** @private */ + showReaderModeOption_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('showReaderModeOption'); + }, + }, + }, + + /** @private {?AppearanceBrowserProxy} */ + appearanceBrowserProxy_: null, + + observers: [ + 'defaultFontSizeChanged_(prefs.webkit.webprefs.default_font_size.value)', + 'themeChanged_(prefs.extensions.theme.id.value, useSystemTheme_)', + + // <if expr="is_linux and not chromeos"> + // NOTE: this pref only exists on Linux. + 'useSystemThemePrefChanged_(prefs.extensions.theme.use_system.value)', + // </if> + ], + + /** @override */ + created() { + this.appearanceBrowserProxy_ = AppearanceBrowserProxyImpl.getInstance(); + }, + + /** @override */ + ready() { + this.$.defaultFontSize.menuOptions = this.fontSizeOptions_; + // TODO(dschuyler): Look into adding a listener for the + // default zoom percent. + this.appearanceBrowserProxy_.getDefaultZoom().then(zoom => { + this.defaultZoom_ = zoom; + }); + + this.pageZoomLevels_ = /** @type {!Array<number>} */ ( + JSON.parse(loadTimeData.getString('presetZoomFactors'))); + }, + + /** + * @param {number} zoom + * @return {number} A zoom easier read by users. + * @private + */ + formatZoom_(zoom) { + return Math.round(zoom * 100); + }, + + /** + * @param {boolean} showHomepage Whether to show home page. + * @param {boolean} isNtp Whether to use the NTP as the home page. + * @param {string} homepageValue If not using NTP, use this URL. + * @return {string} The sub-label. + * @private + */ + getShowHomeSubLabel_(showHomepage, isNtp, homepageValue) { + if (!showHomepage) { + return this.i18n('homeButtonDisabled'); + } + if (isNtp) { + return this.i18n('homePageNtp'); + } + return homepageValue || this.i18n('customWebAddress'); + }, + + /** @private */ + onCustomizeFontsTap_() { + Router.getInstance().navigateTo(routes.FONTS); + }, + + /** @private */ + onDisableExtension_() { + this.fire('refresh-pref', 'homepage'); + }, + + /** + * @param {number} value The changed font size slider value. + * @private + */ + defaultFontSizeChanged_(value) { + // This pref is handled separately in some extensions, but here it is tied + // to default_font_size (to simplify the UI). + this.set( + 'prefs.webkit.webprefs.default_fixed_font_size.value', + value - SIZE_DIFFERENCE_FIXED_STANDARD); + }, + + /** + * Open URL for either current theme or the theme gallery. + * @private + */ + openThemeUrl_() { + window.open(this.themeUrl_ || loadTimeData.getString('themesGalleryUrl')); + }, + + /** @private */ + onUseDefaultTap_() { + this.appearanceBrowserProxy_.useDefaultTheme(); + }, + + // <if expr="is_linux and not chromeos"> + /** + * @param {boolean} useSystemTheme + * @private + */ + useSystemThemePrefChanged_(useSystemTheme) { + this.useSystemTheme_ = useSystemTheme; + }, + + /** + * @param {string} themeId + * @param {boolean} useSystemTheme + * @return {boolean} Whether to show the "USE CLASSIC" button. + * @private + */ + showUseClassic_(themeId, useSystemTheme) { + return !!themeId || useSystemTheme; + }, + + /** + * @param {string} themeId + * @param {boolean} useSystemTheme + * @return {boolean} Whether to show the "USE GTK+" button. + * @private + */ + showUseSystem_(themeId, useSystemTheme) { + return (!!themeId || !useSystemTheme) && + !this.appearanceBrowserProxy_.isSupervised(); + }, + + /** + * @param {string} themeId + * @param {boolean} useSystemTheme + * @return {boolean} Whether to show the secondary area where "USE CLASSIC" + * and "USE GTK+" buttons live. + * @private + */ + showThemesSecondary_(themeId, useSystemTheme) { + return this.showUseClassic_(themeId, useSystemTheme) || + this.showUseSystem_(themeId, useSystemTheme); + }, + + /** @private */ + onUseSystemTap_() { + this.appearanceBrowserProxy_.useSystemTheme(); + }, + // </if> + + /** + * @param {string} themeId + * @param {boolean} useSystemTheme + * @private + */ + themeChanged_(themeId, useSystemTheme) { + if (this.prefs == undefined || useSystemTheme == undefined) { + return; + } + + if (themeId.length > 0 && themeId != AUTOGENERATED_THEME_ID) { + assert(!useSystemTheme); + + this.appearanceBrowserProxy_.getThemeInfo(themeId).then(info => { + this.themeSublabel_ = info.name; + }); + + this.themeUrl_ = 'https://chrome.google.com/webstore/detail/' + themeId; + return; + } + + this.themeUrl_ = ''; + + if (themeId == AUTOGENERATED_THEME_ID) { + this.themeSublabel_ = this.i18n('chromeColors'); + return; + } + + let i18nId; + // <if expr="is_linux and not chromeos"> + i18nId = useSystemTheme ? 'systemTheme' : 'classicTheme'; + // </if> + // <if expr="not is_linux or chromeos"> + i18nId = 'chooseFromWebStore'; + // </if> + this.themeSublabel_ = this.i18n(i18nId); + }, + + /** @private */ + onZoomLevelChange_() { + chrome.settingsPrivate.setDefaultZoom(parseFloat(this.$.zoomLevel.value)); + }, + + /** + * @see blink::PageZoomValuesEqual(). + * @param {number} zoom1 + * @param {number} zoom2 + * @return {boolean} + * @private + */ + zoomValuesEqual_(zoom1, zoom2) { + return Math.abs(zoom1 - zoom2) <= 0.001; + }, +}); diff --git a/pool/shard000/JavaScript/0005133_preferencesBwsUrl.js b/pool/shard000/JavaScript/0005133_preferencesBwsUrl.js new file mode 100644 index 0000000000000000000000000000000000000000..d7f43948b625b5c61ce55546b691f57c414908ca --- /dev/null +++ b/pool/shard000/JavaScript/0005133_preferencesBwsUrl.js @@ -0,0 +1,50 @@ +'use strict'; + +angular.module('copayApp.controllers').controller('preferencesBwsUrlController', + function($scope,$log, configService, isMobile, isCordova, go, applicationService ) { + this.isSafari = isMobile.Safari(); + this.isCordova = isCordova; + this.error = null; + this.success = null; + + var config = configService.getSync(); + + this.bwsurl = config.bws.url; + + this.save = function() { + + var bws; + switch (this.bwsurl) { + case 'prod': + case 'production': + bws = 'https://bws.decred.org/bws/api' + break; + case 'sta': + case 'staging': + bws = 'https://bws-staging.decred.org/bws/api' + break; + case 'loc': + case 'local': + bws = 'http://localhost:3232/bws/api' + break; + }; + if (bws) { + $log.info('Using BWS URL Alias to ' + bws); + this.bwsurl = bws; + } + + var opts = { + bws: { + url: this.bwsurl, + } + }; + + configService.set(opts, function(err) { + if (err) console.log(err); + $scope.$emit('Local/BWSUpdated'); + applicationService.restart(); + }); + }; + + + }); diff --git a/pool/shard000/JavaScript/0005134_shops.js b/pool/shard000/JavaScript/0005134_shops.js new file mode 100644 index 0000000000000000000000000000000000000000..1d22c227bdb9f0c1c3dc0bfebede4588149dfc62 --- /dev/null +++ b/pool/shard000/JavaScript/0005134_shops.js @@ -0,0 +1,89 @@ + +var Shops = function(shopName, minC, maxC, averageC) { + this.minC = minC; + this.maxC = maxC; + this.averageC = averageC; + this.shopName = shopName; + this.averageDonuts = []; + this.total = 0; +}; + +Shops.prototype.render = function() { + var title = document.getElementById('title'); + title.innerHTML = "TOP POT DONUTS"; + var table = document.getElementById('myTable'); + + for (var i = 0; i < 11; i++) { + var randDonuts = Math.floor((Math.random() * (this.maxC - this.minC) + this.minC) * this.averageC) + 1; + this.averageDonuts.push(randDonuts); + this.total += randDonuts; + } + + if (document.getElementById(this.shopName)) { + var shopID = document.getElementById(this.shopName).childNodes; + + for (var i = 1; i < shopID.length-1; i++) { + shopID[i].innerHTML = this.averageDonuts[i-1]; + } + shopID[shopID.length - 1].innerHTML = this.total; + } else { + var locationName = document.createElement('tr'); + locationName.id = this.shopName; + locationName.innerHTML = this.shopName; + table.appendChild(locationName); + + var total = 0; + var hrsOpen = 11; + for (var i =0; i < this.averageDonuts.length; i++) { + var td = document.createElement('td'); + td.innerHTML = this.averageDonuts[i]; + locationName.appendChild(td); + } + + var totD = document.createElement('td'); + totD.innerHTML = this.total; + locationName.appendChild(totD); + } +} + +var mainForm = document.getElementById('submit'); +mainForm.addEventListener('click', function(e) { + e.preventDefault(); + console.log("listener"); + var shopN = document.getElementById('name').value; + var minCus = parseInt(document.getElementById('minCus').value); + var maxCus = parseInt(document.getElementById('maxCus').value); + var avgCus = parseInt(document.getElementById('avgCus').value); + var newShop = new Shops(shopN, minCus, maxCus, avgCus); + donutShopNames.push(newShop); + newShop.render(); +}); + +var donutShopNames = []; + +var dT = new Shops('Downtown', 8, 43, 4.5); +donutShopNames.push(dT); +var cH = new Shops('Capitol Hill', 4, 37, 2); +donutShopNames.push(cH); +var SLU = new Shops('South Lake Union', 9, 23, 6.33); +donutShopNames.push(SLU); +var WW = new Shops('Wedgewood', 2, 28, 1.25); +donutShopNames.push(WW); +var blD = new Shops('Ballard', 8, 58, 3.75); +donutShopNames.push(blD); + +dT.render(); +cH.render(); +SLU.render(); +WW.render(); +blD.render(); + + + + + + + + + + diff --git a/pool/shard000/JavaScript/0005138_script.js b/pool/shard000/JavaScript/0005138_script.js new file mode 100644 index 0000000000000000000000000000000000000000..6d2f1a7b9a8d15b9c6f54951446e189d7272b81c --- /dev/null +++ b/pool/shard000/JavaScript/0005138_script.js @@ -0,0 +1,101 @@ +(function(w, d, $) { + + const state = {}; + state.dom = {}; + + // gather elements + const collectDOM = () => { + state.dom.mainContent = d.getElementById('mainContent'); + state.dom.anchorList = d.getElementById('anchors'); + state.dom.documentation = d.getElementById('documentation'); + state.dom.sideNav = d.getElementById('sideNav'); + state.dom.sideNavOpen = d.getElementById('sideNavOpen'); + state.dom.sideNavClose = d.getElementById('sideNavClose'); + state.dom.responsiveMenuButton = d.getElementById('responsiveMenuButton'); + state.dom.splashDownArrow = d.getElementById('splashDownArrow'); + state.dom.footer = d.getElementsByTagName('footer')[0]; + }; + + // navigation + const controlNavigation = () => { + const setState = method => utils[method](state.dom.sideNav); + const handleAnchorClick = e => { + setState('close'); + if ('ontouchend' in d) w.location.href = $(e.target).attr('href'); + }; + const handleResize = () => { if ($('body').width() > 875) utils.close(state.dom.sideNav); }; + $(state.dom.sideNavOpen).on(utils.interaction(), () => setState('open')); + $(state.dom.sideNavClose).on(utils.interaction(), () => setState('close')); + $('#sideNav a, #navigation a').on(utils.interaction(), handleAnchorClick); + $(w).resize(handleResize); + }; + + // nav button scripts + const controlNavButtons = () => { + const handleResponsiveMenu = (method, toggle = false, e = event) => { + utils[method](toggle ? e.target : state.dom.responsiveMenuButton, toggle)[toggle ? 'show' : 'hide']('#overlay, #navigation', toggle); + $('body')[toggle ? 'toggleClass' : 'removeClass']('overlay-open'); + }; + const handleResize = () => { if ($('body').width() > 650) handleResponsiveMenu('deselect'); }; + $(state.dom.responsiveMenuButton).on(utils.interaction(), e => handleResponsiveMenu('select', true)); + $('#navigation a').on(utils.interaction(), () => handleResponsiveMenu('deselect')); + $(w).resize(handleResize); + }; + + // render top and bottom canvas elements + const renderCanvas = () => { + const render = () => utils.renderCanvas('topCanvas', '#b1b1b1', '#fff').renderCanvas('bottomCanvas', '#fff', '#b1b1b1'); + $(w).resize(() => setTimeout(render, 10)); + render(); + }; + + // build 'UP' button + // only show the scroll-top button if users scroll under the modules nav list + // also only show the mobile side-nav button if users scroll to the Documentation section + const controlScrollTopButton = () => { + const scrollTopButton = '<button id="scrollTop" class="scroll-top">UP</button>'; + const linkToDocs = () => w.location.href = '#documentation'; + const handleScroll = () => { + const anchorOffset = $(state.dom.anchorList).height() + $(state.dom.anchorList).offset('top'); + const docOffset = $(state.dom.documentation).offset('top'); + const methodButton = $(w).scrollTop() > anchorOffset ? 'show' : 'hide'; + const methodSideNav = $(w).scrollTop() > docOffset ? 'show' : 'hide'; + utils[methodButton]('#scrollTop'); + utils[methodSideNav](state.dom.sideNavOpen); + }; + state.dom.footer.innerHTML += scrollTopButton; + $('#scrollTop').on(utils.interaction(), linkToDocs); + $(w).scroll(handleScroll); + }; + + // control splash screen down-arrow + const controlSplashDownArrow = () => { + const linkToBackground = () => w.location.href = '#backgroundInfo'; + $(state.dom.splashDownArrow).on(utils.interaction(), linkToBackground); + }; + + // create mouseable states + const setMouseables = () => $('#responsiveMenuButton, #navigation a, #splashDownArrow, #backgroundInfo a, .footer a, .anchor-link, #scrollTop, #sideNavClose, #sideNavOpen').mouseable(); + + // update copyright year + const updateCopyrightYear = () => { + const copyrightYear = d.getElementById('copyrightYear'); + const dateYear = new Date().getFullYear(); + return copyrightYear.innerHTML = dateYear; + }; + + // do all the things + const init = () => { + collectDOM(); + controlNavigation(); + controlNavButtons(); + renderCanvas(); + controlScrollTopButton(); + controlSplashDownArrow(); + setMouseables(); + updateCopyrightYear(); + }; + + $(d).ready(init); + +})(window, document, Grindstone); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005140_ilios-users.js b/pool/shard000/JavaScript/0005140_ilios-users.js new file mode 100644 index 0000000000000000000000000000000000000000..c0839170c02ec89297971c1f0ebe4ee4a354f3b2 --- /dev/null +++ b/pool/shard000/JavaScript/0005140_ilios-users.js @@ -0,0 +1,53 @@ +/* eslint ember/order-in-components: 0 */ +import { inject as service } from '@ember/service'; +import Component from '@ember/component'; +import { computed } from '@ember/object'; +import { cleanQuery } from 'ilios-common/utils/query-utils'; +import { task, timeout } from 'ember-concurrency'; + +const DEBOUNCE_TIMEOUT = 250; + +export default Component.extend({ + store: service(), + iliosConfig: service(), + classNames: ['ilios-users'], + offset: null, + limit: null, + query: null, + showNewUserForm: false, + showBulkNewUserForm: false, + + didReceiveAttrs(){ + this._super(...arguments); + this.searchForUsers.perform(); + }, + + searchForUsers: task(function * (){ + const query = this.query; + const q = cleanQuery(query); + yield timeout(DEBOUNCE_TIMEOUT); + const { store, offset, limit } = this; + return yield store.query('user', { + limit, q, offset, + 'order_by[lastName]': 'ASC', + 'order_by[firstName]': 'ASC' + }); + + }).cancelOn('deactivate').restartable(), + + newUserComponent: computed('iliosConfig.userSearchType', async function(){ + const iliosConfig = this.iliosConfig; + const userSearchType = await iliosConfig.get('userSearchType'); + + return userSearchType === 'ldap'?'new-directory-user':'new-user'; + }), + + actions: { + setOffset(offset){ + if (offset < 0) { + offset = 0; + } + this.setOffset(offset); + }, + } +}); diff --git a/pool/shard000/JavaScript/0005141_regress-328897.js b/pool/shard000/JavaScript/0005141_regress-328897.js new file mode 100644 index 0000000000000000000000000000000000000000..04b4947ea3d957d102fc6e60d6732c76a7625e16 --- /dev/null +++ b/pool/shard000/JavaScript/0005141_regress-328897.js @@ -0,0 +1,47 @@ +/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +var gTestfile = 'regress-328897.js'; +//----------------------------------------------------------------------------- +var BUGNUMBER = 328897; +var summary = 'JS_ReportPendingException should'; + +var actual = 'No Error'; +var expect = 'No Error'; + +printBugNumber(BUGNUMBER); +printStatus (summary); + +if (typeof window == 'undefined') +{ + reportCompare(expect, actual, summary); +} +else +{ + expect = /(Script error.|uncaught exception: Permission denied to get property UnnamedClass.classes)/; + + window._onerror = window.onerror; + window.onerror = (function (msg, page, line) { + actual = msg; + gDelayTestDriverEnd = false; + jsTestDriverEnd(); + reportMatch(expect, actual, summary); + }); + + gDelayTestDriverEnd = true; + + window.location="javascript:Components.classes"; + actual = 'No Error'; +} + +function onload() +{ + if (actual == 'No Error') + { + gDelayTestDriverEnd = false; + jsTestDriverEnd(); + reportCompare(expect, actual, summary); + } +} diff --git a/pool/shard000/JavaScript/0005151_clock_skew.js b/pool/shard000/JavaScript/0005151_clock_skew.js new file mode 100644 index 0000000000000000000000000000000000000000..9e259c065fa78188371fdea01ab716021ff2c88f --- /dev/null +++ b/pool/shard000/JavaScript/0005151_clock_skew.js @@ -0,0 +1,83 @@ +// Copyright 2014 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. + +export default function load(config) { + let now = () => { + return window.performance.now(); + }; + + const SMEAR_DURATION = config.smear !== undefined ? config.smear : 5000; // ms + + function lerp(a, b, alpha) { + return (1-alpha) * a + alpha * b; + } + + + let currentSkew = 0; + let skewAtLastReference = 0; + // Returns current time, adjusted by reference time. + const getTime = function() { + if (lastReferenceUpdateInLocal == -1) { + return 0.0; + } + // What skew should we report? + // Well, if we are between lastReferenceUpdate and lastReferenceUpdate + + // SMEAR_DURATION, we need to lerp the skew. If we are beyond, we should + // assume a skew of 0. + const localNow = now(); + const alpha = Math.min(Math.max((localNow - lastReferenceUpdateInLocal) / SMEAR_DURATION, 0), 1.0); + currentSkew = lerp(skewAtLastReference, mostRecentSkew, alpha); + + return localNow + currentSkew; + }; + + // Updates internal model with new reference time. Smears skew over subsequent + // updates. + let mostRecentSkew = 0; + let lastReferenceUpdateInLocal = -1; + + const adjustTimeByReference = function(referenceNow) { + const localNow = now(); + mostRecentSkew = referenceNow - localNow; + + // If skew is older than smear amount, just jump. + if (mostRecentSkew < -SMEAR_DURATION) { + currentSkew = mostRecentSkew; + } else { + if (lastReferenceUpdateInLocal == -1) { + // Initialize skew. + currentSkew = mostRecentSkew; + } + } + lastReferenceUpdateInLocal = localNow; + skewAtLastReference = currentSkew; + }; + + const originalNow = now; + + return { + getTime, + adjustTimeByReference, + resetForTest() { + currentSkew = 0; + skewAtLastReference = 0; + mostRecentSkew = 0; + lastReferenceUpdateInLocal = -1; + now = originalNow; + }, + enterTestingMode(fakeNow) { + now = fakeNow; + }, + }; +}; diff --git a/pool/shard000/JavaScript/0005153_ZoomManager.js b/pool/shard000/JavaScript/0005153_ZoomManager.js new file mode 100644 index 0000000000000000000000000000000000000000..83aa496aca5b5d83ea84441def226376ee86a70c --- /dev/null +++ b/pool/shard000/JavaScript/0005153_ZoomManager.js @@ -0,0 +1,42 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @constructor + * @extends {WebInspector.Object} + */ +WebInspector.ZoomManager = function() +{ + this._zoomFactor = InspectorFrontendHost.zoomFactor(); + window.addEventListener("resize", this._onWindowResize.bind(this), true); +}; + +WebInspector.ZoomManager.Events = { + ZoomChanged: "ZoomChanged" +}; + +WebInspector.ZoomManager.prototype = { + /** + * @return {number} + */ + zoomFactor: function() + { + return this._zoomFactor; + }, + + _onWindowResize: function() + { + var oldZoomFactor = this._zoomFactor; + this._zoomFactor = InspectorFrontendHost.zoomFactor(); + if (oldZoomFactor !== this._zoomFactor) + this.dispatchEventToListeners(WebInspector.ZoomManager.Events.ZoomChanged, {from: oldZoomFactor, to: this._zoomFactor}); + }, + + __proto__: WebInspector.Object.prototype +}; + +/** + * @type {!WebInspector.ZoomManager} + */ +WebInspector.zoomManager; diff --git a/pool/shard000/JavaScript/0005156_test-helpers.js b/pool/shard000/JavaScript/0005156_test-helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..a566b4a4f513f7bc121c995a6b83790a60bd012b --- /dev/null +++ b/pool/shard000/JavaScript/0005156_test-helpers.js @@ -0,0 +1,137 @@ +'use strict'; + +const servers = require('./test-servers.json'); +const agent = require('../src'); +const Request = require('../src/request'); +const SimpleFailover = require('../src/simple-failover'); +const ConsulFailover = require('../src/consul-failover'); + +const controllerUrl = `http://${servers.controller.ip}:${servers.controller.port}`; + +module.exports.reset = function () { + return agent + .get(`${controllerUrl}/reset`) + .catch(console.error.bind(console)); +}; + +const getServiceCalls = function () { + return agent + .get(`${controllerUrl}/calls`) + .then(x => x.body, console.error.bind(console)); +} + +const countCallbackCalls = function (fn, waitMs, done) { + let calls = 0; + return function () { + calls += 1; + if (calls > 1) return; + fn.apply(null, arguments); + setTimeout(() => done(calls), waitMs || 0); + }; +}; + +module.exports.createSimpleFailoverFixture = function (serviceName, countCallbacksMs, done) { + const fixture = {}; + fixture.service = servers.services[serviceName]; + fixture.failover = new SimpleFailover({ + servers: fixture.service.map(x => `http://${x.ip}:${x.port}`) + }); + fixture.failover.resolveServers(countCallbackCalls((err, addr) => { + fixture.error = err; + fixture.serviceAddresses = addr; + }, countCallbacksMs, callbackCalls => { + fixture.callbackCalls = callbackCalls; + getServiceCalls().then(serviceCalls => { + fixture.serviceCalls = serviceCalls; + done(); + }, done); + })); + return fixture; +}; + +module.exports.createMultipleRequestFixture = function (serviceName, strategy, failoverOverrides, countCallbacksMs, done) { + const fixture = {}; + fixture.services = servers.services[serviceName]; + fixture.failover = new SimpleFailover({ + servers: fixture.services.map(x => `http://${x.ip}:${x.port}`), + strategy: strategy + }); + fixture.request = new Request('GET', '/endpoint', fixture.failover); + if (failoverOverrides) fixture.request.failover(failoverOverrides); + fixture.request.end(countCallbackCalls((err, res) => { + fixture.error = err; + fixture.response = res; + }, countCallbacksMs, callbackCalls => { + fixture.callbackCalls = callbackCalls; + getServiceCalls().then(serviceCalls => { + fixture.serviceCalls = serviceCalls; + done(); + }, done); + })); + return fixture; +}; + +module.exports.createConsulFailoverFixture = function (clusterName, serviceName, discoveryTimeout, countCallbacksMs, done) { + const fixture = {}; + fixture.cluster = servers.consuls[clusterName]; + fixture.service = servers.services[serviceName]; + fixture.failover = new ConsulFailover({ + serviceName: serviceName, + discoveryServers: fixture.cluster.map(x => `http://${x.ip}:${x.port}`), + discoveryTimeout: discoveryTimeout + }); + fixture.failover.resolveServers(countCallbackCalls((err, addr) => { + fixture.error = err; + fixture.serviceAddresses = addr; + }, countCallbacksMs, callbackCalls => { + fixture.callbackCalls = callbackCalls; + getServiceCalls().then(serviceCalls => { + fixture.serviceCalls = serviceCalls; + done(); + }, done); + })); + return fixture; +}; + +module.exports.createServiceRequestFixture = function (clusterName, serviceName, discoveryTimeout, serviceTimeout, countCallbacksMs, done) { + const fixture = {}; + fixture.cluster = servers.consuls[clusterName]; + fixture.service = servers.services[serviceName]; + fixture.failover = new ConsulFailover({ + serviceName: serviceName, + discoveryServers: fixture.cluster.map(x => `http://${x.ip}:${x.port}`), + discoveryTimeout: discoveryTimeout + }); + fixture.request = new Request('GET', `http://${fixture.service.ip}:${fixture.service.port}/endpoint`, fixture.failover); + fixture.request.timeout(serviceTimeout); + fixture.request.end(countCallbackCalls((err, res) => { + fixture.error = err; + fixture.response = res; + }, countCallbacksMs, callbackCalls => { + fixture.callbackCalls = callbackCalls; + getServiceCalls().then(serviceCalls => { + fixture.serviceCalls = serviceCalls; + done(); + }, done); + })); + return fixture; +}; + +module.exports.createHttpRequestFixture = function (serviceName, query, headers, countCallbacksMs, done) { + const fixture = {}; + fixture.service = servers.services[serviceName][0]; + fixture.request = new Request('GET', `http://${fixture.service.ip}:${fixture.service.port}/endpoint`); + if (query) fixture.request.query(query); + if (headers) Object.keys(headers).forEach(key => fixture.request.set(key, headers[key])); + fixture.request.end(countCallbackCalls((err, res) => { + fixture.error = err; + fixture.response = res; + }, countCallbacksMs, callbackCalls => { + fixture.callbackCalls = callbackCalls; + getServiceCalls().then(serviceCalls => { + fixture.serviceCalls = serviceCalls; + done(); + }, done); + })); + return fixture; +}; diff --git a/pool/shard000/JavaScript/0005158_igvComponent.js b/pool/shard000/JavaScript/0005158_igvComponent.js new file mode 100644 index 0000000000000000000000000000000000000000..99194ac35ac74abcfd7fcbd59ca1ba5c64055eaf --- /dev/null +++ b/pool/shard000/JavaScript/0005158_igvComponent.js @@ -0,0 +1,53 @@ +//require.config({ +// 'shim' : { +// 'bootstrap' : { +// 'deps' :['jquery'] +// }, +// 'igv' : { +// 'deps' :['jquery', 'jquery-ui', 'bootstrap'] +// } +// }, +// 'paths': { +// 'jquery' : 'http://code.jquery.com/jquery-1.12.4.min', +// 'jquery-ui' : 'http://code.jquery.com/ui/1.12.1/jquery-ui.min', +// 'bootstrap' : 'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min', +// 'igv' : 'http://igv.org/web/release/1.0.6/igv-1.0.6' +// } +//}); + +igv = ('igv'); +jquery = require('jquery'); +jqueryui = require('jquery-ui') +//require("./style.css"); + +$(function(){ + console.log("enter igv.js docReady, igv?"); + console.log(igv) + var igvDiv; + + igvDiv = $("#igvDiv"); + options = { + palette: ["#00A0B0", "#6A4A3C", "#CC333F", "#EB6841"], + locus: "7:55,085,725-55,276,031", + reference: {id: "hg19", + fastaURL: "http://igv.broadinstitute.org/genomes/seq/1kg_v37/human_g1k_v37_decoy.fasta", + cytobandURL: "http://igv.broadinstitute.org/genomes/seq/b37/b37_cytoband.txt" + }, + trackDefaults: { + bam: {coverageThreshold: 0.2, + coverageQualityWeight: true + } + }, + tracks: [ + {name: "Genes", + url: "http://igv.broadinstitute.org/annotations/hg19/genes/gencode.v18.collapsed.bed", + index: "http://igv.broadinstitute.org/annotations/hg19/genes/gencode.v18.collapsed.bed.idx", + displayMode: "EXPANDED" + } + ] + }; // options + console.log("about to createBrowser"); + browser = igv.createBrowser(igvDiv, options); + setTimeout(function() {$("#tabs").tabs()}, 1000); +}); // onready funcetion + diff --git a/pool/shard000/JavaScript/0005160_utils.js b/pool/shard000/JavaScript/0005160_utils.js new file mode 100644 index 0000000000000000000000000000000000000000..b75cce41d93e406e94a6a0de709a2b02a005ff39 --- /dev/null +++ b/pool/shard000/JavaScript/0005160_utils.js @@ -0,0 +1,28 @@ +import Emitter from 'event-emitter'; + +exports.emitter = new Emitter(); + +exports.guid = () => { + function S4() { + return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); + } + return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()); +}; + +exports.comparePlainObject = function (a, b) { + return JSON.stringify(a) === JSON.stringify(b); +}; + +['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'].forEach(function (v) { + var toString = Object.prototype.toString; + exports['is' + v] = function (obj) { + return toString.apply(obj) === '[object ' + v + ']'; + }; +}); + + +exports.ClearBr = function (key) { + key = key.replace(/<\/?.+?>/g, ''); + key = key.replace(/[\r\n]/g, ''); + return key; +}; diff --git a/pool/shard000/JavaScript/0005161_Random.js b/pool/shard000/JavaScript/0005161_Random.js new file mode 100644 index 0000000000000000000000000000000000000000..c32146572b343c29d3ef63178ce3d80d3e936104 --- /dev/null +++ b/pool/shard000/JavaScript/0005161_Random.js @@ -0,0 +1,32 @@ +/** + * @author Richard Davey <rich@photonstorm.com> + * @copyright 2019 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a random point within a Rectangle. + * + * @function Phaser.Geom.Rectangle.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Rectangle} rect - The Rectangle to return a point from. + * @param {Phaser.Geom.Point} out - The object to update with the point's coordinates. + * + * @return {Phaser.Geom.Point} The modified `out` object, or a new Point if none was provided. + */ +var Random = function (rect, out) +{ + if (out === undefined) { out = new Point(); } + + out.x = rect.x + (Math.random() * rect.width); + out.y = rect.y + (Math.random() * rect.height); + + return out; +}; + +module.exports = Random; diff --git a/pool/shard000/JavaScript/0005164_index.js b/pool/shard000/JavaScript/0005164_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1969cd70e2d9d234aee841384c89645971fcdcfe --- /dev/null +++ b/pool/shard000/JavaScript/0005164_index.js @@ -0,0 +1,52 @@ +import React from "react"; +import PropTypes from "prop-types"; +import { + getTileImage, + TileLink, + TileSummary, + TileImage, + withTileTracking +} from "../shared"; +import styles from "./styles"; + +const TileI = ({ onPress, tile }) => { + const crop = getTileImage(tile, "crop169"); + + if (!crop) { + return null; + } + + const { + article: { hasVideo } + } = tile; + + return ( + <TileLink onPress={onPress} tile={tile}> + <TileImage + aspectRatio={16 / 9} + relativeWidth={crop.relativeWidth} + relativeHeight={crop.relativeHeight} + relativeHorizontalOffset={crop.relativeHorizontalOffset} + relativeVerticalOffset={crop.relativeVerticalOffset} + style={styles.imageContainer} + uri={crop.url} + fill + hasVideo={hasVideo} + /> + <TileSummary + headlineStyle={styles.headline} + style={styles.summaryContainer} + tile={tile} + centeredStar + underneathTextStar + /> + </TileLink> + ); +}; + +TileI.propTypes = { + onPress: PropTypes.func.isRequired, + tile: PropTypes.shape({}).isRequired +}; + +export default withTileTracking(TileI); diff --git a/pool/shard000/JavaScript/0005165_Choice.js b/pool/shard000/JavaScript/0005165_Choice.js new file mode 100644 index 0000000000000000000000000000000000000000..b162b36462eb8b7afc16a58a163ac5a4a997a005 --- /dev/null +++ b/pool/shard000/JavaScript/0005165_Choice.js @@ -0,0 +1,66 @@ +define([ + 'taoQtiItem/qtiCreator/widgets/states/factory', + 'taoQtiItem/qtiCreator/widgets/choices/states/Choice', + 'tpl!taoQtiItem/qtiCreator/tpl/forms/choices/choice', + 'taoQtiItem/qtiCreator/widgets/helpers/formElement', + 'taoQtiItem/qtiCreator/widgets/helpers/identifier', + 'taoQtiItem/qtiCreator/editor/ckEditor/htmlEditor', + 'taoQtiItem/qtiCreator/editor/gridEditor/content' +], function(stateFactory, Choice, formTpl, formElement, identifierHelper, htmlEditor, contentHelper){ + + var SimpleChoiceStateChoice = stateFactory.extend(Choice, function(){ + + this.buildEditor(); + + }, function(){ + + this.destroyEditor(); + }); + + SimpleChoiceStateChoice.prototype.initForm = function(){ + + var _widget = this.widget; + + //build form: + _widget.$form.html(formTpl({ + serial : _widget.element.getSerial(), + identifier : _widget.element.id() + })); + + formElement.initWidget(_widget.$form); + + //init data validation and binding + formElement.setChangeCallbacks(_widget.$form, _widget.element, { + identifier : identifierHelper.updateChoiceIdentifier + }); + }; + + SimpleChoiceStateChoice.prototype.buildEditor = function(){ + + var _widget = this.widget, + container = _widget.element.getBody(), + $editableContainer = _widget.$container; + + //@todo set them in the tpl + $editableContainer.attr('data-html-editable-container', true); + + if(!htmlEditor.hasEditor($editableContainer)){ + + htmlEditor.buildEditor($editableContainer, { + change : contentHelper.getChangeCallback(container), + data : { + container : container, + widget : _widget + } + }); + } + }; + + SimpleChoiceStateChoice.prototype.destroyEditor = function(){ + + //search and destroy the editor + htmlEditor.destroyEditor(this.widget.$container); + }; + + return SimpleChoiceStateChoice; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005170_index.js b/pool/shard000/JavaScript/0005170_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f0809009de4304a38c4e5055b8c87c41263a2ca7 --- /dev/null +++ b/pool/shard000/JavaScript/0005170_index.js @@ -0,0 +1,115 @@ +(function() { + var fglob, fs, ini, outcome, path, _exists; + + outcome = require("outcome"); + + path = require("path"); + + fs = require("fs"); + + fglob = require("fglob"); + + ini = require("ini"); + + _exists = function(path) { + try { + return !!fs.statSync(path); + } catch (e) { + return false; + } + }; + + exports.plugin = function() { + var _commandFromData, _loadCommands, _loadIni, _name, _packageName, _scanIni, + _this = this; + _packageName = function(data) { + return JSON.parse(fs.readFileSync("" + data.directory + "/package.json", "utf8")).name; + }; + _name = function(data) { + if (data.name) return data.name; + if (_exists("" + data.directory + "/package.json")) { + return _packageName(data); + } + return path.basename(data.directory); + }; + _commandFromData = function(data) { + var cmdParts, command, commands, cwd; + commands = []; + cmdParts = data.command.split(' '); + command = cmdParts.shift(); + arguments = cmdParts; + cwd = process.cwd(); + return { + name: _name(data), + command: command, + arguments: arguments, + directory: cwd, + group: data.group + }; + }; + _loadIni = function(file, data, callback) { + var cfg, commands, procCfg, procName; + cfg = ini.parse(fs.readFileSync(file, 'utf8')); + commands = []; + for (procName in cfg) { + procCfg = cfg[procName]; + procCfg.dir = path.dirname(file); + procCfg.name = procName; + procCfg.group = data.group || path.basename(file).split('.').shift(); + commands.push(_commandFromData(procCfg)); + } + return callback(commands); + }; + _scanIni = function(data, callback) { + return fglob("" + data.directory + "/*.prls", function(files) { + var allCommands, file, numRunning, _i, _len, _results; + if (!files.length) return callback(null, []); + numRunning = files.length; + allCommands = []; + _results = []; + for (_i = 0, _len = files.length; _i < _len; _i++) { + file = files[_i]; + _results.push((function(file) { + return _loadIni(file, data, function(commands) { + allCommands = allCommands.concat(commands); + if (!(--numRunning)) return callback(null, allCommands); + }); + })(file)); + } + return _results; + }); + }; + _loadCommands = function(data, callback) { + if (!data.directory) data.directory = process.cwd(); + if (data.command) return callback(null, [_commandFromData(data)]); + return _scanIni(data, callback); + }; + return { + option: { + command: 'add :group :command OR add :command OR add', + description: 'Adds a command or path to .pls', + optional: { + "--name": "Name of the process to add" + }, + callback: function(data) { + return _loadCommands(data, outcome({ + success: function(commands) { + var command, _i, _len, _results; + _results = []; + for (_i = 0, _len = commands.length; _i < _len; _i++) { + command = commands[_i]; + _results.push(_this.plugin('pearls.core').group(command.group).processes().add(command.name, command, outcome({ + error: function(err) { + return console.log(err.message); + } + }))); + } + return _results; + } + })); + } + } + }; + }; + +}).call(this); diff --git a/pool/shard000/JavaScript/0005172_main.js b/pool/shard000/JavaScript/0005172_main.js new file mode 100644 index 0000000000000000000000000000000000000000..9a926154806ace3b94dc3f1ff573ee3838518d5c --- /dev/null +++ b/pool/shard000/JavaScript/0005172_main.js @@ -0,0 +1,32 @@ +'use strict'; + +var Buddy = require('./buddy'); +var state = require('./state'); + +var UTF_8 = 'utf-8'; +var args = process.argv.slice(2); + +var helpNames = { + help: showHelp, + '-h': showHelp, + '--help': showHelp +}; + +function showHelp() { + // TODO: Show useful help + console.error('I wish I could help you.'); +} + +function main() { + var cmd = args[0]; + var rest = args.slice(1); + var tomodachi = new Buddy(state.load()); + if (!cmd || helpNames[cmd] || !tomodachi[cmd]) { + showHelp(); + } else { + tomodachi[cmd](); + state.save(tomodachi.toJSON()); + } +} + +module.exports = main; diff --git a/pool/shard000/JavaScript/0005173_class.js b/pool/shard000/JavaScript/0005173_class.js new file mode 100644 index 0000000000000000000000000000000000000000..529dae67b7746ea82ca8aa1fe7c8c1db82dfba0b --- /dev/null +++ b/pool/shard000/JavaScript/0005173_class.js @@ -0,0 +1,62 @@ +define([], function() { + var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; + + // The base Class implementation (does nothing) + var Class = function(){}; + + // Create a new Class that inherits from this class + Class.extend = function(prop) { + var _super = this.prototype; + + // Instantiate a base class (but only create the instance, + // don't run the init constructor) + initializing = true; + var prototype = new this(); + initializing = false; + + // Copy the properties over onto the new prototype + for (var name in prop) { + // Check if we're overwriting an existing function + prototype[name] = typeof prop[name] == "function" && + typeof _super[name] == "function" && fnTest.test(prop[name]) ? + (function(name, fn){ + return function() { + var tmp = this._super; + + // Add a new ._super() method that is the same method + // but on the super-class + this._super = _super[name]; + + // The method only need to be bound temporarily, so we + // remove it when we're done executing + var ret = fn.apply(this, arguments); + this._super = tmp; + + return ret; + }; + })(name, prop[name]) : + prop[name]; + } + + // The dummy class constructor + function Class() { + // All construction is actually done in the init method + if ( !initializing && this.init ) + this.init.apply(this, arguments); + } + + // Populate our constructed prototype object + Class.prototype = prototype; + + // Enforce the constructor to be what we expect + Class.prototype.constructor = Class; + + // And make this class extendable + Class.extend = arguments.callee; + + return Class; + }; + + return Class; + +}); diff --git a/pool/shard000/JavaScript/0005177_TeamMember.js b/pool/shard000/JavaScript/0005177_TeamMember.js new file mode 100644 index 0000000000000000000000000000000000000000..87cb74909dd157fa732a744202cf9fc70bef48d5 --- /dev/null +++ b/pool/shard000/JavaScript/0005177_TeamMember.js @@ -0,0 +1,77 @@ +(function(window) +{ + var Gitana = window.Gitana; + + Gitana.TeamMember = Gitana.AbstractObject.extend( + /** @lends Gitana.TeamMember.prototype */ + { + /** + * @constructs + * @augments Gitana.AbstractObject + * + * @class TeamMember + * + * @param {Gitana.Cluster} cluster + * @param [Object] object json object (if no callback required for populating) + */ + constructor: function(team, object) + { + this.base(team.getDriver(), object); + + this.objectType = function() { return "Gitana.TeamMember"; }; + + + + ////////////////////////////////////////////////////////////////////////////////////////////// + // + // PRIVILEGED METHODS + // + ////////////////////////////////////////////////////////////////////////////////////////////// + + this.getTeam = function() { return team; }; + this.getCluster = function() { return team.getCluster(); }; + this.getClusterId = function() { return team.getClusterId(); }; + } + + /*, + + domain: function() + { + var self = this; + + var result = this.subchain(new Gitana.Domain({ + "_doc": this.domainId + })); + + return result.then(function() { + // TODO: read the domain and populate + }); + }, + + principal: function() + { + var self = this; + + // domain + var domain = new Gitana.Domain({ + "" + }) + // temp web host + var webhost = new Gitana.WebHost(this.getPlatform()); + + // we hand back a deployed application and preload some work + var chainable = this.getFactory().deployedApplication(webhost); + return this.chainPost(chainable, uriFunction).then(function() { + + // load the real web host + var webhostId = self["deployments"][deploymentKey]["webhost"]; + this.subchain(this.getPlatform()).readWebHost(webhostId).then(function() { + webhost.loadFrom(this); + }); + + }); + } + */ + }); + +})(window); diff --git a/pool/shard000/JavaScript/0005180_app.js b/pool/shard000/JavaScript/0005180_app.js new file mode 100644 index 0000000000000000000000000000000000000000..1ea1c85b71008991e796fef551685e9cfe46e2e0 --- /dev/null +++ b/pool/shard000/JavaScript/0005180_app.js @@ -0,0 +1,57 @@ +var partner, lefts, i$, ref$, len$, i, right; +partner = require('../../lib/partner'); +lefts = []; +for (i$ = 0, len$ = (ref$ = [1, 2, 3, 4, 5]).length; i$ < len$; ++i$) { + i = ref$[i$]; + lefts.push(partner.create("file://" + __dirname + "/left.js", 'left')); +} +right = partner.create("file://" + __dirname + "/right.js", 'right'); +partner.on('start', function(data, master){ + var i$, ref$, len$, index, item, strategies, strategy, request, i; + for (i$ = 0, len$ = (ref$ = lefts).length; i$ < len$; ++i$) { + index = i$; + item = ref$[i$]; + item.start(index); + } + right.start(); + return; + strategies = [ + { + name: 'first', + describe: "Request with first strategy" + }, { + name: 'last', + describe: "Request with last strategy" + }, { + name: 'random', + describe: "Request with random strategy" + }, { + name: 'next', + describe: "Request with next strategy" + }, { + name: 2, + describe: "Request with specify index" + } + ]; + strategy = strategies[3]; + console.log(strategy.describe); + request = partner.select('left', strategy.name); + for (i$ = 0, len$ = (ref$ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).length; i$ < len$; ++i$) { + i = ref$[i$]; + request.request('Multiple', { + first: 100, + second: 2 + }, fn$); + } + function fn$(error, data, message){ + console.log("------------------------------"); + if (error != null) { + return console.error("Got error: ", error); + } + console.log(JSON.stringify({ + message: message, + data: data + }) + ""); + } +}); +partner.start(); diff --git a/pool/shard000/JavaScript/0005184_custom_event_support.js b/pool/shard000/JavaScript/0005184_custom_event_support.js new file mode 100644 index 0000000000000000000000000000000000000000..fb27837124e30c46b2d2c1a69cebc54684cbab71 --- /dev/null +++ b/pool/shard000/JavaScript/0005184_custom_event_support.js @@ -0,0 +1,228 @@ +Module('CustomEventSupport')({ + + eventListeners : null, + + bind : function(type, eventHandler) { + if (console && console.warn) { + console.warn('bind is deprecated, use addEventListener instead.'); + } + + return CustomEventSupport.addEventListener(type, eventHandler); + }, + + unbind : function(type, eventHandler) { + if (console && console.warn) { + console.warn('unbind is deprecated, use removeEventListener instead.'); + } + + return CustomEventSupport.addEventListener(type, eventHandler); + }, + + dispatch : function(type, eventHandler) { + if (console && console.warn) { + console.warn('dispatch is deprecated, use dispatchEvent instead.'); + } + + return CustomEventSupport.dispatchEvent(type, eventHandler); + }, + + addEventListener : function(type, eventHandler) { + var found, i, listeners; + + if(!this.eventListeners) { + this.eventListeners = {}; + } + + if(!this.eventListeners[type]) { + this.eventListeners[type] = []; + } + + found = false; + + listeners = this.eventListeners[type]; + for (i = 0; i < listeners.length; i++) { + if (listeners[i] === eventHandler) { + found = true; + break; + } + } + + if(!found) { + this.eventListeners[type].push(eventHandler); + } + + return this; + }, + + removeEventListener : function(type, eventHandler) { + var i, found, listeners; + + found = false; + + if(!this.eventListeners) { + this.eventListeners = {}; + } + + if(typeof eventHandler == 'undefined') { + this.eventListeners[type] = []; + } + + listeners = this.eventListeners[type]; + for (i = 0; i < listeners.length; i++) { + if(listeners[i] === eventHandler) { + found = true; + break; + } + } + + if(found) { + this.eventListeners[type].splice(i, 1); + } + + return this; + }, + + dispatchEvent : function(type, data) { + var event, listeners, instance, i; + + if (this.eventListeners === null) { + this.eventListeners = {}; + } + + if (typeof data === 'undefined') { + data = {}; + } + + if (data.hasOwnProperty('target') === false) { + data.target = this; + } + + event = new CustomEvent(type, data); + listeners = this.eventListeners[type] || []; + instance = this; + + for (i = 0; i < listeners.length; i = i + 1) { + listeners[i].call(instance, event); + if (event.areImmediateHandlersPrevented === true) { + break; + } + } + + return event; + }, + + prototype : { + + eventListeners : null, + + bind : function(type, eventHandler) { + if (console && console.warn) { + console.warn('bind is deprecated, use addEventListener instead.'); + } + + return this.addEventListener(type, eventHandler); + }, + + unbind : function(type, eventHandler) { + if (console && console.warn) { + console.warn('unbind is deprecated, use removeEventListener instead.'); + } + + return this.removeEventListener(type, eventHandler); + }, + + dispatch : function(type, eventHandler) { + if (console && console.warn) { + console.warn('dispatch is deprecated, use dispatchEvent instead.'); + } + + return this.dispatchEvent(type, eventHandler); + }, + + addEventListener : function(type, eventHandler) { + var found, i, listeners; + + if(!this.eventListeners) { + this.eventListeners = {}; + } + + if(!this.eventListeners[type]) { + this.eventListeners[type] = []; + } + + found = false; + + listeners = this.eventListeners[type]; + for (i = 0; i < listeners.length; i++) { + if(listeners[i] === eventHandler) { + found = true; + break; + } + } + + if(!found) { + this.eventListeners[type].push(eventHandler); + } + + return this; + }, + + removeEventListener : function(type, eventHandler) { + var i, found, listeners; + + found = false; + i = 0; + + if(!this.eventListeners) { + this.eventListeners = {}; + } + + if(typeof eventHandler == 'undefined') { + this.eventListeners[type] = []; + } + + listeners = this.eventListeners[type]; + for (i = 0; i < listeners.length; i++) { + if(listeners[i] == eventHandler) { + found = true; + break; + } + } + + if(found) { + this.eventListeners[type].splice(i, 1); + } + + return this; + }, + + dispatchEvent : function(type, data) { + var event, listeners, instance, i; + + if (this.eventListeners === null) { + this.eventListeners = {}; + } + + if (typeof data === 'undefined') { + data = {}; + } + + if (data.hasOwnProperty('target') === false) { + data.target = this; + } + + event = new CustomEvent(type, data); + listeners = this.eventListeners[type] || []; + instance = this; + + for (i = 0; i < listeners.length; i = i + 1) { + listeners[i].call(instance, event); + if (event.areImmediateHandlersPrevented === true) { + break; + } + } + + return event; + } + } +}); diff --git a/pool/shard000/JavaScript/0005185_index.js b/pool/shard000/JavaScript/0005185_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4c4aeb493682d90e2bed28fd25d92b9cf85e1503 --- /dev/null +++ b/pool/shard000/JavaScript/0005185_index.js @@ -0,0 +1,17 @@ +var expect = require('chai').expect, + authTest = require('./auth.js'), + usersTest = require('./users.js'), + rolesTest = require('./roles.js'), + testData = { + baseURL: process.env.TEST_URL || 'http://localhost:5000' + }; + +describe('Test Suite', function() { + this.timeout(5000); + + authTest(testData); + + usersTest(testData); + + rolesTest(testData); +}); diff --git a/pool/shard000/JavaScript/0005188_header.ng.controller.js b/pool/shard000/JavaScript/0005188_header.ng.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..5e3fb3dde062c9e7b51fc15f24c046cc558dd25d --- /dev/null +++ b/pool/shard000/JavaScript/0005188_header.ng.controller.js @@ -0,0 +1,18 @@ +(function() { + 'use strict'; + + angular + + .module("myPick10") + + .controller('myHeaderController', myHeaderController); + + myHeaderController.$inject = ['$log', 'appTitle', 'AuthService']; + + function myHeaderController($log, appTitle, AuthService) { + var vm = this; + vm.appTitle = appTitle; + vm.loggedIn = AuthService.isLoggedIn(); + vm.player = AuthService.getUserData(); + } +})(); diff --git a/pool/shard000/JavaScript/0005189_main.js b/pool/shard000/JavaScript/0005189_main.js new file mode 100644 index 0000000000000000000000000000000000000000..ed62fdfb88ecdd1253a1c746cb58485d42ce6029 --- /dev/null +++ b/pool/shard000/JavaScript/0005189_main.js @@ -0,0 +1,169 @@ +axios.defaults.baseURL = 'http://127.0.0.1:8088'; +axios.defaults.headers.common['Authorization'] = "abcdefghijl"; +axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; +Vue.prototype.$http = axios + +var app = new Vue({ + + el: '#app', + data: { + message: 'Hello Vue!', + debitAccount: "", + debitEntry: "", + creditAccount: "", + creditEntry: "", + amount: 0, + datetime: '', + counter: '无', + accounts: [], + entries: [], + + // + firstEntry: "", + secondEntry: "", + thirdEntry: "", + // firstEntries: [], + // secondEntries: [], + // thirdEntries: [], + date: "", + time: "" + }, + computed: { + + firstEntries: function () { + console.log("computed firstEntries, entries: " + "") + console.log(this.debitAccount) + var that = this + var t = this.accounts.filter(function (a) { + console.log(a.Id + " " + that.debitAccount) + return a.Id == that.debitAccount + })[0]; + console.log(t) + var ts = this.entries.filter(function (entry) { + console.log(entry.ParentLvl.Int64) + return entry.Id == (t ? t.EntryId : undefined) + }); + console.log("computed firstEntries: " + ts) + this.firstEntry="" + return ts + }, + secondEntries: function () { + console.log("computed secondEntries, firstEntries: " + this.firstEntry) + + + var firstEntry = this.firstEntry + var ts = this.entries.filter(function (entry) { + return entry.ParentLvl.Int64 == firstEntry + }); + console.log("computed secondEntries, firstEntries: " + firstEntry + ", result: " + ts) + this.secondEntry="" + + return ts + }, + thirdEntries: function () { + console.log("computed thirdEntries, secondEntries: " + this.secondEntry) + var _this = this + return this.entries.filter(function (entry) { + return entry.ParentLvl.Int64 == _this.secondEntry + }) + this.thirdEntry="" + } + }, + created: function () { + console.log("created start") + + console.log("created end") + }, + mounted: function () { + this.$nextTick(function () { + that = this + this.$http.get('/accounts').then(function (res) { + console.log("accounts: " + res.data) + that.accounts = res.data; + }) + this.$http.get('/entries').then(function (res) { + console.log("all entries: ", res.data) + that.entries = res.data; + }) + }) + }, + watch: { + /** + * On update of options-prop, recreate element + */ + // 'options': function() { + // console.log("options watch") + // this.create(); + // }, + options: { + handler: function (val, oldVal) { + this.create(); // call it in the context of your component object + }, + deep: true + } + }, + methods: { + + clear: function () { + var el = this.$el; + $(el).select2('val', ''); + }, + create: function () { + // var el = this.$el; + // $(el).select2().on('change', function(e) { + // this.$set('val', $(el).select2('data').map(function(d) { return { value: d.id, text: d.text } })); + // }.bind(this)); + console.log("create") + }, + submit: function () { + const postData = { + debitAccount: this.debitAccount, + debitEntry: this.debitEntry, + creditAccount: this.creditAccount, + creditEntry: this.creditEntry, + amount: Number(this.amount), + datetime: this.date + " " + this.time + ":00", + counter: this.counter, + } + this.$http.post("/createRecord", postData).then(function (res) { + if (res.status === 200) { + console.log(res.data) + alert("保存成功") + } else { + alert("保存失败") + } + }).catch(function (response) { + console.log(response); + alert("保存失败") + }); + ; + }, + // changeEntry: function (name) { + // console.log(name) + // that = this + // if (name === 2) { + // this.$http.get("/entries/" + this.firstEntry).then(function (res) { + // if (res.status === 200) { + // console.log(res.data) + // that.secondEntries = res.data + // } else { + // } + // }).catch(function (response) { + // console.log(response); + // }); + // } else if (name == 3) { + // this.$http.get("/entries/" + this.secondEntry).then(function (res) { + // if (res.status === 200) { + // console.log(res.data) + // that.thirdEntries = res.data + // + // } else { + // } + // }).catch(function (response) { + // console.log(response); + // }); + // } + // console.log("changeEntry ") + // } + } +}) diff --git a/pool/shard000/JavaScript/0005190_boilerplate.js b/pool/shard000/JavaScript/0005190_boilerplate.js new file mode 100644 index 0000000000000000000000000000000000000000..f430da54bc25026e515c2673326c3fd59d397742 --- /dev/null +++ b/pool/shard000/JavaScript/0005190_boilerplate.js @@ -0,0 +1,257 @@ +const options = require('./options') +const { merge, pipe, assoc, omit, __ } = require('ramda') +const { getReactNativeVersion } = require('./lib/react-native-version') + +/** + * Is Android installed? + * + * $ANDROID_HOME/tools folder has to exist. + * + * @param {*} context - The gluegun context. + * @returns {boolean} + */ +const isAndroidInstalled = function (context) { + const androidHome = process.env['ANDROID_HOME'] + const hasAndroidEnv = !context.strings.isBlank(androidHome) + const hasAndroid = hasAndroidEnv && context.filesystem.exists(`${androidHome}/tools`) === 'dir' + + return Boolean(hasAndroid) +} + +/** + * Let's install. + * + * @param {any} context - The gluegun context. + */ +async function install (context) { + const { + filesystem, + parameters, + ignite, + reactNative, + print, + system, + prompt, + template + } = context + const { colors } = print + const { red, yellow, bold, gray, blue } = colors + + const perfStart = (new Date()).getTime() + + const name = parameters.third + const spinner = print + .spin(`using the ${red('Infinite Red')} boilerplate v2 (code name 'Andross')`) + .succeed() + + // attempt to install React Native or die trying + const rnInstall = await reactNative.install({ + name, + version: getReactNativeVersion(context) + }) + if (rnInstall.exitCode > 0) process.exit(rnInstall.exitCode) + + // remove the __tests__ directory and App.js that come with React Native + filesystem.remove('__tests__') + filesystem.remove('App.js') + + // copy our App, Tests & storybook directories + spinner.text = '▸ copying files' + spinner.start() + filesystem.copy(`${__dirname}/boilerplate/App`, `${process.cwd()}/App`, { + overwrite: true, + matching: '!*.ejs' + }) + filesystem.copy(`${__dirname}/boilerplate/Tests`, `${process.cwd()}/Tests`, { + overwrite: true, + matching: '!*.ejs' + }) + filesystem.copy(`${__dirname}/boilerplate/storybook`, `${process.cwd()}/storybook`, { + overwrite: true, + matching: '!*.ejs' + }) + spinner.stop() + + // --max, --min, interactive + let answers + if (parameters.options.max) { + answers = options.answers.max + } else if (parameters.options.min) { + answers = options.answers.min + } else { + answers = await prompt.ask(options.questions) + } + + // generate some templates + spinner.text = '▸ generating files' + const templates = [ + { template: 'index.js.ejs', target: 'index.js' }, + { template: 'README.md', target: 'README.md' }, + { template: 'ignite.json.ejs', target: 'ignite/ignite.json' }, + { template: '.editorconfig', target: '.editorconfig' }, + { template: '.babelrc', target: '.babelrc' }, + { template: 'Tests/Setup.js.ejs', target: 'Tests/Setup.js' }, + { template: 'storybook/storybook.ejs', target: 'storybook/storybook.js' }, + { template: '.env.example', target: '.env.example' } + ] + const templateProps = { + name, + igniteVersion: ignite.version, + reactNativeVersion: rnInstall.version, + vectorIcons: answers['vector-icons'], + animatable: answers['animatable'], + i18n: answers['i18n'] + } + await ignite.copyBatch(context, templates, templateProps, { + quiet: true, + directory: `${ignite.ignitePluginPath()}/boilerplate` + }) + + /** + * Append to files + */ + // https://github.com/facebook/react-native/issues/12724 + filesystem.appendAsync('.gitattributes', '*.bat text eol=crlf') + filesystem.append('.gitignore', '\n# Misc\n#') + filesystem.append('.gitignore', '\n.env.example\n') + filesystem.append('.gitignore', '.env\n') + + /** + * Merge the package.json from our template into the one provided from react-native init. + */ + async function mergePackageJsons () { + // transform our package.json in case we need to replace variables + const rawJson = await template.generate({ + directory: `${ignite.ignitePluginPath()}/boilerplate`, + template: 'package.json.ejs', + props: templateProps + }) + const newPackageJson = JSON.parse(rawJson) + + // read in the react-native created package.json + const currentPackage = filesystem.read('package.json', 'json') + + // deep merge, lol + const newPackage = pipe( + assoc( + 'dependencies', + merge(currentPackage.dependencies, newPackageJson.dependencies) + ), + assoc( + 'devDependencies', + merge(currentPackage.devDependencies, newPackageJson.devDependencies) + ), + assoc('scripts', merge(currentPackage.scripts, newPackageJson.scripts)), + merge( + __, + omit(['dependencies', 'devDependencies', 'scripts'], newPackageJson) + ) + )(currentPackage) + + // write this out + filesystem.write('package.json', newPackage, { jsonIndent: 2 }) + } + await mergePackageJsons() + + spinner.stop() + + // react native link -- must use spawn & stdio: ignore or it hangs!! :( + spinner.text = `▸ linking native libraries` + spinner.start() + await system.spawn('react-native link', { stdio: 'ignore' }) + spinner.stop() + + // pass long the debug flag if we're running in that mode + const debugFlag = parameters.options.debug ? '--debug' : '' + + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + // NOTE(steve): I'm re-adding this here because boilerplates now hold permanent files + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + try { + // boilerplate adds itself to get plugin.js/generators etc + // Could be directory, npm@version, or just npm name. Default to passed in values + const boilerplate = parameters.options.b || parameters.options.boilerplate || 'ignite-ir-boilerplate' + + await system.spawn(`ignite add ${boilerplate} ${debugFlag}`, { stdio: 'inherit' }) + + // now run install of Ignite Plugins + if (answers['dev-screens'] === 'Yes') { + await system.spawn(`ignite add dev-screens@"~>2.2.0" ${debugFlag}`, { + stdio: 'inherit' + }) + } + + if (answers['vector-icons'] === 'react-native-vector-icons') { + await system.spawn(`ignite add vector-icons@"~>1.0.0" ${debugFlag}`, { + stdio: 'inherit' + }) + } + + if (answers['i18n'] === 'react-native-i18n') { + await system.spawn(`ignite add i18n@"~>1.0.0" ${debugFlag}`, { stdio: 'inherit' }) + } + + if (answers['animatable'] === 'react-native-animatable') { + await system.spawn(`ignite add animatable@"~>1.0.0" ${debugFlag}`, { + stdio: 'inherit' + }) + } + + if (answers['redux-persist'] === 'Yes') { + await system.spawn(`ignite add redux-persist@"~>0.0.7" ${debugFlag}`, { + stdio: 'inherit' + }) + } + + if (parameters.options.lint !== 'false') { + await system.spawn(`ignite add standard@"~>1.0.0" ${debugFlag}`, { + stdio: 'inherit' + }) + } + } catch (e) { + ignite.log(e) + throw e + } + + // git configuration + const gitExists = await filesystem.exists('./.git') + if (!gitExists && !parameters.options['skip-git'] && system.which('git')) { + // initial git + const spinner = print.spin('configuring git') + + // TODO: Make husky hooks optional + const huskyCmd = '' // `&& node node_modules/husky/bin/install .` + system.run(`git init . && git add . && git commit -m "Initial commit." ${huskyCmd}`) + + spinner.succeed(`configured git`) + } + + const perfDuration = parseInt(((new Date()).getTime() - perfStart) / 10) / 100 + spinner.succeed(`ignited ${yellow(name)} in ${perfDuration}s`) + + const androidInfo = isAndroidInstalled(context) ? '' + : `\n\nTo run in Android, make sure you've followed the latest react-native setup instructions at https://facebook.github.io/react-native/docs/getting-started.html before using ignite.\nYou won't be able to run ${bold('react-native run-android')} successfully until you have.` + + const successMessage = ` + ${red('Ignite CLI')} ignited ${yellow(name)} in ${gray(`${perfDuration}s`)} + + To get started: + + cd ${name} + react-native run-ios + react-native run-android${androidInfo} + ignite --help + + ${gray('Read the walkthrough at https://github.com/infinitered/ignite-ir-boilerplate/blob/master/readme.md#boilerplate-walkthrough')} + + ${blue('Need additional help? Join our Slack community at http://community.infinite.red.')} + + ${bold('Now get cooking! 🍽')} + ` + + print.info(successMessage) +} + +module.exports = { + install +} diff --git a/pool/shard000/JavaScript/0005192_test-error.js b/pool/shard000/JavaScript/0005192_test-error.js new file mode 100644 index 0000000000000000000000000000000000000000..1eddfd685c4aaf2e1563ff0063c1b958dce5b288 --- /dev/null +++ b/pool/shard000/JavaScript/0005192_test-error.js @@ -0,0 +1,86 @@ +const assert = require('assert'); +const utils = require('./utils'); +const proxy = require(`../${process.env.TEST_DIR || 'lib'}`); +const pr = require(`../${process.env.TEST_DIR || 'lib'}/post-response`); + +const oldInitResponseProps = pr.initResponseProps; + + +describe('proxy-request error', function () { + it('modifyResponse is not function throw error', function () { + assert.throws(() => { + proxy({headers: {}, connection: {}}, {modifyResponse: 1}) + }, proxy.ProxyRequestError); + }); + + it('promise reject when modifyResponse throw error', function (done) { + utils.test(function(req, res) { + proxy(req, { + url: `http://localhost:${this.upstream.port}`, + modifyResponse() { + throw new Error('test'); + } + }, res) + .catch(err => { + assert.ok(!!err.proxyInfo.headers); + assert.ok(!!err.proxyInfo.resHeaders); + assert.equal(err.proxyInfo.resStatus, 200); + assert.deepEqual(err.proxyInfo.resBody, {success: true}); + assert.ok(err instanceof proxy.ProxyRequestError); + assert.equal(err.message, 'proxy options.modifyResponse error'); + res.end('handle error'); + }); + }, function() { + const ctx = this; + utils.get.call(ctx, null, function() { + done(); + }); + }); + }); + + it('promise reject when options.onResponse error', function (done) { + utils.test(function(req, res) { + proxy(req, { + url: `http://localhost:${this.upstream.port}`, + onResponse() { + throw new Error('test response'); + } + }) + .catch(err => { + assert.ok(err instanceof proxy.ProxyRequestError); + res.end('handle error'); + }) + }, function() { + const ctx = this; + utils.get.call(ctx, null, function() { + done(); + }); + }); + }); + + it('catch _onResponse error', function (done) { + pr.initResponseProps = function () { + throw new Error('testabc'); + } + + utils.test(function(req, res) { + proxy(req, { + url: `http://localhost:${this.upstream.port}`, + onResponse() { + throw new Error('test response'); + } + }) + .catch(err => { + assert.ok(err instanceof proxy.ProxyRequestError); + assert.ok(err.stack.indexOf('testabc') > -1); + res.end('handle error'); + }) + }, function() { + const ctx = this; + utils.get.call(ctx, null, function() { + pr.initResponseProps = oldInitResponseProps; + done(); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005195_index.js b/pool/shard000/JavaScript/0005195_index.js new file mode 100644 index 0000000000000000000000000000000000000000..21c6ff7937cfb04c8884734e2b4e47a4334f8bbf --- /dev/null +++ b/pool/shard000/JavaScript/0005195_index.js @@ -0,0 +1,117 @@ +'use strict'; + +var http = require('http'); +var fs = require('fs'); +var inspect = require('util').inspect; +var path = require('path'); +var browserify = require('browserify'); +var glob = require('glob'); +var istanbulTransform = require('browserify-istanbul'); +var JSONStream = require('jsonstream2'); +var istanbul = require('istanbul'); + +var runPhantom = require('./lib/run-phantom.js') +var html = fs.readFileSync(__dirname + '/lib/test-page.html', 'utf8'); + +module.exports = createServer; +module.exports.runPhantom = runPhantom; +module.exports.createHandler = createHandler; +module.exports.handles = handles; + +function createServer(filename, reports, phantom) { + var handler = createHandler(filename, reports, phantom); + return http.createServer(handler); +} + +function instrumentTransform() { + return istanbulTransform({ + ignore: [ + '**/node_modules/**', + '**/test/**', + '**/tests/**', + '**/run-browser/**' + ], + defaultIgnore: true + }); +} + +function handleError(err, res) { + var e = JSON.stringify(err.toString()); + res.end('document.getElementById("__testling_output").textContent = ' + + e + ';console.error(' + e + ');'); + if (err) console.error(err.stack || err.message || err); +} + +function createHandler(filename, reports, phantom) { + + if (typeof reports === 'boolean' && reports) reports = [ 'text' ]; + else if (typeof reports === 'string') reports = [ reports ]; + + if (reports && !Array.isArray(reports)) return new Error('Invalid reports type' + reports); + + return function (req, res) { + if (req.url === '/') { + res.setHeader('Content-Type', 'text/html'); + return res.end(html); + } + if ('/tests-bundle.js' === req.url) { + var sent = false; + res.setHeader('Content-Type', 'application/javascript'); + return glob(filename, function (err, files) { + if (err || files.length === 0) { + err = err || new Error('No files found matching ' + inspect(filename)); + return handleError(err, res); + } + files = files.map(normalizePath); + files.unshift(path.join(__dirname, '/lib/override-log.js')); + + if (phantom) { + files.unshift(path.join(__dirname, '/lib/phantom-function-bind-shim.js')); + } + + var b = browserify(files); + if (reports) b.transform(instrumentTransform()); + return b.bundle({debug: true}, onBrowserifySrc) + + function onBrowserifySrc(err, src) { + if (sent) return; + sent = true; + return err ? handleError(err, res) : res.end(src); + } + + function normalizePath(p) { + return path.resolve(p); + } + }); + } + if ('/results' === req.url && req.method === 'POST') { + return req.pipe(JSONStream.parse('*')).once('data', function (results) { + + if (results.coverage) { + var collector = new istanbul.Collector(); + var reporter = new istanbul.Reporter(); + var sync = false; + collector.add(results.coverage); + reporter.addAll(reports); + reporter.write(collector, sync, done); + } + else { + done(); + } + + function done(err) { + res.statusCode === 200; + res.end('OK'); + var passed = results.tap.fail.length === 0; + if (phantom) process.exit(passed ? 0 : 1); + } + }) + } + res.statusCode = 404; + res.end('404: Path not found'); + } +} + +function handles(req) { + return req.url === '/' || req.url === '/tests-bundle.js'; +} diff --git a/pool/shard000/JavaScript/0005199_send.js b/pool/shard000/JavaScript/0005199_send.js new file mode 100644 index 0000000000000000000000000000000000000000..14bdb948849bd005c896979c9a092de4987604a8 --- /dev/null +++ b/pool/shard000/JavaScript/0005199_send.js @@ -0,0 +1,89 @@ +'use strict'; + +const etag = require('etag') + , getCompression = require('./getCompression') + , zlib = require('zlib') + , brotli = require('iltorb') + , tools = require('./tools') + , not = tools.not + , isDefined = tools.isDefined + , encoding = 'utf-8' + + , etagMatch = (ifNoneMatch, etagIn) => { + return isDefined(ifNoneMatch) && ifNoneMatch === etagIn; + } + + , setContentTypeHeaders = (data, isBuffer, response) => { + const type = typeof data; + + if (type === 'undefined') { + response.setHeader('Content-Type', `text/plain; charset=${encoding}`); + } else if (type === 'string') { + response.setHeader('Content-Type', `text/html; charset=${encoding}`); + } else if (type === 'object' && not(isBuffer)) { + response.setHeader('Content-Type', `application/json; charset=${encoding}`); + } else if (type === 'object') { + response.setHeader('Content-Type', `text/html; charset=${encoding}`); + } + + return response; + } + + , prepareData = (data, isBuffer) => { + const type = typeof data; + + if (type === 'undefined') { + return ''; + } else if (type === 'object' && isBuffer) { + return data.toString(); + } else if (type === 'string') { + return data; + } else { + return JSON.stringify(data); + } + } + + , setCompressionHeader = (compression, response) => { + if (compression !== 'none') { + response.setHeader('Content-Encoding', compression); + } + } + + , send = (req, config) => { + return function (dataIn) { + // eslint-disable-next-line no-invalid-this + const that = this + , isBuffer = Buffer.isBuffer(dataIn) + , compression = getCompression(req.headers['accept-encoding'], config) + , data = prepareData(dataIn, isBuffer) + , reqEtag = etag(data); + + setContentTypeHeaders(dataIn, isBuffer, that); + + if (etagMatch(req.headers['if-none-match'], reqEtag)) { + that.statusCode = 304; + that.end(); + } else { + that.setHeader('ETag', reqEtag); + setCompressionHeader(compression, that); + + if (compression === 'br') { + brotli.compress(new Buffer(data, 'utf8'), (err, output) => { + that.end(output); + }); + } else if (compression === 'gzip') { + zlib.gzip(data, (err, result) => { + that.end(result, encoding); + }); + } else if (compression === 'deflate') { + zlib.deflate(data, (err, result) => { + that.end(result, encoding); + }); + } else { + that.end(data, encoding); + } + } + }; + }; + +module.exports = send; diff --git a/pool/shard000/JavaScript/0005204_infinite-scroll.js b/pool/shard000/JavaScript/0005204_infinite-scroll.js new file mode 100644 index 0000000000000000000000000000000000000000..0bf65751080848f8fba847886cd56e9034828727 --- /dev/null +++ b/pool/shard000/JavaScript/0005204_infinite-scroll.js @@ -0,0 +1,116 @@ +import { Directive, ElementRef, EventEmitter, Host, Input, NgZone, Output } from '@angular/core'; +import { Content } from '../content/content'; +export class InfiniteScroll { + constructor(_content, _zone, _elementRef) { + this._content = _content; + this._zone = _zone; + this._elementRef = _elementRef; + this._lastCheck = 0; + this._highestY = 0; + this._thr = '15%'; + this._thrPx = 0; + this._thrPc = 0.15; + this._init = false; + this.state = STATE_ENABLED; + this.ionInfinite = new EventEmitter(); + _content.setElementClass('has-infinite-scroll', true); + } + get threshold() { + return this._thr; + } + set threshold(val) { + this._thr = val; + if (val.indexOf('%') > -1) { + this._thrPx = 0; + this._thrPc = (parseFloat(val) / 100); + } + else { + this._thrPx = parseFloat(val); + this._thrPc = 0; + } + } + set enabled(shouldEnable) { + this.enable(shouldEnable); + } + _onScroll() { + if (this.state === STATE_LOADING || this.state === STATE_DISABLED) { + return 1; + } + let now = Date.now(); + if (this._lastCheck + 32 > now) { + return 2; + } + this._lastCheck = now; + let infiniteHeight = this._elementRef.nativeElement.scrollHeight; + if (!infiniteHeight) { + return 3; + } + let d = this._content.getContentDimensions(); + let reloadY = d.contentHeight; + if (this._thrPc) { + reloadY += (reloadY * this._thrPc); + } + else { + reloadY += this._thrPx; + } + let distanceFromInfinite = ((d.scrollHeight - infiniteHeight) - d.scrollTop) - reloadY; + if (distanceFromInfinite < 0) { + this._zone.run(() => { + if (this.state !== STATE_LOADING && this.state !== STATE_DISABLED) { + this.state = STATE_LOADING; + this.ionInfinite.emit(this); + } + }); + return 5; + } + return 6; + } + complete() { + this.state = STATE_ENABLED; + } + enable(shouldEnable) { + this.state = (shouldEnable ? STATE_ENABLED : STATE_DISABLED); + this._setListeners(shouldEnable); + } + _setListeners(shouldListen) { + if (this._init) { + if (shouldListen) { + if (!this._scLsn) { + this._zone.runOutsideAngular(() => { + this._scLsn = this._content.addScrollListener(this._onScroll.bind(this)); + }); + } + } + else { + this._scLsn && this._scLsn(); + this._scLsn = null; + } + } + } + ngAfterContentInit() { + this._init = true; + this._setListeners(this.state !== STATE_DISABLED); + } + ngOnDestroy() { + this._setListeners(false); + } +} +InfiniteScroll.decorators = [ + { type: Directive, args: [{ + selector: 'ion-infinite-scroll' + },] }, +]; +InfiniteScroll.ctorParameters = [ + { type: Content, decorators: [{ type: Host },] }, + { type: NgZone, }, + { type: ElementRef, }, +]; +InfiniteScroll.propDecorators = { + 'threshold': [{ type: Input },], + 'enabled': [{ type: Input },], + 'ionInfinite': [{ type: Output },], +}; +const STATE_ENABLED = 'enabled'; +const STATE_DISABLED = 'disabled'; +const STATE_LOADING = 'loading'; +//# sourceMappingURL=infinite-scroll.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005205_buffer-while.js b/pool/shard000/JavaScript/0005205_buffer-while.js new file mode 100644 index 0000000000000000000000000000000000000000..3c4373aeedc12c73d2469871891f7b9fe3115797 --- /dev/null +++ b/pool/shard000/JavaScript/0005205_buffer-while.js @@ -0,0 +1,47 @@ +import {createStream, createProperty} from '../patterns/one-source'; + +const mixin = { + + _init({fn, flushOnEnd}) { + this._fn = fn; + this._flushOnEnd = flushOnEnd; + this._buff = []; + }, + + _free() { + this._buff = null; + }, + + _flush() { + if (this._buff !== null && this._buff.length !== 0) { + this._emitValue(this._buff); + this._buff = []; + } + }, + + _handleValue(x) { + this._buff.push(x); + const fn = this._fn; + if (!fn(x)) { + this._flush(); + } + }, + + _handleEnd() { + if (this._flushOnEnd) { + this._flush(); + } + this._emitEnd(); + } + +}; + +const S = createStream('bufferWhile', mixin); +const P = createProperty('bufferWhile', mixin); + + +const id = x => x; + +export default function bufferWhile(obs, fn, {flushOnEnd = true} = {}) { + return new (obs._ofSameType(S, P))(obs, {fn: fn || id, flushOnEnd}); +} diff --git a/pool/shard000/JavaScript/0005206_bot.js b/pool/shard000/JavaScript/0005206_bot.js new file mode 100644 index 0000000000000000000000000000000000000000..59cff96815bc6afc981d7dff112122b883f6c5aa --- /dev/null +++ b/pool/shard000/JavaScript/0005206_bot.js @@ -0,0 +1,47 @@ + +console.log('The image bot is starting'); + +var Twit = require('twit'); + +var config = require('./config'); + +var T = new Twit(config); + +var exec = require('child_process').exec; +var fs = require('fs'); + +tweetIt(); +setInterval(tweetIt, 3600000); + +function tweetIt() { + var cmd = 'processing-java --sketch=`pwd`/circles --run'; + exec(cmd, processing); + + function processing() { + var filename = 'circles/output.png'; + var params = { + encoding: 'base64' + } + var b64 = fs.readFileSync(filename, params); + + T.post('media/upload', { media_data: b64 }, uploaded); + + function uploaded(err, data, response) { + var id = data.media_id_string; + var tweet = { + status: '#Weingart cirlces #processing live from #node every hour', + media_ids: [id] + } + T.post('statuses/update', tweet, tweeted); + + } + + function tweeted(err, data, response) { + if (err) { + console.log("Something went wrong!"); + } else { + console.log("It worked!"); + } + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005211_colors.js b/pool/shard000/JavaScript/0005211_colors.js new file mode 100644 index 0000000000000000000000000000000000000000..332bbae3f4257e9a79f6d8bd55fbef12e3d9f609 --- /dev/null +++ b/pool/shard000/JavaScript/0005211_colors.js @@ -0,0 +1,18 @@ +var diff = require('../')({ indent : 2 }); + +var prev = { + yy : 6, + zz : 5, + a : [1,2,3], + fn : 'beep', + c : { x : 7, z : 3 } +}; + +var next = { + a : [ 1, 2, "z", /beep/, new Buffer(3) ], + fn : function qqq () {}, + b : [5,6,7], + c : { x : 8, y : 5 } +}; + +diff(prev, next).pipe(process.stdout); diff --git a/pool/shard000/JavaScript/0005214_day-menu-selection-view.js b/pool/shard000/JavaScript/0005214_day-menu-selection-view.js new file mode 100644 index 0000000000000000000000000000000000000000..6cebf25470b2b4fecdbac6e2625326d6fa5d6356 --- /dev/null +++ b/pool/shard000/JavaScript/0005214_day-menu-selection-view.js @@ -0,0 +1,103 @@ +define(function(require, exports, module){ + + var Marionette = require('marionette'), + UserDishCardView = require('userDishCardView'), + UserDishCardEmpty = require('userDishCardEmpty'), + BackboneRadio = require('backboneRadio'), + template = require('hbs!menu/views/templates/day-menu-selection-view'); + + module.exports = Marionette.CompositeView.extend({ + + template: template, + childView: UserDishCardView, + emptyView: UserDishCardEmpty, + childViewContainer: '.js-selected-day-menu', + childEvents:{ + 'dish:removed': 'dishRemoved', + 'quantity:minus': 'quantityUpdated', + 'quantity:plus': 'quantityUpdated' + }, + events: { + 'click .js-button-icon-save-day-menu': 'saveDayMenu' + }, + ui: { + notification: '.js-menu-notification' + }, + initialize: function () { + this.listenTo(this.model, 'change', this.render); + this.notifyScroll(); + }, + notifyScroll: function(){ + $(window).scroll(function() { + var top = $(document).scrollTop(); + if (top > 50) {$('.js-menu-notification').addClass('b-user-menu-notification_fixed');} + else {$('.js-menu-notification').removeClass('b-user-menu-notification_fixed');} + }); + }, + animateNotify: function(){ + var opacity = 1; + + function changeOpacity(){ + opacity = opacity - 0.04; + $('.js-menu-notification').css('opacity',opacity); + if (opacity < 0){ + clearInterval(timer); + $('.js-menu-notification').css('display','none'); + } + } + var timer = setInterval(changeOpacity,20); + }, + notifyParam: function(notification){ + this.model = new Backbone.Model (notification); + this.updateSummary(); + this.render(); + this.ui.notification.addClass('b-menu-notification_green').css('display','block'); + if ($(document).scrollTop() > 50) $('.js-menu-notification').addClass('b-user-menu-notification_fixed'); + setTimeout(this.animateNotify,5000); + + }, + onRender: function(){ + this.userChannel = BackboneRadio.channel('user'); + this.userChannel.on('notification:add', function(notification) { + //debugger; + console.log(notification); + if (notification.type.toLowerCase() === 'put'){ + notification.type = 'Your day menu successfully updated!'; + this.notifyParam(notification); + } + else if (notification.type === 'GET'){} + + }.bind(this) + + ); + + }, + onDestroy: function () { + this.userChannel.reset(); + }, + saveDayMenu: function () { + this.trigger('user:day:menu:saved',this.collection); + }, + dishRemoved: function (view, model) { + this.collection.remove(model); + this.updateSummary(); + this.trigger('day:menu:dish:removed', model); + }, + quantityUpdated: function (view) { + //debugger; + this.updateSummary(); + }, + setModel: function (model) { + this.listenTo(this.model, 'change', this.render); + //this.model.set('summary', model.get('summary')); + }, + updateSummary: function () { + this.model.set('summary', this.collection.calculateSummary()); + this.render(); + } + + /*initialize: function () { + this.model.set('summary', this.collection.getSu + }*/ + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005216_tracker.js b/pool/shard000/JavaScript/0005216_tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..b2a3bdbfee8f053a2fb97fdb9920e2cf89c68135 --- /dev/null +++ b/pool/shard000/JavaScript/0005216_tracker.js @@ -0,0 +1,69 @@ +import * as $ from 'jquery'; +(function (global) { + var $tracker = $('#uploadTracker'), + $progress = $tracker.find('.progress .progress-bar'), + $textBlock = $tracker.find('#uploadProgress'), + $performance = $tracker.find('#uploadPerformance'), + firstTime = true; + + function updateProgress(incoming) { + if (incoming.total === 0) { + return; + } + + if (incoming.total < 0) { + $textBlock.text('Uploading ...'); + $performance.text('(unable to determine speed)'); + return; + } + + var percent = incoming.percent, + currentkb = Math.round(incoming.current / 1024), + totalkb = Math.round(incoming.total / 1024); + + $progress + .css('width', percent + '%') + .find('.sr-only').text(percent + '%'); + + $textBlock + .text('Uploading ' + currentkb + '/' + totalkb + ' KB (' + percent + '%)'); + + $performance.text(incoming.performance); + } + + function isTrackerRemoved() { + return $tracker.closest('body').length === 0; + } + + function triggerAjax() { + if (isTrackerRemoved()) { + return; + } + + $.getJSON(global.scriptparams.uploadApi, {}) + .done(function(data) { + if (firstTime) { + $progress.stop(); + + firstTime = false; + } + + updateProgress(data); + + global.setTimeout(triggerAjax, 250); + }) + .fail(function() { + if (firstTime) { + $textBlock.text('Waiting for progress information...'); + + $progress.animate({ width: '0%' }, 100); + } else { + $textBlock.text('Error updating progress...'); + } + + global.setTimeout(triggerAjax, 1000); + }); + } + + triggerAjax(); +})(window); diff --git a/pool/shard000/JavaScript/0005219_index.js b/pool/shard000/JavaScript/0005219_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d9fbae1e7c13b001985ab65d82125efa8ce847f --- /dev/null +++ b/pool/shard000/JavaScript/0005219_index.js @@ -0,0 +1,52 @@ +'use strict'; + +var _ = require('lodash'); + +var functions = { + insert: require('./lib/insert'), + insertBulk: require('./lib/insertBulk'), + update: require('./lib/update'), + updateRelatedRecords: require('./lib/updateRelatedRecords'), + updateBulk: require('./lib/updateBulk'), + getBulkById: require('./lib/getBulkById'), + getBulkUpdatedAfter: require('./lib/getBulkUpdatedAfter'), + getBulkByValueIn: require('./lib/getBulkByValueIn'), + getByCriteria: require('./lib/getByCriteria') +}; + +/** + * Construct an object with functions plugged with authToken + * @param {string} authToken + * @returns {Object} + */ +module.exports = function (authToken) { + authToken = authToken || ''; + + return _.mapValues(functions, function (f) { + return f.bind(null, authToken); + }); +}; + +/** + * Construct an object with stubbed functions, or noop if not provided. + * Each function will also be plugged with authToken. + * Useful for testing (stub zohorde, pass the zohorde object to the function to be tested) + * @param {string} authToken + * @param {Object} stubObj - Object with key = function name and value = stub function + * @returns {Object} + */ +module.exports.asStub = function (authToken, stubObj) { + authToken = authToken || ''; + stubObj = stubObj || {}; + + return _.mapValues(functions, function substituteWithStub(originalFunction, functionName) { + var stubbedFunction = stubObj[functionName]; + + // If not exist, use _.noop + if (!_.isFunction(stubbedFunction)) { + return _.noop; + } + + return stubbedFunction.bind(null, authToken); + }); +}; diff --git a/pool/shard000/JavaScript/0005222_Document.js b/pool/shard000/JavaScript/0005222_Document.js new file mode 100644 index 0000000000000000000000000000000000000000..d7c697c597fb1bd1e8e8e2de32532dea06973629 --- /dev/null +++ b/pool/shard000/JavaScript/0005222_Document.js @@ -0,0 +1,41 @@ +var mongoose = include('/node_modules/oils/node_modules/mongoose'); +var Schema = mongoose.Schema; +module.exports = { + name: 'oils.dms.Document', + + + schema: { + docType: {type: String}, + + parentFolderId: {type: Schema.ObjectId, index: true}, + //absolutePath: {type: String, unique: true, index: true} + + name: String, + route: String, + content: Buffer, + + meta: { + lastUpdateDt: {type: Date, default: Date.now}, + lastUpdateBy: {type: String, default: 'SYSTEM'}, + createDt: {type: Date, default: Date.now}, + createBy: {type: String, default: 'SYSTEM'} + }, + + //auto fields + isFolder: Boolean, //need to store for sorting, type == 'Folder' + lowerCaseName: {type: String, lowercase: true}, + }, + + options: { + strict: false + }, + + initSchema: function(schema){ + schema.index({parentFolderId: 1, lowerCaseName: 1}, {unique: true}); + schema.pre('save', function(next) { + this.isFolder = (this.docType == 'Folder'); + this.lowerCaseName = this.name.toLowerCase(); + next(); + }) + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005223_stringUtil.js b/pool/shard000/JavaScript/0005223_stringUtil.js new file mode 100644 index 0000000000000000000000000000000000000000..e6e6ee5c97a939234d671211ca758bbd75022756 --- /dev/null +++ b/pool/shard000/JavaScript/0005223_stringUtil.js @@ -0,0 +1,105 @@ +'use strict'; + +const chai = require('chai'); +const chaiAsPromised = require('chai-as-promised'); +const sinon = require('sinon'); + +chai.use(chaiAsPromised); +const expect = chai.expect; + +const StringUtil = require('../src/utils/stringUtil'); + + +describe('StringUtil', () => { + + describe('replaceAll', () => { + + it('should replace string', () => { + let str = 'hello world this is my first hello world', + find = 'world', + replace ='test', + expectedResult = 'hello test this is my first hello test'; + + let result = StringUtil.replaceAll(str, find, replace); + + expect(result).to.be.eql(expectedResult); + }); + + it('should return empty string', () => { + let str = '', + find = 'world', + replace ='test', + expectedResult = ''; + + let result = StringUtil.replaceAll(str, find, replace); + + expect(result).to.be.eql(expectedResult); + }); + + it('should return original string if there is no string to find', () => { + let str = 'hello world this is my first hello world', + find = null, + replace ='test', + expectedResult = str; + + let result = StringUtil.replaceAll(str, find, replace); + + expect(result).to.be.eql(expectedResult); + }); + + it('should return original string if there is no string to replace', () => { + let str = 'hello world this is my first hello world', + find = 'world', + replace = null, + expectedResult = str; + + let result = StringUtil.replaceAll(str, find, replace); + + expect(result).to.be.eql(expectedResult); + }); + + }); + + + + describe('pad', () => { + + it('should add 0 to string', () => { + let originalString = '1', + width = 3, + numberToAdd = 0, + expectedResult = '001'; + + let result = StringUtil.pad(originalString, width, numberToAdd); + + expect(result).to.be.eql(expectedResult); + }); + + it('should return the original string', () => { + let originalString = '1', + width = 0, + numberToAdd = 0, + expectedResult = originalString; + + let result = StringUtil.pad(originalString, width, numberToAdd); + + expect(result).to.be.eql(expectedResult); + }); + + it('should return null if the original string is null', () => { + let originalString = null, + width = 0, + numberToAdd = 0, + expectedResult = originalString; + + let result = StringUtil.pad(originalString, width, numberToAdd); + + expect(result).to.be.eql(expectedResult); + }); + + + + }); + + +}); diff --git a/pool/shard000/JavaScript/0005232_binary_heap.js b/pool/shard000/JavaScript/0005232_binary_heap.js new file mode 100644 index 0000000000000000000000000000000000000000..c3ec53e16bd1ac1421087eefe50b594ecfe26d24 --- /dev/null +++ b/pool/shard000/JavaScript/0005232_binary_heap.js @@ -0,0 +1,161 @@ +// From http://eloquentjavascript.net/appendix2.html, +// licensed under CCv3.0: http://creativecommons.org/licenses/by/3.0/ +var ozpIwc = ozpIwc || {}; +ozpIwc.metric = ozpIwc.metric || {}; +ozpIwc.metric.stats = ozpIwc.metric.stats || {}; + +/** + * Statistics classes for the ozpIwc Metrics + * @module ozpIwc.metric + * @submodule ozpIwc.metric.stats + */ + +ozpIwc.metric.stats.BinaryHeap = (function () { + /** + * This acts as a ordered binary heap for any serializeable JS object or collection of such objects + * <p>Borrowed from https://github.com/mikejihbe/metrics. Originally from from + * http://eloquentjavascript.net/appendix2.html + * <p>Licenced under CCv3.0 + * + * @class BinaryHeap + * @namespace ozpIwc.metric.stats + * @param {Function} scoreFunction + * @return {ozpIwc.metric.stats.BinaryHeap} + */ + var BinaryHeap = function BinaryHeap(scoreFunction) { + this.content = []; + this.scoreFunction = scoreFunction; + }; + + BinaryHeap.prototype = { + + clone: function () { + var heap = new BinaryHeap(this.scoreFunction); + // A little hacky, but effective. + heap.content = JSON.parse(JSON.stringify(this.content)); + return heap; + }, + + push: function (element) { + // Add the new element to the end of the array. + this.content.push(element); + // Allow it to bubble up. + this.bubbleUp(this.content.length - 1); + }, + + peek: function () { + return this.content[0]; + }, + + pop: function () { + // Store the first element so we can return it later. + var result = this.content[0]; + // Get the element at the end of the array. + var end = this.content.pop(); + // If there are any elements left, put the end element at the + // start, and let it sink down. + if (this.content.length > 0) { + this.content[0] = end; + this.sinkDown(0); + } + return result; + }, + + remove: function (node) { + var len = this.content.length; + // To remove a value, we must search through the array to find + // it. + for (var i = 0; i < len; i++) { + if (this.content[i] === node) { + // When it is found, the process seen in 'pop' is repeated + // to fill up the hole. + var end = this.content.pop(); + if (i !== len - 1) { + this.content[i] = end; + if (this.scoreFunction(end) < this.scoreFunction(node)) { + this.bubbleUp(i); + } + else { + this.sinkDown(i); + } + } + return true; + } + } + throw new Error("Node not found."); + }, + + size: function () { + return this.content.length; + }, + + bubbleUp: function (n) { + // Fetch the element that has to be moved. + var element = this.content[n]; + // When at 0, an element can not go up any further. + while (n > 0) { + // Compute the parent element's index, and fetch it. + var parentN = Math.floor((n + 1) / 2) - 1, + parent = this.content[parentN]; + // Swap the elements if the parent is greater. + if (this.scoreFunction(element) < this.scoreFunction(parent)) { + this.content[parentN] = element; + this.content[n] = parent; + // Update 'n' to continue at the new position. + n = parentN; + } + // Found a parent that is less, no need to move it further. + else { + break; + } + } + }, + + sinkDown: function (n) { + // Look up the target element and its score. + var length = this.content.length, + element = this.content[n], + elemScore = this.scoreFunction(element); + + while (true) { + // Compute the indices of the child elements. + var child2N = (n + 1) * 2, child1N = child2N - 1; + // This is used to store the new position of the element, + // if any. + var swap = null; + var child1Score = null; + // If the first child exists (is inside the array)... + if (child1N < length) { + // Look it up and compute its score. + var child1 = this.content[child1N]; + child1Score = this.scoreFunction(child1); + // If the score is less than our element's, we need to swap. + if (child1Score < elemScore) { + swap = child1N; + } + } + // Do the same checks for the other child. + if (child2N < length) { + var child2 = this.content[child2N], + child2Score = this.scoreFunction(child2); + if (child2Score < (swap === null ? elemScore : child1Score)) { + swap = child2N; + } + } + + // If the element needs to be moved, swap it, and continue. + if (swap !== null) { + this.content[n] = this.content[swap]; + this.content[swap] = element; + n = swap; + } + // Otherwise, we are done. + else { + break; + } + } + } + }; + + return BinaryHeap; +}()); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005240_form.js b/pool/shard000/JavaScript/0005240_form.js new file mode 100644 index 0000000000000000000000000000000000000000..07cc38f92493712047c93a59ddacfb5b6dcfad86 --- /dev/null +++ b/pool/shard000/JavaScript/0005240_form.js @@ -0,0 +1,213 @@ +;(function($) { + var _defaults = { + /** + * Automatically submit the form after it is bound + */ + submitOnBind: false, + + /** + * The expected response dataType + */ + dataType: 'json', + + /** + * Called when a valid form is submitted. + * + * Return false to halt further event execution. + */ + onSubmit: $.noop, + + /** + * Called when a form returns a successful response. + * + * Takes one argument: response + * Return false to halt further event execution. + */ + onSuccess: $.noop, + + /** + * Called when a form returns an error response. + * + * Takes three arguments: jqXHR, textStatus, errorThrown + * Return false to halt further event execution. + */ + onError: $.noop, + + /** + * @see jQuery.validate.settings.showErrors + * + * Overrides the default, funky show/hide functionality. + * If using this implementation, highlight and unhighlight are responsible + * for showing and hiding elements, respectively. + */ + showErrors: function() { + var i, elements; + for (i = 0; this.errorList[i]; i++) { + var error = this.errorList[i]; + if (this.settings.highlight) { + this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass); + } + + this.showLabel(error.element, error.message); + } + + if (this.settings.unhighlight) { + for (i = 0, elements = this.validElements(); elements[i]; i++) { + this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass); + } + } + }, + + /** + * @see jQuery.validate.settings.errorPlacement + */ + errorPlacement: function (error, element) { + var $helpBlock = $(element).closest('.form-group').find('.help-block'); + $helpBlock.data('last-text', $helpBlock.html()); + $helpBlock.html(error.text()).show(); + }, + + /** + * @see jQuery.validate.settings.highlight + */ + highlight: function(element, errorClass, validClass) { + var $helpBlock = $(element).closest('.form-group').addClass(errorClass).find('.help-block').show(); + }, + + /** + * @see jQuery.validate.settings.unhighlight + */ + unhighlight: function(element, errorClass, validClass) { + var $helpBlock = $(element).closest('.form-group').removeClass(errorClass).find('.help-block'); + if ($helpBlock.data('last-text')) { + $helpBlock.html($helpBlock.data('last-text')); + } else { + $helpBlock.text('').hide(); + } + }, + + errorClass: 'error has-error', + + validClass: '' + }; + + var _submitHandlerFactory = function(options) { + var _chainHandlers = function(handlerA, handlerB) { + return function() { + if (false !== handlerA.apply(null, arguments)) { + handlerB.apply(null, arguments); + } + }; + }; + + var successHandler = _chainHandlers(options.onSuccess, Orkestra.response.successHandler); + var errorHandler = _chainHandlers(options.onError, Orkestra.response.errorHandler); + + var defaultSubmitHandler = function(form) { + $(form).ajaxSubmit({ + dataType: options.dataType, + success: successHandler, + error: errorHandler + }); + }; + + return _chainHandlers(options.onSubmit, defaultSubmitHandler); + }; + + var _bindEnhancements = function(form) { + var $form = $(form); + + // Date and time pickers + if ($.isFunction($.fn.datetimepicker)) { + $('input.date', $form).each(function (index,elem) { + var data = $(elem).data() || {}; + $(elem).datetimepicker({ + pickTime : false, + format : data['format'] || Orkestra.dateFormat || 'MM/DD/YY' + }); + }); + + $('input.timepicker', $form).each(function (index,elem) { + var data = $(elem).data() || {}; + $(elem).datetimepicker({ + useSeconds : data['useSeconds'] || false, + pickDate : false, + minuteStepping : data['minuteStep'] || 1, + format : data['format'] || Orkestra.timeFormat || 'hh:mm A' + }); + }); + + $('input.datetimepicker', $form).each(function (index,elem) { + var data = $(elem).data() || {}; + $(elem).datetimepicker({ + useSeconds : data['useSeconds'] || false, + format : data['format'] || ((Orkestra.dateFormat && Orkestra.timeFormat) ? (Orkestra.dateFormat + ' ' + Orkestra.timeFormat) : false) || 'MM/DD/YY hh:mm A' + }); + }); + } + + // USA Currency + if ($.isFunction($.fn.formatCurrency)) { + // Currency + $('input.currency', $form).formatCurrency(true); + } + + // USA Telephone + if ($.isFunction($.fn.formatPhoneNumber)) { + // Telephone + $('input.telephone', $form).formatPhoneNumber(); + } + + // USA SSN + if ($.isFunction($.fn.formatSocial)) { + $('input.social', $form).formatSocial(); + } + + // USA EIN + if ($.isFunction($.fn.formatEin)) { + $('input.ein', $form).formatEin(); + } + + // URL + if ($.isFunction($.fn.formatUrl)) { + $('input.url', $form).formatUrl(); + } + + // Integer + if ($.isFunction($.fn.formatNumber)) { + $('input.integer', $form).formatNumber({ + initValue: true + }); + } + }; + + var helper = function() { + + }; + + helper.prototype = $.extend(helper.prototype, { + bind: function(form, options) { + options = $.extend({}, _defaults, options); + + options.submitHandler = options.submitHandler || _submitHandlerFactory(options); + + $(form).data('validator', null).unbind('submit').validate(options); + _bindEnhancements.call(this, form); + + if (true === options.submitOnBind) { + $(function() { + $(form).submit(); + }); + } + }, + + bindEnhancements: _bindEnhancements, + + setDefaults: function(options) { + $.extend(_defaults, options); + } + }); + + window.Orkestra = window.Orkestra || {}; + window.Orkestra.FormHelper = helper; +})(jQuery); diff --git a/pool/shard000/JavaScript/0005241_images-uploader.js b/pool/shard000/JavaScript/0005241_images-uploader.js new file mode 100644 index 0000000000000000000000000000000000000000..ba92e8e41d3cb303abe0fbc546a89677e07e34f3 --- /dev/null +++ b/pool/shard000/JavaScript/0005241_images-uploader.js @@ -0,0 +1,77 @@ ++function(window, $){ + 'use strict'; + + $.fn.imageUploader = function(){ + + this.change(function(){ + var $this = $(this); + var dataTarget = $this.attr('id'); + var images = $this.val().trim().split(','); + var thumberDiv = $('#' + $this.attr('id') + '-thumber' ); + thumberDiv.html(''); + + if(!images.length) + return; + + for(var i=0; i<images.length; i++){ + var image = images[i]; + if(!image) + continue; + + image = image.replace(/\.([a-zA-Z]+)$/, '_242x121.$1'); + $('<div class="thumbnail"></div>') + .append('<a class="btn btn-default btn-xs thumbnail-closer" data-index="'+i+'" title="Delete" data-target="'+dataTarget+'"><i class="glyphicon glyphicon-remove"></i></a>') + .append('<img alt="IMAGE" src="'+image+'">') + .appendTo(thumberDiv); + } + + thumberDiv.find('.thumbnail-closer').click(function(){ + var el = $(this); + var target = $('#' + el.data('target')); + var index = el.data('index'); + var lastVal = target.val().trim().split(','); + lastVal.splice(index,1); + target.val(lastVal.join(',')); + target.change(); + }); + }); + + this.change(); + }; + + $.fn.imageUploaderBtn = function(){ + + this.click(function(){ + var $this = $(this); + var targetId = $this.data('target'); + var target = $('#' + targetId); + var accept = target.data('accept'); + var type = target.data('type'); + var object = target.data('object'); + + $.selectFile(accept, function(file){ + var opts = {'type': type}; + if(object) + opts.object = object; + opts.name = file.name; + + $.uploadFile(file, opts, function(err, res){ + if(err) + return alert(err); + + var lastVal = target.val().trim().split(','); + lastVal.push(res.media_file); + target.val(lastVal.join(',')); + target.change(); + }); + }); + }); + + } + +}(window, jQuery); + +$(function(){ + $('.images-uploader').imageUploader(); + $('.images-uploader-file').imageUploaderBtn(); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005242_simple-popup.js b/pool/shard000/JavaScript/0005242_simple-popup.js new file mode 100644 index 0000000000000000000000000000000000000000..268d9d687b01826845cc6bc8ddf2b090493b24ce --- /dev/null +++ b/pool/shard000/JavaScript/0005242_simple-popup.js @@ -0,0 +1,204 @@ +/*! + * simple-popup.js + * https://github.com/Alex1990/simple-popup + * Under the MIT License | (c) 2015 Alex Chao + */ + +!(function(global, factory) { + + // Uses CommonJS, AMD or browser global to create a jQuery plugin. + // See: https://github.com/umdjs/umd + if (typeof define === 'function' && define.amd) { + // Expose this plugin as an AMD module. Register an anonymous module. + define(['jquery'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS module + module.exports = factory(require('jquery')); + } else { + // Browser globals + factory(global.jQuery, global); + } + +}(this, function($, global) { + + 'use strict'; + + // Shortand + var win = window; + var doc = document; + var docEl = doc.documentElement; + + var defaults = { + width: 500, + height: 400, + offsetX: 0, + offsetY: 0, + zIndex: 999, + closeBtnClass: 'popup-close' + }; + + var extend = function(to, from) { + for (var p in from) { + if (from.hasOwnProperty(p)) { + to[p] = from[p]; + } + } + return to; + }; + + // Get the viewport width. + var winW = function() { + return win.innerWidth || docEl.clientWidth; + }; + + // Get the viewport height. + var winH = function() { + return win.innerHeight || docEl.clientHeight; + }; + + // Get the horizontal scroll offset. + var scrollX = function() { + return win.pageXOffset || docEl.scrollLeft; + }; + + // Get the vertical scroll offset. + var scrollY = function() { + return win.pageYOffset || docEl.scrollTop; + }; + + // Get elements by className. + var byClass = function(cls, el) { + el = el || doc; + if (el.getElementsByClassName) { + return el.getElementsByClassName(cls); + } else { + var ret = []; + var re = new RegExp('^|\\s+' + cls + '\\s+|$'); + var tags = el.getElementsByTagName('*'); + + for (var i = 0, len = tags.length; i < len; i++) { + if (re.test(tags[i].className)) { + ret.push(tags[i]); + } + } + + return ret; + } + }; + + // Cross-brower bind event. + var bind = function(el, type, listener) { + if (el.addEventListener) { + el.addEventListener(type, listener, false); + } else { + el.attachEvent('on' + type, listener); + } + }; + + // Popup constructor. + function Popup(el, opts) { + if (!(this instanceof Popup)) { + return new Popup(el, opts); + } + this.opts = extend({}, extend(defaults, opts)); + this.el = el; + this.init(); + } + + // Instance methods. + extend(Popup.prototype, { + + // Initialize the element's dimension. + init: function() { + var opts = this.opts; + + extend(this.el.style, { + position: 'absolute', + width: opts.width + 'px', + height: opts.height + 'px', + zIndex: opts.zIndex + }); + + this.bindEvent(); + }, + + // Bind click events to close button. + // Press ESC key to close popup. + bindEvent: function() { + var closeBtn = byClass(this.opts.closeBtnClass)[0]; + var self = this; + + bind(closeBtn, 'click', function() { + self.close(); + }); + + bind(doc, 'keydown', function(e) { + e = e || window.event; + var keyCode = e.which || e.keyCode; + + if (keyCode === 27) { + self.close(); + } + }); + + // When resize the window, reset the element's position. + bind(win, 'resize', function() { + self.setPosition(); + }); + }, + + // Show the popup element. + open: function() { + this.el.style.display = 'block'; + this.setPosition(); + }, + + // Hide the popup element. + close: function() { + this.el.style.display = 'none'; + }, + + // Make the popup element be centered. + setPosition: function() { + var opts = this.opts; + + var top = scrollY() + Math.max(0, (winH() - opts.height) / 2); + var left = scrollX() + Math.max(0, (winW() - opts.width) / 2); + + extend(this.el.style, { + top: top + opts.offsetY + 'px', + left: left + opts.offsetX + 'px' + }); + } + + }); + + // Expose as a jQuery plugin. + if ($ && $.fn) { + $.fn.popup = function(opts) { + var popups = []; + this.each(function(i, el) { + popups.push(new Popup(el, opts)); + }); + + return { + open: function() { + $.each(popups, function(i, popup) { + popup.open(); + }); + }, + close: function() { + $.each(popups, function(i, popup) { + popup.close(); + }); + } + }; + }; + } else if (global) { + // Expose it as a method on global object. + global.Popup = Popup; + } + + return Popup; + +})); diff --git a/pool/shard000/JavaScript/0005245_err.js b/pool/shard000/JavaScript/0005245_err.js new file mode 100644 index 0000000000000000000000000000000000000000..e01d8b98758867f506b55a08b228d55961886805 --- /dev/null +++ b/pool/shard000/JavaScript/0005245_err.js @@ -0,0 +1,52 @@ +var test = require('tap').test; +var burrito = require('.'); + +test('wrap error', function (t) { + t.plan(6); + + try { + var src = burrito('f() && g()', function (node) { + if (node.name === 'binary') node.wrap('h(%a, %b') + }); + t.fail('should have blown up'); + } + catch (err) { + t.ok(err.message.match(/unexpected/i)); + t.ok(err instanceof SyntaxError); + t.ok(!err.stack.match(/uglify-js/)); + t.equal(err.line, 0); + t.equal(err.col, 10); + t.equal(err.pos, 10); + } +}); + +test('non string', function (t) { + t.plan(3); + + t.throws(function () { + burrito.parse(new Buffer('[]')); + }); + + t.throws(function () { + burrito.parse(new String('[]')); + }); + + t.throws(function () { + burrito.parse(); + }); +}); + +test('syntax error', function (t) { + t.plan(3); + try { + var src = burrito('f() && g())', function (node) { + if (node.name === 'binary') node.wrap('h(%a, %b)') + }); + assert.fail('should have blown up'); + } + catch (err) { + t.ok(err.message.match(/unexpected/i)); + t.ok(err instanceof SyntaxError); + t.ok(!err.stack.match(/uglify-js/)); + } +}); diff --git a/pool/shard000/JavaScript/0005247_Boolean.prototype.toSource.js b/pool/shard000/JavaScript/0005247_Boolean.prototype.toSource.js new file mode 100644 index 0000000000000000000000000000000000000000..3f228471c76a43ddef693c6fa300a9db58a746d5 --- /dev/null +++ b/pool/shard000/JavaScript/0005247_Boolean.prototype.toSource.js @@ -0,0 +1,19 @@ + +describe('Boolean.prototype.toSource', (assert, expect) => { + + let cmp1 = '(new Boolean(true))'; + let cmp2 = '(new Boolean(false))'; + let boo1 = true; + let boo2 = false; + + assert(boo1.toSource()); + assert(boo2.toSource()); + + assert(boo1); + assert(boo2); + + expect(boo1.toSource(), cmp1); + expect(boo2.toSource(), cmp2); + +}); + diff --git a/pool/shard000/JavaScript/0005249_index.js b/pool/shard000/JavaScript/0005249_index.js new file mode 100644 index 0000000000000000000000000000000000000000..6154a2218eb4120591783b03afa2acbc6338fc5d --- /dev/null +++ b/pool/shard000/JavaScript/0005249_index.js @@ -0,0 +1,30 @@ +var mongodb = require('mongodb'); + +var uri = "mongodb://localhost:27017/example"; +mongodb.MongoClient.connect(uri, function(err, db){ + + if(err){ + console.log(err); + process.exit(1); + } + + db.collection('sample').insert({x:1}, function(err, result){ + if(err){ + console.log(err); + process.exit(1); + } + + db.collection('sample').find().toArray(function(err, docs){ + if(err){ + console.log(err); + process.exit(1); + } + + console.log('Found docs:'); + docs.forEach(function(doc){ + console.log(JSON.stringify(doc)); + }); + process.exit(0); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005251_PageNew.js b/pool/shard000/JavaScript/0005251_PageNew.js new file mode 100644 index 0000000000000000000000000000000000000000..de80367d64bcdbdd44df59939bfad9b0f5dd7481 --- /dev/null +++ b/pool/shard000/JavaScript/0005251_PageNew.js @@ -0,0 +1,129 @@ +import React, { PropTypes, Component } from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; +import { browserHistory, withRouter } from 'react-router'; +import { ADMIN_PREFIX } from '../../constants'; +import Splitter from '../../components/Splitter'; +import Errors from '../../components/Errors'; +import Breadcrumbs from '../../components/Breadcrumbs'; +import Button from '../../components/Button'; +import InputPath from '../../components/form/InputPath'; +import InputTitle from '../../components/form/InputTitle'; +import Checkbox from '../../components/form/Checkbox'; +import MarkdownEditor from '../../components/MarkdownEditor'; +import Metadata from '../../containers/MetaFields'; +import { updateTitle, updateBody, updatePath, updateDraft } from '../../actions/metadata'; +import { createPage } from '../../actions/pages'; +import { clearErrors } from '../../actions/utils'; +import { + getLeaveMessage, getDeleteMessage, getNotFoundMessage +} from '../../constants/lang'; + +export class PageNew extends Component { + + componentDidMount() { + const { router, route } = this.props; + router.setRouteLeaveHook(route, this.routerWillLeave.bind(this)); + } + + componentWillReceiveProps(nextProps) { + if (this.props.updated !== nextProps.updated) { + browserHistory.push(`${ADMIN_PREFIX}/pages/${nextProps.page.path}`); + } + } + + componentWillUnmount() { + const { clearErrors, errors} = this.props; + // clear errors if any + if (errors.length) { + clearErrors(); + } + } + + routerWillLeave(nextLocation) { + if (this.props.fieldChanged) { + return getLeaveMessage(); + } + } + + handleClickSave() { + const { fieldChanged, createPage, params } = this.props; + if (fieldChanged) { + createPage(params.splat); + } + } + + render() { + const { errors, updated, updateTitle, updateBody, updatePath, + updateDraft, fieldChanged, params } = this.props; + + return ( + <div className="single"> + {errors.length > 0 && <Errors errors={errors} />} + <div className="content-header"> + <Breadcrumbs + type="pages" + splat={params.splat || ''} /> + </div> + + <div className="content-wrapper"> + <div className="content-body"> + <InputPath onChange={updatePath} type="pages" path="" /> + <InputTitle onChange={updateTitle} title="" ref="title" /> + <MarkdownEditor + onChange={updateBody} + onSave={() => this.handleClickSave()} + placeholder="Body" + initialValue="" + ref="editor" /> + <Splitter /> + <Metadata fields={{}} /> + </div> + + <div className="content-side"> + <Button + onClick={() => this.handleClickSave()} + type="create" + active={fieldChanged} + triggered={updated} + icon="plus-square" + block /> + </div> + </div> + </div> + ); + } +} + +PageNew.propTypes = { + createPage: PropTypes.func.isRequired, + updateTitle: PropTypes.func.isRequired, + updateBody: PropTypes.func.isRequired, + updatePath: PropTypes.func.isRequired, + updateDraft: PropTypes.func.isRequired, + clearErrors: PropTypes.func.isRequired, + errors: PropTypes.array.isRequired, + fieldChanged: PropTypes.bool.isRequired, + updated: PropTypes.bool.isRequired, + router: PropTypes.object.isRequired, + route: PropTypes.object.isRequired, + params: PropTypes.object.isRequired +}; + +const mapStateToProps = (state) => ({ + page: state.pages.page, + fieldChanged: state.metadata.fieldChanged, + errors: state.utils.errors, + updated: state.pages.updated +}); + +const mapDispatchToProps = (dispatch) => bindActionCreators({ + updateTitle, + updateBody, + updatePath, + updateDraft, + createPage, + clearErrors +}, dispatch); + +export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PageNew)); diff --git a/pool/shard000/JavaScript/0005254_strategy.js b/pool/shard000/JavaScript/0005254_strategy.js new file mode 100644 index 0000000000000000000000000000000000000000..b35770d9d60b5388e025743b3a148e5fa8797fc2 --- /dev/null +++ b/pool/shard000/JavaScript/0005254_strategy.js @@ -0,0 +1,142 @@ +/*! + * kraken-paypal-passport + * Copyright(c) 2015 Max Metral <opensource@pyralis.com> + * MIT Licensed + */ +'use strict'; + +/** + * Module dependencies. + */ +var util = require('util'), + OAuth2Strategy = require('passport-oauth').OAuth2Strategy, + InternalOAuthError = require('passport-oauth').InternalOAuthError; + +/** + * `Strategy` constructor. + * + * The PayPal authentication strategy authenticates requests by delegating to + * PayPal using the OAuth 2.0 protocol. + * + * Applications must supply a `verify` callback which accepts an `accessToken`, + * `refreshToken` and service-specific `profile`, and then calls the `done` + * callback supplying a `user`, which should be set to `false` if the + * credentials are not valid. If an exception occured, `err` should be set. + * + * Options: + * - `clientID` your application's App ID + * - `clientSecret` your application's App Secret + * - `callbackURL` URL to which PayPal will redirect the user after granting authorization + * + * Examples: + * + * passport.use(new PayPalStrategy({ + * clientID: '123-456-789', + * clientSecret: 'shhh-its-a-secret' + * callbackURL: 'https://www.example.net/auth/paypal/callback' + * }, + * function(accessToken, refreshToken, profile, done) { + * User.findOrCreate(..., function (err, user) { + * done(err, user); + * }); + * } + * )); + * + * @param {Object} options + * @param {Function} verify + * @api public + */ +function Strategy(options, verify) { + options = options || {}; + options.authorizationURL = options.authorizationURL || 'https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize'; + options.tokenURL = options.tokenURL || 'https://api.paypal.com/v1/identity/openidconnect/tokenservice'; + + OAuth2Strategy.call(this, options, verify); + + if (options.secureProtocol || options.insecure) { + var superExecute = this._oauth2._executeRequest; + this._oauth2._executeRequest = function( http_library, http_options ) { + if (options.insecure) { + http_options.rejectUnauthorized = false; + } + if (options.secureProtocol) { + http_options.secureProtocol = options.secureProtocol; + http_options.agent = false; + } + superExecute.apply(this, arguments); + }; + } + + this.localInit(options); + this._oauth2.setAccessTokenName('access_token'); +} + +/** + * Inherit from `OAuth2Strategy`. + */ +util.inherits(Strategy, OAuth2Strategy); + +Strategy.prototype.localInit = function (options) { + this.profileURL = options.profileURL || 'https://api.paypal.com/v1/identity/openidconnect/userinfo?schema=openid'; + this.name = options.name; +}; + +/** + * This is a hook for you to add information to the default user profile returned from PayPal for a user. + * By default we do nothing, so you don't need to call "super" to make this all work. + * @param accessToken + * @param profile + * @param done A function to be called when you're done, with (error, profile) + */ +Strategy.prototype.completeUserProfile = function (accessToken, profile, done) { + done(null, profile); +}; + +/** + * Retrieve user profile from PayPal. + * + * This function constructs a normalized profile, with the following properties: + * + * - `provider` always set to `paypal` + * - `id` + * - `displayName` + * + * @param {String} accessToken + * @param {Function} done + * @api protected + */ +Strategy.prototype.userProfile = function (accessToken, done) { + var t = this; + this._oauth2.get(this.profileURL, accessToken, function (err, body, res) { + if (err) { + return done(new InternalOAuthError('failed to fetch user profile', err)); + } + + try { + var json = JSON.parse(body); + + var profile = { provider: 'paypal' }; + profile.id = json.user_id; + profile.displayName = json.name; + profile.name = { familyName: json.family_name, + givenName: json.given_name, + formatted: json.name }; + profile.emails = []; + profile.emails.push({ value: json.email }); + profile.country = json.address ? json.address.country : null; + + profile._raw = body; + profile._json = json; + profile._payPal = t; + + t.completeUserProfile(accessToken, profile, done); + } catch (e) { + done(e); + } + }); +}; + +/** + * Expose `Strategy`. + */ +module.exports = Strategy; diff --git a/pool/shard000/JavaScript/0005258_errors.js b/pool/shard000/JavaScript/0005258_errors.js new file mode 100644 index 0000000000000000000000000000000000000000..1e129463f82dbc7b72ca58622dec2f8739168d7b --- /dev/null +++ b/pool/shard000/JavaScript/0005258_errors.js @@ -0,0 +1,168 @@ +import {assert} from 'ember-data/debug'; +const EmberError = Ember.Error; + +const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; +const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; +const PRIMARY_ATTRIBUTE_KEY = 'base'; + +/** + @class AdapterError + @namespace DS +*/ +export function AdapterError(errors, message = 'Adapter operation failed') { + EmberError.call(this, message); + + this.errors = errors || [ + { + title: 'Adapter Error', + detail: message + } + ]; +} + +AdapterError.prototype = Object.create(EmberError.prototype); + +/** + A `DS.InvalidError` is used by an adapter to signal the external API + was unable to process a request because the content was not + semantically correct or meaningful per the API. Usually this means a + record failed some form of server side validation. When a promise + from an adapter is rejected with a `DS.InvalidError` the record will + transition to the `invalid` state and the errors will be set to the + `errors` property on the record. + + For Ember Data to correctly map errors to their corresponding + properties on the model, Ember Data expects each error to be + a valid json-api error object with a `source/pointer` that matches + the property name. For example if you had a Post model that + looked like this. + + ```app/models/post.js + import DS from 'ember-data'; + + export default DS.Model.extend({ + title: DS.attr('string'), + content: DS.attr('string') + }); + ``` + + To show an error from the server related to the `title` and + `content` properties your adapter could return a promise that + rejects with a `DS.InvalidError` object that looks like this: + + ```app/adapters/post.js + import Ember from 'ember'; + import DS from 'ember-data'; + + export default DS.RESTAdapter.extend({ + updateRecord: function() { + // Fictional adapter that always rejects + return Ember.RSVP.reject(new DS.InvalidError([ + { + detail: 'Must be unique', + source: { pointer: '/data/attributes/title' } + }, + { + detail: 'Must not be blank', + source: { pointer: '/data/attributes/content'} + } + ])); + } + }); + ``` + + Your backend may use different property names for your records the + store will attempt extract and normalize the errors using the + serializer's `extractErrors` method before the errors get added to + the the model. As a result, it is safe for the `InvalidError` to + wrap the error payload unaltered. + + @class InvalidError + @namespace DS +*/ +export function InvalidError(errors) { + assert('`InvalidError` expects json-api formatted errors array.', Ember.isArray(errors || [])); + AdapterError.call(this, errors, 'The adapter rejected the commit because it was invalid'); +} + +InvalidError.prototype = Object.create(AdapterError.prototype); + +/** + @class TimeoutError + @namespace DS +*/ +export function TimeoutError() { + AdapterError.call(this, null, 'The adapter operation timed out'); +} + +TimeoutError.prototype = Object.create(AdapterError.prototype); + +/** + @class AbortError + @namespace DS +*/ +export function AbortError() { + AdapterError.call(this, null, 'The adapter operation was aborted'); +} + +AbortError.prototype = Object.create(AdapterError.prototype); + +/** + @method errorsHashToArray + @private +*/ +export function errorsHashToArray(errors) { + let out = []; + + if (Ember.isPresent(errors)) { + Object.keys(errors).forEach((key) => { + let messages = Ember.makeArray(errors[key]); + for (let i = 0; i < messages.length; i++) { + let title = 'Invalid Attribute'; + let pointer = `/data/attributes/${key}`; + if (key === PRIMARY_ATTRIBUTE_KEY) { + title = 'Invalid Document'; + pointer = `/data`; + } + out.push({ + title: title, + detail: messages[i], + source: { + pointer: pointer + } + }); + } + }); + } + + return out; +} + +/** + @method errorsArrayToHash + @private +*/ +export function errorsArrayToHash(errors) { + let out = {}; + + if (Ember.isPresent(errors)) { + errors.forEach((error) => { + if (error.source && error.source.pointer) { + let key = error.source.pointer.match(SOURCE_POINTER_REGEXP); + + if (key) { + key = key[2]; + } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { + key = PRIMARY_ATTRIBUTE_KEY; + } + + if (key) { + out[key] = out[key] || []; + out[key].push(error.detail || error.title); + } + } + }); + } + + return out; +} diff --git a/pool/shard000/JavaScript/0005264_visage.js b/pool/shard000/JavaScript/0005264_visage.js new file mode 100644 index 0000000000000000000000000000000000000000..2927200cf8f3a7bb90a7a3e89867212e389fd63a --- /dev/null +++ b/pool/shard000/JavaScript/0005264_visage.js @@ -0,0 +1,38 @@ +"use strict"; + +var debugFunc = function(file, done) { + console.log(file); + console.log("Debug function is being called at least"); + done(); +}; + +var sendingCb = function(file, xhr, formData) { + formData.append("name", "bullshit"); +}; + +var replaceOldWithNew = function(file) { + this.removeAllFiles(); + this.addFile(file); +}; + +var init = function() { + var submitButton = document.querySelector("#submit-image"), + thisDropzone = this; + + submitButton.addEventListener("click", function() { + thisDropzone.processQueue(); + }); +}; + + +/* The form's id is actually `image-upload-form`, but + I think Dropzone implicitly camelizes the identifier here. */ +Dropzone.options.imageUploadForm = { + paramName: "file", + maxFiles: 1, + maxfilesexceeded: replaceOldWithNew, + accept: debugFunc, + autoProcessQueue: false, + init: init, + sending: sendingCb +}; diff --git a/pool/shard000/JavaScript/0005265_conversation.js b/pool/shard000/JavaScript/0005265_conversation.js new file mode 100644 index 0000000000000000000000000000000000000000..7be39a64c5a3b420b9da941c84637cbba0946dd3 --- /dev/null +++ b/pool/shard000/JavaScript/0005265_conversation.js @@ -0,0 +1,128 @@ +var getCoversation = function ($parent) { + var self = this; + var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition; + var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList; + var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent; + var speechRecognitionList = new SpeechGrammarList(); + var recognition = new SpeechRecognition(); + + recognition.continuous = true; + recognition.interimResults = false; + recognition.maxAlternatives = 1; + // recognition.interimResults = false; + // recognition.maxAlternatives = 1; + self.started = false; + self.timeoutObj = null; + self.restartTimeoutObj = null; + + self.startStop = ko.observable('Start'); + + self.restart = function () { + console.log("restarting..."); + self.stopRecognition(); + setTimeout(function () { + self.startRecognition(); + }, 1000); + }; + + self.startRecognition = function () { + recognition.lang = $parent.selectedLanguage().name; + self.started = true; + recognition.start(); + self.timeoutObj = setTimeout(function () { + self.restart(); + }, 15000); + }; + + self.stopRecognition = function () { + console.log("Stopping now.."); + self.started = false; + clearTimeout(self.timeoutObj); + recognition.stop(); + }; + + var matchWords = function (sentence) { + var words = $parent.selectedTopic().words; + var wordsInSentence = sentence.toLowerCase().split(" "); + var wordsFound = []; + wordsInSentence.forEach(function (word) { + if (words[word]) { + wordsFound.push(word); + } + }); + return wordsFound; + }; + + function processResult(event) { + var last = event.results.length - 1; + var lastSentence = event.results[last][0].transcript; + if (event.results[last].isFinal) { + var resultingWords = matchWords(lastSentence); + $parent.post_dialogue(lastSentence, resultingWords); + if (resultingWords.length > 0) { + $parent.showWord(resultingWords); + } + } + } + + recognition.onresult = function (event) { + processResult(event); + }; + + recognition.onend = function () { + console.log('Speech recognition service disconnected'); + if (self.started) { + console.log("connecting again.."); + self.restart(); + } + }; + + recognition.onaudiostart = function () { + console.log('Audio capturing started'); + }; + recognition.onaudioend = function () { + console.log('Audio capturing ended'); + if (self.started) { + console.log("connecting again.."); + self.restart(); + } + }; + + recognition.onspeechend = function () { + console.log('Speech has stopped being detected'); + if (self.started) { + console.log("connecting again.."); + self.restart(); + } + }; + + recognition.onerror = function (event) { + console.log('Speech recognition error detected: ' + event.error); + if (self.started) { + console.log("connecting again.."); + self.restart(); + } + }; + + recognition.onspeechstart = function () { + console.log('Speech has been detected'); + }; + + self.toggleConversation = function () { + if (self.started) { + console.log("stopping.."); + self.startStop("Start"); + self.stopRecognition(); + } else { + console.log("starting.."); + self.startStop("Stop"); + self.startRecognition(); + } + }; + + return { + startRecognition: self.startRecognition, + stopRecognition: self.stopRecognition, + toggleStatus: self.toggleConversation + }; +}; diff --git a/pool/shard000/JavaScript/0005268_pickup.js b/pool/shard000/JavaScript/0005268_pickup.js new file mode 100644 index 0000000000000000000000000000000000000000..a8fe65e50fbc244fe40fe023471c5883780fff2a --- /dev/null +++ b/pool/shard000/JavaScript/0005268_pickup.js @@ -0,0 +1,168 @@ +"use strict"; + +/** +* TODO: Apparently I should replace MUH ITERATORS with higher-order functions +* TODO: Separate pickup logic into it's own repo? Remove team format and stuff +*/ + +class Pickup { + constructor (settings = {}) { + // Just constructor doing constructor things. + // settings is a dict of params. + this.game_on = false; + this.max_teams = settings.max_teams; + this.team_size = settings.team_size; + this.team_filler = settings.team_filler; + this.teams = this.reset_teams(this.max_teams, this.team_size, this.team_filler); + this.player_count = 0; + } + + // Helper functions I guess? But not really? + isAdded(nick) { + /** + * Checks each element of each array of this.teams and checks + * if it is the same as the nickname given. + * Returns true or false. + */ + return this.teams.some(element => element.includes(nick)); + } + + _open_spot(team) { + /** + * Returns the index of the first open spot ("?") in a given + * team (this.teams[team] array) for adding purposes. + * Returns -1 if the team is full. + */ + return this.teams[team].indexOf("?"); + } + + _sort_arr(arr) { + // Does some magic to sort an array + // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort + let mapped = arr.map((element, index) => { + return { index: index, value: element} + }); + mapped.sort((a, b) => { + return +(a.value < b.value) || +(a.value === b.value) - 1; + }); + let result = mapped.map((element) => { + return arr[element.index]; + }); + return result; + } + + // Big boy functions + + start_game(max_teams = this.max_teams, team_size = this.team_size) { + /** + * Starts a game, duh! + * Can create pickups with varying number of teams and team sizes. + */ + this.game_on = true; + this.max_teams = max_teams; + this.team_size = team_size; + this.teams = this.reset_teams(this.max_teams, this.team_size, this.team_filler); + return true; + } + + cancel_game() { + // Cancels a game and resets the teams arrays. + this.game_on = false; + this.teams = this.reset_teams(this.max_teams, this.team_size, this.team_filler); // Redundancy? + this.player_count = 0; + return true; + } + + add(team, nick) { + /** + * Adds a player to a particular team (this.teams[team]). + * Returns false if already added, 0 if there is no space + * and true if added successfully. + * My returns are weird but they are exactly that, MY returns. + */ + if (!this.isAdded(nick)) { + if (this._open_spot(team) != -1) { + this.teams[team][this._open_spot(team)] = nick; + this.teams[team] = this._sort_arr(this.teams[team]); + this.player_count += 1; + return true; + } else + if (this._open_spot(team) == -1) { + return 0; + } + } else + if (this.isAdded(nick)) { + return false; + } + } + + random_add(nick) { + /** + * This, uhhh... adds a player to a random team? + * Returns true or false. + * TODO: Rewrite sometime ¯\_(ツ)_/¯ + */ + let arr = [] + for (let i = 0; i < this.teams.length; i++) { + if (this._open_spot(i) > -1) { + arr.push(i); + } + } + + if (arr[0] == undefined) { + return false; + } + let team = Math.round(Math.random() * (arr.length - 1)) + if (team > -1) { + this.add(arr[team], nick); + return true; + } else { + // Redundant, I know. + console.log("All teams are full?"); + return false; + } + } + + remove(nick) { + // Removes a player from any team. Returns a new 2D array + if (isAdded(nick)) { + return arr.map((x) => { + return x.map((y) => { + return y === nick ? '?' : y + }) + }) + } + } + + /** + * Returns a dynamically sized 2-D array (sized based on input) + * but makes each element equal to "?" to denote a fresh pickup. + */ + reset_teams(width, depth, filler) { + let teams = new Array(width).fill(undefined).map(() => new Array(depth).fill(filler)); + console.log(teams) + return teams + } + + get display_teams() { + /** + * Uses the array "this.teams" and returns a string of + * all players added to every team in the format: + * Team A: (Russ), (?), (?), (?), (?) Team B: (Gryph), (Zoid), (?), (?), (?) - etc + */ + let alphabet = ["A", "B", "C", "D", "E", "F", "G" ,"H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", + "V", "W", "X", "Y", "Z"]; + let fence = '\`\`\`' + let teams = ""; + for (let i = 0; i < this.teams.length; i++) { + teams += `${fence}Team ${alphabet[i]}: (${this.teams[i].join("), (")})${fence}` + } + console.log(this.teams) + return teams; + } +}; + +module.exports = { + Pickup: Pickup +}; diff --git a/pool/shard000/JavaScript/0005273_PlaceholderBox.js b/pool/shard000/JavaScript/0005273_PlaceholderBox.js new file mode 100644 index 0000000000000000000000000000000000000000..4590988bf85c0ab32f3e31bb93289e4fe65b1db3 --- /dev/null +++ b/pool/shard000/JavaScript/0005273_PlaceholderBox.js @@ -0,0 +1,69 @@ +// Copyright 2018-2021, University of Colorado Boulder + +/** + * A rectangle meant as a placeholder in the calculation lines (poolable). + * + * This is pooled for performance, as recreating the view structure had unacceptable performance/GC characteristics. + * + * @author Jonathan Olson <jonathan.olson@colorado.edu> + */ + +import Property from '../../../../../axon/js/Property.js'; +import Poolable from '../../../../../phet-core/js/Poolable.js'; +import { Rectangle } from '../../../../../scenery/js/imports.js'; +import areaModelCommon from '../../../areaModelCommon.js'; +import areaModelCommonStrings from '../../../areaModelCommonStrings.js'; + +const placeholderString = areaModelCommonStrings.a11y.placeholder; + +class PlaceholderBox extends Rectangle { + /** + * @param {Property.<Color>} colorProperty + * @param {boolean} allowExponents - Whether exponents (powers of x) are allowed + */ + constructor( colorProperty, allowExponents ) { + + super( 0, 0, 16, 16, { + lineWidth: 0.7, + + // pdom + tagName: 'mi', + pdomNamespace: 'http://www.w3.org/1998/Math/MathML', + innerContent: placeholderString + } ); + + // @public {string} + this.accessibleText = placeholderString; + + this.initialize( colorProperty, allowExponents ); + } + + /** + * @public + * + * @param {Property.<Color>} colorProperty + * @param {boolean} allowExponents - Whether exponents (powers of x) are allowed + */ + initialize( colorProperty, allowExponents ) { + assert && assert( colorProperty instanceof Property ); + assert && assert( typeof allowExponents === 'boolean' ); + + this.stroke = colorProperty; + this.localBounds = this.selfBounds.dilatedX( allowExponents ? 2 : 0 ); + } + + /** + * Clears the state of this node (releasing references) so it can be freed to the pool (and potentially GC'ed). + * @public + */ + clean() { + this.stroke = null; + this.freeToPool(); + } +} + +areaModelCommon.register( 'PlaceholderBox', PlaceholderBox ); + +Poolable.mixInto( PlaceholderBox ); + +export default PlaceholderBox; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005278_performance.js b/pool/shard000/JavaScript/0005278_performance.js new file mode 100644 index 0000000000000000000000000000000000000000..0fa21e90fb32cd7afedc9de226fb92c790eb6fc4 --- /dev/null +++ b/pool/shard000/JavaScript/0005278_performance.js @@ -0,0 +1,33 @@ +const SerialPort = require('../') +const port = process.env.TEST_PORT + +if (!port) { + console.error('Please pass TEST_PORT environment variable') + process.exit(1) +} + +// var Binding = require('@serialport/binding-mock'); +// Binding.createPort(port); +// SerialPort.Binding = Binding; +// debugger; + +const writeData = Buffer.alloc(50000, 1) + +const serialPort = new SerialPort(port, { + // baudRate: 115200 +}) + +serialPort.once('data', () => { + console.log('writing', writeData.length, 'bytes of data') + serialPort.write(writeData) +}) + +let recieved = 0 +serialPort.on('data', data => { + recieved += data.length + if (recieved >= writeData.length) { + serialPort.close(() => { + console.log('finished reading', recieved, 'bytes') + }) + } +}) diff --git a/pool/shard000/JavaScript/0005280_items.js b/pool/shard000/JavaScript/0005280_items.js new file mode 100644 index 0000000000000000000000000000000000000000..09e9c444b3cbdb9123ee09f84f5e88e4f0773f74 --- /dev/null +++ b/pool/shard000/JavaScript/0005280_items.js @@ -0,0 +1,32 @@ +var o2 = o2 || {}; + +o2.Collections = o2.Collections || {}; + +o2.Collections.LiveCommentsItems = ( function( $, Backbone ) { + return Backbone.Collection.extend( { + model: o2.Models.LiveCommentsItem, + + comparator: function( item1, item2 ) { + // the collection should have newer items at the end of the collection + return o2.Utilities.compareTimes( item1.get( 'unixtime' ), item2.get( 'unixtime' ) ); + }, + + addOrUpdateItem: function( itemHash ) { + // Check and see if we already have one + // Since post and comment IDs can overlap, we cannot use the postID and commentID directly as the + // backbone model ID, so we have to use the type and the externalID here + + var foundItem = _.find( this.models, function( item ) { + return ( ( item.type === itemHash.type ) && ( item.externalID === itemHash.externalID ) ); + } ); + + if ( 'undefined' !== typeof foundItem ) { + foundItem.set( itemHash ); + } else { + if ( ! o2.options.isPreview ) { + this.add( new o2.Models.LiveCommentsItem( itemHash ) ); + } + } + } + } ); +} )( jQuery, Backbone ); diff --git a/pool/shard000/JavaScript/0005287_application.js b/pool/shard000/JavaScript/0005287_application.js new file mode 100644 index 0000000000000000000000000000000000000000..f70d161526f360c4ae4b482779b72af680b14443 --- /dev/null +++ b/pool/shard000/JavaScript/0005287_application.js @@ -0,0 +1,82 @@ +import Ember from "ember"; + +export default Ember.Controller.extend({ + + tableOfContents: function(){ + return [ + { route: "index", title: "Introduction"}, + { route: "helpers", title: "Template Helpers", + children: [ + {route: "helpers.liquid-outlet", title: "liquid-outlet"}, + {route: "helpers.liquid-with", title: "liquid-with"}, + {route: "helpers.liquid-bind", title: "liquid-bind"}, + {route: "helpers.liquid-if", title: "liquid-if"}, + {route: "helpers.liquid-measure", title: "liquid-measure"}, + {route: "helpers.liquid-box", title: "liquid-box"}, + ] + }, + { route: 'transition-map', title: 'Transition Map', + children: [ + {route: 'transition-map.route-constraints', title: 'Matching by route'}, + {route: 'transition-map.model-constraints', title: 'Matching by model'}, + {route: 'transition-map.dom-constraints', title: 'Matching by DOM context'}, + {route: 'transition-map.defining-transitions', title: 'Defining transition animations'} + ] + }, + { title: 'Transitions', + children: [ + "Predefined transitions", + "Custom transitions", + "animate", + "stop" + ] + } + ]; + }.property(), + + flatContents: function(){ + var flattened = []; + this.get('tableOfContents').forEach(function(entry) { + flattened.push(entry); + if (entry.children){ + flattened = flattened.concat(entry.children); + } + }); + return flattened; + }.property('tableOfContents'), + + + currentIndex: function(){ + var contents = this.get('flatContents'), + current = this.get('currentRouteName'), + bestMatch, + entry; + + for (var i=0; i<contents.length; i++) { + entry = contents[i]; + if (entry.route && new RegExp('^' + entry.route.replace(/\./g, '\\.')).test(current)) { + if (typeof(bestMatch) === 'undefined' || contents[bestMatch].route.length < entry.route.length) { + bestMatch = i; + } + } + } + return bestMatch; + }.property('currentRouteName', 'flatContents'), + + nextTopic: function(){ + var contents = this.get('flatContents'), + index = this.get('currentIndex'); + if (typeof(index) !== "undefined") { + return contents[index+1]; + } + }.property('currentIndex', 'flatContents'), + + prevTopic: function(){ + var contents = this.get('flatContents'), + index = this.get('currentIndex'); + if (typeof(index) !== "undefined") { + return contents[index-1]; + } + }.property('currentIndex', 'flatContents') + +}); diff --git a/pool/shard000/JavaScript/0005288_dev-config.js b/pool/shard000/JavaScript/0005288_dev-config.js new file mode 100644 index 0000000000000000000000000000000000000000..b270bf51ff444b726112a75b3b7e3ed8e9b3d63d --- /dev/null +++ b/pool/shard000/JavaScript/0005288_dev-config.js @@ -0,0 +1,69 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const fs = require('fs'); + +const DEV_CONFIG_FILE = '.moodleapp-dev-config'; + +/** + * Class to read and write dev-config data from a file. + */ +class DevConfig { + + constructor() { + this.loadFileData(); + } + + /** + * Get a setting. + * + * @param name Name of the setting to get. + * @param defaultValue Value to use if not found. + */ + get(name, defaultValue) { + return typeof this.config[name] != 'undefined' ? this.config[name] : defaultValue; + } + + /** + * Load file data to memory. + */ + loadFileData() { + if (!fs.existsSync(DEV_CONFIG_FILE)) { + this.config = {}; + + return; + } + + try { + this.config = JSON.parse(fs.readFileSync(DEV_CONFIG_FILE)); + } catch (error) { + console.error('Error reading dev config file.', error); + this.config = {}; + } + } + + /** + * Save some settings. + * + * @param settings Object with the settings to save. + */ + save(settings) { + this.config = Object.assign(this.config, settings); + + // Save the data in the dev file. + fs.writeFileSync(DEV_CONFIG_FILE, JSON.stringify(this.config, null, 4)); + } +} + +module.exports = new DevConfig(); diff --git a/pool/shard000/JavaScript/0005289_actangular-form.js b/pool/shard000/JavaScript/0005289_actangular-form.js new file mode 100644 index 0000000000000000000000000000000000000000..dec2569a88c3f2562dd9f26dec064687e2d96bad --- /dev/null +++ b/pool/shard000/JavaScript/0005289_actangular-form.js @@ -0,0 +1,170 @@ +(function() {'use strict'; + +/* agForm */ + +function $form(FormData, $injector, formConfig){ + + this.getFormData = function (param, success, fail){ + FormData.one().get(param).then( + function(formData){ + if(success) + success(formData); + }, + function(response){ + if(fail) + fail(response); + } + ); + }; + + this.handleStartForm = function (processDefinitionId, options, noForm, success, fail){ + var param = {processDefinitionId: processDefinitionId}; + this.getFormData(param, function(formData){ + handleForm(formData, options, noForm, success, fail); + }, fail); + }; + + this.handleTaskForm = function (taskId, options, noForm, success, fail){ + var param = {taskId: taskId}; + this.getFormData(param, function(formData){ + handleForm(formData, options, noForm, success, fail); + }, fail); + }; + + this.submitStartForm = function (processDefinitionId, formProperties, success, failure) { + submitFormData({processDefinitionId: processDefinitionId}, formProperties, success, failure); + }; + this.submitTaskForm = function (taskId, formProperties, success, failure) { + submitFormData({taskId: taskId}, formProperties, success, failure); + }; + + this.getFormViewProperties = function (formProperties){ + var formViewProperties = angular.copy(formProperties); + for(var i=0;i<formViewProperties.length;i++){ + var formPropertyHandler = formConfig.formPropertyHandlers[formViewProperties[i].type] || formConfig.formPropertyHandlers['string']; + if(formPropertyHandler){ + if(formPropertyHandler.viewId) + formViewProperties[i].view = formPropertyHandler.viewId; + if(formPropertyHandler.initFormProperty) + $injector.invoke(formPropertyHandler.initFormProperty, formPropertyHandler, {formProperty: formViewProperties[i]}); + } + } + return formViewProperties; + }; + + function handleForm (formData, options, noForm, success, fail){ + var formHandler = formConfig.formHandlers[formData.formKey]; + + if(formHandler) + $injector.get(formHandler).handleForm(formData, options, noForm, success, fail); + + }; + + function submitFormData (formData, formProperties, success, failure) { + formData.properties = []; + for(var i = 0; i<formProperties.length;i++){ + if(formProperties[i].writable === false) continue; + var formPropertyHandler = formConfig.formPropertyHandlers[formProperties[i].type]; + if(formPropertyHandler){ + if(formPropertyHandler.prepareForSubmit) + $injector.invoke(formPropertyHandler.prepareForSubmit, formPropertyHandler, {formProperty: formProperties[i]}); + } + formData.properties.push({id: formProperties[i].id, value: formProperties[i].value}); + } + FormData.post(formData).then(function(resource){ + if(success) success(resource); + }, failure); + }; +}; + +angular.module('agForm', []) +.factory('FormData', function(Restangular) { + return Restangular.withConfig(function(RestangularConfigurer) { + RestangularConfigurer.setBaseUrl('service/form/'); + }).service('form-data'); +}) +.provider('$form', function $FormProvider() { + + var formConfig = {formHandlers: {}, formPropertyHandlers: {}}; + + this.addFormPropertyHandler = function(formPropertyType, formPropertyHandler){ + formConfig.formPropertyHandlers[formPropertyType] = formPropertyHandler; + }; + + this.addFormHandler = function (formKey, formHandler){ + formConfig.formHandlers[formKey] = formHandler; + }; + + this.$get = ['FormData','$injector', function formFactory(FormData, $injector) { + if(angular.isUndefined(formConfig.formHandlers[null])){ + formConfig.formHandlers[null] = 'DefaultFormHandler'; + } + if(angular.isUndefined(formConfig.formPropertyHandlers['string'])){ + formConfig.formPropertyHandlers['string'] = {viewId: 'views/form/string.html'}; + } + return new $form(FormData, $injector, formConfig); + }]; +}) +.factory('DefaultFormHandler', function ($ui, $form){ + return { + handleForm : function(formData, options, noForm, success, fail){ + if(formData.formProperties.length > 0){ + var formProperties = $form.getFormViewProperties(formData.formProperties); + $ui.showModal('views/form/form.html', 'FormPropertiesController', + {formInfo: function () {return {formProperties: formProperties, options: options};}}, function(formProperties){ + if(formData.taskId !== null) + $form.submitTaskForm(formData.taskId, formProperties, success, fail); + else if(formData.processDefinitionId !== null) + $form.submitStartForm(formData.processDefinitionId, formProperties, success, fail); + }); + }else{ + if(noForm) noForm(); + } + } + }; +}) +.controller('FormPropertiesController', function ($scope, $modalInstance, formInfo) { + $scope.readOnly = formInfo.options.isReadOnly || false; + $scope.title = formInfo.options.title || '_FORM'; + + $scope.formProperties = formInfo.formProperties; + $scope.showErrors = false; + + $scope.submitForm = function(isValid) { + // check to make sure the form is completely valid + if (isValid) { + $modalInstance.close($scope.formProperties); + }else{ + $scope.showErrors = true; + } + }; + + $scope.cancel = function () { + $modalInstance.dismiss('cancel'); + }; + +}) +.directive('agName', function($compile) { +// http://stackoverflow.com/questions/14378401/dynamic-validation-and-name-in-a-form-with-angularjs + return{ + restrict: 'A', + terminal: true, + priority: 100000, + link: function(scope, element, attrs) { + var name = scope.$eval(attrs.agName); + element.removeAttr('ag-name'); + element.attr('name', name); + $compile(element)(scope); + }}; +}) +.run(function($ui, $form){ + $ui.registerModal('showStartForm', function(processDefinition, options, noForm, success, fail){ + $form.handleStartForm(processDefinition.id, options, noForm, success, fail); + }); + $ui.registerModal('showTaskForm', function(task, options, noForm, success, fail){ + $form.handleTaskForm(task.id, options, noForm, success, fail); + }); + +}); + +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005290_master.js b/pool/shard000/JavaScript/0005290_master.js new file mode 100644 index 0000000000000000000000000000000000000000..08c6bb417790109a16c748e1593c5d542b1dfdff --- /dev/null +++ b/pool/shard000/JavaScript/0005290_master.js @@ -0,0 +1,16 @@ +var child_process = require('child_process'); + +for(var i = 0; i < 3; i++) { + var process = child_process.exec('node ./support.js ' + i, function (error, stdout, stdin) { + if(error) { + console.error(error); + } + + console.log(stdout); + console.log(stdin); + }); + + process.on('exit', function (code) { + console.log("子进程退出, 退出码 " + code); + }) +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005293_tileset.js b/pool/shard000/JavaScript/0005293_tileset.js new file mode 100644 index 0000000000000000000000000000000000000000..85ab4d4958788bc355ac261698e6d1c630c9fa92 --- /dev/null +++ b/pool/shard000/JavaScript/0005293_tileset.js @@ -0,0 +1,51 @@ +"use strict"; + +// TileSet +function TileSet(tileSetData, sprite) { + this.sprite = sprite; + + this.tileWidth = tileSetData.tilewidth; + this.tileHeight = tileSetData.tileheight; + + this.cols = tileSetData.imagewidth / this.tileWidth; + this.rows = tileSetData.imageheight / this.tileHeight; +}; + +TileSet.prototype.draw = function(context, x, y, tileNum) { + var tileXY = this.toXY(tileNum); + + context.drawImage( + this.sprite, + tileXY.x * this.tileWidth, tileXY.y * this.tileHeight, this.tileWidth, this.tileHeight, + x, y, this.tileWidth, this.tileHeight + ); +}; + +TileSet.prototype.clear = function(context, x, y) { + context.clearRect(x, y, this.tileWidth, this.tileHeight); +}; + +TileSet.prototype.toXY = function(pos) { + var x = pos % this.cols; + var y = (pos - x)/ this.cols; + return { + x: x, + y: y, + toString: function() { + return "(" + x + "," + y + ")"; + } + } +}; + +TileSet.prototype.fromXY = function(pos) { + return pos.y * this.cols + pos.x; +}; + +TileSet.prototype.getTileWidth = function() { + return this.tileWidth; +}; + +TileSet.prototype.getTileHeight = function() { + return this.tileHeight; +}; + diff --git a/pool/shard000/JavaScript/0005295_animation.js b/pool/shard000/JavaScript/0005295_animation.js new file mode 100644 index 0000000000000000000000000000000000000000..239fda8a8309eecbeb9ecb2824207e423d22a6af --- /dev/null +++ b/pool/shard000/JavaScript/0005295_animation.js @@ -0,0 +1,104 @@ + function Animation(options) + { + [% WRAPPER per_second name="New Animations" %] + if ($.isFunction(options)) + { + options = { get_gfx: options }; + } + + $.extend(this, { + name: null, + img: null, + + frames: 1, + frame_inc: 1/8, + can_interrupt: true, + loop: true, + + frame_x: null, + frame_y: null, + x: 0, + y: 0, + + is_tile_sized: false, + xw: 1, + yh: 1, + + flip_xw: false, + center: 5, + trim_s: 0, + trim_b: 0, + }, options); + + var self = this; + + if (this.is_tile_sized) + { + this.xw *= runtime.tiles.tiles_xw + this.yh *= runtime.tiles.tiles_yh + delete this.is_tile_sized + } + + if (this.gfx instanceof Gfx && this.get_gfx == undefined) + { + this.get_gfx = function() { return this.gfx } + this.xw = this.gfx.xw() + this.yh = this.gfx.yh() + } + + if (this.gfx == undefined) + this.gfx = new Gfx(this.xw, this.yh) + + if (this.get_gfx == undefined) + { + if ($.type(this.img) != "string") + throw "Must provide img or get_gfx for an Animation"; + + var img = new Gfx(1, 1); + img + .preload(this.img) + .then(function(img) + { + self.img = img; + self.xw = img.xw() + self.yh = img.yh() + self.gfx = new Gfx(self.xw, self.yh) + } + ) + + this.get_gfx = function() + { + return self.img + } + } + + var did_last_frame = false + var frame = 0 + + this.reset = function() + { + frame = 0 + did_last_frame = false + } + + this.was_last_frame = function() + { + return did_last_frame + } + + this.frame = function() + { + frame += this.frame_inc || 1 + + did_last_frame = false + + if (frame >= this.frames) + { + frame -= this.frames + did_last_frame = true + } + + return did_last_frame + } + [% END %] + } diff --git a/pool/shard000/JavaScript/0005297_alertDirective.js b/pool/shard000/JavaScript/0005297_alertDirective.js new file mode 100644 index 0000000000000000000000000000000000000000..4517b486a6e713b13036a6e83ab03d2fb8dc1409 --- /dev/null +++ b/pool/shard000/JavaScript/0005297_alertDirective.js @@ -0,0 +1,24 @@ +module.exports=function() { + + return { + restrict: "E", + scope : {style: "@", closeButton: "@", onClose:"&"}, + templateUrl: 'js/ex8-alert-dir/app/templates/alert.html', + transclude: true, + replace:false, + link: function(scope, elm, attrs,ctrl,transclude) { + attrs.$observe('closeButton', function() { + scope.closeButton = scope.$eval(attrs.closeButton); + }); + elm.on("close.bs.alert",function(){ + var result; + scope.$apply(function(){ + if(angular.isDefined(scope.onClose)){ + result= scope.onClose(); + } + }); + return result; + }); + } + }; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005299_models.js b/pool/shard000/JavaScript/0005299_models.js new file mode 100644 index 0000000000000000000000000000000000000000..0c5ae1bde803023eb58daaaf172176c31e98f975 --- /dev/null +++ b/pool/shard000/JavaScript/0005299_models.js @@ -0,0 +1,115 @@ +'use strict'; + +var htmlFormulae = require('html-formulae') + , stripHtml = require('strip-html') + , concat = require('concat-stream'); + +var Backbone = require('backbone') + , _ = require('underscore'); + + +/** + * Converter holds a single input/output pair: + * - input: string, input value; + * - output(*): string, unwrapped HTML output. + * + * (*) - computed property. + */ +exports.Converter = Backbone.Model.extend({ + defaults: { + input: '' + }, + + initialize: function () { + this.on('change:input', this.setOutput, this); + }, + + setOutput: function () { + var input = this.get('input'); + + var htmlStripper = stripHtml(); + htmlStripper.pipe(concat({ encoding: 'string' }, function (output) { + this.set('output', output); + }.bind(this))); + htmlStripper.end(htmlFormulae(input)); + } +}); + + +/** + * Theme descriptor: + * - name: string, unique theme identifier; + * - src: theme .css path; + * - icon: theme icon color. + */ +exports.Theme = Backbone.Model; + + +exports.Themes = Backbone.Collection.extend({ + model: exports.Theme +}); + + +/** + * Currently set theme. + * Persistently stored in LocalStorage. + */ +exports.CurrentTheme = exports.Theme.extend({ + defaults: { + // Fixed ID between sessions. + id: 0 + }, + + localStorage: new Backbone.LocalStorage('current-theme'), + + initialize: function () { + this.fetch(); + } +}); + + +/** + * History of formulas. + * Persistently stored in LocalStorage. + */ +exports.History = Backbone.Collection.extend({ + model: exports.Converter, + + localStorage: new Backbone.LocalStorage('history'), + + // While individual converters can be stored out of order, + // the entire collection grows only on one of its ends. + // Thus, if one element is added after another, then it is + // guaranteed that it is located above in the history stack. + // This insertion order is mirrored by this variable. + // Its domain is negative to avoid collisions with existing IDs. + nextId: -1, + + initialize: function () { + // These lines rely on the synchrony of LocalStorage. + this.once('sync', this.renumerate, this); + this.fetch(); + }, + + // Item IDs will constantly increase over time, + // so it is necessary to renumerate them on sync. + // But the most important reason to do it is to normalize IDs + // to keep them non-negative for further insertions. + renumerate: function () { + this.reset(_.chain(this.models) + .sortBy('id') + .each(function (model) { + model.sync('delete', model); + }) + .value()); + this.each(function (model, index) { + model.save('id', index); + }); + }, + + pushItem: function (model) { + this.create(model.clone().set({ + id: this.nextId-- + }), {at: 0}); + } +}); diff --git a/pool/shard000/JavaScript/0005305_arena-schema.js b/pool/shard000/JavaScript/0005305_arena-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..7a7294fb0336822c3a8a3e44e465988b127d39eb --- /dev/null +++ b/pool/shard000/JavaScript/0005305_arena-schema.js @@ -0,0 +1,76 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const ArenaSchema = new Schema({ + + number: { + unique: true, + type: Number, + require: true, + }, + + name: { + unique: true, + type: String, + require: true, + }, + + idName: { + type: String, + unique: true, + require: true, + }, + + victoryGold: { + type: Number, + require: true, + }, + + minTrophies: { + type: Number, + require: true, + }, + + clan: { + request: { + common: { type: Number, require: true }, + rare: { type: Number, require: true }, + }, + donate: { + common: { type: Number, require: true }, + rare: { type: Number, require: true }, + }, + }, + + chests: [{ + type: mongoose.Schema.Types.ObjectId, + ref: 'Chest', + }], + + cardUnlocks: [{ + type: mongoose.Schema.Types.ObjectId, + ref: 'Card', + }], + + leagues: [{ + type: mongoose.Schema.Types.ObjectId, + ref: 'League', + }], + + order: { + type: Number, + require: true, + }, + +}); + +ArenaSchema.pre('save', function preSave(next) { + if (!this.idName) { + this.idName = JSON.parse(JSON.stringify(this.name.toLowerCase())); + this.idName = this.idName.replace(/ /g, '-'); + this.idName = this.idName.replace(/\./g, ''); + } + next(); +}); + +module.exports = mongoose.model('Arena', ArenaSchema); diff --git a/pool/shard000/JavaScript/0005307_globalize-runtime.js b/pool/shard000/JavaScript/0005307_globalize-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..1cac34f47f7cba7d8c3764d1d7ba1a3f7052577d --- /dev/null +++ b/pool/shard000/JavaScript/0005307_globalize-runtime.js @@ -0,0 +1,252 @@ +/** + * Globalize Runtime v1.4.0 + * + * http://github.com/jquery/globalize + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2018-07-17T20:38Z + */ +/*! + * Globalize Runtime v1.4.0 2018-07-17T20:38Z Released under the MIT license + * http://git.io/TrdQbw + */ +(function( root, factory ) { + + "use strict"; + + // UMD returnExports + if ( typeof define === "function" && define.amd ) { + + // AMD + define( factory ); + } else if ( typeof exports === "object" ) { + + // Node, CommonJS + module.exports = factory(); + } else { + + // Globalize + root.Globalize = factory(); + } +}( this, function() { + + + + +/** + * A toString method that outputs meaningful values for objects or arrays and + * still performs as fast as a plain string in case variable is string, or as + * fast as `"" + number` in case variable is a number. + * Ref: http://jsperf.com/my-stringify + */ +var toString = function( variable ) { + return typeof variable === "string" ? variable : ( typeof variable === "number" ? "" + + variable : JSON.stringify( variable ) ); +}; + + + + +/** + * formatMessage( message, data ) + * + * @message [String] A message with optional {vars} to be replaced. + * + * @data [Array or JSON] Object with replacing-variables content. + * + * Return the formatted message. For example: + * + * - formatMessage( "{0} second", [ 1 ] ); // 1 second + * + * - formatMessage( "{0}/{1}", ["m", "s"] ); // m/s + * + * - formatMessage( "{name} <{email}>", { + * name: "Foo", + * email: "bar@baz.qux" + * }); // Foo <bar@baz.qux> + */ +var formatMessage = function( message, data ) { + + // Replace {attribute}'s + message = message.replace( /{[0-9a-zA-Z-_. ]+}/g, function( name ) { + name = name.replace( /^{([^}]*)}$/, "$1" ); + return toString( data[ name ] ); + }); + + return message; +}; + + + + +var objectExtend = function() { + var destination = arguments[ 0 ], + sources = [].slice.call( arguments, 1 ); + + sources.forEach(function( source ) { + var prop; + for ( prop in source ) { + destination[ prop ] = source[ prop ]; + } + }); + + return destination; +}; + + + + +var createError = function( code, message, attributes ) { + var error; + + message = code + ( message ? ": " + formatMessage( message, attributes ) : "" ); + error = new Error( message ); + error.code = code; + + objectExtend( error, attributes ); + + return error; +}; + + + + +var runtimeStringify = function( args ) { + return JSON.stringify( args, function( key, value ) { + if ( value && value.runtimeKey ) { + return value.runtimeKey; + } + return value; + } ); +}; + + + + +// Based on http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery +var stringHash = function( str ) { + return [].reduce.call( str, function( hash, i ) { + var chr = i.charCodeAt( 0 ); + hash = ( ( hash << 5 ) - hash ) + chr; + return hash | 0; + }, 0 ); +}; + + + + +var runtimeKey = function( fnName, locale, args, argsStr ) { + var hash; + argsStr = argsStr || runtimeStringify( args ); + hash = stringHash( fnName + locale + argsStr ); + return hash > 0 ? "a" + hash : "b" + Math.abs( hash ); +}; + + + + +var validate = function( code, message, check, attributes ) { + if ( !check ) { + throw createError( code, message, attributes ); + } +}; + + + + +var validateParameterPresence = function( value, name ) { + validate( "E_MISSING_PARAMETER", "Missing required parameter `{name}`.", + value !== undefined, { name: name }); +}; + + + + +var validateParameterType = function( value, name, check, expected ) { + validate( + "E_INVALID_PAR_TYPE", + "Invalid `{name}` parameter ({value}). {expected} expected.", + check, + { + expected: expected, + name: name, + value: value + } + ); +}; + + + + +var validateParameterTypeString = function( value, name ) { + validateParameterType( + value, + name, + value === undefined || typeof value === "string", + "a string" + ); +}; + + + + +// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions +var regexpEscape = function( string ) { + return string.replace( /([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1" ); +}; + + + + +var stringPad = function( str, count, right ) { + var length; + if ( typeof str !== "string" ) { + str = String( str ); + } + for ( length = str.length; length < count; length += 1 ) { + str = ( right ? ( str + "0" ) : ( "0" + str ) ); + } + return str; +}; + + + + +function Globalize( locale ) { + if ( !( this instanceof Globalize ) ) { + return new Globalize( locale ); + } + + validateParameterPresence( locale, "locale" ); + validateParameterTypeString( locale, "locale" ); + + this._locale = locale; +} + +Globalize.locale = function( locale ) { + validateParameterTypeString( locale, "locale" ); + + if ( arguments.length ) { + this._locale = locale; + } + return this._locale; +}; + +Globalize._createError = createError; +Globalize._formatMessage = formatMessage; +Globalize._regexpEscape = regexpEscape; +Globalize._runtimeKey = runtimeKey; +Globalize._stringPad = stringPad; +Globalize._validateParameterPresence = validateParameterPresence; +Globalize._validateParameterTypeString = validateParameterTypeString; +Globalize._validateParameterType = validateParameterType; + +return Globalize; + + + + +})); diff --git a/pool/shard000/JavaScript/0005312_app.js b/pool/shard000/JavaScript/0005312_app.js new file mode 100644 index 0000000000000000000000000000000000000000..838b679498f66914dd12729fc4037aae5eee2ce2 --- /dev/null +++ b/pool/shard000/JavaScript/0005312_app.js @@ -0,0 +1,172 @@ +var express = require('express'); +var HelperModule = require("./helper"); +var Helper = new HelperModule(); +var app = express(); +var bodyParser = require('body-parser'); +app.use(bodyParser.json()); + +var ALUMNOS_HOST = "localhost:3001"; +var DOCENTES_HOST = "localhost:3002"; + +var alumnos = []; +var docentes = []; +var consultas = {}; + +var server = app.listen(3000, function () { + var host = server.address().address; + var port = server.address().port; + console.log('Servidor levantado en http://%s:%s', host, port); +}); + + +// Alumnos + +app.post('/alumnos', function (req, res) { + console.log("====================================="); + console.log("alumnos creado -> " + JSON.stringify(req.body)); + if(!req.body.nombre) { + res.status(401); + res.send(); + } + var alumnoId = alumnos.length + 1 + var nombre = req.body.nombre; + var alumno = { "id": alumnoId, "nombre": nombre}; + alumnos.push(alumno); + + + recibirConsulta(alumnoId, function(consultaId, consulta){ + consultas[consultaId] = consulta; + alumnos.forEach(function(alumno) { + if(alumno.id != alumnoId) { + enviarConsultaAlumno(alumno.id, consulta); + } + }); + docentes.forEach(function(docente) { + enviarConsultaDocente(docente.id, consulta); + }); + }); + + res.status(200); + res.send(alumno); +}); + +function enviarConsultaAlumno(alumnoId, consulta) { + var url = "http://" + ALUMNOS_HOST + "/alumnos/" + alumnoId + "/consultas"; + Helper.makePostPromise(consulta, url).then(function(response) { + console.log("Response status de enviar consulta al alumno: " + response.statusCode); + }).catch(function(err){ + console.log("Hubo un error al enviar la consulta al alumno " + alumnoId + ": " + err); + }); +} + +function recibirConsulta(alumnoId, cont){ + app.post('/alumnos/' + alumnoId + '/consultas', function (req, res) { + console.log("====================================="); + console.log("el alumno " + alumnoId + " hizo una consulta -> " + JSON.stringify(req.body)); + var descripcion = req.body.descripcion; + var consultaId = Math.floor((Math.random() * 1000000) + 1); + var consulta = { "consulta": consultaId, "alumno": alumnoId, "descripcion": descripcion}; + cont(consultaId, consulta); + res.status(200); + res.send(consulta); + }); +} + +function enviarRespuestaAlumno(alumnoId, respuesta) { + var url = "http://" + ALUMNOS_HOST + "/alumnos/" + alumnoId + "/respuesta"; + Helper.makePostPromise(respuesta, url).then(function(response) { + console.log("Response de recibir respuesta: " + alumnoId); + }).catch(function(err){ + console.log("Hubo un error al recibir respuesta de alumno " + alumnoId + ": " + err); + }); +} + + +// Docentes + +app.post('/docentes', function (req, res) { + console.log("====================================="); + console.log("docentes creado -> " + JSON.stringify(req.body)); + if(!req.body.nombre) { + res.status(401); + res.send(); + } + var docenteId = docentes.length + 1 + var nombre = req.body.nombre; + var docente = { "id": docenteId, "nombre": nombre}; + docentes.push(docente); + + app.post('/docentes/' + docenteId + '/respuesta/start', function (req, res) { + console.log("====================================="); + console.log("docente " + docenteId + " empezo a responder -> " + JSON.stringify(req.body)); + var consultaId = req.body.consulta; + if(!consultas[consultaId].started){ + console.log("el docente " + docenteId + " trato de empezar a responder " + consultaId + " con exito"); + consultas[consultaId].started = true; + recibirRespuesta(docenteId, function(response) { + consultas[response.consulta].respuesta = response.respuesta; + docentes.forEach(function(docente) { + if(docente.id != docenteId) { + enviarRespuestaDocente(docente.id, response); + } + }); + alumnos.forEach(function(alumno) { + enviarRespuestaAlumno(alumno.id, response); + }); + }); + + docentes.forEach(function(docente) { + if(docente.id != docenteId) { + enviarStartRespuesta(docente.id, {"docente": docenteId, "consulta": consultaId}); + } + }); + + res.status(200); + res.send(); + } else { + console.log("el docente " + docenteId + " trato de empezar a responder " + consultaId + " pero ya estaba empezada"); + res.status(401); + res.send({error: true, causa: "already started"}); + } + }); + + res.status(200); + res.send(docente); +}); + + +function enviarConsultaDocente(doncenteId, consulta) { + var url = "http://" + DOCENTES_HOST + "/docentes/" + doncenteId + "/consultas"; + Helper.makePostPromise(consulta, url).then(function(response) { + console.log("Response status de enviar consulta al docente: " + response.statusCode); + }).catch(function(err){ + console.log("Hubo un error al enviar la consulta al docente " + doncenteId + ": " + err); + }); +} + +function enviarStartRespuesta(doncenteId, infoRespuesta) { + var url = "http://" + DOCENTES_HOST + "/docentes/" + doncenteId + "/respuesta/start"; + Helper.makePostPromise(infoRespuesta, url).then(function(response) { + console.log("Response status de start respuesta al doncente: " + response.statusCode + " and body: " + JSON.stringify(response.body)); + }).catch(function(err){ + console.log("Hubo un error al enviar la consulta al docente " + doncenteId + ": " + err); + }); +} + +function recibirRespuesta(docenteId, cont) { + app.post('/docentes/' + docenteId + '/respuesta/finish', function (req, res) { + console.log("el docente " + docenteId + " finalizo la respuesta: " + JSON.stringify(req.body)); + cont(req.body); + res.status(200); + res.send(); + }); +} + +function enviarRespuestaDocente(docenteId, respuesta) { + var url = "http://" + DOCENTES_HOST + "/docentes/" + docenteId + "/respuesta"; + Helper.makePostPromise(respuesta, url).then(function(response) { + console.log("Response de recibir respuesta docente: " + docenteId + " and body: " + JSON.stringify(response.body)); + }).catch(function(err){ + console.log("Hubo un error al recibir respuesta de docente " + docenteId + ": " + err); + }); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005313_feature-events.js b/pool/shard000/JavaScript/0005313_feature-events.js new file mode 100644 index 0000000000000000000000000000000000000000..8a6fe28ebbdd9c6f37a1991595b69f26b331dfac --- /dev/null +++ b/pool/shard000/JavaScript/0005313_feature-events.js @@ -0,0 +1,67 @@ +var layerListeners = { + featureclick: function(e) { + log(e.object.name + " says: " + e.feature.id + " clicked."); + return false; + }, + nofeatureclick: function(e) { + log(e.object.name + " says: No feature clicked."); + } +}; + +var style = new OpenLayers.StyleMap({ + 'default': OpenLayers.Util.applyDefaults( + {label: "${l}", pointRadius: 10}, + OpenLayers.Feature.Vector.style["default"] + ), + 'select': OpenLayers.Util.applyDefaults( + {pointRadius: 10}, + OpenLayers.Feature.Vector.style.select + ) +}); +var layer1 = new OpenLayers.Layer.Vector("Layer 1", { + styleMap: style, + eventListeners: layerListeners +}); +layer1.addFeatures([ + new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT("POINT(-1 -1)"), {l:1}), + new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT("POINT(1 1)"), {l:1}) +]); +var layer2 = new OpenLayers.Layer.Vector("Layer 2", { + styleMap: style, + eventListeners: layerListeners +}); +layer2.addFeatures([ + new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT("POINT(-1 1)"), {l:2}), + new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT("POINT(1 -1)"), {l:2}) +]); + +var map = new OpenLayers.Map({ + div: "map", + allOverlays: true, + layers: [layer1, layer2], + zoom: 6, + center: [0, 0], + eventListeners: { + featureover: function(e) { + e.feature.renderIntent = "select"; + e.feature.layer.drawFeature(e.feature); + log("Map says: Pointer entered " + e.feature.id + " on " + e.feature.layer.name); + }, + featureout: function(e) { + e.feature.renderIntent = "default"; + e.feature.layer.drawFeature(e.feature); + log("Map says: Pointer left " + e.feature.id + " on " + e.feature.layer.name); + }, + featureclick: function(e) { + log("Map says: " + e.feature.id + " clicked on " + e.feature.layer.name); + } + } +}); + +function log(msg) { + if (!log.timer) { + result.innerHTML = ""; + log.timer = window.setTimeout(function() {delete log.timer;}, 100); + } + result.innerHTML += msg + "<br>"; +} diff --git a/pool/shard000/JavaScript/0005316_index.js b/pool/shard000/JavaScript/0005316_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e63779e1afc35a47cccf46fd1cb760df0dbb2298 --- /dev/null +++ b/pool/shard000/JavaScript/0005316_index.js @@ -0,0 +1,61 @@ +'use strict' +var url = require('url') + +function except (options) { + var parent = this + + var opts = typeof options === 'function' ? [{custom: options}] : coerceToArray(options) + + function middleware (ctx, next) { + var skip = opts.reduce(function (result, opts) { + opts.useOriginalUrl = (typeof opts.useOriginalUrl === 'undefined') ? true : opts.useOriginalUrl + var requestedUrl = url.parse((opts.useOriginalUrl ? ctx.originalUrl : ctx.url) || '', true) + + var skip = true + + if (opts.custom) { + skip = skip && opts.custom(ctx) + } + + var paths = opts.path && coerceToArray(opts.path) + + if (paths) { + skip = skip && paths.some(function (p) { + return (typeof p === 'string' && p === requestedUrl.pathname) || + (p instanceof RegExp && !!p.exec(requestedUrl.pathname)) + }) + } + + var exts = opts.ext && coerceToArray(opts.ext) + + if (exts) { + skip = skip && exts.some(function (ext) { + return requestedUrl.pathname.substr(ext.length * -1) === ext + }) + } + + var methods = opts.method && coerceToArray(opts.method) + + if (methods) { + skip = skip && !!~methods.indexOf(ctx.method) + } + + return skip || result + }, false) + + if (skip) { + return next() + } + + return parent(ctx, next) + } + + middleware.and = except + return middleware +} + +function coerceToArray (val) { + return Array.isArray(val) ? val : [val] +} + +module.exports = except diff --git a/pool/shard000/JavaScript/0005324_wikipedia.org.js b/pool/shard000/JavaScript/0005324_wikipedia.org.js new file mode 100644 index 0000000000000000000000000000000000000000..57e7821f9e8ecb38dd6e5de391338cc77209bffb --- /dev/null +++ b/pool/shard000/JavaScript/0005324_wikipedia.org.js @@ -0,0 +1,72 @@ +module.exports = { + + re: [ + /https:\/\/\w+\.(m\.)?wikipedia\.org\/wiki\/.+/i, + /https:\/\/\w+\.(m\.)?wikimedia\.org\/wiki\/.+/i + ], + + provides: 'wikiData', + + mixins: ["*"], + + getMeta: function(wikiData) { + return { + title: wikiData.title, + description: wikiData.description + }; + }, + + getData: function(cheerio, decode) { + + var result = {}; + + var $head = cheerio('#firstHeading'); + + if ($head.length) { + result.title = decode($head.text()); + } + + // Select image of file, or image of article. + var $img = cheerio('#file img,.infobox .image img,.vcard .image img,.thumbimage'); + if ($img.length) { + $img = cheerio($img[0]); + result.thumb = $img.attr('src'); + result.thumb_width = $img.attr('width'); + result.thumb_height = $img.attr('height'); + } + + // File description. + var $p = cheerio('.description'); + if ($p.length) { + // Remove language label. + $p.find('.language').remove(); + } else { + // Article first paragraph. + $p = cheerio('#mw-content-text>p'); + } + if ($p.length) { + result.description = decode(cheerio($p[0]).text()); + } + + return { + wikiData: result + }; + }, + + getLink: function(wikiData) { + return { + href: wikiData.thumb, + type: CONFIG.T.image, + rel: CONFIG.R.thumbnail, + width: wikiData.thumb_width, + height: wikiData.thumb_height + }; + }, + + tests: [{ + page: 'https://en.wikipedia.org/wiki/Main_Page', + selector: '#mp-itn a' + }, + "https://en.wikipedia.org/wiki/Paris" + ] +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005325_register.component.js b/pool/shard000/JavaScript/0005325_register.component.js new file mode 100644 index 0000000000000000000000000000000000000000..dafaef3bfd5ddb9f789cddedbd64297c24a2abd4 --- /dev/null +++ b/pool/shard000/JavaScript/0005325_register.component.js @@ -0,0 +1,54 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var core_1 = require("@angular/core"); +var router_1 = require("@angular/router"); +var login_service_1 = require("../../services/login.service"); +var usuario_1 = require("../../models/usuario"); +var RegisterComponent = /** @class */ (function () { + function RegisterComponent(_loginService, _route, _router) { + this._loginService = _loginService; + this._route = _route; + this._router = _router; + this.title = "Register"; + } + RegisterComponent.prototype.ngOnInit = function () { + this.user_to_register = new usuario_1.Usuario(1, "", "", ""); + }; + RegisterComponent.prototype.onSubmit = function () { + var _this = this; + this._loginService.register(this.user_to_register).subscribe(function (response) { + { + _this.status = response.status; + _this.msg = response.msg; + } + }, function (error) { + _this.errorMessage = error; + if (_this.errorMessage != null) { + console.log(_this.errorMessage); + alert("Request error"); + } + }); + }; + RegisterComponent = __decorate([ + core_1.Component({ + selector: 'register', + templateUrl: 'app/views/register.html', + providers: [login_service_1.LoginService] + }), + __metadata("design:paramtypes", [login_service_1.LoginService, + router_1.ActivatedRoute, + router_1.Router]) + ], RegisterComponent); + return RegisterComponent; +}()); +exports.RegisterComponent = RegisterComponent; +//# sourceMappingURL=register.component.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005334_CircularLinearGauge.js b/pool/shard000/JavaScript/0005334_CircularLinearGauge.js new file mode 100644 index 0000000000000000000000000000000000000000..7c7f0dde0f14efa77ca79bbaf7ce4c5dd00c8c1a --- /dev/null +++ b/pool/shard000/JavaScript/0005334_CircularLinearGauge.js @@ -0,0 +1,176 @@ +define([ + "dojo/_base/lang", + "dojo/_base/declare", + "dojo/_base/Color", + "../utils", + "../../CircularGauge", + "../../LinearScaler", + "../../CircularScale", + "../../CircularValueIndicator", + "../../TextIndicator", + "../DefaultPropertiesMixin" + ], + function(lang, declare, Color, utils, CircularGauge, LinearScaler, CircularScale, CircularValueIndicator, TextIndicator, DefaultPropertiesMixin){ + return declare("dojox.dgauges.components.default.CircularLinearGauge", [CircularGauge, DefaultPropertiesMixin], { + // summary: + // A circular gauge widget. + + // _radius: Number + _radius: 100, + // borderColor: Object|Array|int + // The border color. Default is "#C9DFF2". + borderColor: "#C9DFF2", + // fillColor: Object|Array|int + // The background color. Default is "#FCFCFF". + fillColor: "#FCFCFF", + // indicatorColor: Object|Array|int + // The indicator fill color. Default is "#F01E28". + indicatorColor: "#F01E28", + constructor: function(){ + + // Base colors + this.borderColor = new Color(this.borderColor); + this.fillColor = new Color(this.fillColor); + this.indicatorColor = new Color(this.indicatorColor); + + // Draw background + this.addElement("background", lang.hitch(this, this.drawBackground)); + + // Scaler + var scaler = new LinearScaler(); + + // Scale + var scale = new CircularScale(); + scale.set("scaler", scaler); + this.addElement("scale", scale); + + // Value indicator + var indicator = new CircularValueIndicator(); + scale.addIndicator("indicator", indicator); + + // Gauge Foreground (needle cap) + this.addElement("foreground", lang.hitch(this, this.drawForeground)); + + // Indicator Text + var indicatorText = new TextIndicator(); + indicatorText.set("indicator", indicator); + indicatorText.set("x", 100); + indicatorText.set("y", 150); + this.addElement("indicatorText", indicatorText); + + utils.genericCircularGauge(scale, indicator, this._radius, this._radius, 0.65 * this._radius, 130, 50, null, null, "outside"); + }, + + drawBackground: function(g){ + // summary: + // Draws the background shape of the gauge. + // g: dojox/gfx/Group + // The group used to draw the background. + // tags: + // protected + var r = this._radius; + var w = 2 * r; + var h = w; + var entries = utils.createGradient([0, utils.brightness(this.borderColor, 70), 1, utils.brightness(this.borderColor, -40)]); + g.createEllipse({ + cx: r, + cy: r, + rx: r, + ry: r + }).setFill(lang.mixin({ + type: "linear", + x1: w, + y1: 0, + x2: 0, + y2: h + }, entries)).setStroke({ + color: "#A5A5A5", + width: 0.2 + }); + + entries = utils.createGradient([0, utils.brightness(this.borderColor, 70), 1, utils.brightness(this.borderColor, -50)]); + g.createEllipse({ + cx: r, + cy: r, + rx: r * 0.99, + ry: r * 0.99 + }).setFill(lang.mixin({ + type: "linear", + x1: 0, + y1: 0, + x2: w, + y2: h + }, entries)); + + entries = utils.createGradient([0, utils.brightness(this.borderColor, 60), 1, utils.brightness(this.borderColor, -40)]); + g.createEllipse({ + cx: r, + cy: r, + rx: r * 0.92, + ry: r * 0.92 + }).setFill(lang.mixin({ + type: "linear", + x1: 0, + y1: 0, + x2: w, + y2: h + }, entries)); + + entries = utils.createGradient([0, utils.brightness(this.borderColor, 70), 1, utils.brightness(this.borderColor, -40)]); + g.createEllipse({ + cx: r, + cy: r, + rx: r * 0.9, + ry: r * 0.9 + }).setFill(lang.mixin({ + type: "linear", + x1: w, + y1: 0, + x2: 0, + y2: h + }, entries)); + + entries = utils.createGradient([0, [255, 255, 255, 220], 0.8, utils.brightness(this.fillColor, -5), 1, utils.brightness(this.fillColor, -30)]); + g.createEllipse({ + cx: r, + cy: r, + rx: r * 0.9, + ry: r * 0.9 + }).setFill(lang.mixin({ + type: "radial", + cx: r, + cy: r, + r: r + }, entries)).setStroke({ + color: utils.brightness(this.fillColor, -40), + width: 0.4 + }); + + }, + + drawForeground: function(g){ + // summary: + // Draws the foreground shape of the gauge. + // g: dojox/gfx/Group + // The group used to draw the foreground. + // tags: + // protected + var r = 0.07 * this._radius; + var entries = utils.createGradient([0, this.borderColor, 1, utils.brightness(this.borderColor, -20)]); + g.createEllipse({ + cx: this._radius, + cy: this._radius, + rx: r, + ry: r + }).setFill(lang.mixin({ + type: "radial", + cx: 0.96 * this._radius, + cy: 0.96 * this._radius, + r: r + }, entries)).setStroke({ + color: utils.brightness(this.fillColor, -50), + width: 0.4 + }); + } + }); +}); diff --git a/pool/shard000/JavaScript/0005335_purge.js b/pool/shard000/JavaScript/0005335_purge.js new file mode 100644 index 0000000000000000000000000000000000000000..c4937dfbcdeaee4b84469747e1d72f9a1e49e61d --- /dev/null +++ b/pool/shard000/JavaScript/0005335_purge.js @@ -0,0 +1,23 @@ +module.exports = { + run: function(client, message, args) { + var deleteCount = parseInt(args[0], 10); + if(deleteCount < 2) + return message.reply("You can do a message. Come on, mate!"); + if(!deleteCount) + return message.reply("Help me out here: I need a number"); + if(deleteCount > 100) { + while(deleteCount > 100) { + deleteCount--; + } + } + const fetched = message.channel.fetchMessages({limit: deleteCount}); + message.channel.bulkDelete(fetched).catch(err => { + message.reply("Something went wrong! The Ghost Busters are on the case!"); + console.error(`Couldn't delete some messages because ${error}`); + }); + }, + + help: { + name: "purge" + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005336_index.js b/pool/shard000/JavaScript/0005336_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d9167233a6e50ca6f87057eef21c7871f1cda90e --- /dev/null +++ b/pool/shard000/JavaScript/0005336_index.js @@ -0,0 +1,23 @@ +// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + +import '../scss/index.scss'; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Router, useRouterHistory } from 'react-router'; +import { createHistory } from 'history'; +import routes from './routes'; + +const onRouteUpdate = () => { + window.scrollTo(0, 0); + document.getElementById('content').focus(); +}; + +let historyOptions = { basename: '/docs/grommet-index' }; +const history = useRouterHistory(createHistory)(historyOptions); + +const element = document.getElementById('content'); +ReactDOM.render( + <Router onUpdate={onRouteUpdate} routes={routes} + history={history} />, element); + +document.body.classList.remove('loading'); diff --git a/pool/shard000/JavaScript/0005341_code.js b/pool/shard000/JavaScript/0005341_code.js new file mode 100644 index 0000000000000000000000000000000000000000..5b84b0d45c66981f3f6ddc001cd7cd32a03f9bd1 --- /dev/null +++ b/pool/shard000/JavaScript/0005341_code.js @@ -0,0 +1,71 @@ +/* + * code() is a named function that will parse `inline code` and ```codeblock``` syntaxes + * @param {Object} message - The message object + */ +import { unescapeHTML } from '@rocket.chat/string-helpers'; + +import hljs from '../../hljs'; +import { addAsToken } from './token'; + +const inlinecode = (message) => { + // Support `text` + message.html = message.html.replace(/\`([^`\r\n]+)\`([<_*~]|\B|\b|$)/gm, (match, p1, p2) => + addAsToken(message, `<span class=\"copyonly\">\`</span><span><code class=\"code-colors inline\">${ p1 }</code></span><span class=\"copyonly\">\`</span>${ p2 }`, 'inlinecode', { noHtml: match }), + ); +}; + +const codeblocks = (message) => { + // Count occurencies of ``` + const count = (message.html.match(/```/gm) || []).length; + + if (count) { + // Check if we need to add a final ``` + if ((count % 2) > 0) { + message.html = `${ message.html }\n\`\`\``; + message.msg = `${ message.msg }\n\`\`\``; + } + + // Separate text in code blocks and non code blocks + const msgParts = message.html.split(/(^.*)(```(?:[a-zA-Z]+)?(?:(?:.|\r|\n)*?)```)(.*\n?)$/gm); + + for (let index = 0; index < msgParts.length; index++) { + // Verify if this part is code + const part = msgParts[index]; + const codeMatch = part.match(/^```[\r\n]*(.*[\r\n\ ]?)[\r\n]*([\s\S]*?)```+?$/); + + if (codeMatch) { + // Process highlight if this part is code + const singleLine = codeMatch[0].indexOf('\n') === -1; + const lang = !singleLine && Array.from(hljs.listLanguages()).includes(codeMatch[1].trim()) ? codeMatch[1].trim() : ''; + const emptyLanguage = lang === '' ? unescapeHTML(codeMatch[1] + codeMatch[2]) : unescapeHTML(codeMatch[2]); + const code = singleLine ? unescapeHTML(codeMatch[1]) : emptyLanguage; + + const result = lang === '' ? hljs.highlightAuto(lang + code) : hljs.highlight(lang, code); + const token = addAsToken( + message, + `<pre><code class='code-colors hljs ${ result.language }'><span class='copyonly'>\`\`\`<br></span>${ result.value }<span class='copyonly'><br>\`\`\`</span></code></pre>`, + 'code', + { + noHtml: codeMatch[0], + highlight: true, + }); + + msgParts[index] = token; + } else { + msgParts[index] = part; + } + } + + // Re-mount message + message.html = msgParts.join(''); + } +}; + +export const code = (message) => { + if (message.html?.trim()) { + codeblocks(message); + inlinecode(message); + } + + return message; +}; diff --git a/pool/shard000/JavaScript/0005342_datalist-polyfill.js b/pool/shard000/JavaScript/0005342_datalist-polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..6b7c45d8f0d93c83bd862f2ea39278616da3e804 --- /dev/null +++ b/pool/shard000/JavaScript/0005342_datalist-polyfill.js @@ -0,0 +1,241 @@ +/* +* datalist-polyfill.js - https://github.com/mfranzke/datalist-polyfill +* @license Copyright(c) 2017 by Maximilian Franzke +* Supported by Christian and Johannes - many thanks for that ! +*//* +* A lightweight and library dependency free vanilla JavaScript datalist polyfill. +* Tests for native support of an inputs elements datalist functionality. +* Elsewhere the functionality gets emulated by a select element. +*/ + +(function() { + 'use strict'; + + // feature detection + var nativedatalist = !!( 'list' in document.createElement( 'input' ) ) && + !!( document.createElement( 'datalist' ) && window.HTMLDataListElement ); + + // in case of that the feature doesn't exist, emulate it's functionality + if ( !nativedatalist ) { + + // function regarding the inputs interactions + var inputInputList = function( event ) { + + var $eventTarget = event.target; + + // check for whether the events target was an input datalist + if ( $eventTarget.matches( 'input[list]' ) ) { + + var list = $eventTarget.getAttribute( 'list' ), + $dataList = document.getElementById( list ); + + // still check for an existing instance + if ( $dataList !== null ) { + + var $dataListSelect = $dataList.getElementsByTagName('select')[0]; + + // still check for an existing instance + if ( $dataListSelect !== undefined ) { + + // on an ESC key press within the input, let's break here and hide the select + if ( event.keyCode === 27 ) { + $dataListSelect.classList.remove( 'visible' ); + $dataListSelect.setAttribute( 'aria-hidden', true ); + + return; + } + + var $dataListOptions = $dataList.querySelectorAll( 'option[value]' ), + inputValue = $eventTarget.value, + newSelectValues = document.createDocumentFragment(), + disabledValues = document.createDocumentFragment(), + visible = false; + + // if the input contains a value, than ... + if ( inputValue !== "" ) { + + // ... create an array out of the options list + var nodeArray = Array.prototype.slice.call( $dataListOptions ); + + // ... sort all entries and + nodeArray.sort( function( a, b ) { + return a.value.localeCompare( b.value ); + }).forEach( function( opt ) { + var optionValue = opt.value; + + // ... put this option into the fragment that is meant to get inserted into the select + // "Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label." (W3C) + if ( optionValue !== "" && optionValue.toLowerCase().indexOf( inputValue.toLowerCase() ) !== -1 && opt.disabled === false ) { + opt.innerText = optionValue; + + newSelectValues.appendChild( opt ); + + // ... and set the state of the select to get displayed in that case + visible = true; + } else { + // ... or put this option that isn't relevant to the users into the fragment that is supposed to get inserted outside of the select + disabledValues.appendChild( opt ); + } + }); + + // input the options fragment into the datalists select + $dataListSelect.appendChild( newSelectValues ); + + // preselect best fitting index + $dataListSelect.selectedIndex = 0; + + // input the unused options as siblings next to the select + $dataList.appendChild( disabledValues ); + } + + // toggle the visibility of the select according to previous checks + $dataListSelect.classList.toggle( 'visible', visible ); + $dataListSelect.setAttribute( 'aria-hidden', !visible ); + + // on arrow up or down keys, focus the select + if ( event.keyCode === 38 || event.keyCode === 40 ) { + + $dataListSelect.focus(); + } + } + } + } + }; + + // focus or blur events + var changesInputList = function( event ) { + + var $eventTarget = event.target; + + // check for whether the events target was an input datalist + if ( $eventTarget.matches( 'input[list]' ) ) { + + var eventType = event.type, + list = $eventTarget.getAttribute( 'list' ), + $dataList = document.getElementById( list ); + + // still check for an existing instance + if ( $dataList !== null ) { + + var $dataListSelect = $dataList.getElementsByTagName('select')[0], + // either have the select set to the state to get displayed in case of that it would have been focused or because it's the target on the inputs blur + visible = ( ( eventType === "focus" && event.target.value !== "" ) || ( event.relatedTarget && event.relatedTarget === $dataListSelect ) ), + message = $dataList.title; + + // creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted) + if ( $dataListSelect === undefined ) { + var rects = $eventTarget.getClientRects(), + $message = document.createElement('option'); + + $dataListSelect = document.createElement( 'select' ); + + // WAI ARIA attributes + $dataListSelect.setAttribute( 'aria-hidden', true ); + $dataListSelect.setAttribute( 'aria-live', 'polite' ); + $dataListSelect.setAttribute( 'role', 'listbox' ); + + // the select should get positioned underneath the input field ... + $dataListSelect.style.marginLeft = "-" + rects[0].width + "px"; + $dataListSelect.style.marginTop = rects[0].height + 'px'; + $dataListSelect.style.minWidth = rects[0].width + 'px'; + + // ... and it's first entry should contain the localized message to select an entry + $message.innerText = message; + // ... and disable this option, as it shouldn't get selected by the user + $message.disabled = true; + // ... and finally insert it into the select + $dataListSelect.appendChild( $message ); + + // add select to datalist element ... + $dataList.appendChild( $dataListSelect ); + + // ... and our upfollowing function to the change event + $dataListSelect.addEventListener( 'change', changeDataListSelect ); + $dataListSelect.addEventListener( 'blur', changeDataListSelect ); + $dataListSelect.addEventListener( 'keyup', changeDataListSelect ); + + + // plus we'd like to prevent autocomplete on the input datalist field + $eventTarget.setAttribute( 'autocomplete', 'off' ); + + // WAI ARIA attributes + $eventTarget.setAttribute( 'role', 'textbox' ); + $eventTarget.setAttribute( 'aria-haspopup', 'true' ); + $eventTarget.setAttribute( 'aria-autocomplete', 'list' ); + $eventTarget.setAttribute( 'aria-owns', list ); + } + + // toggle the visibility of the select according to previous checks + $dataListSelect.classList.toggle( 'visible', visible ); + $dataListSelect.setAttribute( 'aria-hidden', !visible ); + + // bind the keyup event on the related dalalists input + switch( eventType ) { + case "focus": + $eventTarget.addEventListener( 'keyup', inputInputList ); + + $eventTarget.addEventListener( 'blur', changesInputList, true ); + break; + case "blur": + $eventTarget.removeEventListener( 'keyup', inputInputList ); + + $eventTarget.removeEventListener( 'blur', changesInputList, true ); + break; + } + } + } + }; + + // function regarding changes to the datalist polyfilling created select + var changeDataListSelect = function( event ) { + + var $eventTarget = event.target, + message = $eventTarget.parentNode.title; + + // check for whether the events target was a select + if ( $eventTarget.matches( 'select' ) ) { + + var eventType = event.type, + // ENTER and ESC keys + visible = ( eventType === "keyup" && ( event.keyCode !== 13 && event.keyCode !== 27 ) ); + + // change event or enter key + if ( eventType === "change" || ( eventType === "keyup" && event.keyCode === 13 ) ) { + + var list = $eventTarget.parentNode.id, + $inputList = document.querySelector('input[list="' + list + '"]'), + eventTargetValue = $eventTarget.value; + + // input the selects value into the input on a change within the list + if ( $inputList !== null && eventTargetValue.length > 0 && eventTargetValue !== message ) { + $inputList.value = eventTargetValue; + } + } + + // toggle the visibility of the select according to previous checks + $eventTarget.classList.toggle( 'visible', visible ); + $eventTarget.setAttribute( 'aria-hidden', !visible ); + } + }; + + // binding the focus event - matching the input[list]s happens in the function afterwards + document.addEventListener( 'focus', changesInputList, true ); + + + // matches() polyfill - just in case ... + if (!Element.prototype.matches) { + Element.prototype.matches = + Element.prototype.matchesSelector || + Element.prototype.mozMatchesSelector || + Element.prototype.msMatchesSelector || + Element.prototype.oMatchesSelector || + Element.prototype.webkitMatchesSelector || + function(s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s), + i = matches.length; + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1; + }; + } + } +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005347_popup.js b/pool/shard000/JavaScript/0005347_popup.js new file mode 100644 index 0000000000000000000000000000000000000000..8cc515c456bb37f80ddae6e74d026e777b65d99d --- /dev/null +++ b/pool/shard000/JavaScript/0005347_popup.js @@ -0,0 +1,106 @@ +var Popup = {}; +Popup.active = true; + +function parseDomain(url) { + var urlLocation = url.parseLocation(); + return urlLocation.protocol + "//" + urlLocation.hostname + "/*"; +} + +Popup.getBlacklisted = function(callback) { + var blacklists = Settings.blacklistedsites.filter(function(e) { + return e; + }); + this.getActiveTab(function(tab) { + var url = parseDomain(tab.url); + for (var i = 0, l = blacklists.length; i < l; ++i) { + if (blacklists[i].substring(0, url.length) === url) { + callback(true); + } + } + }); +}; + +Popup.getActiveTab = function(callback) { + chrome.tabs.query({active: true, currentWindow: true}, function(tab) { + callback(tab[0]); + }); +}; + +Popup.setIconDisabled = function() { + this.getActiveTab(function(tab) { + chrome.browserAction.setIcon({path: "icons/disabled.png", tabId: tab.id}); + }); +}; + +Popup.setIconEnabled = function(obj) { + if (obj.sender) { + return chrome.browserAction.setIcon({path: "icons/38.png", tabId: obj.sender.tab.id}); + } + this.getActiveTab(function(tab) { + chrome.browserAction.setIcon({path: "icons/38.png", tabId: tab.id}); + }); +}; + +Popup.getActiveState = function(obj) { + obj.callback(this.active); +}; + +Popup.toggleEnabled = function(obj) { + var request = obj.request; + if (request.singleTab) { + this.getActiveTab(function(tab) { + chrome.tabs.sendMessage(tab.id, {action: "toggleEnabled", state: !request.blacklisted}); + }); + if (request.blacklisted) { + return this.setIconDisabled({}); + } + return this.setIconEnabled({}); + } + chrome.tabs.query({}, function(tabs) { + this.active = !this.active; + if (!request.blacklisted) { + tabs.map(function(tab) { return tab.id; }).forEach(function(id) { + chrome.tabs.sendMessage(id, {action: "toggleEnabled", state: this.active}); + if (this.active) { + chrome.browserAction.setIcon({path: "icons/38.png", tabId: id}); + } else { + chrome.browserAction.setIcon({path: "icons/disabled.png", tabId: id}); + } + }.bind(this)); + } + }.bind(this)); +}; + +Popup.toggleBlacklisted = function() { + var blacklists = Settings.blacklistedsites.filter(function(e) { + return e; + }); + this.getActiveTab(function(tab) { + var url = parseDomain(tab.url); + var foundMatch = false; + for (var i = 0, l = blacklists.length; i < l; ++i) { + if (blacklists[i].substring(0, url.length) === url) { + blacklists.splice(i, 1); + foundMatch = true; + } + } + if (!foundMatch) { + blacklists.push(url); + } + Settings.blacklistedsites = blacklists; + Options.updateBlacklistsMappings(); + Options.saveSettings({settings: Settings}); + }); +}; + +chrome.runtime.onMessage.addListener(function(request, sender, callback) { + if (Popup.hasOwnProperty(request.action)) { + Popup[request.action]({ + callback: function(response) { + callback(response); + }, + request: request, + sender: sender + }); + } +}); diff --git a/pool/shard000/JavaScript/0005349_SurveyApi.js b/pool/shard000/JavaScript/0005349_SurveyApi.js new file mode 100644 index 0000000000000000000000000000000000000000..6a2e6fd018c6ef022a65fc5ad2b04452e495c2d9 --- /dev/null +++ b/pool/shard000/JavaScript/0005349_SurveyApi.js @@ -0,0 +1,132 @@ +import { WebApiServer } from 'Config' +import * as tokenStorage from 'services/AuthTokenStorage' +import fetchWithResponceValidation from 'api/fetchWithResponceValidation' + +export const fetchSurveys = (page, name = '') => { + return fetchWithResponceValidation(WebApiServer + `/api/survey?page=${page}&name=${name}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchTemplateSurveys = (page, name = '') => { + return fetchWithResponceValidation(WebApiServer + `/api/survey?page=${page}&name=${name}&template=true`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchSurvey = ({id, token}) => { + return fetchWithResponceValidation(WebApiServer + `/api/survey/${id}?token=${token}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchSurveyStats = (id) => { + return fetchWithResponceValidation(WebApiServer + `/surveystatistics/getsurveystats/${id}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchUsersSurveyStats = (surveyId, userId) => { + return fetchWithResponceValidation(WebApiServer + + `/surveystatistics/getuserssurveystats/${surveyId}?userId=${userId}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchSurveyTextStats = (textId, page) => { + return fetchWithResponceValidation(WebApiServer + + `/surveystatistics/gettextanswers/${textId}?page=${page}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const fetchUserNames = (name) => { + return fetchWithResponceValidation(WebApiServer + `/surveystatistics/getusernames?name=${name}`, { + method: 'GET', + headers: { + Authorization: tokenStorage.get() + } + }) +} + +export const addSurvey = (form) => { + return fetchWithResponceValidation(WebApiServer + '/api/survey', { + method: 'POST', + body: JSON.stringify(form), + headers: { + 'Content-Type': 'application/json', + Authorization: tokenStorage.get() + } + }) +} + +export const addSurveyTemplate = (form) => { + return fetchWithResponceValidation(WebApiServer + '/api/survey?template=true', { + method: 'POST', + body: JSON.stringify(form), + headers: { + 'Content-Type': 'application/json', + Authorization: tokenStorage.get() + } + }) +} + +export const sendSurveyAnswer = (form) => { + return fetchWithResponceValidation(WebApiServer + '/api/surveypass', { + method: 'POST', + body: JSON.stringify(form), + headers: { + 'Content-Type': 'application/json', + Authorization: tokenStorage.get() + } + }) +} + +export const editSurvey = (form) => { + return fetchWithResponceValidation(WebApiServer + `/api/survey/${form.id}`, { + method: 'PUT', + body: JSON.stringify(form), + headers: { + 'Content-Type': 'application/json', + Authorization: tokenStorage.get() + } + }) +} + +export const editSurveyTemplate = (form) => { + return fetchWithResponceValidation(WebApiServer + `/api/survey/${form.id}?template=true`, { + method: 'PUT', + body: JSON.stringify(form), + headers: { + 'Content-Type': 'application/json', + Authorization: tokenStorage.get() + } + }) +} + +export const deleteSurvey = (id) => { + return fetchWithResponceValidation(WebApiServer + `/api/survey/${id}`, { + method: 'DELETE', + headers: { + Authorization: tokenStorage.get() + } + }) +} diff --git a/pool/shard000/JavaScript/0005350_check-array.js b/pool/shard000/JavaScript/0005350_check-array.js new file mode 100644 index 0000000000000000000000000000000000000000..27fa2e150ce7e4bb55ab6810dafebf1778d58b6c --- /dev/null +++ b/pool/shard000/JavaScript/0005350_check-array.js @@ -0,0 +1,19 @@ +const { whoops } = require('./whoops-error'); + +module.exports.checkArray = (value, message = 'invalid array') => { + if (!Array.isArray(value)) { + whoops(message); + } + + return true; +}; + +module.exports.checkArrayEmpty = (value, message = 'empty array') => { + this.checkArray(value, message); + + if (value.length <= 0) { + whoops(message); + } + + return true; +}; diff --git a/pool/shard000/JavaScript/0005351_bg.js b/pool/shard000/JavaScript/0005351_bg.js new file mode 100644 index 0000000000000000000000000000000000000000..33f2cfa0e0bc46fae8614ec88255036622467dee --- /dev/null +++ b/pool/shard000/JavaScript/0005351_bg.js @@ -0,0 +1,182 @@ +// Magic Number (don't go too low): +var blockSize = 100; + +/* Reactive CSS Transitions © Yogev Ahuvia + * ======================================= + * These simple CSS blocks are alive. Each + * block reacts to its neighbors by + * transforming border-radius and color. + * Endless block formations, endless + * reactions between them. + * --------------------------------------- + * Works best on Google Chrome. + */ + +var elements = []; +var x, y, index, isEvenRow; +var $container, $window; + +function init() { + $container = $('#bg'); + $window = $(window); + x = (blockSize * 0.25); + y = -(blockSize * 0.5); + index = 0; + isEvenRow = false; +} + +$(document).ready(function () { + init(); + build(); +}); + +$(window).resize(function () { + init(); + build(); + onCheck(); +}); + +function build() { + do { + updateRowFlag(); + + if (!elements[index]) { + createNewBlock(x, y, index); + } else { + var elemObj = elements[index]; + $(elemObj.input).css({ 'left': x + 'px', 'top': y + 'px' }); + $(elemObj.block).css({ 'left': x + 'px', 'top': y + 'px' }); + } + + updateCoords(); + index++; + } while (y <= $window.height() + blockSize); +} + +function createNewBlock(x, y, index) { + var style = ' style="width: ' + blockSize + 'px; height: ' + blockSize + 'px; left: ' + x + 'px; top: ' + y + 'px;"'; + var $input = $('<input class="inputblock" type="checkbox"' + style + '></input>'); + var $block = $('<div class="block"' + style + '></div>'); + + $input.on('click', onCheck); + + elements.push({ input: $input[0], block: $block[0] }); + $container.append($input, $block); +} + +function updateRowFlag() { + if (x > $window.width()) { + isEvenRow = !isEvenRow; + x = (isEvenRow ? -(blockSize * 0.5) : (blockSize * 0.25)); + y += (blockSize * 0.75); + } +} + +function updateCoords() { + x += blockSize + (blockSize * 0.5); +} + +function getNeighbours(index, elem) { + var neighbors = { Ne: undefined, NEe: undefined, Ee: undefined, SEe: undefined, Se: undefined, SWe: undefined, We: undefined, NWe: undefined }; + + var Nc = { + x: elem.offsetLeft + (elem.offsetWidth / 2), + y: elem.offsetTop - elem.offsetHeight + }; + + var NEc = { + x: elem.offsetLeft + elem.offsetWidth, + y: elem.offsetTop - (elem.offsetHeight / 2) + }; + + var SEc = { + x: elem.offsetLeft + elem.offsetWidth, + y: elem.offsetTop + elem.offsetHeight + }; + + var Sc = { + x: elem.offsetLeft + (elem.offsetWidth / 2), + y: elem.offsetTop + (elem.offsetHeight * 2) + }; + + var SWc = { + x: elem.offsetLeft, + y: elem.offsetTop + elem.offsetHeight + }; + + var NWc = { + x: elem.offsetLeft, + y: elem.offsetTop - (elem.offsetHeight / 2) + }; + + for (var i = 0; i < elements.length; i++) { + var cur = elements[i].input; + + if (isCoordOnElement(Nc.x, Nc.y, cur)) { + neighbors.Ne = cur; + } + else if (isCoordOnElement(NEc.x, NEc.y, cur)) { + neighbors.NEe = cur; + } + else if (isCoordOnElement(SEc.x, SEc.y, cur)) { + neighbors.SEe = cur; + } + else if (isCoordOnElement(Sc.x, Sc.y, cur)) { + neighbors.Se = cur; + } + else if (isCoordOnElement(SWc.x, SWc.y, cur)) { + neighbors.SWe = cur; + } + else if (isCoordOnElement(NWc.x, NWc.y, cur)) { + neighbors.NWe = cur; + } + } + + if (elements[index - 1]) + neighbors.We = elements[index - 1].input; + if (elements[index + 1]) + neighbors.Ee = elements[index + 1].input; + + return neighbors; +} + +function isCoordOnElement(x, y, elem) { + if (x > elem.offsetLeft && + x < (elem.offsetLeft + elem.offsetWidth) && + y > elem.offsetTop && + y < (elem.offsetTop + elem.offsetHeight)) { + return true; + } + + return false; +} + +function clearEffects($elem) { + $elem.removeClass('Ns NWs NEs NWNEs Es SEs NESEs Ss SWs SESWs Ws NWs NWSWs NSs WEs'); +} + +function onCheck(e) { + for (var i = 0; i < elements.length; i++) { + var elemObj = elements[i]; + var neighbors = getNeighbours(i, elemObj.input); + var $block = $(elemObj.block); + clearEffects($block); + + if (neighbors.Ne && neighbors.Ne.checked) + $block.addClass('Ns'); + if (neighbors.NEe && neighbors.NEe.checked) + $block.addClass('NEs'); + if (neighbors.Ee && neighbors.Ee.checked) + $block.addClass('Es'); + if (neighbors.SEe && neighbors.SEe.checked) + $block.addClass('SEs'); + if (neighbors.Se && neighbors.Se.checked) + $block.addClass('Ss'); + if (neighbors.SWe && neighbors.SWe.checked) + $block.addClass('SWs'); + if (neighbors.We && neighbors.We.checked) + $block.addClass('Ws'); + if (neighbors.NWe && neighbors.NWe.checked) + $block.addClass('NWs'); + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005352_ensure-elements.js b/pool/shard000/JavaScript/0005352_ensure-elements.js new file mode 100644 index 0000000000000000000000000000000000000000..1cd94cd9591a864d03f22f025f4c23944d8b329c --- /dev/null +++ b/pool/shard000/JavaScript/0005352_ensure-elements.js @@ -0,0 +1,71 @@ +import { Promise } from '../deps/hammerhead'; + +import { domUtils, NODE_TYPE_DESCRIPTIONS } from '../deps/testcafe-core'; + +import SelectorExecutor from '../command-executors/client-functions/selector-executor'; + +import { + ActionElementNotFoundError, + ActionElementIsInvisibleError, + ActionSelectorMatchesWrongNodeTypeError, + ActionAdditionalElementNotFoundError, + ActionAdditionalElementIsInvisibleError, + ActionAdditionalSelectorMatchesWrongNodeTypeError +} from '../../../errors/test-run'; + + +class ElementsRetriever { + constructor (elementDescriptors, globalSelectorTimeout) { + this.elements = []; + this.globalSelectorTimeout = globalSelectorTimeout; + this.ensureElementsPromise = Promise.resolve(); + this.ensureElementsStartTime = new Date(); + + elementDescriptors.forEach(descriptor => this._ensureElement(descriptor)); + } + + _ensureElement ({ selector, createNotFoundError, createIsInvisibleError, createHasWrongNodeTypeError }) { + this.ensureElementsPromise = this.ensureElementsPromise + .then(() => { + const selectorExecutor = new SelectorExecutor(selector, this.globalSelectorTimeout, this.ensureElementsStartTime, + createNotFoundError, createIsInvisibleError); + + return selectorExecutor.getResult(); + }) + .then(el => { + if (!domUtils.isDomElement(el)) + throw createHasWrongNodeTypeError(NODE_TYPE_DESCRIPTIONS[el.nodeType]); + + this.elements.push(el); + }); + } + + getElements () { + return this.ensureElementsPromise + .then(() => this.elements); + } +} + +export function ensureElements (elementDescriptors, globalSelectorTimeout) { + const elementsRetriever = new ElementsRetriever(elementDescriptors, globalSelectorTimeout); + + return elementsRetriever.getElements(); +} + +export function createElementDescriptor (selector) { + return { + selector: selector, + createNotFoundError: fn => new ActionElementNotFoundError(fn), + createIsInvisibleError: () => new ActionElementIsInvisibleError(), + createHasWrongNodeTypeError: nodeDescription => new ActionSelectorMatchesWrongNodeTypeError(nodeDescription) + }; +} + +export function createAdditionalElementDescriptor (selector, elementName) { + return { + selector: selector, + createNotFoundError: fn => new ActionAdditionalElementNotFoundError(elementName, fn), + createIsInvisibleError: () => new ActionAdditionalElementIsInvisibleError(elementName), + createHasWrongNodeTypeError: nodeDescription => new ActionAdditionalSelectorMatchesWrongNodeTypeError(elementName, nodeDescription) + }; +} diff --git a/pool/shard000/JavaScript/0005353_index.js b/pool/shard000/JavaScript/0005353_index.js new file mode 100644 index 0000000000000000000000000000000000000000..70fb5b4103fee678106ccb8fa9c28e76b625622a --- /dev/null +++ b/pool/shard000/JavaScript/0005353_index.js @@ -0,0 +1,40 @@ +var _ = require('lodash'); +var Handlebars = require('handlebars'); + +var Engine = {}; + +Engine.engines = {}; + +/** + * + * @param type + * @param fn(template, data, relativePath) + * + * relativePath - path with which to resolve relative rules + */ +Engine.register = function(type, fn){ + + if (_.isString(type)) { + Engine.engines[type] = fn; + }else if(_.isPlainObject(type)){ + _.extend(Engine.engines, type); + }else{ + throw new Error('Engine.register: first argument must be string or object. Argument provided was \'' + String(type) + '\'.'); + } + +}; + +Engine.get = function(type){ + return Engine.engines[type]; +}; + +Engine.register('template', { + compile: function(source, relativePath){ + return Handlebars.compile(source); + }, + render: function(compiled, context){ + return compiled(context); + } +}); + +module.exports = Engine; diff --git a/pool/shard000/JavaScript/0005357_game.js b/pool/shard000/JavaScript/0005357_game.js new file mode 100644 index 0000000000000000000000000000000000000000..050cec087b4f03ec116cf496ad31f063adc4cd16 --- /dev/null +++ b/pool/shard000/JavaScript/0005357_game.js @@ -0,0 +1,120 @@ +var fileName = 'words.txt'; +var syllables; +var syllablesArray; +var words; +var wordsArray; +var usedWords = []; +var countUsedWords = []; +var countOfWords; +var markUsed = []; +var indexOfWord; +var countLevels = 3; + +function randomNumber(min, max) { + 'use strict'; + return Math.floor(Math.random() * (max - min + 1) + min); +} + +function shuffle(array) { + 'use strict'; + var counter = array.length, temp, index; + + while (counter > 0) { + index = Math.floor(Math.random() * counter); + counter -= 1; + temp = array[counter]; + array[counter] = array[index]; + array[index] = temp; + } + + return array; +} + +function resetRound() { + 'use strict'; + shuffle(syllables); + $('#syllablesHolder').empty(); + for (var i = 0; i < syllables.length; i += 1) { + $('<span />', + {text: syllables[i], class: 'draggable droppable'}) + .appendTo('#syllablesHolder'); + } + $('.draggable').draggable({revert: true, revertDuration: 0}); + + $('.droppable').droppable({ + hoverClass: 'drop-hover', + drop: function (event, ui) { + var oldSyllable = $(this).html(); + $(this).html(ui.draggable.html()); + ui.draggable.html(oldSyllable); + } + }); +} + +function startNewRound() { + 'use strict'; + var level = Dyslexio.getLevel('syllables'); + indexOfWord = getWordIndex(level); + words = wordsArray[indexOfWord]; + syllables = syllablesArray[indexOfWord]; + resetRound(); +} + +function getWordIndex(level) { + 'use strict'; + if (countUsedWords[level] === countOfWords) { + countUsedWords[level] = 0; + markUsed[level] += 1; + } + var index; + while (true) { + index = randomNumber(level * countOfWords, (level + 1) * countOfWords - 1); + if (usedWords[index] !== markUsed[level]) { + usedWords[index] = markUsed[level]; + countUsedWords[level] += 1; + break; + } + } + return index; +} + +function init() { + 'use strict'; + var jsonData = JSON.parse($('#helpDiv').text()); + wordsArray = jsonData.words; + countOfWords = jsonData.countOfWordsForEachLevel; + syllablesArray = jsonData.syllables; + var length = countOfWords * countLevels; + while (length) { + usedWords.push(0); + length -= 1; + if (length < countLevels) { + countUsedWords.push(0); + markUsed.push(1); + } + } + startNewRound(); +} + +function checkSolution() { + 'use strict'; + var spelledWord = $('#syllablesHolder').text(); + var correct = $.inArray(spelledWord, words) > -1; + if (correct) { + alert('Поздравления! Решихте правилно задачата'); + Dyslexio.correctSolution('syllables'); + startNewRound(); + } else { + alert('Имате грешки в решението. Опитайте отново'); + Dyslexio.incorrectSolution('syllables'); + } +} + +function initGame() { + 'use strict'; + $('#checkButton').click(checkSolution); + $('#resetButton').click(resetRound); + $('#newRoundButton').click(startNewRound); + $('#helpDiv').load(fileName, init); +} + diff --git a/pool/shard000/JavaScript/0005358_detect.js b/pool/shard000/JavaScript/0005358_detect.js new file mode 100644 index 0000000000000000000000000000000000000000..a5544590e79186f9120a1e13ed4594f6692d5f8f --- /dev/null +++ b/pool/shard000/JavaScript/0005358_detect.js @@ -0,0 +1,32 @@ +var parser = require('../'); +var test = require('tap').test; +var JSONStream = require('JSONStream'); +var packer = require('browser-pack'); +var path = require('path'); + +test('detect', function (t) { + t.plan(1); + var p = parser({ + detect: function (source) { + var rx = /require\(["'](.*?)["']\)/g; + var m, deps = []; + while (m = rx.exec(source)) { + deps.push(m[1]); + } + return deps; + } + }); + p.end(path.join(__dirname, '/files/main.js')); + p.on('error', t.fail.bind(t)); + var pack = packer(); + + p.pipe(JSONStream.stringify()).pipe(pack); + + var src = ''; + pack.on('data', function (buf) { src += buf }); + pack.on('end', function () { + Function('console', src)({ + log: function (s) { t.equal(s, 'main: 1055') } + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005361_u_test_e2e_issue_355.js b/pool/shard000/JavaScript/0005361_u_test_e2e_issue_355.js new file mode 100644 index 0000000000000000000000000000000000000000..f185b98e7a6d46896b2e3e9833e3b36ffb19ca1b --- /dev/null +++ b/pool/shard000/JavaScript/0005361_u_test_e2e_issue_355.js @@ -0,0 +1,73 @@ +/* global describe, it, require*/ +"use strict"; + +const should = require("should"); + +const opcua = require("node-opcua"); + +const perform_operation_on_subscription = require("../../test_helpers/perform_operation_on_client_session").perform_operation_on_subscription; +const redirectToFile = require("node-opcua-debug").redirectToFile; + +module.exports = function (test) { + + + describe("Testing server when client sessionName is not defined #355", function () { + + before(function(done){ + done(); + }); + it("#355 Client MonitoredItem event handler should be protected against exception raised in user code", function (done) { + + const server = test.server; + + if (!server) { + return done(); + } + + const client = opcua.OPCUAClient.create(); + + perform_operation_on_subscription(client,test.endpointUrl,function(session,subscription,callback) { + + redirectToFile("issue_355", function (callback) { + + const monitoredItem = opcua.ClientMonitoredItem.create(subscription, + {nodeId: "ns=1;s=FanSpeed", attributeId: opcua.AttributeIds.Value}, + { + samplingInterval: 10, // sampling twice as fast as variable refresh rate + discardOldest: true, + queueSize: 10 + }); + + let count = 0; + let timerId; + monitoredItem.on("changed",function(dataValue){ + + count++; + if (count >= 5) { + clearInterval(timerId); + return callback(); + } + // simulate an user error in event handler + throw new Error("Exception in user code"); + + }); + + timerId = setInterval(function() { + const node = test.server.engine.addressSpace.findNode("ns=1;s=FanSpeed"); + console.log("Set"); + node.setValueFromSource( new opcua.Variant({ + value: Math.random(), + dataType: "Float" + })); + },100); + + }, callback); + + + },done); + + }); + + }); + +}; diff --git a/pool/shard000/JavaScript/0005362_TodoList.js b/pool/shard000/JavaScript/0005362_TodoList.js new file mode 100644 index 0000000000000000000000000000000000000000..236a4f9c09f074ff31a547a2ca4a9ba4350b404f --- /dev/null +++ b/pool/shard000/JavaScript/0005362_TodoList.js @@ -0,0 +1,25 @@ +import React, { PropTypes } from 'react' +import Todo from './Todo' + +const TodoList = ({ todos, onTodoClick }) => ( + <ul> + {todos.map(todo => + <Todo + key={todo.id} + {...todo} + onClick={() => onTodoClick(todo.id)} + /> + )} + </ul> +); + +TodoList.propTypes = { + todos: PropTypes.arrayOf(PropTypes.shape({ + id: PropTypes.number.isRequired, + completed: PropTypes.bool.isRequired, + text: PropTypes.string.isRequired + }).isRequired).isRequired, + onTodoClick: PropTypes.func.isRequired +}; + +export default TodoList; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005364_course.server.model.test.js b/pool/shard000/JavaScript/0005364_course.server.model.test.js new file mode 100644 index 0000000000000000000000000000000000000000..120af13c905d1e7b7c804bf211360324fb1c537e --- /dev/null +++ b/pool/shard000/JavaScript/0005364_course.server.model.test.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * Module dependencies. + */ +var should = require('should'), + mongoose = require('mongoose'), + User = mongoose.model('User'), + Course = mongoose.model('Course'); + +/** + * Globals + */ +var user, course; + +/** + * Unit tests + */ +describe('Course Model Unit Tests:', function() { + beforeEach(function(done) { + user = new User({ + firstName: 'Full', + lastName: 'Name', + displayName: 'Full Name', + email: 'test@test.com', + username: 'username', + password: 'password', + roles: ['admin'] + }); + + user.save(function() { + course = new Course({ + name: 'Course Name', + description: 'Course Description', + price: 12, + instructor: 'Bruce Lee', + style: 'Karate', + belt: { + color: 'White', + level: 1 + } + }); + + done(); + }); + }); + + describe('Method Save', function() { + it('should be able to save without problems', function(done) { + return course.save(function(err) { + should.not.exist(err); + done(); + }); + }); + }); + + afterEach(function(done) { + Course.remove().exec(); + User.remove().exec(); + + done(); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005368_index_ctrl.js b/pool/shard000/JavaScript/0005368_index_ctrl.js new file mode 100644 index 0000000000000000000000000000000000000000..3b39ad7b70c5c1b4b9b1557ec89766cba58a1fb6 --- /dev/null +++ b/pool/shard000/JavaScript/0005368_index_ctrl.js @@ -0,0 +1,72 @@ +//index_ctrl.js + +var index = angular.module('index', ['ngRoute']); + +index.controller('iList', function($scope, $http, $sce){ + $scope.total = 0; + parseHtml = function(array){ + for(var p=0; p<array.length; p++){ + array[p] = $sce.trustAsHtml(array[p]); + } + } + + $http.jsonp('https://jdc.jd.com/jdccase/jsonp/project?category=app&callback=json1'); + + window.json1 = function (data) { + var tmplist = data.reverse(); + $scope.ilist = []; + + for(var i=0; i<tmplist.length; i++){ + var tmpObj = {}; + tmpObj.title=$sce.trustAsHtml(tmplist[i].title); + tmpObj.date=tmplist[i].projectTime; + tmpObj.id = tmplist[i]._id; + $scope.ilist.push(tmpObj); + } + + $http.get('js/vol.js') + .success(function(res){ + json2(res); + }); + } + + window.json2 = function(res){ + $scope.volList = res.reverse(); + $scope.total = $scope.volList.length; + + var latest = $scope.volList[$scope.total-1], + pt, projectTime; + + if($scope.total>0){ + for(var v=0; v<$scope.total; v++){ + var tmpCases = [], + tmpIndex = 0; + + $scope.volList[v].date = $scope.volList[v].date.split('-').join('.'); + $scope.volList[v].titles = []; + + pt = $scope.volList[v].date.split('.'); + projectTime = new Date(parseInt(pt[0]), parseInt(pt[1])-1, parseInt(pt[2])).toISOString(); + + for(var i=0; i<$scope.ilist.length; i++){ + if($scope.ilist[i].date === projectTime){ + $scope.ilist[i].num=++tmpIndex; + tmpCases.push($scope.ilist[i]); + } + } + $scope.volList[v].titles = tmpCases; + } + } + + document.querySelector('.loading').setAttribute('class', 'loading loaded'); + setTimeout(function(){document.querySelector('.loading').style.display="none";}, 400); + } + +}); + +function GetQueryString(name) +{ + var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); + var r = window.location.search.substr(1).match(reg); + if(r!=null)return unescape(r[2]); return null; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005370_index.js b/pool/shard000/JavaScript/0005370_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2479f1c23bdbc504c208b08862b57f67042ea94a --- /dev/null +++ b/pool/shard000/JavaScript/0005370_index.js @@ -0,0 +1,50 @@ +'use strict'; + +var path = require('path'); +var _ = require('lodash'); + +function requiredProcessEnv(name) { + if(!process.env[name]) { + throw new Error('You must set the ' + name + ' environment variable'); + } + return process.env[name]; +} + +// All configurations will extend these options +// ============================================ +var all = { + env: process.env.NODE_ENV, + + // Root path of server + root: path.normalize(__dirname + '/../../..'), + + // Server port + port: process.env.PORT || 8080, + + // Should we populate the DB with sample data? + seedDB: false, + + // Secret for session, you will want to change this and make it an environment variable + secrets: { + session: 'angular-full-stack-secret' + }, + + // List of user roles + userRoles: ['guest', 'user', 'admin'], + + // MongoDB connection options + mongo: { + options: { + db: { + safe: true + } + } + }, + +}; + +// Export the config object based on the NODE_ENV +// ============================================== +module.exports = _.merge( + all, + require('./' + process.env.NODE_ENV + '.js') || {}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005373_sbPushSpec.js b/pool/shard000/JavaScript/0005373_sbPushSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..0f515a8341f21e13ede3451fc0eed5242cf3f8d5 --- /dev/null +++ b/pool/shard000/JavaScript/0005373_sbPushSpec.js @@ -0,0 +1,77 @@ +'use strict'; + +describe('sbPush Factory', function() { + + beforeEach(function() { + var self = this; + module('selfbitsAngular', function(_$sbApiProvider_) { + self.$sbApiProvider = _$sbApiProvider_; + }) + inject(function(_$sbPush_, _$httpBackend_, _$http_, _$window_, _$interval_, _sbGuid_) { + self.$sbPush = _$sbPush_; + self.$httpBackend = _$httpBackend_; + self.$http = _$http_; + self.$window = _$window_; + self.$interval = _$interval_; + }); + self.$sbApiProvider.appId = 'fancyId'; + self.$sbApiProvider.appSecret = 'fancySecret'; + self.$sbApiProvider.domain = 'http://www.test.de'; + + // Stub for PushNotification + self.$window.PushNotification = { + init: function() { + return { + on: function() { + return; + } + }; + } + } + // Stub for device + self.$window.device = { + uuid: 1234588 + } + return; + }); + + afterEach(function() { + this.$httpBackend.verifyNoOutstandingExpectation(); + this.$httpBackend.verifyNoOutstandingRequest(); + }); + + it('should load', function() { + expect(this.$sbPush).to.be.ok; + }); + + it('should have Id and Secret set in Header', function() { + expect(this.$http.defaults.headers.common['SB-App-Id']).to.equal('fancyId'); + expect(this.$http.defaults.headers.common['SB-App-Secret']).to.equal('fancySecret'); + }); + + it('should allow to initialize the Push Service', function(done) { + var spy = sinon.spy(this.$window.PushNotification, 'init'); + this.$sbPush.init(); + expect(spy.called).to.be.true; + done(); + }); + + it('should allow to sync the token with the backend', function(done) { + this.$sbPush.pushRegistrationData = { + registrationId: '1234' + } + this.$httpBackend.expect('POST', 'http://www.test.de/api/v1/user/device/notification', { + 'uuid': 1234588, + 'deviceToken': '1234' + }).respond(200, { + data: 'fancyData' + }); + + this.$sbPush.sync().then(function() { + + }); + this.$httpBackend.flush(); + done(); + }); + +}); diff --git a/pool/shard000/JavaScript/0005376_ringNPC.js b/pool/shard000/JavaScript/0005376_ringNPC.js new file mode 100644 index 0000000000000000000000000000000000000000..4b47f9af717c24651ee50fd5f235681cb38a2c55 --- /dev/null +++ b/pool/shard000/JavaScript/0005376_ringNPC.js @@ -0,0 +1,43 @@ +var status; +var chr; + +function start() { + chr = cm.getSender(); + status = -1; + action(1, 0, 0); +} + +function action(mode, type, selection) { + if (chr == null) { + cm.sendOk("Unfortunately the player has disconnected"); + cm.dispose(); + return; + } else if (mode == 1) + status++; + else { + if (status == 1 && mode == 0) { + chr.dropMessage(1, "Your partner has declined your request."); + } else { + chr.dropMessage(1, "Your partner closed the npc chat."); + } + chr.setRingRequested(0); + cm.dispose(); + return; + } + + if (status == 0) + cm.sendNext(chr.getName()+" has sent you a ring."); + else if (status == 1) + cm.sendAcceptDecline("Please note that if you accept, the ring is permanent until a GM destroys your rings.\r\n\r\nIf you accept this invitation it will cost you 10,000,000 mesos."); + else if (status == 2) { + var i = cm.makeRing(chr, chr.getRingRequested()); + if (i == 1) { + cm.sendOk("Sucess"); + } else { + cm.sendOk("Failed to create ring"); + chr.dropMessage("Failed to create ring"); + } + chr.setRingRequested(0); + cm.dispose(); + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005377_AlwaysShowToolbar.js b/pool/shard000/JavaScript/0005377_AlwaysShowToolbar.js new file mode 100644 index 0000000000000000000000000000000000000000..f4f1302d750bc2cbf2c245301a45b276b6d520ad --- /dev/null +++ b/pool/shard000/JavaScript/0005377_AlwaysShowToolbar.js @@ -0,0 +1,191 @@ +/* + Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. + Available via Academic Free License >= 2.1 OR the modified BSD license. + see: http://dojotoolkit.org/license for details +*/ + + +if(!dojo._hasResource["dijit._editor.plugins.AlwaysShowToolbar"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. +dojo._hasResource["dijit._editor.plugins.AlwaysShowToolbar"] = true; +dojo.provide("dijit._editor.plugins.AlwaysShowToolbar"); +dojo.require("dijit._editor._Plugin"); + + + +dojo.declare("dijit._editor.plugins.AlwaysShowToolbar", dijit._editor._Plugin, + { + // summary: + // This plugin is required for Editors in auto-expand mode. + // It handles the auto-expansion as the user adds/deletes text, + // and keeps the editor's toolbar visible even when the top of the editor + // has scrolled off the top of the viewport (usually when editing a long + // document). + // description: + // Specify this in extraPlugins (or plugins) parameter and also set + // height to "". + // example: + // | <div dojoType="dijit.Editor" height="" + // | extraPlugins="['dijit._editor.plugins.AlwaysShowToolbar']"> + + // _handleScroll: Boolean + // Enables/disables the handler for scroll events + _handleScroll: true, + + setEditor: function(e){ + // Overrides _Plugin.setEditor(). + if(!e.iframe){ + console.log('Port AlwaysShowToolbar plugin to work with Editor without iframe'); + return; + } + + this.editor = e; + + e.onLoadDeferred.addCallback(dojo.hitch(this, this.enable)); + }, + + enable: function(d){ + // summary: + // Enable plugin. Called when Editor has finished initializing. + // tags: + // private + + this._updateHeight(); + this.connect(window, 'onscroll', "globalOnScrollHandler"); + this.connect(this.editor, 'onNormalizedDisplayChanged', "_updateHeight"); + return d; + }, + + _updateHeight: function(){ + // summary: + // Updates the height of the editor area to fit the contents. + var e = this.editor; + if(!e.isLoaded){ return; } + if(e.height){ return; } + + var height = dojo._getMarginSize(e.editNode).h; + if(dojo.isOpera){ + height = e.editNode.scrollHeight; + } + // console.debug('height',height); + // alert(this.editNode); + + //height maybe zero in some cases even though the content is not empty, + //we try the height of body instead + if(!height){ + height = dojo._getMarginSize(e.document.body).h; + } + + if(height == 0){ + console.debug("Can not figure out the height of the editing area!"); + return; //prevent setting height to 0 + } + if(dojo.isIE <= 7 && this.editor.minHeight){ + var min = parseInt(this.editor.minHeight); + if(height < min){ height = min; } + } + if(height != this._lastHeight){ + this._lastHeight = height; + // this.editorObject.style.height = this._lastHeight + "px"; + dojo.marginBox(e.iframe, { h: this._lastHeight }); + } + }, + + // _lastHeight: Integer + // Height in px of the editor at the last time we did sizing + _lastHeight: 0, + + globalOnScrollHandler: function(){ + // summary: + // Handler for scroll events that bubbled up to <html> + // tags: + // private + + var isIE6 = dojo.isIE < 7; + if(!this._handleScroll){ return; } + var tdn = this.editor.header; + var db = dojo.body; + + if(!this._scrollSetUp){ + this._scrollSetUp = true; + this._scrollThreshold = dojo.position(tdn, true).y; +// console.log("threshold:", this._scrollThreshold); + //what's this for?? comment out for now +// if((isIE6)&&(db)&&(dojo.style(db, "backgroundIimage")=="none")){ +// db.style.backgroundImage = "url(" + dojo.uri.moduleUri("dijit", "templates/blank.gif") + ")"; +// db.style.backgroundAttachment = "fixed"; +// } + } + + var scrollPos = dojo._docScroll().y; + var s = tdn.style; + + if(scrollPos > this._scrollThreshold && scrollPos < this._scrollThreshold+this._lastHeight){ + // dojo.debug(scrollPos); + if(!this._fixEnabled){ + var tdnbox = dojo._getMarginSize(tdn); + this.editor.iframe.style.marginTop = tdnbox.h+"px"; + + if(isIE6){ + s.left = dojo.position(tdn).x; + if(tdn.previousSibling){ + this._IEOriginalPos = ['after',tdn.previousSibling]; + }else if(tdn.nextSibling){ + this._IEOriginalPos = ['before',tdn.nextSibling]; + }else{ + this._IEOriginalPos = ['last',tdn.parentNode]; + } + dojo.body().appendChild(tdn); + dojo.addClass(tdn,'dijitIEFixedToolbar'); + }else{ + s.position = "fixed"; + s.top = "0px"; + } + + dojo.marginBox(tdn, { w: tdnbox.w }); + s.zIndex = 2000; + this._fixEnabled = true; + } + // if we're showing the floating toolbar, make sure that if + // we've scrolled past the bottom of the editor that we hide + // the toolbar for this instance of the editor. + + // TODO: when we get multiple editor toolbar support working + // correctly, ensure that we check this against the scroll + // position of the bottom-most editor instance. + var eHeight = (this.height) ? parseInt(this.editor.height) : this.editor._lastHeight; + s.display = (scrollPos > this._scrollThreshold+eHeight) ? "none" : ""; + }else if(this._fixEnabled){ + this.editor.iframe.style.marginTop = ''; + s.position = ""; + s.top = ""; + s.zIndex = ""; + s.display = ""; + if(isIE6){ + s.left = ""; + dojo.removeClass(tdn,'dijitIEFixedToolbar'); + if(this._IEOriginalPos){ + dojo.place(tdn, this._IEOriginalPos[1], this._IEOriginalPos[0]); + this._IEOriginalPos = null; + }else{ + dojo.place(tdn, this.editor.iframe, 'before'); + } + } + s.width = ""; + this._fixEnabled = false; + } + }, + + destroy: function(){ + // Overrides _Plugin.destroy(). TODO: call this.inherited() rather than repeating code. + this._IEOriginalPos = null; + this._handleScroll = false; + dojo.forEach(this._connects, dojo.disconnect); +// clearInterval(this.scrollInterval); + + if(dojo.isIE < 7){ + dojo.removeClass(this.editor.header, 'dijitIEFixedToolbar'); + } + } +}); + +} diff --git a/pool/shard000/JavaScript/0005378_main.js b/pool/shard000/JavaScript/0005378_main.js new file mode 100644 index 0000000000000000000000000000000000000000..d58212486662427eb160161bbc68967755990e7d --- /dev/null +++ b/pool/shard000/JavaScript/0005378_main.js @@ -0,0 +1,93 @@ +const electron = require('electron') +// Module to control application life. +const app = electron.app +// Module to create native browser window. +const BrowserWindow = electron.BrowserWindow +const fs = require('fs'); +const path = require('path') +const url = require('url') + +app.commandLine.appendSwitch("enable-smooth-scrolling"); + +// Keep a global reference of the window object, if you don't, the window will +// be closed automatically when the JavaScript object is garbage collected. +let mainWindow +let window_info_store_path = path.join(app.getPath("userData"), "bounds-info.json"); + +const remote = electron.remote; +//var sing = require("./dist/singleton") +var obj = new Object(); +obj.a = 88; +var singIns = obj; + +//alert(singIns); + + +exports.sing = singIns; +exports.funcA = function() { + + return singIns.a; +}; + +function createWindow() { + var bounds_info; + try { + bounds_info = JSON.parse(fs.readFileSync(window_info_store_path, 'utf8')); + } + catch (e) { + bounds_info = { width: 800, height: 1000 }; + } + + mainWindow = new BrowserWindow(bounds_info) + + // and load the index.html of the app. + + //mainWindow.loadURL("http://www.google.co.jp"); + + mainWindow.loadURL(url.format({ + pathname: path.join(__dirname, 'index.html'), + protocol: 'file:', + slashes: true + })) + + console.log(bounds_info); + var f3 = 100; + + // Open the DevTools. + // mainWindow.webContents.openDevTools() + mainWindow.on('close', () => { + fs.writeFileSync(window_info_store_path, JSON.stringify(mainWindow.getBounds())); + }); + // Emitted when the window is closed. + mainWindow.on('closed', function () { + // Dereference the window object, usually you would store windows + // in an array if your app supports multi windows, this is the time + // when you should delete the corresponding element. + mainWindow = null + }) +} + +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +// Some APIs can only be used after this event occurs. +app.on('ready', createWindow) + +// Quit when all windows are closed. +app.on('window-all-closed', function () { + // On OS X it is common for applications and their menu bar + // to stay active until the user quits explicitly with Cmd + Q + if (process.platform !== 'darwin') { + app.quit() + } +}) + +app.on('activate', function () { + // On OS X it's common to re-create a window in the app when the + // dock icon is clicked and there are no other windows open. + if (mainWindow === null) { + createWindow() + } +}) + +// In this file you can include the rest of your app's specific main process +// code. You can also put them in separate files and require them here. \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005380_samesite_handler.js b/pool/shard000/JavaScript/0005380_samesite_handler.js new file mode 100644 index 0000000000000000000000000000000000000000..8dfefd934bf03a07d0978f2ea7758a270ac4ee19 --- /dev/null +++ b/pool/shard000/JavaScript/0005380_samesite_handler.js @@ -0,0 +1,18 @@ +module.exports = { + get(cookies, name, opts) { + let value = cookies.get(name, opts); + + if (value === undefined && opts && /none/i.test(opts.sameSite)) { + value = cookies.get(`${name}.legacy`, opts); + } + + return value; + }, + set(cookies, name, value, opts) { + cookies.set(name, value, opts); + if (opts && /none/i.test(opts.sameSite)) { + const { sameSite, ...noSS } = opts; + cookies.set(`${name}.legacy`, value, noSS); + } + }, +}; diff --git a/pool/shard000/JavaScript/0005386_index.js b/pool/shard000/JavaScript/0005386_index.js new file mode 100644 index 0000000000000000000000000000000000000000..7ff639bd1e9e5306c19bc5ce96cb49c46f1e8712 --- /dev/null +++ b/pool/shard000/JavaScript/0005386_index.js @@ -0,0 +1,201 @@ +$(document).ready(function() { + $.extend(danceword,{loop:true}) + $('#superContainer').fullpage({ + navigation: true, + continuousVertical: true + }); + function getOs(){ + var OsObject = ""; + if(navigator.userAgent.indexOf("MSIE")>0) { + return "MSIE"; + } + if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ + $.getScript('./js/mousefollow.js'); + return "Firefox"; + } + if(isSafari=navigator.userAgent.indexOf("Safari")>0) { + $.getScript('./js/mousefollow.js'); + return "Safari"; + } + if(isCamino=navigator.userAgent.indexOf("Camino")>0){ + $.getScript('./js/mousefollow.js'); + return "Camino"; + } + if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){ + $.getScript('./js/mousefollow.js'); + return "Gecko"; + } + if(isChrome=navigator.userAgent.indexOf("Chrome/")>0){ + $.getScript('./js/mousefollow.js'); + return "Chrome"; + } + } + getOs(); + // // 花瓣飘落 + // $(document).snowfall('clear'); + // $(document).snowfall({ + // image: "images/flower.png", + // flakeCount: 16, + // minSize: 6, + // maxSize: 25 + // }); + // 万年历 + Date.prototype.Format = function (fmt) { //author: meizz + var o = { + "M+": this.getMonth() + 1, //月份 + "d+": this.getDate(), //日 + "h+": this.getHours(), //小时 + "m+": this.getMinutes(), //分 + "s+": this.getSeconds(), //秒 + "q+": Math.floor((this.getMonth() + 3) / 3), //季度 + "S": this.getMilliseconds() //毫秒 + }; + if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); + for (var k in o) + if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); + return fmt; + } + + function calendar () { + var date = new Date().Format("yyyy-MM-dd"); + var url = 'http://api.jisuapi.com/calendar/query'; + var data = { + date: date, + appkey: 'de9653892eba48b8' + } + var calendarData = localStorage.getItem("calendarData"); + if (!!calendarData) { + calendarData = JSON.parse(calendarData); + } + if (!calendarData || (!!calendarData && parseInt(calendarData.day) !== new Date().getDate())) { + $.ajax({ + type: "get", + url: url, + data: data, + dataType: 'jsonp', + success: function(res){ + if (res.status == 0) { + localStorage.setItem('calendarData', JSON.stringify(res.result)); + setCalendar(res.result); + } + }, + error: function(){ + alert('fail'); + } + }); + }else { + setCalendar(calendarData) + } + // var json = { + // year: "2017", + // month: "02", + // day: "14", + // week: "二", + // lunaryear: "2017", + // lunarmonth: "正月", + // lunarday: "十八", + // ganzhi: "丁酉", + // shengxiao: "鸡", + // festival: { + // solar: '情人節' + // }, + // "huangli": { + // "nongli": "农历二〇一五年九月初十", + // "taishen": "厨灶厕外西南", + // "wuxing": "路旁土", + // "chong": "冲(乙丑)牛", + // "sha": "煞西", + // "jiri": "朱雀(黑道)收日", + // "zhiri": "朱雀(黑道凶日)", + // "xiongshen": "地曩 月刑 河魁 五虚 朱雀", + // "jishenyiqu": "天德合 母仓 不将 玉宇 月德合", + // "caishen": "正东", + // "xishen": "西南", + // "fushen": "西南", + // "suici": [ + // "乙未年", + // "丙戌月", + // "辛未日" + // ], + // "yi": [ + // "祭祀", + // "冠笄", + // "移徙", + // "会亲友", + // "纳财", + // "理发", + // "捕捉" + // ], + // "ji": [ + // "嫁娶", + // "开市", + // "开池", + // "作厕", + // "破土" + // ] + // } + // }; + // setCalendar(json); + } + function setCalendar(json) { + var ganzhi = $('.calendar-ganzhi'); + ganzhi.html(json.ganzhi + '年 ' + json.lunaryear); + var shengxiao = $('.calendar-zodiac'); + shengxiao.html(json.shengxiao); + var day = $('.calendar-day'); + day.html(json.day); + var month = $('.calendar-month'); + month.html(json.month); + var lunar = $('.calendar-lunar'); + lunar.html(json.lunarmonth + ' ' + json.lunarday + ' 星期' + json.week + ' ' + (json.festival && json.festival.solar || '')); + var taboo = $('.calendar-taboo'); + var ji = json.huangli.ji; + if (ji.length > 5) { + ji = ji.slice(0, 5); + } + taboo.html('忌: ' + ji.join(' ')); + var benefit = $('.calendar-benefit'); + var yi = json.huangli.yi; + if (yi.length > 5) { + yi = yi.slice(0, 5); + } + var yiHtml = ''; + for (var i = 0; i < yi.length; i++) { + yiHtml += '<li>' + yi[i] + '</li>'; + } + benefit.html(yiHtml); + } + calendar(); + // 點擊查看更多工作經歷 + $('.work-more').click(function () { + var $el = $(this); + var openSatate = $el.attr('open-state') || 0; + var workBoxEl = $el.parents('.work-box'); + var workBoxElTop; + if (workBoxEl.index() === 2) { + workBoxElTop = parseInt(workBoxEl.css('top')) /12; + } + if (openSatate == 1) { + $el.attr('open-state', 0); + $el.html('展開').css({ + 'bottom': '-5em' + }).siblings('.work-content').css({ + '-webkit-line-clamp': '1' + }).parents('.work-box').css({ + 'top': workBoxElTop + 6 + 'em' + }).siblings('.work-box').show(); + }else { + $el.attr('open-state', 1); + $el.html('收起').css({ + 'bottom': '-12.5em' + }).siblings('.work-content').css({ + '-webkit-line-clamp': '10' + }).parents('.work-box').css({ + 'top': workBoxElTop - 6 + 'em' + }).siblings('.work-box').hide(); + } + // $el.parents('.work-box').siblings('.work-box').find('.work-content').css({ + // '-webkit-line-clamp': '1' + // }).siblings('.work-more').show(); + }); +}); diff --git a/pool/shard000/JavaScript/0005387_filters.js b/pool/shard000/JavaScript/0005387_filters.js new file mode 100644 index 0000000000000000000000000000000000000000..f3efa53e0a49b192e3c7baa51c400c859edfb54b --- /dev/null +++ b/pool/shard000/JavaScript/0005387_filters.js @@ -0,0 +1,25 @@ +'use strict'; + +/* Filters */ + +angular.module('myApp.filters', []). + filter('interpolate', ['version', function(version) { + return function(text) { + return String(text).replace(/\%VERSION\%/mg, version); + } + .filter('total', function () { + return function (input, property) { + var i = input instanceof Array ? input.length : 0; + if (typeof property === 'undefined' || i === 0) { + return i; + } else if (isNaN(input[0][property])) { + throw 'filter total can count only numeric values'; + } else { + var total = 0; + while (i--) + total += input[i][property]; + return total; + } + }; + }) +}]); diff --git a/pool/shard000/JavaScript/0005388_ForgotPassword.js b/pool/shard000/JavaScript/0005388_ForgotPassword.js new file mode 100644 index 0000000000000000000000000000000000000000..08a817a669906ff5202cb46e1aa6cbe3a2c808c6 --- /dev/null +++ b/pool/shard000/JavaScript/0005388_ForgotPassword.js @@ -0,0 +1,85 @@ +import { SERVER_API_BASE } from 'config'; +import Notifications from 'react-notification-system-redux'; + +import { + CHANGE_FP_MOBILE, + CHANGE_FP_OTP, + CHANGE_FP_PASSWORD, + FORGOT_PASSWORD_OTP_ERROR, + RESET_FORGOT_PASSWORD, +} from './types'; +import { toggleModal, redirect } from './index'; +import { showSuccessMessage } from './notifications'; + +export const changeFPMobile = (value) => { + return { + type: CHANGE_FP_MOBILE, + value, + }; +}; + +export const changeFPOTP = (value) => { + return { + type: CHANGE_FP_OTP, + value, + }; +}; + +export const changeFPPassword = (value) => { + return { + type: CHANGE_FP_PASSWORD, + value, + }; +}; + +export const submitForgotPassword = () => { + return (dispatch, getState) => { + const state = getState(); + const { password, mobile, otp } = state.forgotPassword; + const url = `${SERVER_API_BASE}users/otp-password-reset/`; + + fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + mobile_no: mobile, + password, + otp, + }), + }) + .then((res) => { + if (res.status === 200) { + return res.json().then((result) => { + return { + success: true, + result, + }; + }); + } + + return res.json().then((result) => { + return { + success: false, + result, + }; + }); + }) + .then((result) => { + if (result.success) { + dispatch(toggleModal('enterPassword')); + dispatch(Notifications.success(showSuccessMessage('Password Update!', 'Password updated successfully!'))); + dispatch({ + type: RESET_FORGOT_PASSWORD, + }); + // dispatch(redirect('/login')); + } else { + dispatch({ + type: FORGOT_PASSWORD_OTP_ERROR, + value: result.result, + }); + } + }); + }; +}; diff --git a/pool/shard000/JavaScript/0005390_jSQLParseUpdateTokens.js b/pool/shard000/JavaScript/0005390_jSQLParseUpdateTokens.js new file mode 100644 index 0000000000000000000000000000000000000000..900ca846ed7c092af9d096176a373602bbb3e33c --- /dev/null +++ b/pool/shard000/JavaScript/0005390_jSQLParseUpdateTokens.js @@ -0,0 +1,31 @@ + +function jSQLParseUpdateTokens(tokens){ + var table_name, query, newVals = {}; + var token = tokens.shift(); + + table_name = jSQLParseQuery.validateTableNameToken(token); + token = tokens.shift(); + + if(token.type !== "KEYWORD" && token.name !== "SET") + return _throw(new jSQL_Parse_Error(token, "SET")); + + while(tokens.length){ + var column_name = jSQLParseQuery.validateColumnName(tokens.shift().value, table_name); + token = tokens.shift(); + if(token.type !== 'SYMBOL' && token.name !== 'EQUALS') + return _throw(new jSQL_Parse_Error(token, "EQUALS")); + var value = tokens.shift().value; + newVals[column_name] = value; + if(!tokens.length) break; + token = tokens.shift(); + if(token.type === "SYMBOL" && token.name === "COMMA") continue; + if(token.type === "KEYWORD" && token.name === "WHERE"){ + tokens.unshift(token); + break; + } + } + + query = jSQL.update(table_name).set(newVals); + query = jSQLParseWhereClause(query, tokens, table_name); + return query; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005399_athena.js b/pool/shard000/JavaScript/0005399_athena.js new file mode 100644 index 0000000000000000000000000000000000000000..f7b13e88ec0d5aba82480b361d2650500c5896e8 --- /dev/null +++ b/pool/shard000/JavaScript/0005399_athena.js @@ -0,0 +1,274 @@ +"use strict"; +/* ------------------------------------------------------------------- + * Require Statements << Keep in alphabetical order >> + * ---------------------------------------------------------------- */ + +var arguer = require('arguer').thrower; +var httpLog = require('./httpLog.js'); +var Util = require('util'); + +/* ============================================================================= + * + * Athena (Async Control Framework) + * + * ========================================================================== */ + +var async = module.exports; + +/* ------------------------------------------------------------------- + * Public Methods << Keep in alphabetical order >> + * ---------------------------------------------------------------- */ + +var _mapFormat = +[ + { name: 'hlog', instance: httpLog, optional: true }, + { name: 'arr', type: 'object' }, + { name: 'method', type: 'function' }, + { name: 'resultsHandler', type: 'function' } +]; +async.map = function (/* hlog, */ arr, method, resultsHandler) +{ + var args = arguer.apply(_mapFormat, arguments); + + var hlog = args.hlog || null; + + var waiting = {}; + var finished = false; + var results = args.arr instanceof Array ? new Array(args.arr.length) : {}; + var context = new AsyncContext(hlog); + + for (var i in args.arr) + { + waiting[i] = true; + args.method.call(context, callback.bind(null, i), args.arr[i], i); + } + + finished = true; + checkDone(); // in case all methods actually ran synchronously. + + function callback (key, err, result) + { + delete waiting[key]; + results[key] = result; + context.log(err); + checkDone(); + } + + function checkDone () + { + if (finished && Object.keys(waiting).length === 0 && typeof args.resultsHandler === 'function') + { + args.resultsHandler.call(context, context.logChain, results); + args.resultsHandler = null; // prevent from being called multiple times + } + } +}; + +async.mapSeries = function (/* hlog, */ arr, method, resultsHandler) +{ + var args = arguer.apply(_mapFormat, arguments); + var hlog = args.hlog || null; + arr = args.arr; + method = args.method; + resultsHandler = args.resultsHandler; + + var results = arr instanceof Array ? new Array(arr.length) : {}; + var context = new AsyncContext(hlog); + + var keys = arr instanceof Array ? null : Object.keys(arr); + var length = keys ? keys.length : arr.length; + var i = 0; + var key; + + iterate(); + + function iterate () + { + if (i < length) + { + key = keys === null ? i : keys[i]; + method.call(context, iterateCallback, arr[key], key); + } + else + { + done(); + } + } + + function iterateCallback (error, item) + { + results[key] = item; + context.log(error); + if (context.logChain.failed) + { + done(); + } + else + { + i++; + setImmediate(iterate); // just so we don't get a stack overflow if someone calls everything sync + } + } + + function done () + { + resultsHandler.call(context, context.logChain, results); + } +}; + +var _parallelFormat = +[ + { name: 'hlog', instance: httpLog, optional: true }, + { name: 'methods', type: 'object' }, + { name: 'resultsHandler', type: 'function' } +]; +async.parallel = function (/* hlog, */ methods, resultsHandler) +{ + var args = arguer.apply(_parallelFormat, arguments); + + var hlog = args.hlog || null; + + var waiting = {}; + var finished = false; + var results = args.methods instanceof Array ? new Array(args.methods.length) : {}; + var context = new AsyncContext(hlog); + + for (var i in args.methods) + { + if (typeof args.methods[i] !== 'function') + continue; + + waiting[i] = true; + args.methods[i].call(context, callback.bind(null, i)); + } + + finished = true; + checkDone(); // in case all methods actually ran synchronously. + + function callback (key, err, result) + { + delete waiting[key]; + results[key] = result; + context.log(err); + checkDone(); + } + + function checkDone() + { + if (finished && Object.keys(waiting).length === 0 && typeof args.resultsHandler === 'function') + { + args.resultsHandler.call(context, context.logChain, results); + args.resultsHandler = null; // prevent from being called multiple times + } + } +}; + +var _waterfallFormat = + [ + { name: 'hlog', instance: httpLog, optional: true }, + { name: 'methods', instance: Array }, + { name: 'errorHandler', type: 'function' } + ]; +async.waterfall = function (/* hlog, */ methods, errorHandler) +{ + var args = arguer.apply(_waterfallFormat, arguments); + + var hlog = args.hlog || null; + + var iterator = { fn: null, called: false, allowReinvoke: false }; + for (var i = methods.length - 1; i > -1; i--) + { + iterator = { fn: methods[i], next: iterator, called: false, allowReinvoke: false }; + } + + var context = new WaterfallContext(hlog); + process.nextTick(WaterfallRun.bind(context, iterator, errorHandler)); +}; + +/* ------------------------------------------------------------------- + * AsyncContext (Base Context Class) + * ---------------------------------------------------------------- */ + +function AsyncContext (hlog) +{ + this.logChain = httpLog(hlog); +} + +AsyncContext.prototype.log = function (hlog) +{ + this.logChain = httpLog.chain(this.logChain, hlog); +}; + +/* ------------------------------------------------------------------- + * WaterfallContext + * ---------------------------------------------------------------- */ + +Util.inherits(WaterfallContext, AsyncContext); + +function WaterfallContext (hlog) +{ + AsyncContext.call(this, hlog); +} + +function WaterfallRun (iterator, errorHandler) +{ + var context = this; + + function createCallback (iterator) + { + var _break = false; + var cb = function () + { + var args = Array.prototype.slice.call(arguments); + + process.nextTick(function () + { + if (args.length > 0) + { + context.log(args[0]); + } + else + { + args = [ null ] + } + + if (iterator.called && (iterator.next &&!iterator.next.allowReinvoke)) + return; + + iterator.called = true; + + if (!iterator.fn || _break || context.logChain.failed) + { + args[0] = context.logChain || httpLog.none; + errorHandler.apply(context, args); + } + else + { + iterator.next.allowReinvoke = false; + args[0] = createCallback(iterator.next); + iterator.fn.apply(context, args); + } + }); + }; + + cb.break = function (hlog) + { + _break = true; + cb(hlog); + }; + + cb.enableReinvoke = function () + { + iterator.allowReinvoke = true; + }; + + cb.preventReinvoke = function () + { + iterator.allowReinvoke = false; + }; + + return cb; + } + + createCallback(iterator)(); +} diff --git a/pool/shard000/JavaScript/0005401_Study.template.js b/pool/shard000/JavaScript/0005401_Study.template.js new file mode 100644 index 0000000000000000000000000000000000000000..9e29cdeff29fe93acbdb04bf2b8e2dc709727ce0 --- /dev/null +++ b/pool/shard000/JavaScript/0005401_Study.template.js @@ -0,0 +1,84 @@ +// Source code licensed under Apache License 2.0. +// Copyright © 2017 William Ngan. (https://github.com/williamngan/pts) + + +Pts.namespace( window ); + +var space = new CanvasSpace("#pt").setup({retina: true, resize: true}); +var form = space.getForm(); + + +space.add( { + + start: init, + + animate: (time, ftime) => { + guidelines(); + + // Begin Test Code -- + + form.stroke("#f00", 2); + + // End + }, + + action:( type, px, py) => { + + }, + + resize:( bound, evt) => { + + } + +}); + +// Template: Predefined shapes for testing --- + +let gp = new Group(); +let line1, line2, line3, line4; +let rect1, rect2, rect3; +let poly1; +let circle1, circle2; + +function init(bound, space) { + let ux = space.width / 20; + let uy = space.height / 20; + + // vertical and horizontal line + line1 = Group.fromArray([[-ux, -space.height / 3], [ux, space.height / 3]]); + line2 = Group.fromArray([[0, -space.height / 2], [0, space.height / 2]]); + line3 = Group.fromArray([[-space.width / 3, -uy], [space.width / 3, uy]]); + line4 = Group.fromArray([[-space.width / 2, 0], [space.width / 2, 0]]); + gp.push(line1, line2, line3, line4); + + // bounds + rect1 = Group.fromArray([[-ux * 3, -uy * 3], [ux, uy]]); + rect2 = Group.fromArray([[-ux, -ux], [ux * 4, ux * 4]]); + gp.push(rect1, rect2); + + // shapes + poly1 = Group.fromArray([[-ux * 2, -uy * 2], [ux, uy * 3], [ux * 4, 0], [ux * 6, uy * 5]]); + gp.push(poly1); + + for (let i = 0, len = gp.length; i < len; i++) { + gp[i].anchorFrom(space.center); + } + + circle1 = Circle.fromRect(rect1); + circle2 = Circle.fromRect(rect1, true); + circle3 = Circle.fromRect(rect2, true); + rect3 = Rectangle.boundingBox([rect1, rect2]); +}; + +function guidelines() { + form.stroke("#c1c5ca", 1).fill(false); + form.lines( [line1, line2, line3, line4, poly1] ); + form.rects( [rect1, rect2, rect3] ); + form.circles( [circle1, circle2, circle3] ); +} + + + +space.bindMouse().bindTouch(); +space.play(); +// space.playOnce(5000); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005403_await.js b/pool/shard000/JavaScript/0005403_await.js new file mode 100644 index 0000000000000000000000000000000000000000..44e1814aa1f4838cfee981a4e9e5391f65409dfa --- /dev/null +++ b/pool/shard000/JavaScript/0005403_await.js @@ -0,0 +1,59 @@ +const assert = require('chai').assert; +const path = require('path'); +const fs = require('fs'); + +const valid_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'valid.apib'), 'utf8'); +const warning_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'warning.apib'), 'utf8'); +const error_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'error.apib'), 'utf8'); + +const valid_refract = require('../fixtures/valid.parse.json'); +const valid_sourcemap_refract = require('../fixtures/valid.parse.sourcemap.json'); +const warning_parse_refract = require('../fixtures/warning.parse.json'); +const warning_validate_refract = require('../fixtures/warning.validate.json'); +const error_refract = require('../fixtures/error.json'); + +module.exports = (parser) => { + describe('Parse with async/await', () => { + it('valid fixture without options should return parse result', async () => { + const refract = await parser.parse(valid_fixture); + assert.deepEqual(refract, valid_refract); + }); + + it('valid fixture with options should return parse result', async () => { + const refract = await parser.parse(valid_fixture, { generateSourceMap: true }); + assert.deepEqual(refract, valid_sourcemap_refract); + }); + + it('error fixture without options should return parse result', async () => { + const refract = await parser.parse(error_fixture); + assert.deepEqual(refract, error_refract); + }); + + it('warning fixture without options should return parse result', async () => { + const refract = await parser.parse(warning_fixture); + assert.deepEqual(refract, warning_parse_refract); + }); + }); + + describe('Validate with async/await', () => { + it('valid fixture without options should return null', async () => { + const refract = await parser.validate(valid_fixture); + assert.isNull(refract); + }); + + it('valid fixture with options should return null', async () => { + const refract = await parser.validate(valid_fixture, {}); + assert.isNull(refract); + }); + + it('error fixture without options should return annotations', async () => { + const refract = await parser.validate(error_fixture); + assert.deepEqual(refract, error_refract); + }); + + it('warning fixture without options should return annotations', async () => { + const refract = await parser.validate(warning_fixture); + assert.deepEqual(refract, warning_validate_refract); + }); + }); +}; diff --git a/pool/shard000/JavaScript/0005406_help.js b/pool/shard000/JavaScript/0005406_help.js new file mode 100644 index 0000000000000000000000000000000000000000..305d92c324254e9ffca8f171b221bd6c6321ad47 --- /dev/null +++ b/pool/shard000/JavaScript/0005406_help.js @@ -0,0 +1,37 @@ +const fs = require('fs'); +const path = require('path'); +const mdHelp = fs.readFileSync( + path.resolve(__dirname, '../templates/help.md'), + 'utf8' +); +const logger = require('../../../winston'); + +module.exports = function(controller) { + // apiai.hears for intents. in this example is 'hello' the intent + const helpLink = `[here](${controller.public_address}/#/help)`; + + controller.hears(['help$', 's*?help$'], 'direct_message', function( + bot, + message + ) { + bot.reply(message, { + markdown: mdHelp + }); + }); + controller.hears(['help$', 's*?help$'], 'direct_mention', function( + bot, + message + ) { + bot.startPrivateConversation(message, (error, convo) => { + if (error) logger.error(error); + convo.say({ + text: mdHelp, + markdown: mdHelp + }); + }); + let shortHelp = `Help has been sent to you individually. For the full help page click ${helpLink}. `; + bot.reply(message, { + markdown: shortHelp + }); + }); +}; diff --git a/pool/shard000/JavaScript/0005407_main.js b/pool/shard000/JavaScript/0005407_main.js new file mode 100644 index 0000000000000000000000000000000000000000..a1e70e5d831a6c77640374e9ae8be52ad2e56f26 --- /dev/null +++ b/pool/shard000/JavaScript/0005407_main.js @@ -0,0 +1,67 @@ +jQuery(document).ready(function($) { + + // scrollTo animation only for page anchors + $('.nav-main-link-anchor').on('click', function(event) { + event.preventDefault(); + $this = $(this); + var href = $this.attr('href'); + var pos; + var vert_offset = 56; + + if(href === '#') { + pos = "0"; + } else { + pos = $(href).offset().top - vert_offset; + } + + $('html, body').animate({ + scrollTop: pos + }, 1000); + }); + + // highlight current nav element + $(window).on('DOMContentLoaded load resize scroll', function() { + var target_nav_data = null; + var priority_target_nav_data = null; + var $tested_section = null; + + $('.nav-main-link').each(function(index, value) { + $this = $(this); + var location = window.location; + var url = location.href; + var url_tokens = url.split('/'); + var url_folder = url_tokens[url_tokens.length - 2]; + var link_data = $this.attr('data-site-nav'); + var link_data_tokens = link_data.split('#'); + + if(link_data_tokens.length == 1 && url_folder === link_data_tokens[0]) { + target_nav_data = '#'; + } else if(link_data_tokens.length == 2 && url_folder === link_data_tokens[0]) { + $tested_section = $('#' + link_data_tokens[1]); + if(customJS.isInViewport($tested_section)) { + priority_target_nav_data = link_data; + } + } + // override with the folder in the url path when scrolled to top + if($(window).scrollTop() === 0) { + priority_target_nav_data = url_folder; + } + }); + + if(priority_target_nav_data) { + target_nav_data = priority_target_nav_data; + } + + if(target_nav_data !== null) { + $('.nav-main-link-anchor').removeClass('nav-main-link-active'); + $('.nav-main-link-anchor[data-site-nav="' + target_nav_data + '"]').addClass('nav-main-link-active'); + } + }); + + // Page-Specific scripts + if ($(".page-home").length > 0) { + // do something on the Home page + // customJS.doSomething(); + } + +}); diff --git a/pool/shard000/JavaScript/0005409_index.js b/pool/shard000/JavaScript/0005409_index.js new file mode 100644 index 0000000000000000000000000000000000000000..6305b790060eb11aef84db5f4330fff845f09f1f --- /dev/null +++ b/pool/shard000/JavaScript/0005409_index.js @@ -0,0 +1,64 @@ +'use strict'; + +const express = require('express'); +const bodyParser = require('body-parser'); + + +const restService = express(); +restService.use(bodyParser.json()); + +restService.post('/hook', function (req, res) { + + console.log('hook request'); + + try { + var speech = 'empty speech'; + + if (req.body) { + var requestBody = req.body; + + if (requestBody.result) { + speech = ''; + + if (requestBody.result.fulfillment) { + speech += requestBody.result.fulfillment.speech; + speech += ' '; + } + + if (requestBody.result.action) { + speech += 'action: ' + requestBody.result.action + ' '; + } + + var parameters = requestBody.result.parameters; + if (parameters){ + for (var p in parameters){ + if(parameters.hasOwnProperty(p) ) { + speech += p + ": " + parameters[p] + "; "; + } + } + } + } + } + + console.log('result: ', speech); + + return res.json({ + speech: speech, + displayText: speech, + source: 'apiai-webhook-sample' + }); + } catch (err) { + console.error("Can't process request", err); + + return res.status(400).json({ + status: { + code: 400, + errorType: err.message + } + }); + } +}); + +restService.listen((process.env.PORT || 5000), function () { + console.log("Server listening"); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005411_undeployApiRevision.js b/pool/shard000/JavaScript/0005411_undeployApiRevision.js new file mode 100644 index 0000000000000000000000000000000000000000..185da79e98beceb11889e02ae91e0323ad9322ba --- /dev/null +++ b/pool/shard000/JavaScript/0005411_undeployApiRevision.js @@ -0,0 +1,25 @@ +'use strict'; + +var grunt_common = require('../libs/apigee-grunt-common.js'); + +module.exports = function(grunt) { + grunt.registerTask('undeployApiRevision', 'Undeploy an API revision. e.g. grunt undeployApiRevision:{revision_id}', function(revision) { + var undeployedRevision = function(error, response, body) { + if (!error && response.statusCode == 200) { + var undeployResult = JSON.parse(body); + grunt.option('revisions_undeployed', undeployResult) + } + grunt.log.debug(response.statusCode) + grunt.log.debug(body); + done(); + } + var revisionl = revision || (grunt.option('revisions_deployed') && grunt.option('revisions_deployed').revision && grunt.option('revisions_deployed').revision[0].name); + //revisions_deployed are only set when grunt is run in sequence, otherwise it'll be null + if(!revisionl){ + grunt.log.warn('Invalid revision id. e.g. grunt undeployApiRevision:{revision_id}'); + }else{ + var done = this.async(); + grunt_common.undeployApiRevision(grunt.config.get('apigee_profiles'), revisionl, undeployedRevision, grunt.option.flags().indexOf('--curl')!= -1); //send cURL switch to log curl commands + } + }); +}; diff --git a/pool/shard000/JavaScript/0005416_dialin.js b/pool/shard000/JavaScript/0005416_dialin.js new file mode 100644 index 0000000000000000000000000000000000000000..74fe3520be04fd2dd830de401792fa69d4e0c609 --- /dev/null +++ b/pool/shard000/JavaScript/0005416_dialin.js @@ -0,0 +1,91 @@ +//** +// * Asterisk SugarCRM Integration +// * (c) KINAMU Business Solutions AG 2009 +// * +// * Parts of this code are (c) 2006. RustyBrick, Inc. http://www.rustybrick.com/ +// * Parts of this code are (c) 2008 vertico software GmbH +// * Parts of this code are (c) 2009 abcona e. K. Angelo Malaguarnera E-Mail admin@abcona.de +// * http://www.sugarforge.org/projects/yaai/ +// * +// * This program is free software; you can redistribute it and/or modify it under +// * the terms of the GNU General Public License version 3 as published by the +// * Free Software Foundation with the addition of the following permission added +// * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK +// * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY +// * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. +// * +// * 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 or write to the Free +// * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +// * 02110-1301 USA. +// * +// * You can contact KINAMU Business Solutions AG at office@kinamu.com +// * +// * The interactive user interfaces in modified source and object code versions +// * of this program must display Appropriate Legal Notices, as required under +// * Section 5 of the GNU General Public License version 3. +// * +// */ + +var asterGritter = null; + +// look for new events logged from asterisk +function checkForNewStates(){ + $.getJSON('custom/modules/Asterisk/include/callListener.php', function(data){ + checkData(data);/*alert(data)*/ + }); + setTimeout('checkForNewStates()', 1000); +} + +function checkData(data){ + if(data == "."){ + if (asterGritter != null) { + $.gritter.removeAll(); + asterGritter = null; + } + return; + } + $.each(data, function(entryIndex, entry){ + // response is not empty, lets walk through the json array + var sfDiv = $("div[id='" + entry['asterisk_id'] + "']"); + if(!sfDiv.is("div")){ + var subs = /<h4>(.+?)<\/h4>/mig.exec(entry['html']); + asterGritter = $.gritter.add({ + title: subs[1], + text: entry['html'], + sticky: true + }); + sfDiv = $("div[id='" + entry['asterisk_id'] + "']"); + $('.asterisk_open_memo', sfDiv).click(function(){ + var newHREF = "index.php?module=Calls&action=DetailView&return_module=Calls&return_action=DetailView&parent_type=Contacts"; + newHREF += "&record=" + entry['call_record_id']; + //newHREF += "&direction=" + entry['direction']; + //newHREF += "&status=Held"; + //newHREF += "&parent_id=" + entry['contact_id']; + //newHREF += "&parent_name=" + entry['full_name']; + location.href = newHREF; + }); + + $('.asterisk_close', sfDiv).click(function(){ + $.gritter.removeAll(); + asterGritter = null; + }); + }else{ + $(".asterisk_state", sfDiv).text(entry['state']); + } + }); +} + +$(document).ready(function(){ + // no checking for the login page + if(location.href.indexOf('action=Login') == -1){ + $('<div id="asterisk_ajaxContent" style="display:none;"></div>').prependTo('#main'); + checkForNewStates(); + } +}); + diff --git a/pool/shard000/JavaScript/0005417_Shape.js b/pool/shard000/JavaScript/0005417_Shape.js new file mode 100644 index 0000000000000000000000000000000000000000..023f97f6fb1c4b6d7365b431950194a32fa515ec --- /dev/null +++ b/pool/shard000/JavaScript/0005417_Shape.js @@ -0,0 +1,143 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ShapeType_1 = require("../../../../Enums/ShapeType"); +var ImageShape_1 = require("./ImageShape"); +var PolygonShape_1 = require("./PolygonShape"); +var CharacterShape_1 = require("./CharacterShape"); +var Shape = (function () { + function Shape() { + this.options = {}; + this.character = new CharacterShape_1.CharacterShape(); + this.image = new ImageShape_1.ImageShape(); + this.polygon = new PolygonShape_1.PolygonShape(); + this.type = ShapeType_1.ShapeType.circle; + } + Object.defineProperty(Shape.prototype, "custom", { + get: function () { + return this.options; + }, + set: function (value) { + this.options = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Shape.prototype, "images", { + get: function () { + return this.image instanceof Array ? this.image : [this.image]; + }, + set: function (value) { + this.image = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Shape.prototype, "stroke", { + get: function () { + return []; + }, + set: function (value) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Shape.prototype, "character", { + get: function () { + var _a; + return ((_a = this.options[ShapeType_1.ShapeType.character]) !== null && _a !== void 0 ? _a : this.options[ShapeType_1.ShapeType.char]); + }, + set: function (value) { + this.options[ShapeType_1.ShapeType.character] = value; + this.options[ShapeType_1.ShapeType.char] = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Shape.prototype, "polygon", { + get: function () { + var _a; + return ((_a = this.options[ShapeType_1.ShapeType.polygon]) !== null && _a !== void 0 ? _a : this.options[ShapeType_1.ShapeType.star]); + }, + set: function (value) { + this.options[ShapeType_1.ShapeType.polygon] = value; + this.options[ShapeType_1.ShapeType.star] = value; + }, + enumerable: true, + configurable: true + }); + Shape.prototype.load = function (data) { + var _a; + if (data !== undefined) { + var options = (_a = data.options) !== null && _a !== void 0 ? _a : data.custom; + if (options !== undefined) { + for (var shape in options) { + var item = options[shape]; + if (item !== undefined) { + if (item instanceof Array) { + this.options[shape] = item.filter(function (t) { return t !== undefined; }).map(function (t) { + return t; + }); + } + else { + this.options[shape] = item; + } + } + } + } + if (data.character !== undefined) { + var item = data.character; + if (item !== undefined) { + if (item instanceof Array) { + this.options[ShapeType_1.ShapeType.character] = item.filter(function (t) { return t !== undefined; }).map(function (s) { + return s; + }); + this.options[ShapeType_1.ShapeType.char] = item.filter(function (t) { return t !== undefined; }).map(function (s) { + return s; + }); + } + else { + this.options[ShapeType_1.ShapeType.character] = item; + this.options[ShapeType_1.ShapeType.char] = item; + } + } + } + if (data.polygon !== undefined) { + var item = data.polygon; + if (item !== undefined) { + if (item instanceof Array) { + this.options[ShapeType_1.ShapeType.polygon] = item.filter(function (t) { return t !== undefined; }).map(function (s) { + return s; + }); + this.options[ShapeType_1.ShapeType.star] = item.filter(function (t) { return t !== undefined; }).map(function (s) { + return s; + }); + } + else { + this.options[ShapeType_1.ShapeType.polygon] = item; + this.options[ShapeType_1.ShapeType.star] = item; + } + } + } + if (data.image !== undefined) { + if (data.image instanceof Array) { + this.image = data.image.map(function (s) { + var tmp = new ImageShape_1.ImageShape(); + tmp.load(s); + return tmp; + }); + } + else { + if (this.image instanceof Array) { + this.image = new ImageShape_1.ImageShape(); + } + this.image.load(data.image); + } + } + if (data.type !== undefined) { + this.type = data.type; + } + } + }; + return Shape; +}()); +exports.Shape = Shape; diff --git a/pool/shard000/JavaScript/0005420_object.js b/pool/shard000/JavaScript/0005420_object.js new file mode 100644 index 0000000000000000000000000000000000000000..b647fb04414026c093adb8e31c99bf71ae4235b8 --- /dev/null +++ b/pool/shard000/JavaScript/0005420_object.js @@ -0,0 +1,84 @@ +/** + * Utility function to see if one or many properties differ between two + * provided objects + * + * This is useful for checking for differences between e.g. props and nextProps + * in a shouldComponentUpdate method + * + * @example + * + * const obj1 = { val: true }; + * const obj2 = { val: true }; + * + * valueChanged(obj1, obj2, 'val'); // false + * + * const obj1 = { val1: true, val2: 1 }; + * const obj2 = { val1: false, val2: 1 }; + * + * valueChanged(obj1, obj2, [ 'val1', 'val2' ]); // true + * + * @returns {Boolean} Whether any of the specified properties differ between + * the two provided objects (by strict equality comparison) + */ +export function valueChanged(obj1, obj2, props) { + // Support a string or an array for the final property + const propsArr = Array.isArray(props) ? props : [props]; + + for (let i = 0; i < propsArr.length; i += 1) { + if (obj1[propsArr[i]] !== obj2[propsArr[i]]) { + return true; + } + } + + return false; +} + +/** + * omit one or many properties from an object + * + * @example + * + * omit({ a: 1, b: 2, c: 3}, ['b', 'c']) // {a: 1} + * omit({ a: 1, b: 2, c: 3}, 'a') // {b: 2, c: 3} + * + * @param {Object} obj An object from which to omit props + * @param {String|String[]} props A string property or array thereof + * @returns {Object} A new object with only the specified properties + */ +export function omit(obj, props) { + // Support a string or an array for the final property + const propsArr = Array.isArray(props) ? props : [props]; + return Object.keys(obj).reduce((carry, prop) => { + if (propsArr.includes(prop)) { + return carry; + } + return Object.assign(carry, { + [prop]: obj[prop], + }); + }, {}); +} + +/** + * Pick one or many properties from an object + * + * @example + * + * pick({ a: 1, b: 2, c: 3}, ['b', 'c']) // {b: 2, c: 3} + * pick({ a: 1, b: 2, c: 3}, 'a') // {a: 1} + * + * @param {Object} obj An object from which to pick props + * @param {String|String[]} props A string property or array thereof + * @returns {Object} A new object with only the specified properties + */ +export function pick(obj, props) { + // Support a string or an array for the final property + const propsArr = Array.isArray(props) ? props : [props]; + return propsArr.reduce((carry, prop) => { + if (! obj[prop]) { + return carry; + } + return Object.assign({}, carry, { + [prop]: obj[prop], + }); + }, {}); +} diff --git a/pool/shard000/JavaScript/0005422_FormularioController.js b/pool/shard000/JavaScript/0005422_FormularioController.js new file mode 100644 index 0000000000000000000000000000000000000000..0f08cc18669dffaf9d54149dd81f1d709e3e7d7c --- /dev/null +++ b/pool/shard000/JavaScript/0005422_FormularioController.js @@ -0,0 +1,249 @@ +/************************************************************************************************** + * Archivo: FormularioController.js + * ------------------------------------------------------------------------------------------------ + * Version: 1.0 + * Descripcion: + * Modificaciones: + * - + * + * Nota: Registrar en este encabezado todas las modificaciones hechas al archivo. + **************************************************************************************************/ + +Ext.define ('Sistema.view.Produccion.NovedadCentroDeTrabajo.FormularioController', { + extend: 'Ext.app.ViewController', + alias: 'controller.prod-novct-FormularioController', + + init: function () { + FormularioControllerBase.InyectarDependencia (this, 'Sistema.view.Produccion.model.NovedadCentroDeTrabajo', 'Produccion:NovedadCentroDeTrabajo'); + + this.control ({ + "button[name='btnBorrar']": { + click: this.onBtnBorrarClick + }, + "button[name='btnGuardar']": { + click: this.onBtnGuardarClick + }, + "button[name='btnCerrar']": { + click: this.onBtnCerrarClick + }, + "prod-novct-Formulario": { + afterrender: this.onRender + } + }); + }, + + //---------- EventHandlers ---------- + + onBtnCerrarClick: function () { + this.IntentarCerrarVentanaContenedora (); + }, + + //---------- metodos privados---------- + + // + // Crea un store vacio para el combo. + // + InicialiarComboTipo: function () { + var st = Ext.create ('Sistema.view.Produccion.store.StoreTipoNovedadCentroDeTrabajo', {autoDestroy:true}); + this.ctl.cbTipoNovedad.setStore (st); + st.load (); + }, + + CargarComponentes: function () { + var me = this; + + this.params.nombreEntidad = 'Novedad Centro de Trabajo'; + // Carga de componentes + this.ctl.tbNroNovedad = this.getView ().down ("textfield[name='tbNroNovedad']"); + this.ctl.tbNroNovedad = this.getView ().down ("textfield[name='tbNroNovedad']"); + this.ctl.tbFecha = this.getView ().down ("textfield[name='tbFecha']"); + this.ctl.tbUsuarioDeCarga = this.getView ().down ("textfield[name='tbUsuarioDeCarga']"); + this.ctl.tbCodCentroDeTrabajo = this.getView ().down ("textfield[name='tbCodCentroDeTrabajo']"); + this.ctl.tbDescCentroDeTrabajo = this.getView ().down ("textfield[name='tbDescCentroDeTrabajo']"); + this.ctl.tbCodMaquina = this.getView ().down ("textfield[name='tbCodMaquina']"); + this.ctl.tbDescMaquina = this.getView ().down ("textfield[name='tbDescMaquina']"); + this.ctl.tbComentarios = this.getView ().down ("textareafield[name='tbComentarios']"); + this.ctl.cbTipoNovedad = this.getView ().down ("combo[name='cbTipoNovedad']"); + this.ctl.tbFechaCreacion = this.getView ().down ("datefield[name='tbFechaCreacion']"); + this.ctl.nfHoras = this.getView ().down ("numberfield[name='nfHoras']"); + this.ctl.nfMinutos = this.getView ().down ("numberfield[name='nfMinutos']"); + this.ctl.btnGuardar = this.getView ().down ("button[name='btnGuardar']"); + this.ctl.btnBorrar = this.getView ().down ("button[name='btnBorrar']"); + this.ctl.btnCerrar = this.getView ().down ("button[name='btnCerrar']"); + + this.InicialiarComboTipo (); + + // Centro de Trabajo + this.ctl.CampoCentroDeTrabajo = new CampoBusqueda (); + this.ctl.CampoCentroDeTrabajo.SetClaseModelo ('Sistema.view.Produccion.model.CentroDeTrabajo'); + this.ctl.CampoCentroDeTrabajo.SetClaseListado ('Sistema.view.Produccion.CentroDeTrabajo.Listado'); + this.ctl.CampoCentroDeTrabajo.SetClaseFormulario ('Sistema.view.Produccion.CentroDeTrabajo.Formulario'); + this.ctl.CampoCentroDeTrabajo.SetUrlBusqueda ('Server/Sysgran/Aplicacion/Modulos/Produccion/CentroDeTrabajo/FormularioController.php'); + this.ctl.CampoCentroDeTrabajo.SetController (this); + this.ctl.CampoCentroDeTrabajo.SetTextFieldCodigo ('tbCodCentroDeTrabajo'); + this.ctl.CampoCentroDeTrabajo.SetBtnBuscar ('btnBuscarCentroDeTrabajo'); + this.ctl.CampoCentroDeTrabajo.SetBtnVerRegistro ('btnVerCentroDeTrabajo'); + + this.ctl.CampoCentroDeTrabajo.onRegistroSeleccionadoOk = function (rec) { + me.ctl.tbCodCentroDeTrabajo.setValue (rec.get ('codigo')); + me.ctl.tbDescCentroDeTrabajo.setValue (rec.get ('nombre')); + this.itemId = rec.get ('id'); + + // Limpiamos la seleccion de maquina. + me.ctl.CampoMaquina.itemId = 0; + me.ctl.tbCodMaquina.setValue (''); + me.ctl.tbDescMaquina.setValue (''); + }; + + this.ctl.CampoCentroDeTrabajo.onRegistroSeleccionadoError = function () { + me.ctl.tbCodCentroDeTrabajo.setValue (''); + me.ctl.tbDescCentroDeTrabajo.setValue (''); + + // Limpiamos la seleccion de maquina. + me.ctl.CampoMaquina.itemId = 0; + me.ctl.tbCodMaquina.setValue (''); + me.ctl.tbDescMaquina.setValue (''); + }; + + // Maquina + this.ctl.CampoMaquina = new CampoBusqueda (); + this.ctl.CampoMaquina.SetClaseModelo ('Sistema.view.Produccion.model.Maquina'); + this.ctl.CampoMaquina.SetClaseListado ('Sistema.view.Produccion.Maquina.Listado'); + this.ctl.CampoMaquina.SetClaseFormulario ('Sistema.view.Produccion.Maquina.Formulario'); + this.ctl.CampoMaquina.SetUrlBusqueda ('Server/Sysgran/Aplicacion/Modulos/Produccion/Maquina/FormularioController.php'); + this.ctl.CampoMaquina.SetController (this); + this.ctl.CampoMaquina.SetTextFieldCodigo ('tbCodMaquina'); + this.ctl.CampoMaquina.SetBtnBuscar ('btnBuscarMaquina'); + this.ctl.CampoMaquina.SetBtnVerRegistro ('btnVerMaquina'); + + // Filtramos las maquinas que no pertenecen al CT seleccionado + this.ctl.CampoMaquina.SetFiltroListado (function () { + var ret = [{ + nombre: 'centro_trabajo', + params: { + id: me.ctl.CampoCentroDeTrabajo.itemId + } + }]; + + return ret; + }); + + this.ctl.CampoMaquina.onRegistroSeleccionadoOk = function (rec) { + // Chequeamos que la maquina pertenezca al CT seleccionado + if (rec.get ('centroDeTrabajoId') != me.ctl.CampoCentroDeTrabajo.itemId) { + me.ctl.tbCodMaquina.setValue (''); + Ext.Msg.alert('Atencion', 'La Maquina indicada no pertenece al centro de trabajo seleccionado'); + + } else { + me.ctl.tbCodMaquina.setValue (rec.get ('codigo')); + me.ctl.tbDescMaquina.setValue (rec.get ('descripcion')); + this.itemId = rec.get ('id'); + } + }; + + this.ctl.CampoMaquina.onRegistroSeleccionadoError = function () { + me.ctl.tbCodMaquina.setValue (''); + me.ctl.tbDescMaquina.setValue (''); + }; + }, + + GetElementoFoco: function () { + return "textfield[name='tbCodCentroDeTrabajo']"; + }, + + SetearParametrosFormulario: function (ctl) { + ctl.params.anchoVentana = 1024; + ctl.params.altoVentana = 400; + }, + + CargarRegistroEnFormulario: function (rec, esNuevo) { + var me = this; + + this.params.registro = rec; + if (esNuevo) { + this.ctl.tbNroNovedad.setValue ('----'); + + // Cargamos la fecha y hora actuales por default. + new ConsultaWS ().Ejecutar ('Core', 'Servicios', 'Controller', 'GetFechaYHoraActual', null, function (resp) { + if (this.RespuestaOK ()) { + me.ctl.tbFechaCreacion.setValue (resp.fecha); + me.ctl.nfHoras.setValue (resp.hora); + me.ctl.nfMinutos.setValue (resp.minutos); + + } else { + Ext.Msg.alert('Error', this.GetMensajeRespuesta ()); + } + }); + + } else { + this.ctl.btnGuardar.hide (); + this.ctl.btnCerrar.setHidden (false); + + this.ctl.tbNroNovedad.setValue (rec.get ('id')); + this.ctl.CampoCentroDeTrabajo.BuscarPorId (rec.get ('centroDeTrabajoId')); + this.ctl.CampoCentroDeTrabajo.Deshabilitar (); + + if (rec.get ('maquinaId') != null) { + this.ctl.CampoMaquina.BuscarPorId (rec.get ('maquinaId')); + } + + this.ctl.CampoMaquina.Deshabilitar (); + + this.ctl.cbTipoNovedad.setValue (rec.get ('tipoNovedadCTId')); + this.ctl.cbTipoNovedad.setReadOnly (true); + + this.ctl.tbComentarios.setValue (rec.get ('comentarios')); + this.ctl.tbComentarios.setReadOnly (true); + + this.ctl.tbFechaCreacion.setValue (rec.get ('fecha')); + this.ctl.tbFechaCreacion.setReadOnly (true); + + this.ctl.nfHoras.setValue (rec.get ('hora')); + this.ctl.nfHoras.setReadOnly (true); + + this.ctl.nfMinutos.setValue (rec.get ('minutos')); + this.ctl.nfMinutos.setReadOnly (true); + + this.ctl.tbFecha.setValue (rec.get ('timestamp')); + this.ctl.tbUsuarioDeCarga.setValue (rec.get ('usuario').loginName); + } + }, + + ObtenerRegistroDeFormulario: function () { + if (!this.ValidarFormulario ()) { + return null; + } + + this.params.registro.set ('maquinaId', this.ctl.CampoMaquina.itemId); + this.params.registro.set ('centroDeTrabajoId', this.ctl.CampoCentroDeTrabajo.itemId); + this.params.registro.set ('tipoNovedadCTId', this.ctl.cbTipoNovedad.value); + this.params.registro.set ('comentarios', this.ctl.tbComentarios.value); + this.params.registro.set ('fecha', this.ctl.tbFechaCreacion.getRawValue ()); + this.params.registro.set ('hora', this.ctl.nfHoras.value); + this.params.registro.set ('minutos', this.ctl.nfMinutos.value); + + return this.params.registro; + }, + + ValidarFormulario: function () { + if (this.ctl.CampoCentroDeTrabajo.itemId == 0) { + Ext.Msg.alert('Error', 'Debe indicar el Centro de Trabajo'); + + return false; + } + + if (this.ctl.nfHoras.value < 0 || this.ctl.nfHoras.value >= 24) { + Ext.Msg.alert('Error', 'Formato de Hora invalido'); + + return false; + } + + if (this.ctl.nfMinutos.value < 0 || this.ctl.nfMinutos.value >= 60) { + Ext.Msg.alert('Error', 'Formato de Minutos invalido'); + + return false; + } + + return true; + } +}); diff --git a/pool/shard000/JavaScript/0005426_headerfooter.js b/pool/shard000/JavaScript/0005426_headerfooter.js new file mode 100644 index 0000000000000000000000000000000000000000..9fac4dec4776966920f8cb8b2430c32bb4195592 --- /dev/null +++ b/pool/shard000/JavaScript/0005426_headerfooter.js @@ -0,0 +1,51 @@ +/*- + * #%L + * ARROWHEAD::WP5::Aggregator Manager + * %% + * Copyright (C) 2016 The ARROWHEAD Consortium + * %% + * 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. + * #L% + */ +'use strict'; + +angular.module('foaManApp') + .controller('HeaderCtrl', function ($scope, $location, $timeout, serviceFOA) { + $scope.isActive = function (viewLocation) { + return viewLocation === $location.path(); + }; + + $scope.connect = function(connect) { + var c = new serviceFOA.Connection(); + c.value = connect; + c.$save(); + }; + + $scope.isConnected = { value: false }; + (function tick() { + serviceFOA.Connection.get().$promise.then( + function(val) { + $scope.isConnected = val; + }, function(error){ + $scope.isConnected = null; + }); + $timeout(tick, 2000); + })(); + + }); diff --git a/pool/shard000/JavaScript/0005427_logo.js b/pool/shard000/JavaScript/0005427_logo.js new file mode 100644 index 0000000000000000000000000000000000000000..7fba69435f8e768e09860324cb47f27a7e747997 --- /dev/null +++ b/pool/shard000/JavaScript/0005427_logo.js @@ -0,0 +1,22 @@ +/** + * Generate logo prompt + */ + +'use strict'; + +var logoPrompt = function logoPrompt() { + var pistacheoLogo = '' + + ' _ _ _ \n'.green + + ' (_) | | | | '.green + 'Welcome to'.red + ' \n'.green + + ' _ __ _ ___| |_ __ _ ___| |__ ___ ___ \n'.green + + '| _ \| / __| __/ _` |/ __| \'_ \\ / _ \\/ _ \\ \n'.green + + '| |_) | \\__ \\ || (_| | (__| | | | __/ (_) |\n'.green + + '| .__/|_|___/\\__\\__,_|\\___|_| |_|\\___|\\___/ \n'.green + + '| | \n'.green + + '|_| \n'.green; + + // have Yeogurt greet the user. + this.log(pistacheoLogo); +}; + +module.exports = logoPrompt; diff --git a/pool/shard000/JavaScript/0005429_user_badge.js b/pool/shard000/JavaScript/0005429_user_badge.js new file mode 100644 index 0000000000000000000000000000000000000000..ca7562581121a973c4f877f88b44571fd9bef1e6 --- /dev/null +++ b/pool/shard000/JavaScript/0005429_user_badge.js @@ -0,0 +1,23 @@ +/** @jsx React.DOM */ + +var React = require("react"); +var UserImage = require("./user_image"); + +var UserBadge = React.createClass({ + getDefaultProps: function(){ + return { + friendlyName: "Billy McGee", + userSlug: "billymcgee" + }; + }, + render: function(){ + return ( + <div> + <h1>{this.props.friendlyName}</h1> + <UserImage slug={this.props.userSlug} /> + </div> + ); + } +}); + +module.exports = UserBadge; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005430_failures-test.js b/pool/shard000/JavaScript/0005430_failures-test.js new file mode 100644 index 0000000000000000000000000000000000000000..527a6ac2fb9509e4bf9dac2a5c95f5bf4aba1235 --- /dev/null +++ b/pool/shard000/JavaScript/0005430_failures-test.js @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2014-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. + */ + +'use strict'; + +const {extractSummary} = require('../utils'); +const path = require('path'); +const runJest = require('../runJest'); +const skipOnWindows = require('skipOnWindows'); + +const dir = path.resolve(__dirname, '../failures'); + +skipOnWindows.suite(); + +test('throwing not Error objects', () => { + let stderr; + stderr = runJest(dir, ['throw-number-test.js']).stderr; + expect(extractSummary(stderr)).toMatchSnapshot(); + stderr = runJest(dir, ['throw-string-test.js']).stderr; + expect(extractSummary(stderr)).toMatchSnapshot(); + stderr = runJest(dir, ['throw-object-test.js']).stderr; + expect(extractSummary(stderr)).toMatchSnapshot(); +}); diff --git a/pool/shard000/JavaScript/0005431_htmlDiff.js b/pool/shard000/JavaScript/0005431_htmlDiff.js new file mode 100644 index 0000000000000000000000000000000000000000..16108389e56c927d92744d070346ca0798dce5d3 --- /dev/null +++ b/pool/shard000/JavaScript/0005431_htmlDiff.js @@ -0,0 +1,76 @@ +function htmlDiff() { + var _htmlHash; + var _revHtmlHash; + var _currentHash; + var _is_debug = false; + + function pushHash(tag) { + if (typeof(_htmlHash[tag]) == 'undefined') { + var value = eval('"\\u'+_currentHash.toString(16)+'"'); + _htmlHash[tag] = value; + _revHtmlHash[value] = tag; + _currentHash++; + } + return _htmlHash[tag]; + } + + this.clearHash = function() { + _htmlHash = {}; + _revHtmlHash = {}; + _currentHash = 44032; //朝鲜文音节 Hangul Syllables + }; + function html2plain(html) { + html = html.replace(/<(S*?)[^>]*>.*?|<.*?\/>/g, function(tag){ + //debug: + if (_is_debug) { + return pushHash(tag.replace(/</g, '<').replace(/>/g, '>')); + } else { + return pushHash(tag); + } + }); + + return html; + } + function plain2html(plain) { + var back = ''; + for (i=0;i<plain.length;i++){ + if(_revHtmlHash[plain[i]]){ + back += _revHtmlHash[plain[i]]; + } + else{ + back += plain[i]; + } + } + return back; + }; + var dmp = new diff_match_patch(); + this.diff = function(first,second){ + console.time('html2plain'); + var convertedFirst = html2plain(first); + var convertedSecond = html2plain(second); + console.timeEnd('html2plain'); + console.time('toDiff'); + var diffs = dmp.diff_main(convertedFirst,convertedSecond); + dmp.diff_cleanupSemantic(diffs); + console.timeEnd('toDiff'); + var modified = ''; + console.time('toModify'); + for (i=0;i<diffs.length;i++){ + var diff = diffs[i]; + if (diff[0]==0){ + modified += diff[1]; + } + else if (diff[0]==1){ + modified += '<ins id='+i+'>'+diff[1]+'</ins>'; + } + else { + modified += '<del id='+i+'>'+diff[1]+'</del>'; + } + } + console.timeEnd('toModify'); + console.time('convertBack'); + var complete = plain2html(modified); + console.timeEnd('convertBack'); + return complete; + }; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005434_superevent.js b/pool/shard000/JavaScript/0005434_superevent.js new file mode 100644 index 0000000000000000000000000000000000000000..72d9f41a09cf7a113b5558922d36052533a4bef7 --- /dev/null +++ b/pool/shard000/JavaScript/0005434_superevent.js @@ -0,0 +1,53 @@ +var SuperEvent = { + on: function(name, callback){ + var args = jQuery.makeArray(arguments); + var names = args.shift().split(" "); + + for (var i=0; i < names.length; i++) + this.onEvent(names[i], callback); + }, + + onEvent: function(name, callback){ + if ( !name || !callback ) return; + if ( !this.handlers ) this.handlers = {}; + if ( !this.handlers[name] ) this.handlers[name] = []; + this.handlers[name].push(callback); + }, + + trigger: function(names){ + var args = jQuery.makeArray(arguments); + var names = args.shift().split(" "); + + for (var i=0; i < names.length; i++) + if (this.triggerEvent(names[i], args) === false) return false; + }, + + triggerEvent: function(name, args){ + if ( !this.handlers ) return; + + var callbacks = this.handlers[name]; + if ( !callbacks ) return; + + for(var i=0, len = callbacks.length; i < len; i++) + if (callbacks[i].apply(this, args) === false) return false; + }, + + setupEvents: function(events){ + events = jQuery.makeArray(events); + jQuery.each(events, this.proxy(function(i, name){ + this[name] = function(){ + var args = jQuery.makeArray(arguments); + + if (typeof args[0] == "function") { + args.unshift(name); + this.on.apply(this, args); + } else { + args.unshift(name); + this.trigger.apply(this, args); + } + }; + })); + } +}; + +SuperEvent.bind = SuperEvent.on; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005436_server.js b/pool/shard000/JavaScript/0005436_server.js new file mode 100644 index 0000000000000000000000000000000000000000..cf2d53127554c7f94ffa4f9daf912a74d7b89065 --- /dev/null +++ b/pool/shard000/JavaScript/0005436_server.js @@ -0,0 +1,40 @@ +var express = require("express"); +var path = require("path"); +var bodyParser = require("body-parser"); +var favicon = require('serve-favicon'); +var basicAuth = require('basic-auth'); + +var app = express(); + + +var auth = function (req, res, next) { + function unauthorized(res) { + res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); + return res.sendStatus(401); + }; + + var user = basicAuth(req); + + if (!user || !user.name || !user.pass) { + return unauthorized(res); + }; + + if (user.name === 'kate' && user.pass === 'wanless') { + return next(); + } else { + return unauthorized(res); + }; +}; + + +app.use(favicon(__dirname + '/dist/images/favicon.ico')); +app.use( '/', [ auth, express.static( __dirname + "/dist" ) ] ); + + +app.use(bodyParser.json()); + + +var server = app.listen(process.env.PORT || 8080, function () { + var port = server.address().port; + console.log("App now running on port", port); +}); diff --git a/pool/shard000/JavaScript/0005442_strategy.js b/pool/shard000/JavaScript/0005442_strategy.js new file mode 100644 index 0000000000000000000000000000000000000000..2e62dd68c5d75987426813a229062088404187fc --- /dev/null +++ b/pool/shard000/JavaScript/0005442_strategy.js @@ -0,0 +1,77 @@ +var ndn = require('ndn-on-node'); + + +// ---------------------------------------------------------------- +// class Strategy +var Strategy = function Strategy(fib, pit, facemgr) { + this.fib = fib; + this.pit = pit; + this.facemgr = facemgr; +}; + +// public method interest +Strategy.prototype.interest = function Strategy_interest(interest) { + console.log('Strategy.interest('+interest.name.to_uri()+' from '+interest.incoming_face+')'); + var pe = this.pit.seek(interest); + if (pe.n_downstreams() >= 1) {// old PitEntry + pe.add_downstream(interest); + this.propagate(pe, interest); + return; + } + pe.add_downstream(interest); + this.bind_pe(pe); + this.propagate(pe, interest); +}; + +// protected method propagate +Strategy.prototype.propagate = function Strategy_propagate(pe, interest) { + var fe = this.fib.lookup(interest); + if (!fe) { + console.log('Strategy.propagate('+interest.name.to_uri()+') no FIB entry'); + return; + } + if (fe.handler) { + console.log('Strategy.propagate('+interest.name.to_uri()+') handler'); + fe.handler(interest); + } + // broadcast strategy + var sent_to = fe.faceids.filter(function(faceid){ + return this.propagate_to(pe, faceid); + }.bind(this)); + if (sent_to.length > 0) console.log('Strategy.propagate('+interest.name.to_uri()+') to '+sent_to.join()); +}; + +// protected method propagate_to +Strategy.prototype.propagate_to = function Strategy_propagate_to(pe, upstream, expect) { + var face = this.facemgr.get(upstream); + if (!face) return false; + var nonce = pe.pick_nonce(upstream); + if (!nonce) return false; + pe.add_upstream(upstream, nonce, expect); + pe.interest.nonce = nonce; + face.send(pe.interest); + return true; +}; + +// public method co +Strategy.prototype.co = function Strategy_co(co) { + console.log('Strategy.co('+co.name.to_uri()+' from '+co.incoming_face+')'); + this.pit.match(co); +}; + +// protected method bind_pe +Strategy.prototype.bind_pe = function Strategy_bind_pe(pe) { + pe.on('satisfy', this.send_co.bind(this)); +}; + +// protected method send_co +// PitEntry.satisfy event handler +Strategy.prototype.send_co = function Strategy_send_co(faceid, co) { + var face = this.facemgr.get(faceid); + if (face) face.send(co); +}; + + +// ---------------------------------------------------------------- +exports.Strategy = Strategy; + diff --git a/pool/shard000/JavaScript/0005446_xlabkey.js b/pool/shard000/JavaScript/0005446_xlabkey.js new file mode 100644 index 0000000000000000000000000000000000000000..507b10eb67b95a1e7188717b3014b7165e552fd6 --- /dev/null +++ b/pool/shard000/JavaScript/0005446_xlabkey.js @@ -0,0 +1,104 @@ +define(['underscore'], function(_) { + /* + * External wrappers for LABKEY functions. The main purpose of this is for Ajax involved + * functions, so that we can control the login screen. + */ + var failureWrapper = function (callback) { + return function (errorInfo) { + if (!_.isUndefined(errorInfo) && (errorInfo.exception == 'Unauthorized')) { + EHRMobile.Utils.LoginFailure(); + } + else { + // Now call normal handler + callback(errorInfo); + } + } + }; + + var getContainer = function() { + return "WNPRC/EHR"; + }; + + var XLABKEY = {}; + + XLABKEY.Utils = { + generateUUID: function() { + return LABKEY.Utils.generateUUID(); + } + }; + + XLABKEY.Meta = XLABKEY.Meta || {}; + + XLABKEY.Query = XLABKEY.Query || {}; + + XLABKEY.Query.selectRows = function(config) { + //Save off current query. + XLABKEY.Meta.currentQuery = function() { + XLABKEY.Query.selectRows(config); + }; + + // Wrap the Success function + var origSuccess = config.success || function(data) {}; + config.success = function(data) { + XLABKEY.Meta.currentQuery = undefined; + origSuccess(data); + }; + + // Set a proper container path. + config.containerPath = getContainer(); + + // Wrap the Failure function + var origFailure = config.failure || function() {}; + config.failure = failureWrapper(origFailure); + + LABKEY.Query.selectRows(config); + }; + + XLABKEY.Query.saveRows = function(config) { + //Save off current query. + XLABKEY.Meta.currentQuery = function() { + XLABKEY.Query.selectRows(config); + }; + + // Wrap the Success function + var origSuccess = config.success || function(data) {}; + config.success = function(data) { + XLABKEY.Meta.currentQuery = undefined; + origSuccess(data); + }; + + // Set a proper container path. + config.containerPath = getContainer(); + + // Wrap the Failure function + var origFailure = config.failure || function() {}; + config.failure = failureWrapper(origFailure); + + LABKEY.Query.saveRows(config); + }; + + XLABKEY.Query.deleteRows = function(config) { + //Save off current query. + XLABKEY.Meta.currentQuery = function() { + XLABKEY.Query.selectRows(config); + }; + + // Wrap the Success function + var origSuccess = config.success || function(data) {}; + config.success = function(data) { + XLABKEY.Meta.currentQuery = undefined; + origSuccess(data); + }; + + // Set a proper container path. + config.containerPath = getContainer(); + + // Wrap the Failure function + var origFailure = config.failure || function() {}; + config.failure = failureWrapper(origFailure); + + LABKEY.Query.deleteRows(config); + }; + + return XLABKEY; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005449_tree.js b/pool/shard000/JavaScript/0005449_tree.js new file mode 100644 index 0000000000000000000000000000000000000000..0278c84ecb2924260b7ec51c30e15fbf114f857f --- /dev/null +++ b/pool/shard000/JavaScript/0005449_tree.js @@ -0,0 +1,259 @@ +import Service from '../service'; + +/** + * @class + * @classdesc Class representing a Sentence Tree Node + */ +export class Node { + constructor(pos = '', word = '', children = [], paren = null) { + this._pos = pos; + this._word = word; + this._children = children; + this._parent = paren; + } + + pos() { + return this._pos; + } + + posInfo() { + // itf it's a subtree + if (this._children.length) { + return Service.getSentenceParseInfo(this._pos, this.getLanguageISO()); + } + + // if it's a leaf + return Service.getTokenPosInfo(this._pos, this.getLanguageISO()); + } + + token(token = null) { + if (token) { + this._token = token; + } + + return this._token; + } + + word() { + return this._word; + } + + /** + * Sets the language ISO (given by the pipeline during the annotation process) + * This is solely to keep track of the language chosen for further analysis + * @return {string} text + */ + setLanguageISO(iso) { + this._language = iso; + } + + /** + * Retrieves the language ISO + * @return {string} text + */ + getLanguageISO() { + return this._language; + } + + children() { + return this._children; + } + + appendChild(node) { + this._children.push(node); + } + + parent(paren = null) { + if (paren) { + this._parent = paren; + } + + return this._parent; + } + + toJSON() { + return { + pos: this._pos, + posInfo: this.posInfo(), + word: this._word, + token: this._token, + children: this._children, + }; + } +} + +/** + * @class + * @classdesc Class representing a Parse tree structure + * @memberof CoreNLP/util + * @description + * The nodes are given in order left to right as the words in a sentence appears + * The leaves are grouped into semantic representations provided by the Annotator + * This class is pretty useful to use along with the ParserAnnotator + * @see inspired on {@link http://www.nltk.org/howto/tree.html|Tree} + * @see the lecture {@link http://www.cs.cornell.edu/courses/cs474/2004fa/lec1.pdf|Tree Syntax of Natural Language} + */ +class Tree { + /** + * Create a Tree + * @param {Node} node + */ + constructor(node) { + this.rootNode = node; + } + + /** + * Get a Tree string representation for debugging purposes + * @returns {string} tree + */ + dump() { + return JSON.stringify(this.rootNode, (key, val) => { + if (val instanceof Node) { + return val.children().length ? { + pos: val.pos(), + info: val.info(), + children: val.children(), + } : { + pos: val.pos(), + info: val.info(), + word: val.word(), + token: val.token(), + }; + } + + return val; + }, 2); + } + + /** + * Performs Deep-first Search calling a visitor for each node + * @see {@link https://en.wikipedia.org/wiki/Depth-first_search|DFS} + */ + visitDeepFirst(visitor, node = this.rootNode) { + node.children().forEach((childNode) => { + this.visitDeepFirst(visitor, childNode); + visitor(childNode); + }); + + visitor(node); + } + + /** + * Performs Deep-first Search calling a visitor for each node, from right to left + * @see {@link https://en.wikipedia.org/wiki/Depth-first_search|DFS} + */ + visitDeepFirstRight(visitor, node = this.rootNode) { + node.children().reverse().forEach((childNode) => { + this.visitDeepFirstRight(visitor, childNode); + visitor(childNode); + }); + + visitor(node); + } + + /** + * Performs Deep-first Search calling a visitor only over leaves + * @see {@link https://en.wikipedia.org/wiki/Depth-first_search|DFS} + */ + visitLeaves(visitor, node = this.rootNode) { + node.children().forEach((childNode) => { + if (childNode.children().length) { + this.visitLeaves(visitor, childNode); + } else { + visitor(childNode); + } + }); + + if (!node.children().length) { + visitor(node); + } + } + + /** + * @param {Sentence} sentence + * @param {boolean} [doubleLink] whether the child nodes should have a reference + * to their parent or not - this allows the use of {@link Node.parent()} + * @returns {Tree} tree + */ + static fromSentence(sentence, doubleLink = false) { + const parse = sentence.parse(); + if (!parse) { + throw new Error('Unable to create Tree from Sentence, did you run ParserAnnotator first?'); + } + + const tree = Tree.fromString(parse, doubleLink); + // link nodes with tokens + let visitedLeaves = 0; + // eslint-disable-next-line no-plusplus + tree.visitLeaves(node => node.token(sentence.token(visitedLeaves++))); + + const languageIso = sentence.getLanguageISO(); + if (languageIso) { + tree.visitDeepFirst(node => node.setLanguageISO(languageIso)); + } + + return tree; + } + + /** + * @param {string} str + * @param {boolean} [doubleLink] whether the child nodes should have a reference + * to their parent or not - this allows the use of {@link Node.parent()} + * @returns {Tree} tree + */ + static fromString(str, doubleLink = false) { + return new Tree(this._transformTree(this._buildTree(str), doubleLink)); + } + + static _buildTree(str) { + let currentNode = { children: [] }; + const openNodes = [currentNode]; + const l = str.length; + // eslint-disable-next-line no-plusplus + for (let i = 0; i < l; i++) { + if (str[i] === '(') { + currentNode = { str: '', children: [] }; + openNodes[openNodes.length - 1].children.push(currentNode); + openNodes.push(currentNode); + } else if (str[i] === ')') { + this._cleanNode(currentNode); + openNodes.pop(); + currentNode = openNodes[openNodes.length - 1]; + } else { + currentNode.str += str[i]; + } + } + return currentNode.children[0]; + } + + static _cleanNode(node) { + const str = node.str.trim(); + const delimiterPos = str.indexOf(' '); + if (delimiterPos > -1) { + // eslint-disable-next-line no-param-reassign + node.pos = str.substr(0, delimiterPos); + // eslint-disable-next-line no-param-reassign + node.word = str.substr(delimiterPos + 1); + } else { + // eslint-disable-next-line no-param-reassign + node.pos = str; + } + } + + static _transformTree(node, doubleLink) { + if (doubleLink) { + const parentNode = new Node(node.pos, node.word); + node.children.forEach((n) => { + const childNode = this._transformTree(n, doubleLink); + childNode.parent(parentNode); + parentNode.appendChild(childNode); + }); + + return parentNode; + } + + return new Node(node.pos, node.word, node.children.map(n => this._transformTree(n))); + } +} + +export default Tree; diff --git a/pool/shard000/JavaScript/0005450_control.js b/pool/shard000/JavaScript/0005450_control.js new file mode 100644 index 0000000000000000000000000000000000000000..3ad666e0fe7c80d73f0dbbd52ef0e559bc9c0b1f --- /dev/null +++ b/pool/shard000/JavaScript/0005450_control.js @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2014 rafa + * + * 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 2 + * 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, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +var usuarioControl = function (strClase) { + this.clase = strClase; +}; +usuarioControl.prototype = new control('usuario'); +usuarioControl.prototype.getClassNameUsuario = function () { + return this.getClassName() + "Control"; +}; +var oUsuarioControl = new usuarioControl('usuario'); + +usuarioControl.prototype.view = function (place, id, oModel, oView) { + $(place).empty(); + var oDocumentoModel = oModel; + oDocumentoModel.loadAggregateViewOne(id); + $(place).append(oView.getPanel("Detalle de " + this.clase, oView.getObjectTable(oDocumentoModel.getCachedPrettyFieldNames(), oDocumentoModel.getCachedOne(), oDocumentoModel.getCachedFieldNames()))); + $(place).append('<br /><a class="btn btn-danger" href="jsp#/' + this.clase + '/remove/' + id + '">Borrar</a><br />'); + $(place).append('<a class="btn btn-primary botonperfil" href="jsp#/' + this.clase + '/edit/' + id + '">Editar</a>'); + $(place).append('<a class="btn btn-primary botonperfil" href="jsp#/' + this.clase + '/list/' + id + '">Listar</a>'); + + $(place).append('<br /><a class="btn btn-warning" href="jsp#/pedido/list/page=1&rpp=10&vf=4&systemfilter=' + 'id_usuario' + '&systemfilteroperator=equals' + '&systemfiltervalue=' + id + '">Pedidos</a>'); +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005451_index.js b/pool/shard000/JavaScript/0005451_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c8cfdc4851712bc62cc1a14355c017a7aa50aa --- /dev/null +++ b/pool/shard000/JavaScript/0005451_index.js @@ -0,0 +1,263 @@ +import R from 'ramda' +import React, { + Component, +} from 'react' +import { + Text, + View, + Image, + TouchableWithoutFeedback, +} from 'react-native' +import {bindActionCreators} from 'redux' +import {connect} from 'react-redux' + +import Container from '../../component/layout/container' +import * as Jpush from '../../lib/jpush' + +import * as variable from '../../theme/ume-theme/variable.js' + +import style from './style.js' + +import Dynamic from './dynamic' +import Homepage from './homepage' +import Diary from './diary' +import Weibo from './weibo' +import Me from './me' + +import * as homepage_reducer from './homepage/reducer' +import * as staff_reducer from './diary/staff/reducer' + +export const TAB_HEADER_HEIGHT = 58 + +const DYNAMIC_ICON = require('../../../../content/img/icon/flash.png') +const DYNAMIC_ACTIVE_ICON = require('../../../../content/img/icon/flash_1.png') + +const HOME_ICON = require('../../../../content/img/icon/home.png') +const HOME_ACTIVE_ICON = require('../../../../content/img/icon/home_1.png') + +const DATE_ICON = require('../../../../content/img/icon/date.png') +const DATE_ACTIVE_ICON = require('../../../../content/img/icon/date_1.png') + +const Weibo_ICON = require('../../../../content/img/icon/share.png') +const Weibo_ACTIVE_ICON = require('../../../../content/img/icon/share_1.png') + +const ACCOUNT_ICON = require('../../../../content/img/icon/account.png') +const ACCOUNT_ACTIVE_ICON = require('../../../../content/img/icon/account_1.png') + +import { + DIARY_MANAGER, +} from '../../reducer/user/role' + +class Home extends Component { + + constructor(prop) { + super(prop) + this.state = { + view: { + Homepage: { + active: true, + inited: true, + }, + Diary: { + active: false, + inited: false, + }, + Weibo: { + active: false, + inited: false, + }, + Me: { + active: false, + inited: false, + }, + } + } + } + + componentDidMount() { + this.props.action.home_diary_staff_list_refresh() + Jpush.callbackListener && Jpush.callbackListener(this.props.action.homepage_get_oa_count) + } + + handle_item_press(view) { + this.setState({ + ...this.state, + view: R.compose( + R.assocPath([view, 'inited'], true), + R.assocPath([view, 'active'], true), + R.map( + R.assoc('active', false) + ) + )(this.state.view), + }) + } + + render() { + const { + i18n: { + t, + }, + homepage: { + tab_count_text, + }, + diary_staff: { + count, + }, + role: { + operation, + type, + }, + navigation, + } = this.props + + const { + view, + } = this.state + + return ( + <View style={{ + flex: 1, + backgroundColor: 'white', + }}> + <View style={{ + flex: 1, + flexDirection: 'column', + }}> + <View style={{ + flex: 1, + // height: variable.SCREEN_HEIGHT - TAB_HEADER_HEIGHT, + }}> + <View style={view.Homepage.active ? style.view : style.hidden}> + { + view.Homepage.inited || view.Homepage.active + ? <Homepage navigation={navigation}/> + : null + } + </View> + + <View style={view.Diary.active ? style.view : style.hidden}> + { + view.Diary.inited || view.Diary.active + ? <Diary navigation={navigation}/> + : null + } + </View> + + <View style={view.Weibo.active ? style.view : style.hidden}> + { + view.Weibo.inited || view.Weibo.active + ? <Weibo navigation={navigation}/> + : null + } + </View> + + <View style={view.Me.active ? style.view : style.hidden}> + { + view.Me.inited || view.Me.active + ? <Me navigation={navigation}/> + : null + } + </View> + </View> + + <View style={{ + height: TAB_HEADER_HEIGHT, + flexDirection: 'row', + borderTopWidth: variable.BORDER_WIDTH, + borderTopColor: variable.BORDER_COLOR, + justifyContent: 'space-between', + }}> + + <TouchableWithoutFeedback onPress={this.handle_item_press.bind(this, 'Homepage')}> + <View style={style.item}> + <View style={style.item_wrap}> + <Image source={view.Homepage.active ? HOME_ACTIVE_ICON : HOME_ICON} style={style.item_icon}/> + <Text style={view.Homepage.active ? [style.item_text, style.item_text_active] : style.item_text}>{t.tab_home}</Text> + { + tab_count_text + ? <View style={{ + position: 'absolute', + top: 0, + right: 0, + backgroundColor: variable.COLOR_POINT, + borderRadius: 8, + paddingLeft: variable.N_5, + paddingRight: variable.N_5, + zIndex: 1000, + }}> + <Text style={style.item_point_text}> + {tab_count_text} + </Text> + </View> + : null + } + </View> + </View> + </TouchableWithoutFeedback> + + { + operation.indexOf(DIARY_MANAGER) !== -1 + ? <TouchableWithoutFeedback onPress={this.handle_item_press.bind(this, 'Diary')}> + <View style={style.item}> + <View style={style.item_wrap}> + <Image source={view.Diary.active ? DATE_ACTIVE_ICON : DATE_ICON} style={style.item_icon}/> + <Text style={view.Diary.active ? [style.item_text, style.item_text_active] : style.item_text}>{t.tab_diary}</Text> + { + count > 0 + ?<View style={{ + position: 'absolute', + top: 0, + right: 0, + backgroundColor: variable.COLOR_POINT, + borderRadius: 8, + paddingLeft: variable.N_5, + paddingRight: variable.N_5, + zIndex: 1000, + }}> + <Text style={style.item_point_text}>{count > 99 ? '99+' : count}</Text> + </View> + :null + } + </View> + </View> + </TouchableWithoutFeedback> + : null + } + + + + <TouchableWithoutFeedback onPress={this.handle_item_press.bind(this, 'Weibo')}> + <View style={style.item}> + <Image source={view.Weibo.active ? Weibo_ACTIVE_ICON : Weibo_ICON} style={style.item_icon}/> + <Text style={view.Weibo.active ? [style.item_text, style.item_text_active] : style.item_text}>{t.tab_share}</Text> + </View> + </TouchableWithoutFeedback> + + <TouchableWithoutFeedback onPress={this.handle_item_press.bind(this, 'Me')}> + <View style={style.item}> + <Image source={view.Me.active ? ACCOUNT_ACTIVE_ICON : ACCOUNT_ICON} style={style.item_icon}/> + <Text style={view.Me.active ? [style.item_text, style.item_text_active] : style.item_text}>{t.tab_me}</Text> + </View> + </TouchableWithoutFeedback> + </View> + </View> + </View> + ) + } +} + +export default connect( + state => ({ + homepage: state.Homepage, + diary_staff: state.Diary_staff, + todo: state.Dynamic_todo, + i18n: state.I18n, + role: state.User_role, + }), + dispatch => ({ + action: bindActionCreators({ + ...homepage_reducer, + ...staff_reducer, + }, dispatch), + }) +)(Home) diff --git a/pool/shard000/JavaScript/0005454_campaign.js b/pool/shard000/JavaScript/0005454_campaign.js new file mode 100644 index 0000000000000000000000000000000000000000..800bdf9cd88dfd69361a40eaf014a947ea9b7b3c --- /dev/null +++ b/pool/shard000/JavaScript/0005454_campaign.js @@ -0,0 +1,26 @@ +'use strict'; + +const stubs = require('../stubs'); + +/** + * @return {Object} + */ +function getValidCampaign() { + return { + id: stubs.getRandomNumericId(), + internalTitle: stubs.getRandomName(), + endDate: null, + }; +} + +/** + * @return {Object} + */ +function getValidClosedCampaign() { + return { ...module.exports.getValidCampaign(), endDate: '2018-07-19T00:00:00Z' }; +} + +module.exports = { + getValidCampaign, + getValidClosedCampaign, +}; diff --git a/pool/shard000/JavaScript/0005457_banner.js b/pool/shard000/JavaScript/0005457_banner.js new file mode 100644 index 0000000000000000000000000000000000000000..843cc142a64c546e78ae67463703cef44fdce404 --- /dev/null +++ b/pool/shard000/JavaScript/0005457_banner.js @@ -0,0 +1,23 @@ +function setBannerHeight() { + var headerHeight = $('.header-banner').outerHeight(); + var navHeight = $('nav').outerHeight(); + $('.hero-banner').css('margin-top', - (headerHeight + navHeight)); + console.log(headerHeight); +} + +$(document).ready(function() { + if($(window).width() > mediumBreakPoint) { + setBannerHeight(); + } else { + $('.hero-banner').css('margin-top', 0); + } +}); + +$(window).resize(function() { + if($(window).width() > mediumBreakPoint) { + setBannerHeight(); + console.log($(window).width()); + } else { + $('.hero-banner').css('margin-top', 0); + } +}); diff --git a/pool/shard000/JavaScript/0005458_script2.js b/pool/shard000/JavaScript/0005458_script2.js new file mode 100644 index 0000000000000000000000000000000000000000..477e56b2ff932b4649822290836f4cd2aa48c6ff --- /dev/null +++ b/pool/shard000/JavaScript/0005458_script2.js @@ -0,0 +1,35 @@ +/** + Write a function that checks if an array of person contains only people of age (with age 18 or greater) + Use only array methods and no regular loops (for, while) + */ + +function generatePerson(firstname, lastname, age, gender){ + return { + fName: firstname, + lName: lastname, + age: age, + gender: gender + } +} + +var batkov = generatePerson('Baj', 'Ganyo', 58, false); +var domusa = generatePerson('Kiro', 'Gela', 50, false); +var lupi = generatePerson('Sasho', 'Apasho', 52, false); +var mara = generatePerson('Mara', 'Otvarachkata', 18, true); +var nikoleta = generatePerson('Ni', 'Lo', 18, true); +var pepa = generatePerson('Pepa', 'Seksa', 18, true); +var venci = generatePerson('Venci', 'Shekembeto', 59, false); +var goshko = generatePerson('Georgi', 'Vratarcheto', 38, false); +var bobi = generatePerson('Bobi', 'Peruka', 53, false); +var konchita = generatePerson('Konchita', 'Vurst', 21, true); //gender is not fault!!! + +var pseudoStars = []; +pseudoStars.push(batkov, domusa, lupi, mara, nikoleta, pepa, venci, goshko, bobi, konchita); + +var result = pseudoStars.filter(inAge); +console.log(result); + +function inAge(person){ + return person.age > 18; // can check with preferred age +} + diff --git a/pool/shard000/JavaScript/0005459_Client.js b/pool/shard000/JavaScript/0005459_Client.js new file mode 100644 index 0000000000000000000000000000000000000000..4acc6a6d4b4183d59f0e96391635f261bd655318 --- /dev/null +++ b/pool/shard000/JavaScript/0005459_Client.js @@ -0,0 +1,254 @@ +'use strict'; + +let _ = require('lodash'); + +const PUSHOVER_HOST = 'https://api.pushover.net'; +const PUSHOVER_VERSION = '1'; + +/** + * Main client class + */ +class Client { + /** + * Constructor for client + * + * @param {string} apiToken Api token + */ + constructor(apiToken) { + this.options = { + host: PUSHOVER_HOST, + version: PUSHOVER_VERSION + }; + + this.app = { + limit: null, + remaining: null, + reset: null + } + + this.apiToken = apiToken; + } + + /** + * Get api token + * + * @return {string} Get api token + */ + get apiToken() { + return this.options.apiToken; + } + + /** + * Set api token + * + * @param {string} value Api token + */ + set apiToken(value) { + validateApiToken(value); + + this.options.apiToken = value; + } + + /** + * Send message + * + * @param {Message} message Message + * + * @return {Promise} Promise for chaining + */ + sendMessage(message) { + let SendMessage = require('./Command/SendMessage'); + + return this.invokeCommand(new SendMessage(message)); + } + + /** + * Verify user + * + * @param {User} user User + * + * @return {Promise} Promise for chaining + */ + verifyUser(user) { + let VerifyUser = require('./Command/VerifyUser'); + + return this.invokeCommand(new VerifyUser(user)); + } + + /** + * Get receipt + * + * @param {string} receipt Receipt + * + * @return {Promise} Promise for chaining + */ + getReceipt(receipt) { + let GetReceipt = require('./Command/GetReceipt'); + + return this.invokeCommand(new GetReceipt(receipt)); + } + + /** + * Cancel emergency + * + * @param {receipt} receipt Receipt + * + * @return {boolean} Cancellation status + */ + cancelEmergency(receipt) { + let CancelEmergency = require('./Command/CancelEmergency'); + + return this.invokeCommand(new CancelEmergency(receipt)); + } + + /** + * Get group details + * + * @param {Group} group Group + * + * @return {Promise} Promise for chaining + */ + getGroupDetails(group) { + let GetGroupDetails = require('./Command/GetGroupDetails'); + + return this.invokeCommand(new GetGroupDetails(group)); + } + + /** + * Add user to group + * + * @param {User} user User + * @param {Group} group Group + * + * @return {Promise} Promise for chaining + */ + addUserToGroup(user, group) { + let AddUserToGroup = require('./Command/AddUserToGroup'); + + return this.invokeCommand(new AddUserToGroup(user, group)); + } + + /** + * Remove user from group + * + * @param {User} user User + * @param {Group} group Group + * + * @return {Promise} Promise for chaining + */ + removeUserFromGroup(user, group) { + let RemoveUserFromGroup = require('./Command/RemoveUserFromGroup'); + + return this.invokeCommand(new RemoveUserFromGroup(user, group)); + } + + /** + * Enable group user + * + * @param {User} user User + * @param {Group} group Group + * + * @return {Promise} Promise for chaining + */ + enableGroupUser(user, group) { + let EnableGroupUser = require('./Command/EnableGroupUser'); + + return this.invokeCommand(new EnableGroupUser(user, group)); + } + + /** + * Disable group user + * + * @param {User} user User + * @param {Group} group Group + * + * @return {Promise} Promise for chaining + */ + disableGroupUser(user, group) { + let DisableGroupUser = require('./Command/DisableGroupUser'); + + return this.invokeCommand(new DisableGroupUser(user, group)); + } + + /** + * Rename group + * + * @param {Group} group Group + * @param {string} name Name + * + * @return {Promise} Promise for chaining + */ + renameGroup(group, name) { + let RenameGroup = require('./Command/RenameGroup'); + + return this.invokeCommand(new RenameGroup(group, name)); + } + + /** + * Get transport + * + * Lazy loads transport + * + * @return {object} Transport + */ + getTransport() { + if (_.isUndefined(this.transport)) { + let Transport = require('./Transport'); + + this.transport = new Transport(this); + } + + return this.transport; + } + + /** + * Invoke command + * + * @param {mixed} command Command + * + * @return {Promise} Promise for chaining + */ + invokeCommand(command) { + return command.invoke(this); + } + + /** + * Get app limit + * + * @return {integer} Limit + */ + get appLimit() { + return this.app.limit; + } + + /** + * Get app remaining + * + * @return {integer} Remaining + */ + get appRemaining() { + return this.app.remaining; + } + + /** + * Get app reset + * + * @return {integer} Timestamp + */ + get appReset() { + return this.app.reset; + } +} + +/** + * Validate api token + * + * @param {string} value Api token + */ +function validateApiToken(value) { + if (!value.match(/^[a-z0-9]{30}$/i)) { + throw new Error('API token must be 30 characters long and alphanumeric'); + } +} + +module.exports = Client; diff --git a/pool/shard000/JavaScript/0005460_explorer.js b/pool/shard000/JavaScript/0005460_explorer.js new file mode 100644 index 0000000000000000000000000000000000000000..5bffae17430bddf46e7c0c98b58ad50f175bd621 --- /dev/null +++ b/pool/shard000/JavaScript/0005460_explorer.js @@ -0,0 +1,64 @@ +/** + * Main explorer Panel for admin + * + * + */ +/*Ext.override(Ext.dd.DDProxy, { + startDrag: function(x, y) { + var dragEl = Ext.get(this.getDragEl()); + var el = Ext.get(this.getEl()); + + dragEl.applyStyles({border:'','z-index':2000}); + dragEl.update(el.dom.innerHTML); + dragEl.addClass(el.dom.className + ' dd-proxy'); + }, + + +}); */ + +Ext.namespace('KaraCos.Explorer'); +KaraCos.Explorer.DomainExplorer = function(config) { + Ext.apply(this, config); + this.treePanel = new KaraCos.Explorer.DomainTree({ + title: 'Navigation', + region: 'west', + animate:true, + autoScroll:true, + loader: new KaraCos.Explorer.TreeLoader({dataUrl:'/'}),//KaraCos.Explorer.TreeLoader({dataUrl:'/'}), + enableDD:true, + containerScroll: true, + border: false, + width: 250, + height: 300, + dropConfig: {appendOnly:true} + }); + console.log(this); + + this.tabPanel = new KaraCos.Explorer.ItemTabPanel({ + title: 'Content', + region: 'center', + margins:'3 3 3 0', + activeTab: 0, + defaults:{autoScroll:true} + }); + this.items = [this.treePanel,this.tabPanel]; + KaraCos.Explorer.DomainExplorer.superclass.constructor.call(this); + this.treePanel.on('nodeselected',this.onTreeSelection, this); +}; + +Ext.extend(KaraCos.Explorer.DomainExplorer, Ext.Window, { + onTreeSelection: function(node) { + //this.contentElementsStore + this.tabPanel.nodeSelected(node); + //this.tabPanel.contentElementsStore.loadData(items); + } +}); +KaraCos.Explorer.domainExplorer = new KaraCos.Explorer.DomainExplorer({ + title: 'Explorer', + width:600, + height:350, + //border:false, + plain:true, + layout: 'border', + closeAction: 'hide', +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005461_initdata.js b/pool/shard000/JavaScript/0005461_initdata.js new file mode 100644 index 0000000000000000000000000000000000000000..017693330914a6d13fc10e500ab09a27f98b06a0 --- /dev/null +++ b/pool/shard000/JavaScript/0005461_initdata.js @@ -0,0 +1,91 @@ + +const MUserBaseInfo = require('../../service/user/model/userBaseInfo') +const UserService = require('../../service/user/userService') +const MUserRole = require('../../service/user/model/userRole') + + +/** + * 初始化数据 + */ + + + +async function createUserRoles (ctx, next) { + + const roleList = [ + { + "_id" : GMongoose.Types.ObjectId("59ae7885cba8a4766ee00eeb"), + name : 'normal', + displayName : '普通用户', + permissions : [ + 'user.getOwn', + 'user.update', + 'user.updatePassword' + ] + }, + { + "_id" : GMongoose.Types.ObjectId("59ae7885cba8a4766ee00eec"), + name : 'admin', + displayName : '管理员', + permissions : [ + 'user.getList', + 'user.getOwn', + 'user.create', + 'user.update', + 'user.updatePassword', + 'user.delete' + ] + } + ] + + const currentRoles = await MUserRole.findAll({}) + + if (currentRoles && currentRoles.length > 0) { + return currentRoles + }else { + return await MUserRole.create(roleList) + } + +} + +exports.createUserRoles = createUserRoles + + + +async function createAdmin (ctx, next) { + + const currentAdmin = await MUserBaseInfo.find1({username : 'admin'}) + + if (currentAdmin) { + return currentAdmin + }else { + return await UserService.signUp({ + username : 'admin', + mobilePhone : '13564511111', + email : 'admin@gmail.com', + password : '123456', + roles : [ + GMongoose.Types.ObjectId(GConfig.role.normal), + GMongoose.Types.ObjectId(GConfig.role.admin) + ] + }) + } +} + +exports.createAdmin = createAdmin + + + +exports.run = async function (ctx, next) { + + const [roles, userAdmin] = await Promise.all([ + createUserRoles (), + createAdmin() + ]); + + ctx.body = { + roles, + userAdmin + } +} + diff --git a/pool/shard000/JavaScript/0005470_ex-change-rest-host.js b/pool/shard000/JavaScript/0005470_ex-change-rest-host.js new file mode 100644 index 0000000000000000000000000000000000000000..d9e6e45ae46bfb80b507b3c883a724c948ff9144 --- /dev/null +++ b/pool/shard000/JavaScript/0005470_ex-change-rest-host.js @@ -0,0 +1,14 @@ +module.exports = function(callback, config) { + + var Nexmo = require('../lib/Nexmo'); + + var nexmo = new Nexmo({ + apiKey: config.API_KEY, + apiSecret: config.API_SECRET + }, { + debug: config.DEBUG, + restHost: config.REST_HOST + }); + + nexmo.message.sendSms(config.FROM_NUMBER, config.TO_NUMBER, 'testing', callback); +}; diff --git a/pool/shard000/JavaScript/0005472_cache.js b/pool/shard000/JavaScript/0005472_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..788119c1119ab85520a73ef523325211a939d419 --- /dev/null +++ b/pool/shard000/JavaScript/0005472_cache.js @@ -0,0 +1,54 @@ +'use strict' + +module.exports = [ { + name: 'cacheTest', + description: 'I will test the internal cache function of the API', + + inputs: { + key: { + description: 'Key to store', + required: true + }, + value: { + description: 'Value to store', + required: true + } + }, + + async run (api, { params, response }) { + const key = 'cache_test_' + params.key + + // create the base response object + response.cacheTestResults = {} + + // create a new cache entry + let resp = await api.cache.save(key, params.value, 5000) + + // append the cache response to the request response + response.cacheTestResults.saveResp = resp + + // get the cache size + const numberOfCacheObjects = await api.cache.size() + + // append the cache size to the response object + response.cacheTestResults.sizeResp = numberOfCacheObjects + + // load the cache entry + const { value, expireTimestamp, createdAt, readAt } = await api.cache.load(key) + + // append the load response to the request response + response.cacheTestResults.loadResp = { + key, + value, + expireTimestamp, + createdAt, + readAt + } + + // try destroy the cache entry + resp = await api.cache.destroy(key) + + // append the response to the request response + response.cacheTestResults.deleteResp = resp + } +} ] diff --git a/pool/shard000/JavaScript/0005479_CourseType.js b/pool/shard000/JavaScript/0005479_CourseType.js new file mode 100644 index 0000000000000000000000000000000000000000..50e7650044b42e2f6dfa5bb4a3230a3a1a4f0ea7 --- /dev/null +++ b/pool/shard000/JavaScript/0005479_CourseType.js @@ -0,0 +1,45 @@ +(function (angular) { + 'use strict'; + + angular.module('masterkey.api') + + /** + * Factory to load CouorseType configuration + */ + .factory('CourseType', ["dataFile", function (dataFile) { + + var + file = 'courseType', + defaultValues = { + language: true, + category: true, + area: true + }; + + function CourseType(params) { + angular.extend(this, params, defaultValues); + } + + CourseType.get = function (type) { + + return CourseType.query().then(function (courseTypesList) { + return _.find(courseTypesList, { value: type }); + }); + }; + + /** + * Load data from local server with the CourseType configuration + * + * @return {Promise} + */ + CourseType.query = function () { + return dataFile.loadSource(file).then(function (courseTypes) { + return courseTypes.map(function (it) { return new CourseType(it); }); + }); + }; + + return CourseType; + }]); +})(angular); + + diff --git a/pool/shard000/JavaScript/0005480_silver.js b/pool/shard000/JavaScript/0005480_silver.js new file mode 100644 index 0000000000000000000000000000000000000000..be358a5a2a3a3cd36c6e0b3881803e16059f580e --- /dev/null +++ b/pool/shard000/JavaScript/0005480_silver.js @@ -0,0 +1,15 @@ +'use strict'; +var Card = require('../card'); +var Treasure = require('../treasure'); + +var Silver = Card.extend(Treasure, { + initialize: function() { + Card.initialize.call(this, { + name: 'Silver', + cost: 3, + }); + Treasure.initialize.call(this, 2); + } +}); + +module.exports = Silver; diff --git a/pool/shard000/JavaScript/0005496_concat.js b/pool/shard000/JavaScript/0005496_concat.js new file mode 100644 index 0000000000000000000000000000000000000000..a2c47b56f5b2f7a7536709681c475f6b65914426 --- /dev/null +++ b/pool/shard000/JavaScript/0005496_concat.js @@ -0,0 +1,101 @@ +"use strict"; + +var test = require("./util/test") +var concat = require("../concat") +var into = require("../into") +var delay = require("../delay") +var capture = require("../capture") + +exports["test concat"] = function(assert) { + var actual = concat([ 1 ], [ 2, 3 ], [ 4, 5, 6 ]) + + assert.deepEqual(into(actual), + [ 1, 2, 3, 4, 5, 6 ], + "reducers were joined") + assert.deepEqual(into(actual), + [ 1, 2, 3, 4, 5, 6 ], + "can be re-reduced") +} + +exports["test concat empty streams"] = function(assert) { + var actual = concat([], []) + + assert.deepEqual(into(actual), [], "concat on empty sequences is empty") +} + +exports["test concat empty"] = function(assert) { + var actual = concat([1, 2], []) + + assert.deepEqual(into(actual), [ 1, 2 ], "concat with empty returns same") +} + +exports["test concat to empty"] = function(assert) { + var actual = concat([], [3, 4]) + + assert.deepEqual(into(actual), [ 3, 4 ], "concat to empty returns same") +} + +exports["test concat many streams"] = function(assert) { + var actual = concat([1, 2], [], ["a", "b"], []) + + assert.deepEqual(into(actual), [ 1, 2, "a", "b" ], "many concats work") +} + +exports["test concat sync & async streams"] = test(function(assert) { + var async = delay([3, 2, 1]) + var actual = concat(concat(async, []), + async, + ["a", "b"]) + + assert(actual, [3, 2, 1, 3, 2, 1, "a", "b"], "concat sync async works") +}) + +exports["test concat & reconcat"] = test(function(assert) { + var async = delay([2, 1]) + var stream = concat(async, ["a", "b"]) + var actual = concat(stream, ["||"], stream) + + assert(actual, [2, 1, "a", "b", "||", 2, 1, "a", "b"], "concat reconcat") +}) + +exports["test map broken stream"] = test(function(assert) { + var boom = Error("Boom!") + var async = delay(concat([3, 2, 1], boom)) + var concated = concat([">"], async, [1, 2], async) + var actual = capture(concated, function(error) { return error.message }) + + assert(actual, [">", 3, 2, 1, boom.message], "test concat on broken stream") +}) + +exports["test concat error and sequence"] = test(function(assert) { + var boom = Error("Boom!") + var concated = concat(boom, [ 1, 2, 3 ]) + var actual = capture(concated, function(error) { + return error.message + }) + + + assert(actual, [boom.message], "sequence has an error") +}) + +exports["test concat sequence & error"] = test(function(assert) { + var boom = Error("Boom!") + var concated = concat([ 1, 2, 3 ], boom) + var actual = capture(concated, function(error) { + return error.message + }) + + + assert(actual, [1, 2, 3, boom.message], "sequence has an error") +}) + +exports["test concat sequence & error & sequence"] = test(function(assert) { + var boom = Error("Boom!") + var concated = concat([ 1, 2, 3 ], boom, [ 4, 5, 6 ]) + var actual = capture(concated, function(error) { + return error.message + }) + + + assert(actual, [1, 2, 3, boom.message], "sequence has an error") +}) diff --git a/pool/shard000/JavaScript/0005499_webpack.js b/pool/shard000/JavaScript/0005499_webpack.js new file mode 100644 index 0000000000000000000000000000000000000000..45865ad4a46ec5905a57b4d1f921ecba6ef29dc3 --- /dev/null +++ b/pool/shard000/JavaScript/0005499_webpack.js @@ -0,0 +1,17 @@ +import {wrap} from './core.js'; + +const _ = require('lodash'); +const webpackStream = require('webpack-stream'); +const webpackConfig = require('../webpack.config.js'); +const named = require('vinyl-named'); + +export const compileExecutable = wrap(function(src, dest){ + return src + .pipe(named()) + .pipe(webpackStream(_.extend(webpackConfig, { + output: { sourceMapFilename: '[file].map' } + }))) + .on('error', function handleError() { + this.emit('end'); // Recover from errors + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005500_register.js b/pool/shard000/JavaScript/0005500_register.js new file mode 100644 index 0000000000000000000000000000000000000000..00a8b233e9954756eb4a3125f566820d1d10eae5 --- /dev/null +++ b/pool/shard000/JavaScript/0005500_register.js @@ -0,0 +1,28 @@ +'use strict'; + +angular.module('frontendApp') + .controller('RegisterCtrl', function ($scope, $location, Auth) { + $scope.map = { + center: { + latitude: 39, + longitude: -101 + }, + zoom: 4 + }; + + $scope.user = {}; + $scope.message = ''; + $scope.types = [ + 'Shelter', + 'Restaurant', + 'Volunteer Group' + ]; + $scope.submit = function () { + Auth.register($scope.user, function () { + $scope.message = 'Account created successfully.'; + $location.path('/login'); + }, function () { + $scope.message = 'Error creating account.'; + }); + }; + }); diff --git a/pool/shard000/JavaScript/0005506_incidentView.js b/pool/shard000/JavaScript/0005506_incidentView.js new file mode 100644 index 0000000000000000000000000000000000000000..30addf292313c2d4ccb3b2e4913da0d68882fd35 --- /dev/null +++ b/pool/shard000/JavaScript/0005506_incidentView.js @@ -0,0 +1,68 @@ + + + +function incidentView(input) { + + var view = Ti.UI.createView({ + backgroundColor: 'white', + borderColor: 'black', + height: 200, + width: '100%' + }); + + + var causes = Ti.UI.createLabel({ + text: input.causes?input.causes:'Incident', + left: 5, + font: { fontSize: 20 }, + color: 'black', + height: 45, + top: 0 + }); + + var top_line = Ti.UI.createView({ height: 1, width: '80%', left: 0, top: 45, backgroundColor: 'blue', borderColor: 'black' }); + + var date = Ti.UI.createLabel({ + text: input.date, + textAlign: 1, + font: { fontSize: 30, fontWeight: 'bold' }, + top: 70, + width: '100%' + }); + + var time = Ti.UI.createLabel({ + text: input.time, + textAlign: 1, + font: { fontSize: 25, fontWeight: 'bold' }, + top: 105, + width: '100%' + }); + + view.add(causes); + view.add(top_line); + view.add(date); + view.add(time); + + + view.addEventListener('click', function() { + var incident = require('ui/common/forms/incident_form'); + incidentWindow = new incident(input); + incidentWindow.open(); + + incidentWindow.addEventListener('close', function() { + if(incidentWindow.result != null) + { + input = incidentWindow.result; + causes.text = input.causes?input.causes:'Incident'; + date.text = input.date; + time.text = input.time; + } + }); + }); + + + return view; + +} + +module.exports = incidentView; diff --git a/pool/shard000/JavaScript/0005507_readingapp.js b/pool/shard000/JavaScript/0005507_readingapp.js new file mode 100644 index 0000000000000000000000000000000000000000..0eb5d15cb8bc2f62bda897785ae59f613888568b --- /dev/null +++ b/pool/shard000/JavaScript/0005507_readingapp.js @@ -0,0 +1,37 @@ +var fs = require("fs"); +console.log("start"); +fs.readFile("employee.csv", function (error, data) { + if (error) { + throw error; + } + data.toString().split("\n").forEach(function (line, index, arr) { + if (index === arr.length - 1 && line === "") { + return; + } + console.log(index + " " + line); + }); + console.log("end"); +}); + +var max = require('compute-max'); +var mathSum = require('math-sum'); +fs.readFile("employee.csv", function (error, data) { + if (error) { + throw error; + } + var data = [100, 200, 300, 900]; + var val = max(data); + console.log("Sum of all salaries is: " + + mathSum(data)); + console.log("Highest Salary is " + val); + +}); + + +//var dt = require('node-datetime'); +//var sorter = { +//d1 = new Date(2016, 1, 20), +// d3 = new Date 2015 2, 2 +//}; +//var res = datetime.dtdelta.reorder.apply(null, a); +//console.log(res); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005509_ChatAvatar.js b/pool/shard000/JavaScript/0005509_ChatAvatar.js new file mode 100644 index 0000000000000000000000000000000000000000..06a764eb7c58bfd26f10ca9b65a8e4ef267007d0 --- /dev/null +++ b/pool/shard000/JavaScript/0005509_ChatAvatar.js @@ -0,0 +1,92 @@ +import React from 'react'; +import { + View, +} from 'react-native'; +// import { Actions } from 'react-native-router-flux'; +import { CachedImage } from 'react-native-img-cache'; +import UserAvatar from 'react-native-user-avatar'; +import AppUtil from '../../../lib/util'; +import t from '../../../i18n'; + + +export default class ChatAvatar extends React.Component { + constructor(props) { + super(props); + const avatarUri = this.props.avatar; + const displayTitle = this.props.name; + const size = this.props.size; + const borderRad = this.props.borderRad; + this.state = { + avatarUri, + displayTitle, + size, + borderRad, + showAvatar: true, + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ + avatarUri: nextProps.avatar, + avatarName: nextProps.name, + showAvatar: true, + }); + } + + _hideAvatarView() { + this.setState({ + showAvatar: false, + }); + } + + render() { + if (this.state.showAvatar) { + return ( + <View + style={{ + width: this.state.size, + height: this.state.size, + justifyContent: 'center', + alignItems: 'center' }} + > + <CachedImage + style={{ + width: this.state.size, + height: this.state.size, + borderRadius: this.state.borderRad ? this.state.borderRad : this.state.size / 2, + }} + source={{ uri: this.state.avatarUri }} + onError={() => { this._hideAvatarView(); }} + /> + </View> + ); + } + return ( + <View + style={{ width: this.state.size, height: this.state.size, justifyContent: 'center', alignItems: 'center' }} + > + <UserAvatar + name={this.state.displayTitle ? AppUtil.avatarInitials(this.state.displayTitle) : t('info_no_avatar')} + size={this.state.size} + style={{ + borderRadius: this.state.borderRad ? this.state.borderRad : this.state.size / 2, + }} + /> + </View> + ); + } +} + +ChatAvatar.defaultProps = { + avatar: '', + name: '', + size: 0, + borderRad: null, +}; + +ChatAvatar.propTypes = { + avatar: React.PropTypes.string, + name: React.PropTypes.string, + size: React.PropTypes.number, + borderRad: React.PropTypes.number, +}; diff --git a/pool/shard000/JavaScript/0005512_subtract.js b/pool/shard000/JavaScript/0005512_subtract.js new file mode 100644 index 0000000000000000000000000000000000000000..4241d8255619b08952a0c085ba9995e7ea938c4f --- /dev/null +++ b/pool/shard000/JavaScript/0005512_subtract.js @@ -0,0 +1,19 @@ +var R = require('..'); +var eq = require('./shared/eq'); + + +describe('subtract', function() { + it('subtracts two numbers', function() { + eq(R.subtract(22, 7), 15); + }); + + it('coerces its arguments to numbers', function() { + eq(R.subtract('1', '2'), -1); + eq(R.subtract(1, '2'), -1); + eq(R.subtract(true, false), 1); + eq(R.subtract(null, null), 0); + eq(R.subtract(undefined, undefined), NaN); + eq(R.subtract(new Date(1), new Date(2)), -1); + }); + +}); diff --git a/pool/shard000/JavaScript/0005513_top-collapse.js b/pool/shard000/JavaScript/0005513_top-collapse.js new file mode 100644 index 0000000000000000000000000000000000000000..899bea1f4aa963edc9e1930ae6f5e67a929879c8 --- /dev/null +++ b/pool/shard000/JavaScript/0005513_top-collapse.js @@ -0,0 +1,73 @@ +(function(factory) { + if (typeof define === 'function' && define.amd) { + define([ + '$', + 'velocity' + ], factory); + } else { + var framework = window.Zepto || window.jQuery; + factory(framework, framework.Velocity); + } +}(function($, Velocity) { + return function() { + var plugin = this; + var coverage = this._coverage(); + var $animators = plugin.$animators; + + var windowHeight; + + this.$pikabu + .css({ + top: 0, + left: 0, + right: 0, + bottom: coverage ? coverage : 'auto', + height: coverage ? 'auto' : this.options.coverage, + width: 'auto' + }); + + return { + open: function() { + // Force feed the initial value + Velocity.animate( + $animators, + { translateY: [this.options.coverage, '0'] }, + { + easing: plugin.options.easing, + duration: plugin.options.duration, + complete: function() { + plugin.animation.openComplete.call(plugin); + } + } + ); + + Velocity.animate( + plugin.$pikabu, + { + translateY: [0, '-20%'] + }, + { + easing: plugin.options.easing, + duration: plugin.options.duration + } + ); + }, + close: function() { + Velocity.animate( + $animators.add(plugin.$pikabu), + 'reverse', + { + begin: function() { + plugin.animation.beginClose.call(plugin); + }, + easing: plugin.options.easing, + duration: plugin.options.duration, + complete: function() { + plugin.animation.closeComplete.call(plugin); + } + } + ); + } + }; + }; +})); diff --git a/pool/shard000/JavaScript/0005516_shared-class.js b/pool/shard000/JavaScript/0005516_shared-class.js new file mode 100644 index 0000000000000000000000000000000000000000..893f059c58eb0d9118d2e9ffdc048dbafb449cef --- /dev/null +++ b/pool/shard000/JavaScript/0005516_shared-class.js @@ -0,0 +1,255 @@ +/*! + * Expose `SharedClass`. + */ + +module.exports = SharedClass; + +/*! + * Module dependencies. + */ + +var debug = require('debug')('strong-remoting:shared-class'); +var util = require('util'); +var inherits = util.inherits; +var inflection = require('inflection'); +var SharedMethod = require('./shared-method'); +var assert = require('assert'); + +/** + * Create a new `SharedClass` with the given `options`. + * + * @param {String} name The `SharedClass` name + * @param {Function} constructor The `constructor` the `SharedClass` represents + * @param {Object} options Additional options. + * @property {Function} ctor The `constructor` + * @property {Object} http The HTTP settings + * @class + */ + +function SharedClass(name, ctor, options) { + options = options || {}; + this.name = name || ctor.remoteNamespace; + this.ctor = ctor; + this._methods = []; + this._resolvers = []; + this._disabledMethods = {}; + var http = ctor && ctor.http; + var normalize = options.normalizeHttpPath; + + var defaultHttp = {}; + defaultHttp.path = '/' + this.name; + + if (Array.isArray(http)) { + // use array as is + this.http = http; + if (http.length === 0) { + http.push(defaultHttp); + } + if (normalize) { + this.http.forEach(function(h) { + h.path = SharedClass.normalizeHttpPath(h.path); + }); + } + } else { + // set http.path using the name unless it is defined + // TODO(ritch) move http normalization from adapter.getRoutes() to a + // better place... eg SharedMethod#getRoutes() or RestClass + this.http = util._extend(defaultHttp, http); + if (normalize) this.http.path = SharedClass.normalizeHttpPath(this.http.path); + } + + if (typeof ctor === 'function' && ctor.sharedCtor) { + // TODO(schoon) - Can we fall back to using the ctor as a method directly? + // Without that, all remote methods have to be two levels deep, e.g. + // `/meta/routes`. + + this.sharedCtor = new SharedMethod(ctor.sharedCtor, 'sharedCtor', this); + } + assert(this.name, 'must include a remoteNamespace when creating a SharedClass'); +} + +/** + * Normalize HTTP path. + */ + +SharedClass.normalizeHttpPath = function(path) { + if (typeof path !== 'string') return; + return path.replace(/[^\/]+/g, function(match) { + if (match.indexOf(':') > -1) return match; // skip placeholders + return inflection.transform(match, ['underscore', 'dasherize']); + }); +}; + +/** + * Get all shared methods belonging to this shared class. + * + * @returns {SharedMethod[]} An array of shared methods + */ + +SharedClass.prototype.methods = function() { + var ctor = this.ctor; + var methods = []; + var sc = this; + var functionIndex = []; + + // static methods + eachRemoteFunctionInObject(ctor, function(fn, name) { + if (functionIndex.indexOf(fn) === -1) { + functionIndex.push(fn); + } else { + var sharedMethod = find(methods, fn); + sharedMethod.addAlias(name); + return; + } + methods.push(SharedMethod.fromFunction(fn, name, sc, true)); + }); + + // instance methods + eachRemoteFunctionInObject(ctor.prototype, function(fn, name) { + if (functionIndex.indexOf(fn) === -1) { + functionIndex.push(fn); + } else { + var sharedMethod = find(methods, fn); + sharedMethod.addAlias(name); + return; + } + methods.push(SharedMethod.fromFunction(fn, name, sc)); + }); + + // resolvers + this._resolvers.forEach(function(resolver) { + resolver.call(this, _define.bind(sc, methods)); + }); + + methods = methods.concat(this._methods); + + return methods.filter(sc.isMethodEnabled.bind(sc)); +}; + +SharedClass.prototype.isMethodEnabled = function(sharedMethod) { + if (!sharedMethod.shared) return false; + + var key = this.getKeyFromMethodNameAndTarget(sharedMethod.name, sharedMethod.isStatic); + + if (this._disabledMethods.hasOwnProperty(key)) { + return false; + } + + return true; +}; + +/** + * Define a shared method with the given name. + * + * @param {String} name The method name + * @param {Object} [options] Set of options used to create a `SharedMethod`. + * [See the full set of options](#sharedmethod) + */ + +SharedClass.prototype.defineMethod = function(name, options, fn) { + return _define.call(this, this._methods, name, options, fn); +}; + +function _define(methods, name, options, fn) { + options = options || {}; + var sharedMethod = new SharedMethod(fn, name, this, options); + methods.push(sharedMethod); + return sharedMethod; +} + +/** + * Define a shared method resolver for dynamically defining methods. + * + * @example + * ```js + * // below is a simple example + * sharedClass.resolve(function(define) { + * define('myMethod', { + * accepts: {arg: 'str', type: 'string'}, + * returns: {arg: 'str', type: 'string'} + * errors: [ { code: 404, message: 'Not Found', responseModel: 'Error' } ] + * }, myMethod); + * }); + * function myMethod(str, cb) { + * cb(null, str); + * } + * ``` + * + * @param {Function} resolver The resolver function. + */ + +SharedClass.prototype.resolve = function(resolver) { + this._resolvers.push(resolver); +}; + +/** + * Find a sharedMethod with the given name or function object. + * + * @param {String|Function} fn The function or method name + * @param {Boolean} [isStatic] Required if `fn` is a `String`. + * Only find a static method with the given name. + * @returns {SharedMethod} + */ + +SharedClass.prototype.find = function(fn, isStatic) { + var methods = this.methods(); + return find(methods, fn, isStatic); +}; + +/** + * Disable a sharedMethod with the given name or function object. + * + * @param {String} fn The function or method name + * @param {Boolean} isStatic Disable a static or prototype method + */ + +SharedClass.prototype.disableMethod = function(fn, isStatic) { + var disableMethods = this._disabledMethods; + var key = this.getKeyFromMethodNameAndTarget(fn, isStatic); + disableMethods[key] = true; +}; + +/** + * Get a key for the given method. + * + * @param {String} fn The function or method name. + * @param {Boolean} isStatic True if the method is static. + */ + +SharedClass.prototype.getKeyFromMethodNameAndTarget = function(name, isStatic) { + return (isStatic ? '' : 'prototype.') + name; +}; + +function find(methods, fn, isStatic) { + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + if (method.isDelegateFor(fn, isStatic)) return method; + } + return null; +} + +function eachRemoteFunctionInObject(obj, f) { + if (!obj) return; + + for (var key in obj) { + if (key === 'super_') { + // Skip super class + continue; + } + var fn; + + try { + fn = obj[key]; + } catch (e) { + } + + // HACK: [rfeng] Do not expose model constructors + // We have the following usage to set other model classes as properties + // User.email = Email; + // User.accessToken = AccessToken; + // Both Email and AccessToken can have shared flag set to true + if (typeof fn === 'function' && fn.shared && !fn.modelName) { + f(fn, key); + } + } +} diff --git a/pool/shard000/JavaScript/0005518_webpack.config.js b/pool/shard000/JavaScript/0005518_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..dd03c3d1eff8b6dd5b2571a35a8e68219f09d7e8 --- /dev/null +++ b/pool/shard000/JavaScript/0005518_webpack.config.js @@ -0,0 +1,68 @@ +'use strict' + +const ExtractTextPlugin = require("extract-text-webpack-plugin") +const HtmlWebpackPlugin = require('html-webpack-plugin') +const autoprefixer = require('autoprefixer') +const path = require('path') +const precss = require('precss') + +module.exports = { + entry: { app: './app/App.js' }, + output: { + path: path.resolve('./dist'), + filename: '[name].[hash].js', + publicPath: '/' + }, + devServer: { + contentBase: 'dist', + historyApiFallback: true, + proxy: { + '/api': { target: 'http://localhost:9080' } + } + }, + module: { + rules: [{ + test: /\.ico$/, + loader: 'file-loader?name=[name].[ext]' + }, { + test: /\.css$/, + use: ExtractTextPlugin.extract({ + fallback: 'style-loader', + use: [{ + loader: 'css-loader', + options: { importLoaders: 1 } + }, { + loader: 'postcss-loader', + options: { plugins: () => [autoprefixer, precss] } + }] + }) + }, { + test: /\.js$/, + exclude: /node_modules/, + use: [{ + loader: 'babel-loader', + options: { presets: [['es2015', { modules: false }]] } + }] + }, { + test: /\.(png|jpg|jpeg)$/, + loader: 'url-loader?limit=8192' + }, { + test: /\.(woff|eot|ttf|svg)/, + loader: 'file-loader' + }] + }, + resolve: { + modules: [path.resolve('./app'), 'node_modules'], + extensions: ['.js'] + }, + devtool: '#inline-source-map', + plugins: [ + new HtmlWebpackPlugin({ + filename: 'index.html', + template: 'app/index.html', + chunks: ['app'], + minify: { minifyCSS: true } + }), + new ExtractTextPlugin('styles.css') + ] +} diff --git a/pool/shard000/JavaScript/0005521_decorative-axis.test.js b/pool/shard000/JavaScript/0005521_decorative-axis.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8898cdd02c1d928055d0a07159bb9f992446ed5a --- /dev/null +++ b/pool/shard000/JavaScript/0005521_decorative-axis.test.js @@ -0,0 +1,39 @@ +import React from 'react'; +import {mount} from 'enzyme'; +import DecorativeAxis from 'plot/axis/decorative-axis'; +import {testRenderWithProps, GENERIC_XYPLOT_SERIES_PROPS} from '../test-utils'; +import DecorativeAxisCrissCross from '../../../showcase/axes/decorative-axes-criss-cross'; +import ParallelCoordinatesExample from '../../../showcase/axes/parallel-coordinates-example'; + +testRenderWithProps( + DecorativeAxis, + { + ...GENERIC_XYPLOT_SERIES_PROPS, + axisStart: {x: 0, y: 1}, + axisEnd: {x: 0, y: 1}, + axisDomain: [0, 1] + }, + true +); + +describe('DecorativeAxis', () => { + test('Showcase Example - DecorativeAxisCrissCross', () => { + const $ = mount(<DecorativeAxisCrissCross />); + expect($.text()).toBe( + '-101.01223344556677889100¡1000!¡990!¡980!¡970!¡960!¡950!¡940!¡930!¡920!¡910!¡900!' + ); + expect($.find('.rv-xy-manipulable-axis').length).toBe(2); + expect($.find('.rv-xy-plot__axis__tick__line').length).toBe(22); + expect($.find('.rv-xy-plot__axis__tick__text').length).toBe(22); + }); + + test('Showcase Example - ParallelCoordinatesExample', () => { + const $ = mount(<ParallelCoordinatesExample />); + expect($.text()).toBe( + '0.04.79.314192328333742473.03.54.04.55.05.56.06.57.07.58.0681101501802202603003403804204600.023466992120140160180210230160020002300270030003400370041004400480051008.09.71113151618202123257071727475767778808182' + ); + expect($.find('.rv-xy-manipulable-axis').length).toBe(7); + expect($.find('.rv-xy-plot__axis__tick__line').length).toBe(77); + expect($.find('.rv-xy-plot__axis__tick__text').length).toBe(77); + }); +}); diff --git a/pool/shard000/JavaScript/0005523_changeMaterial.js b/pool/shard000/JavaScript/0005523_changeMaterial.js new file mode 100644 index 0000000000000000000000000000000000000000..9fe5cec7cedcc65d1649bb5d5624063beafcd513 --- /dev/null +++ b/pool/shard000/JavaScript/0005523_changeMaterial.js @@ -0,0 +1,29 @@ +const Article = require('./../server/models/article'); +const mongoose = require('mongoose'); +const chalk = require('chalk'); + + + + +const main = async() => { + let articles = await Article.find().exec(); + + for(let i = 0; i < articles.length; i++) { + let a = articles[i]; + //console.log(a); + if(a.maxLoanDuration < 10) { + a.maxLoanDuration = 10; + try { + await a.save(); + console.log(chalk.green("article ", a._id)); + } catch(err) { + console.log(chalk.red("error article: ", err)); + } + } + + } + + process.exit(1); +} + +main(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005527_component.js b/pool/shard000/JavaScript/0005527_component.js new file mode 100644 index 0000000000000000000000000000000000000000..1713ea30064f5c6aa4b9488fdc49e3a2c12229b4 --- /dev/null +++ b/pool/shard000/JavaScript/0005527_component.js @@ -0,0 +1,22 @@ +import ZeroClipboard from 'zeroclipboard' + +var component = FlowComponents.define("shareButton", function(props) { + this.setFn("shareLink", props.shareLinkFn); + this.set("className", props.className); + + this.onRendered(function() { + this.autorun(function() { + this.initZeroClipboard(props.buttonName, props.className); + }); + }); +}); + +component.prototype.initZeroClipboard = function (buttonName, className) { + var client = new ZeroClipboard($("." + className + " .copy-button")); + client.on( "load", function(client) { + client.on( "complete", function() { + var copiedMessage = i18n("common.copied_to_clipboard", buttonName) + "\n"; + growlAlert.success(copiedMessage); + }); + }); +}; diff --git a/pool/shard000/JavaScript/0005530_execute.js b/pool/shard000/JavaScript/0005530_execute.js new file mode 100644 index 0000000000000000000000000000000000000000..86d0db815ab3b81307365c815f7aead2c27f66e0 --- /dev/null +++ b/pool/shard000/JavaScript/0005530_execute.js @@ -0,0 +1,47 @@ +/* global document */ +var async = require('async'); + +describe('execute', function() { + before(h.setupMultibrowser()); + + before(function(done) { + var self = this; + + this.browserA.url(conf.testPage.subPage); + this.browserB.url(conf.testPage.start); + this.matrix.call(done); + }); + + it('should be able to execute some js', function(done) { + this.matrix + .execute('return document.title', [], function(err, res) { + assert.ifError(err); + res.browserA.value.should.be.equal('two'); + res.browserB.value.should.be.equal(conf.testPage.title); + }) + .call(done); + }); + + it('should be forgiving on giving an `args` parameter', function(done) { + this.matrix + .execute('return document.title', function(err, res) { + assert.ifError(err); + res.browserA.value.should.be.equal('two'); + res.browserB.value.should.be.equal(conf.testPage.title); + }) + .call(done); + }); + + it('should be able to execute a pure function', function(done) { + this.matrix + .execute(function() { + return document.title; + }, function(err, res) { + assert.ifError(err); + res.browserA.value.should.be.equal('two'); + res.browserB.value.should.be.equal(conf.testPage.title); + }) + .call(done); + }); + +}); diff --git a/pool/shard000/JavaScript/0005533_findActiveMembersForPhase.test.js b/pool/shard000/JavaScript/0005533_findActiveMembersForPhase.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1a17f48be3542cb22595650e869c984638583f19 --- /dev/null +++ b/pool/shard000/JavaScript/0005533_findActiveMembersForPhase.test.js @@ -0,0 +1,27 @@ +/* eslint-env mocha */ +/* global expect, testContext */ +/* eslint-disable prefer-arrow-callback, no-unused-expressions, max-nested-callbacks */ +import {resetDB, useFixture} from 'src/test/helpers' +import factory from 'src/test/factories' + +import findActiveMembersForPhase from '../findActiveMembersForPhase' + +describe(testContext(__filename), function () { + before(resetDB) + + beforeEach(function () { + useFixture.nockClean() + }) + + it('returns members for the given phase who are active according to IDM', async function () { + const phase = await factory.create('phase') + const members = await factory.createMany('member', {phaseId: phase.id}, 5) + const users = members.map(u => ({id: u.id, active: true})) + users[0].active = users[1].active = false + useFixture.nockIDMFindUsers(users) + + const activePhaseMembers = await findActiveMembersForPhase(phase.id) + + expect(activePhaseMembers.length).to.equal(3) + }) +}) diff --git a/pool/shard000/JavaScript/0005535_active_tab.js b/pool/shard000/JavaScript/0005535_active_tab.js new file mode 100644 index 0000000000000000000000000000000000000000..f77d4819e054ebe93ae223862be3e588a6912d9b --- /dev/null +++ b/pool/shard000/JavaScript/0005535_active_tab.js @@ -0,0 +1,52 @@ +/** + * @description + * ActiveTab directive for activating correct tab based on current location. + * + * The activeTab attribute should contain a path search string to match on, i.e., + * <li><a href="#/nested/section1/partial" active-tab="/section1">First Partial</a></li> + * + * @example + <ul> + <li><a href="#/about" active-tab="/about">About</a></li> + <li><a ui-sref="home" active-tab="/home">Home</a></li> + </ul> + */ +define([], function () { + "use strict"; + + var activeTabCls = 'tabActiveHeader'; + + var processTab = function ($location, element, attrs) { + if ($location.path().indexOf(attrs.activeTab) >= 0) { + element.parent().addClass(activeTabCls); //parent to get the <li> + } else { + element.parent().removeClass(activeTabCls); + } + }; + + var ActiveTab = function ($location) { + return { + restrict: 'A', + link: function postLink(scope, element, attrs) { + + // Broadcasted after a route dependencies are resolved. ngView listens for the directive + // to instantiate the controller and render the view. + scope.$on("$routeChangeSuccess", function (event, current, previous) { + processTab($location, element, attrs); + }); + + // $stateChangeSuccess - fired once the state transition is complete. + // see https://github.com/angular-ui/ui-router/wiki + scope.$on("$stateChangeSuccess", function (event, current, previous) { + processTab($location, element, attrs); + }); + } + }; + }; + + return { + feature: 'directive', + name: 'activeTab', + cls: ['$location', ActiveTab] + }; +}); diff --git a/pool/shard000/JavaScript/0005536_send-status-message.js b/pool/shard000/JavaScript/0005536_send-status-message.js new file mode 100644 index 0000000000000000000000000000000000000000..d88fbc17066d234228029c34a962594b41012b8a --- /dev/null +++ b/pool/shard000/JavaScript/0005536_send-status-message.js @@ -0,0 +1,32 @@ +'use strict' + +const miss = require('mississippi') +const Wreck = require('wreck') +const generateToken = require('tfk-generate-jwt') +const config = require('../config') +const token = generateToken({key: config.JWT_KEY, payload: {system: 'tfk-saksbehandling-elev-varsel'}}) +var wreckOptions = { + json: true, + headers: { + Authorization: token + } +} + +module.exports = miss.through((chunck, encoding, callback) => { + var item = JSON.parse(chunck) + + if (item.CALLBACK_STATUS_URL) { + wreckOptions.payload = JSON.stringify({status: item.CALLBACK_STATUS_MESSAGE}) + console.log(item._id + ': send-status-message') + + Wreck.post(item.CALLBACK_STATUS_URL, wreckOptions, function (error, response, payload) { + if (error) { + item.errors.push(JSON.stringify(error)) + } + return callback(null, JSON.stringify(item)) + }) + } else { + console.log(item._id + ': send-status-message. No message to send') + return callback(null, JSON.stringify(item)) + } +}) diff --git a/pool/shard000/JavaScript/0005537_Session.js b/pool/shard000/JavaScript/0005537_Session.js new file mode 100644 index 0000000000000000000000000000000000000000..3166f7d33731ead66e542b35944b5c5b2a7b4ab5 --- /dev/null +++ b/pool/shard000/JavaScript/0005537_Session.js @@ -0,0 +1,60 @@ +var Model = require('./Model.js'); +var mysql = require('./mysql.js'); +var crypto = require('crypto'); +var dateFormat = require('dateformat'); + +var Session = Object.create(Model); + +Session.table = 'sessions'; + +Session.create = function(data,callback) { + var generator = crypto.createHash('md5'); + var date = new Date(); + generator.write(data.username+':'+data.password+':'+date.toISOString()); + generator.end(); + data.token = generator.read().toString('base64'); + + delete data.password; + delete data.username; + + var day = date.getDate(); + date.setDate(day+1); + date.toTimezone + + data.expires_at = dateFormat(date,'UTC:yyyy/mm/dd HH:MM:ss'); + + Session.__proto__.create.call(this,data,callback); +}; + +Session.check = function(token,callback) { + var date = dateFormat(new Date(), 'UTC:yyyy/mm/dd HH:MM:ss'); + Session.where('token',token).where('expires_at','>',date).get(function(err,result){ + if (err) { + if (callback) callback(err); + } + else if (result.length > 0) { + callback(null,result[0]); + } + else { + callback(null,false); + } + }); +} + +Session.delete = function(token,callback) { + var sql = "UPDATE sessions SET expires_at = CURRENT_TIMESTAMP WHERE token = ?"; + var values = [token]; + + mysql.getConnection(function(err,connection){ + if (err) { + if (callback) callback(err); + return; + } + connection.query(sql,values,function(err,result){ + if (callback) callback(err,result); + connection.release(); + }); + }) +}; + +module.exports = Session; diff --git a/pool/shard000/JavaScript/0005538_tab_search.js b/pool/shard000/JavaScript/0005538_tab_search.js new file mode 100644 index 0000000000000000000000000000000000000000..df49f74193cebf2ef6d7e649d955158bf3ed4786 --- /dev/null +++ b/pool/shard000/JavaScript/0005538_tab_search.js @@ -0,0 +1,61 @@ +//Libraries +const React = require("react") + , _ = require("lodash"); + +const DataStore = require("../stores/data_store"); +const TabActions = require("../actions/tabs_actions"); + +const Search = require("../vanilla_components/search"); +const TabItems = require("./tab_items"); +const TabButton = require("./tab_button"); +const TabsHolder = require("./tabs_holder"); + +// var MorseBootstrap = require("morse-bootstrap-react"); +// const FlashNotice = MorseBootstrap.FlashNotice; + +class TabSearch extends React.Component { + + constructor(props) { + super(props); + this.state = {tabsId:null}; + } + + componentWillMount(){ + if(this.props.tabs){ + let id = _.uniqueId("tabs"); + TabActions.addingTabs(this.props.tabs, id); + // console.log(id); + this.setState({tabsId:id}); + } + } + + _renderIntro(){ + if(this.props.intro){ + return ( + <p className="intro" key="intro">{this.props.intro}</p> + ); + } + + return ""; + } + + render() { + // console.log("tabs", this.props.icon) + return ( + <div className="search"> + <TabsHolder tabsId={this.state.tabsId} /> + <div className="search-body"> + {this._renderIntro()} + <Search {...this.props} > + <h2 className="osw-r up-c gamma sub">Or browse all Jobs... </h2> + <TabItems {...this.props} key = "GenericItems" /> + </Search> + </div> + </div> + ); + } + +} + +module.exports = TabSearch; + diff --git a/pool/shard000/JavaScript/0005539_page.js b/pool/shard000/JavaScript/0005539_page.js new file mode 100644 index 0000000000000000000000000000000000000000..db624c42d2890627c40cba6ecf9634a15d48c74d --- /dev/null +++ b/pool/shard000/JavaScript/0005539_page.js @@ -0,0 +1,145 @@ +var offset = 10; +var category = 'newest'; +var content = $('#content'); +var dialog = $( "#notification_dialog" ); + +$(function() { + dialog.dialog({ + autoOpen: false + }); +}); + +function handleNewRating(data) { + console.log(data); + var likeBar = $(".progress-bar-success[data-request_slug='" + + data.requestSlug + "'][data-response_author='" + + data.responseAuthor + "']"); + var dislikeBar = $(".progress-bar-danger[data-request_slug='" + + data.requestSlug + "'][data-response_author='" + + data.responseAuthor + "']"); + + likeBar.css('width', data.likesPercent + "%"); + var likeText = data.likes; + if(data.likes == '0') { + likeText = ''; + } + likeBar.text(likeText); + + dislikeBar.css('width', data.dislikesPercent + "%"); + var dislikeText = data.dislikes; + if(data.dislikes == '0') { + dislikeText = ''; + } + dislikeBar.text(dislikeText); + +} + +content.on('click', '.like_button', (function(event){ + var type = 'create'; + if($(this).hasClass('liked')) { + type = 'remove'; + } + var likeButton = $(this); + + (function() { + $.ajax({ + type: "POST", + url: '/app_dev.php/rating/' + type, + data: { + request_slug: likeButton.data('request_slug'), + response_author: likeButton.data('response_author'), + rate: true + } + }) + .success(function(data){ + if(data.status == 'success') { + if(type == 'create') { + likeButton.addClass('liked'); + likeButton.parent().children('.dislike_button').removeClass('disliked'); + }else{ + likeButton.removeClass('liked'); + } + }else{ + dialog.text(data.message); + dialog.dialog('open'); + } + }); + })(); + + + event.preventDefault(); +})); + +content.on('click','.dislike_button', (function(event){ + var type = 'create'; + if($(this).hasClass('disliked')) { + type = 'remove'; + } + + var dislikeButton = $(this); + + (function() { + $.ajax({ + type: "POST", + url: '/app_dev.php/rating/' + type, + data: { + request_slug: dislikeButton.data('request_slug'), + response_author: dislikeButton.data('response_author'), + rate: false + } + }) + .success(function (data) { + if (data.status == 'success') { + if (type == 'create') { + dislikeButton.parent().children('.like_button').removeClass('liked'); + dislikeButton.addClass('disliked'); + } else { + dislikeButton.removeClass('disliked'); + } + } else { + dialog.text(data.message); + dialog.dialog('open'); + } + }); + })(); + + event.preventDefault(); +})); + +$(window).scroll(function() +{ + if($(window).scrollTop() == $(document).height() - $(window).height()) + { + $('#small-ajax-loader').show(); + $.ajax({ + url: "/app_dev.php/load/" + category, + type: 'POST', + data: {offset: offset}, + success: function(html) + { + if(html) + { + $("#content").append(html); + $('#small-ajax-loader').hide(); + offset += 5; + }else + { + $('#small-ajax-loader').html('No more photos to show.'); + } + } + }); + } +}); + +var conn = new ab.Session('ws://127.0.0.1:8080', + function() { + conn.subscribe('rating', function(topic, data) { + this.handleNewRating(data); + }); + }, + function() { + console.log("Connection could not be established"); + + }, + {'skipSubprotocolCheck': true} +); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005540_index4.js b/pool/shard000/JavaScript/0005540_index4.js new file mode 100644 index 0000000000000000000000000000000000000000..4e99e9adf594954f7ad961a7fe33864d2ef8acb3 --- /dev/null +++ b/pool/shard000/JavaScript/0005540_index4.js @@ -0,0 +1,108 @@ +(function () { + 'use strict'; + angular + .module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache']) + .controller('ContactChipDemoCtrl', DemoCtrl); + + function DemoCtrl ($q, $timeout) { + var self = this; + var pendingSearch, cancelSearch = angular.noop; + var cachedQuery, lastSearch; + + self.allContacts = loadContacts(); + self.contacts = [self.allContacts[0]]; + self.asyncContacts = []; + self.filterSelected = true; + + self.querySearch = querySearch; + self.delayedQuerySearch = delayedQuerySearch; + + /** + * Search for contacts; use a random delay to simulate a remote call + */ + function querySearch (criteria) { + cachedQuery = cachedQuery || criteria; + return cachedQuery ? self.allContacts.filter(createFilterFor(cachedQuery)) : []; + } + + /** + * Async search for contacts + * Also debounce the queries; since the md-contact-chips does not support this + */ + function delayedQuerySearch(criteria) { + cachedQuery = criteria; + if ( !pendingSearch || !debounceSearch() ) { + cancelSearch(); + + return pendingSearch = $q(function(resolve, reject) { + // Simulate async search... (after debouncing) + cancelSearch = reject; + $timeout(function() { + + resolve( self.querySearch() ); + + refreshDebounce(); + }, Math.random() * 500, true) + }); + } + + return pendingSearch; + } + + function refreshDebounce() { + lastSearch = 0; + pendingSearch = null; + cancelSearch = angular.noop; + } + + /** + * Debounce if querying faster than 300ms + */ + function debounceSearch() { + var now = new Date().getMilliseconds(); + lastSearch = lastSearch || now; + + return ((now - lastSearch) < 300); + } + + /** + * Create filter function for a query string + */ + function createFilterFor(query) { + var lowercaseQuery = angular.lowercase(query); + + return function filterFn(contact) { + return (contact._lowername.indexOf(lowercaseQuery) != -1);; + }; + + } + + function loadContacts() { + var contacts = [ + 'Feroze Chickenwala', + 'Keshava Javeragowda', + 'Ritobroto Maitra', + 'Mainak Bhattacharya', + 'Sombodhi Ghosh', + 'Makhanlal Chawalwala', + 'Donald Trump', + 'Hillary Clinton', + 'Karan Jakhar' + ]; + + return contacts.map(function (c, index) { + var cParts = c.split(' '); + var contact = { + name: c, + email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase() + '@aficionadoventures.com', + image: 'img/contacts/face.png' + }; + contact._lowername = contact.name.toLowerCase(); + return contact; + }); + } + } + + +})(); + diff --git a/pool/shard000/JavaScript/0005542_index.js b/pool/shard000/JavaScript/0005542_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d00597edba338331856649a5866ab402580007a5 --- /dev/null +++ b/pool/shard000/JavaScript/0005542_index.js @@ -0,0 +1,88 @@ +'use strict'; + +const packageData = require('../../package.json'); +const shared = require('../shared'); + +/** + * Generates a Transport object for Sendmail + * + * Possible options can be the following: + * + * * **path** optional path to sendmail binary + * * **newline** either 'windows' or 'unix' + * * **args** an array of arguments for the sendmail binary + * + * @constructor + * @param {Object} optional config parameter for the AWS Sendmail service + */ +class JSONTransport { + constructor(options) { + options = options || {}; + + this.options = options || {}; + + this.name = 'JSONTransport'; + this.version = packageData.version; + + this.logger = shared.getLogger(this.options, { + component: this.options.component || 'json-transport' + }); + } + + /** + * <p>Compiles a mailcomposer message and forwards it to handler that sends it.</p> + * + * @param {Object} emailMessage MailComposer object + * @param {Function} callback Callback function to run when the sending is completed + */ + send(mail, done) { + // Sendmail strips this header line by itself + mail.message.keepBcc = true; + + let envelope = mail.data.envelope || mail.message.getEnvelope(); + let messageId = mail.message.messageId(); + + let recipients = [].concat(envelope.to || []); + if (recipients.length > 3) { + recipients.push('...and ' + recipients.splice(2).length + ' more'); + } + this.logger.info( + { + tnx: 'send', + messageId + }, + 'Composing JSON structure of %s to <%s>', + messageId, + recipients.join(', ') + ); + + setImmediate(() => { + mail.normalize((err, data) => { + if (err) { + this.logger.error( + { + err, + tnx: 'send', + messageId + }, + 'Failed building JSON structure for %s. %s', + messageId, + err.message + ); + return done(err); + } + + delete data.envelope; + delete data.normalizedHeaders; + + return done(null, { + envelope, + messageId, + message: JSON.stringify(data) + }); + }); + }); + } +} + +module.exports = JSONTransport; diff --git a/pool/shard000/JavaScript/0005543_dstr-gen-meth-static-ary-ptrn-elem-id-init-hole.js b/pool/shard000/JavaScript/0005543_dstr-gen-meth-static-ary-ptrn-elem-id-init-hole.js new file mode 100644 index 0000000000000000000000000000000000000000..72eeec73140916e7ba63f73da6f928acc9f3f06f --- /dev/null +++ b/pool/shard000/JavaScript/0005543_dstr-gen-meth-static-ary-ptrn-elem-id-init-hole.js @@ -0,0 +1,83 @@ +// This file was procedurally generated from the following sources: +// - src/dstr-binding/ary-ptrn-elem-id-init-hole.case +// - src/dstr-binding/default/cls-expr-gen-meth-static.template +/*--- +description: Destructuring initializer with a "hole" (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 + SingleNameBinding : BindingIdentifier Initializeropt + [...] 6. If Initializer is present and v is undefined, then + a. Let defaultValue be the result of evaluating Initializer. + b. Let v be GetValue(defaultValue). + [...] + 7. If environment is undefined, return PutValue(lhs, v). 8. Return InitializeReferencedBinding(lhs, v). +---*/ + +var callCount = 0; +var C = class { + static *method([x = 23]) { + assert.sameValue(x, 23); + // another statement + callCount = callCount + 1; + } +}; + +C.method([,]).next(); +assert.sameValue(callCount, 1, 'method invoked exactly once'); diff --git a/pool/shard000/JavaScript/0005545_auto-trigger.js b/pool/shard000/JavaScript/0005545_auto-trigger.js new file mode 100644 index 0000000000000000000000000000000000000000..528e30150f37ae674c3ce44e22ef498a8ee5d122 --- /dev/null +++ b/pool/shard000/JavaScript/0005545_auto-trigger.js @@ -0,0 +1,169 @@ +/* AutoTrigger */ ++function($, window, document, Math) +{ + "use strict"; + + var AutoTrigger = function(element, options) + { + this.$ = $(element); + this.options = this.getOptions(options); + + this.init(); + }; + + AutoTrigger.DEFAULTS = + { + trigger: 'toggle', + selector: null, + animate: 'slide', + easing: 'linear', + animateSpeed: 'fast', + events: 'click', + preventDefault: true, + cancelBubble: true, + target: null + //,before: + //,after: + }; // default options + + AutoTrigger.prototype.getOptions = function (options) + { + options = $.extend({}, AutoTrigger.DEFAULTS, this.$.data(), options); + return options; + }; + + AutoTrigger.prototype.init = function() + { + this.bindEvents(); + }; + + AutoTrigger.prototype.bindEvents = function() + { + var options = this.options, that = this; + this.bindTrigger(options); + + if($.isArray(options.triggers)) + { + for(var i in options.triggers) + { + this.bindTrigger($.extend({}, options, options.triggers[i])); + } + } + else if(typeof options.triggers === 'string') + { + /* events,trigger,target,data */ + var triggers = options.triggers.split('|'); + for(var i in triggers) + { + var ops = triggers[i].split(',', 4); + if(ops.length < 2) continue; + var option = {}; + if(ops[0]) option.events = ops[0]; + if(ops[1]) option.trigger = ops[1]; + if(ops[2]) option.target = ops[2]; + if(ops[3]) option.data = ops[3]; + + this.bindTrigger($.extend({}, options, option)); + } + } + }; + + AutoTrigger.prototype.bindTrigger = function(options) + { + var that = this; + that.$.on(options.events, options.selector, function(event) + { + var target = (!options.target) || options.target == 'self' ? that.$ : $(options.target); + var data = {event: event, element: this, target: target, options: options}; + if(!$.callEvent(options.before, data, that)) return; + + if($.isFunction(options.trigger)) + { + $.callEvent(options.trigger, data, that); + } + else + { + var type = options.trigger; + if(type === 'toggle') + { + type = target.hasClass('hide') ? 'show' : 'hide'; + } + switch(type) + { + case 'toggle': + target.toggle(); + break; + case 'show': + var params = {duration: options.animateSpeed, easing: options.easing}; + + target.removeClass('hide'); + if(options.animate === 'slide') + { + target.slideDown(params); + } + else if(options.animate === 'fade') + { + target.fadeIn(params); + } + else + { + target.show(params); + } + break; + case 'hide': + var params = {duration: options.animateSpeed, easing: options.easing, complete: function(){target.addClass('hide');}}; + if(options.animate === 'slide') + { + target.slideUp(params); + } + else if(options.animate === 'fade') + { + target.fadeOut(params); + } + else + { + target.hide(params); + } + break; + case 'addClass': + case 'removeClass': + case 'toggleClass': + target[type](options.data); + break; + } + } + + $.callEvent(options.after, data, that); + + if(options.preventDefault) event.preventDefault(); + if(options.cancelBubble) event.stopPropagation(); + }); + } + + $.fn.autoTrigger = function(option) + { + return this.each(function() + { + var $this = $(this); + var data = $this.data('zui.autoTrigger'); + var options = typeof option == 'object' && option; + + if (!data) $this.data('zui.autoTrigger', (data = new AutoTrigger(this, options))); + + if (typeof option == 'string') data[option](); + }) + }; + + $.fn.autoTrigger.Constructor = AutoTrigger; + + $(function() + { + $('[data-toggle="autoTrigger"]').autoTrigger(); + $('[data-toggle="toggle"]').autoTrigger(); + $('[data-toggle="show"]').autoTrigger({trigger: 'show'}); + $('[data-toggle="hide"]').autoTrigger({trigger: 'hide'}); + $('[data-toggle="addClass"]').autoTrigger({trigger: 'addClass'}); + $('[data-toggle="removeClass"]').autoTrigger({trigger: 'removeClass'}); + $('[data-toggle="toggleClass"]').autoTrigger({trigger: 'toggleClass'}); + }); +}(jQuery,window,document,Math); diff --git a/pool/shard000/JavaScript/0005546_sha1.js b/pool/shard000/JavaScript/0005546_sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..b4db3a4a1d5e268a9521b17eb17431ad814ca040 --- /dev/null +++ b/pool/shard000/JavaScript/0005546_sha1.js @@ -0,0 +1,32 @@ +var _sha1_block_size = 64, + _sha1_hash_size = 20; + +function sha1_constructor ( options ) { + options = options || {}; + options.heapSize = options.heapSize || 4096; + + if ( options.heapSize <= 0 || options.heapSize % 4096 ) + throw new IllegalArgumentError("heapSize must be a positive number and multiple of 4096"); + + this.heap = options.heap || new Uint8Array(options.heapSize); + this.asm = options.asm || sha1_asm( global, null, this.heap.buffer ); + + this.BLOCK_SIZE = _sha1_block_size; + this.HASH_SIZE = _sha1_hash_size; + + this.reset(); +} + +sha1_constructor.BLOCK_SIZE = _sha1_block_size; +sha1_constructor.HASH_SIZE = _sha1_hash_size; +var sha1_prototype = sha1_constructor.prototype; +sha1_prototype.reset = hash_reset; +sha1_prototype.process = hash_process; +sha1_prototype.finish = hash_finish; + +var sha1_instance = null; + +function get_sha1_instance () { + if ( sha1_instance === null ) sha1_instance = new sha1_constructor( { heapSize: 0x100000 } ); + return sha1_instance; +} diff --git a/pool/shard000/JavaScript/0005550_helpers.js b/pool/shard000/JavaScript/0005550_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..bf9082204b259726333794b3bbffe048362805f0 --- /dev/null +++ b/pool/shard000/JavaScript/0005550_helpers.js @@ -0,0 +1,34 @@ +/* global define */ + +(function () { + 'use strict'; + + /** + * Helpers + */ + + var helpers = { + toArray: function (obj) { + return [].slice.call(obj, 0); + }, + mixin: function (target, obj) { + helpers.toArray(Object.keys(obj)).forEach(function (key) { + target[key] = obj[key]; + }); + } + }; + + + // Expose the class either via AMD, CommonJS or the global object + if (typeof define === 'function' && define.amd) { + define(function () { + return helpers; + }); + } + else if (typeof module === 'object' && module.exports) { + module.exports = helpers; + } + else { + this.helpers = helpers; + } +}.call(this)); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005556_6f51982663abf2d83034964b5a227178d99cc4a6.js b/pool/shard000/JavaScript/0005556_6f51982663abf2d83034964b5a227178d99cc4a6.js new file mode 100644 index 0000000000000000000000000000000000000000..62374340f0c5be8bcbddfdc6fadde5425fbaab40 --- /dev/null +++ b/pool/shard000/JavaScript/0005556_6f51982663abf2d83034964b5a227178d99cc4a6.js @@ -0,0 +1,80 @@ +var Todo = React.createClass({displayName: "Todo", + render: function() { + return ( + React.createElement("li", {id: '"' + this.props.key + '"', className: "list-group-item todo"}, + React.createElement("a", {href: "#", className: "pull-left todo-check"}, + React.createElement("span", {className: "todo-check-mark glyphicon glyphicon-ok", "aria-hidden": "true"}) + ), + React.createElement("span", {contentEditable: "true", "data-ph": "Todo", class: "todo-text"}, this.props.text) + ) + ); + } +}); + +var TodoList = React.createClass({displayName: "TodoList", + getInitialState: function() { + this.todos = []; + return {todos: []}; + }, + componentWillMount: function() { + this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/"); + + // Add an empty todo if none currently exist. + this.ref.once("value", function(snap) { + if (snap.val() === null) { + this.ref.push({ + text: "", + checked: false, + }); + } + console.log(snap.val()); + }.bind(this)); + this.ref.on("child_added", function(childSnap) { + this.todos.push(childSnap.val()); + this.setState({ + todos: this.todos + }); + }.bind(this)); + }, + componentWillUnmount: function() { + this.ref.off(); + }, + render: function() { + var todos = this.state.todos.map(function (todo) { + console.log(todo); + return ( + React.createElement(Todo, null) + ); + }); + return ( + React.createElement("div", null, + React.createElement("h1", {id: "list_title"}, this.props.title), + React.createElement("ul", {id: "todo-list", className: "list-group"}, + todos + ) + ) + ); + } +}); + +var ListPage = React.createClass({displayName: "ListPage", + render: function() { + return ( + React.createElement("div", null, + React.createElement("div", {id: "list_page"}, + React.createElement("a", {href: "?", id: "lists_link", className: "btn btn-primary"}, "Back to Lists") + ), + React.createElement("div", {className: "page-header"}, + this.props.children + ) + ) + ); + } +}); + +React.render( + React.createElement(ListPage, null, + React.createElement(TodoList, {key: "asdf", title: "hi", todos: []}) + ), + document.getElementById('content') +); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005562_factlist.js b/pool/shard000/JavaScript/0005562_factlist.js new file mode 100644 index 0000000000000000000000000000000000000000..11114e2f68be91dc2db35caecc78d45ba2dbac86 --- /dev/null +++ b/pool/shard000/JavaScript/0005562_factlist.js @@ -0,0 +1,222 @@ +var $text = null; +var $factList = null; +var $save = null; +var $poster = null; +var $themeButtons = null; +var $aspectRatioButtons = null; +var $fontSize = null; +var $timestamp = null; +var $timestampToggleButtons = null; +var $kicker = null; +var $kickerInput = null; +var $source = null; +var $logoWrapper = null; +var $updateTime = null; +var timestampInterval = null; + +/* + * Run on page load. + */ +var onDocumentLoad = function() { + $text = $('.poster blockquote p, .source'); + $factList = $('.poster blockquote'); + $save = $('#save'); + $poster = $('.poster'); + $themeButtons = $('#theme .btn'); + $aspectRatioButtons = $('#aspect-ratio .btn'); + $fontSize = $('#fontsize'); + $timestamp = $('.timestamp'); + $timestampToggleButtons = $('#timestamp-toggle .btn'); + $kicker = $('.kicker'); + $kickerInput = $('#kicker'); + $logoWrapper = $('.logo-wrapper'); + $updateTime = $('#update-time'); + + $save.on('click', saveImage); + $themeButtons.on('click', onThemeClick); + $aspectRatioButtons.on('click', onAspectRatioClick); + $timestampToggleButtons.on('click', onTimestampToggleClick); + $fontSize.on('change', adjustFontSize); + $kickerInput.on('keyup', onKickerKeyup); + + adjustFontSize(null, 32); + processText(); + updateTimestamp(); + timestampInterval = setInterval(updateTimestamp, 1000); + setupMediumEditor(); + + $('[data-toggle="tooltip"]').tooltip(); +} + +/* + * Change straight quotes to curly and double hyphens to em-dashes. + */ +var smarten = function(a) { + a = a.replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018"); // opening singles + a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes + a = a.replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c"); // opening doubles + a = a.replace(/"/g, "\u201d"); // closing doubles + a = a.replace(/--/g, "\u2014"); // em-dashes + a = a.replace(/ \u2014 /g, "\u2009\u2014\u2009"); // full spaces wrapping em dash + return a; +} + +/* + * Convert a string to slug format + */ +var convertToSlug = function(text) { + return text + .toLowerCase() + .replace(/[^\w ]+/g,'') + .replace(/ +/g,'-'); +} + +/* + * Cleanup whitespace and smart quotes on text inputs + */ +var processText = function() { + $text = $('.poster blockquote p, .source'); + $text.each(function() { + var rawText = $.trim($(this).html()); + $(this).html(smarten(rawText)).find('br').remove(); + }); +} + +/* + * Set the timestamp text to the current time + */ +var updateTimestamp = function() { + var latestTime = moment().format('MMMM D, YYYY h:mm A'); + if (latestTime != $timestamp.text()) { + $timestamp.text(latestTime); + } +} + +/* + * Convert the poster HTML/CSS to canvas and export an image + */ +var saveImage = function() { + // first check if the quote actually fits + if (($factList.offset().top + $factList.height()) > $logoWrapper.offset().top) { + var tooTallMessage = "Your list is too long. Shorten the text or choose a smaller font-size."; + } + + if ($kicker.width() > $poster.width()) { + var tooWideMessage = "Your headline is too wide. Shorten the headline."; + } + + if (tooTallMessage || tooWideMessage) { + var alertMessage; + if (tooTallMessage && tooWideMessage) { + alertMessage = tooTallMessage + '\n' + tooWideMessage; + } else { + alertMessage = (tooTallMessage) ? tooTallMessage : tooWideMessage; + } + alert(alertMessage); + return; + } + + $('canvas').remove(); + processText(); + + html2canvas($poster, { + letterRendering: true, + onrendered: function(canvas) { + document.body.appendChild(canvas); + window.oCanvas = document.getElementsByTagName("canvas"); + window.oCanvas = window.oCanvas[0]; + var strDataURI = window.oCanvas.toDataURL(); + + var headline = $kicker.text().split(' ', 9); + var filename = convertToSlug(headline.join(' ')); + + var a = $("<a>").attr("href", strDataURI).attr("download", "factlist-" + filename + ".png").appendTo("body"); + + a[0].click(); + + a.remove(); + + $('#download').attr('href', strDataURI).attr('target', '_blank'); + $('#download').trigger('click'); + } + }); +} + +/* + * Adjust the poster font size + */ +var adjustFontSize = function(e, size) { + var newSize = size||$(this).val(); + + var fontSize = newSize.toString() + 'px'; + $poster.css('font-size', fontSize); + if ($fontSize.val() !== newSize){ + $fontSize.val(newSize); + }; +} + +/* + * Select a poster theme + */ +var onThemeClick = function(e) { + $themeButtons.removeClass().addClass('btn btn-primary'); + $(this).addClass('active'); + $poster.removeClass('poster-theme1 poster-theme2 poster-theme3 poster-theme4 poster-election-2016') + .addClass('poster-' + $(this).attr('id')); +} + +/* + * Select the poster aspect ratio + */ +var onAspectRatioClick = function(e) { + $aspectRatioButtons.removeClass().addClass('btn btn-primary'); + $(this).addClass('active'); + $poster.removeClass('square sixteen-by-nine').addClass($(this).attr('id')); + + if ($poster.hasClass('sixteen-by-nine')) { + $fontSize.attr('min', 24); + $fontSize.val(24); + adjustFontSize(null, 32); + } else { + $fontSize.attr('min', 32); + $fontSize.val(42); + adjustFontSize(null, 42); + } +} + +/* + * Select the poster aspect ratio + */ +var onTimestampToggleClick = function(e) { + $timestampToggleButtons.removeClass().addClass('btn btn-primary'); + $(this).addClass('active'); + if ($(this).attr('id') === 'show-timestamp') { + $timestamp.show(); + } else { + $timestamp.hide(); + } +} + +/* + * Update the kicker text + */ +var onKickerKeyup = function(e) { + var inputText = $(this).val(); + $kicker.text(inputText); +} + +/* + * Bind a medium editor to the poster blockquote + */ +var setupMediumEditor = function(){ + var quoteEl = document.querySelectorAll('.poster blockquote'); + + var quoteEditor = new MediumEditor(quoteEl, { + disableToolbar: true, + placeholder: '' + }); + + $factList.focus(); +} + +$(onDocumentLoad); diff --git a/pool/shard000/JavaScript/0005563_get-fa-glyphs.js b/pool/shard000/JavaScript/0005563_get-fa-glyphs.js new file mode 100644 index 0000000000000000000000000000000000000000..07412d257a60335e897f9343dcbe8889a14ce269 --- /dev/null +++ b/pool/shard000/JavaScript/0005563_get-fa-glyphs.js @@ -0,0 +1,33 @@ +"use strict"; +const fs = require("fs"); +const glyphs = [ ]; + +module.exports = function() { + return new Promise((resolve, reject) => { + if(glyphs.length) { + return resolve(glyphs); + } + + fs.exists("node_modules/font-awesome/less/variables.less", exists => { + if(exists) { + const glyphRegex = /@fa-var-([^:]+):\s*"([^"]+)";/ig; + fs.readFile("node_modules/font-awesome/less/variables.less", { encoding: "utf-8" }, (err, variables) => { + if(err) { + return reject(err); + } + + let match; + while((match = glyphRegex.exec(variables))) { + glyphs.push({ + name: match[1], + unicode: match[2] + }); + } + resolve(glyphs); + }); + } else { + reject(new Error("No font-awesome LESS file found")); + } + }); + }); +}; diff --git a/pool/shard000/JavaScript/0005567_clone.js b/pool/shard000/JavaScript/0005567_clone.js new file mode 100644 index 0000000000000000000000000000000000000000..ca2abd24c111f954dcc817b4297f81820fe3c4dc --- /dev/null +++ b/pool/shard000/JavaScript/0005567_clone.js @@ -0,0 +1,41 @@ + 'use strict'; +define(function() { + var BUILTIN_OBJECT = { + '[object Function]': 1, + '[object RegExp]': 1, + '[object Date]': 1, + '[object Error]': 1, + '[object CanvasGradient]': 1 + }; + + /** + * 克隆类 + * @author ray wu + * @class clone + * @since 0.1.0 + * @module basic + */ + return { + clone: function(source) { + if (typeof source === 'object' && source !== null) { + var result = source; + if (source instanceof Array) { + result = []; + for (var i = 0, len = source.length; i < len; i++) { + result[i] = this.clone(source[i]); + } + } else if (!BUILTIN_OBJECT[Object.prototype.toString.call(source)]) { + result = {}; + for (var key in source) { + if (source.hasOwnProperty(key)) { + result[key] = this.clone(source[key]); + } + } + } + + return result; + } + return source; + } + }; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005568_method-audit.js b/pool/shard000/JavaScript/0005568_method-audit.js new file mode 100644 index 0000000000000000000000000000000000000000..30a4f4cabf0c342744262c46d5f171083764500d --- /dev/null +++ b/pool/shard000/JavaScript/0005568_method-audit.js @@ -0,0 +1,98 @@ +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; +import classNames from 'classnames'; +import { + buildDDPMethodTester, + testCollectionSecurity, +} from '../lib'; +import { + setCollectionSecurity +} from '../actions'; +import Analytics from '../../../common/analytics'; +import Bridge from '../../../common/bridge'; +import JSONTree from 'react-json-tree'; +import MethodStatus from './method-audit'; + +export default React.createClass({ + propTypes : { + traces: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + params : PropTypes.array, + }, + + shouldComponentUpdate: function(nextProps, nextState) { + return !this.props.traces.equals(nextProps.traces); + }, + + _auditMethod(argType, argument) { + // send a DDP probe + Bridge.sendMessageToThePage({ + source: 'security-auditor', + event: 'test-method-params', + ddpMessage: buildDDPMethodTester(this.props.name, argType, argument), + }); + this.setState({'testing': true}); + + Analytics.trackEvent('security', 'method:audit'); + }, + + _showResult(argType) { + const response = this.props.traces.find((trace) => { + return trace.message.id === `/audit/${this.props.name}/${argType}`; + }); + if (!response) { return; } + if(response.message && response.message.error) { + if(response.message.error.reason === 'Match failed'){ + return <div className="valid"><span className="check-status">⬤</span>Blocked by check</div>; + } else { + return <div className="error"><span className="check-status">⬤</span>Unknown error</div>; + } + } else { + return <div className="warning"><span className="check-status">⬤</span>Method called</div>; + } + }, + + render () { + const theme = { + tree: { + backgroundColor: 'transparent', + fontSize: '1em' + }, + arrow: ({ style }, type, expanded) => ({ + style: Object.assign(style, { + marginTop: 2 + }) + }), + }; + + const valueRenderer = (raw) => { + const type = typeof raw; + return <span>{raw} <span className="arg-type">// {type}</span></span> + }; + + const checkMethod = ['string', 'number', 'object'].map((argType) => { + return (<div className="check-method"> + <button onClick={() => this._auditMethod(argType)}>Call with <em>{argType}</em></button> + <div>{this._showResult(argType)}</div> + </div>); + }); + + return ( + <li key={this.props.name}> + <div><strong>{this.props.name}</strong></div> + <div className="method-content"> + <div className="args">Called with args: </div> + <JSONTree + data={this.props.params} + hideRoot + theme={theme} + valueRenderer={valueRenderer} + /> + <div className="method-audit"> + {checkMethod} + </div> + </div> + </li> + ) + } +}); diff --git a/pool/shard000/JavaScript/0005570_memstore.js b/pool/shard000/JavaScript/0005570_memstore.js new file mode 100644 index 0000000000000000000000000000000000000000..d73cbdd9ad09ae45875e5bafc15f5de4913f0eac --- /dev/null +++ b/pool/shard000/JavaScript/0005570_memstore.js @@ -0,0 +1,118 @@ +var tough = require('./cookie'); +var permuteDomain = tough.permuteDomain; +var permutePath = tough.permutePath; +var util = require('util'); + +function MemoryCookieStore() { + this.idx = {}; +} +module.exports.MemoryCookieStore = MemoryCookieStore; +MemoryCookieStore.prototype.idx = null; + +// force a default depth: +MemoryCookieStore.prototype.inspect = function inspect() { + return "{ idx: " + util.inspect(this.idx, false, 2) + ' }'; +}; + +MemoryCookieStore.prototype.findCookie = function findCookie(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null, undefined); + } + if (!this.idx[domain][path]) { + return cb(null, undefined); + } + return cb(null, this.idx[domain][path][key] || null); +}; + +MemoryCookieStore.prototype.findCookies = function findCookies(domain, path, cb) { + var results = []; + if (!domain) { + return cb(null, []); + } + + var pathMatcher; + if (!path) { + // null or '/' means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (var curPath in domainIndex) { + var pathIndex = domainIndex[curPath]; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + + } else if (path === '/') { + pathMatcher = function matchSlash(domainIndex) { + var pathIndex = domainIndex['/']; + if (!pathIndex) { + return; + } + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + }; + + } else { + var paths = permutePath(path) || [path]; + pathMatcher = function matchRFC(domainIndex) { + paths.forEach(function (curPath) { + var pathIndex = domainIndex[curPath]; + if (!pathIndex) { + return; + } + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + }); + }; + } + + var domains = permuteDomain(domain) || [domain]; + var idx = this.idx; + domains.forEach(function (curDomain) { + var domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null, results); +}; + +MemoryCookieStore.prototype.putCookie = function putCookie(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); +}; + +MemoryCookieStore.prototype.updateCookie = function updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie, cb); +}; + +MemoryCookieStore.prototype.removeCookie = function removeCookie(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); +}; + +MemoryCookieStore.prototype.removeCookies = function removeCookies(domain, path, cb) { + if (!this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); +}; diff --git a/pool/shard000/JavaScript/0005572_widget.js b/pool/shard000/JavaScript/0005572_widget.js new file mode 100644 index 0000000000000000000000000000000000000000..c5d3b8629ac7ac876f8d803a01decfc8ffaee620 --- /dev/null +++ b/pool/shard000/JavaScript/0005572_widget.js @@ -0,0 +1,80 @@ +// Generated by CoffeeScript 1.9.1 +var StatusPageWidget; + +StatusPageWidget = (function() { + StatusPageWidget.prototype.pageId = null; + + StatusPageWidget.prototype.options = { + alwaysShow: false, + linkNewWindow: true, + updateInterval: 0 + }; + + StatusPageWidget.prototype.page = null; + + StatusPageWidget.prototype.data = null; + + StatusPageWidget.prototype.div = null; + + function StatusPageWidget(pageId, options) { + this.pageId = pageId; + this.processOptions(options); + this.page = new StatusPage.page({ + page: this.pageId + }); + this.updateStatus(); + if (this.options.updateInterval) { + setInterval((function(_this) { + return function() { + return _this.updateStatus(); + }; + })(this), this.options.updateInterval * 1000); + } + } + + StatusPageWidget.prototype.processOptions = function(options) { + var key, results, val; + if (typeof options !== 'object') { + return; + } + results = []; + for (key in options) { + val = options[key]; + results.push(this.options[key] = val); + } + return results; + }; + + StatusPageWidget.prototype.updateStatus = function() { + return this.page.status({ + success: (function(_this) { + return function(data) { + _this.data = data; + return _this.updateDiv(); + }; + })(this) + }); + }; + + StatusPageWidget.prototype.updateDiv = function() { + if (!this.data || !this.data.status) { + return; + } + if (this.data.status.indicator === 'none' && !this.options.alwaysShow) { + if (this.div) { + this.div.remove(); + this.div = null; + } + return; + } + if (!this.div) { + this.div = document.createElement('div'); + this.div.className = 'status-page-container'; + document.body.appendChild(this.div); + } + return this.div.innerHTML = '<a class="status-page-link status-page-indicator-' + this.data.status.indicator + '" href="https://' + this.pageId + '.statuspage.io/" target="' + (this.options.linkNewWindow === true ? '_blank' : '_top') + '">' + this.data.status.description + ' →</a>'; + }; + + return StatusPageWidget; + +})(); diff --git a/pool/shard000/JavaScript/0005573_test.js b/pool/shard000/JavaScript/0005573_test.js new file mode 100644 index 0000000000000000000000000000000000000000..1ff9701f41e502ff51710d4625320ce977e2f209 --- /dev/null +++ b/pool/shard000/JavaScript/0005573_test.js @@ -0,0 +1,38 @@ +'use strict'; + +require("chai").should() + +const main =require("./package").main + +const add = require(main) + +describe("add",()=>{ + it('should be a function with 1 param',()=> + { + add.should + .be.a('function') + .have.lengthOf(1) + }) + it('should add up to 3 numbers',()=>{ + add('1').should.equal(1) + add('2,5').should.equal(7) + add('3,6,1').should.equal(10) + }) + + it('should handle newlines between numbers',()=>{ + add('1\n2,3').should.equal(6) + add('1,\n').should.be.nan + }) + + it('should return nan for incorrect input',()=>{ + add('1\n2,3').should.equal(6) + add('1,\n').should.be.nan + }) + + it('should allow supplying custom delimiter',()=>{ + add('//;\n1;2;3').should.equal(6) + add('//*\n1*2*5').should.equal(7) + }) + + +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005575_limitablemap.js b/pool/shard000/JavaScript/0005575_limitablemap.js new file mode 100644 index 0000000000000000000000000000000000000000..670035b82156a608d1dadc229e60107e429a0c89 --- /dev/null +++ b/pool/shard000/JavaScript/0005575_limitablemap.js @@ -0,0 +1,26 @@ +var LimitableMap = function (limit) { + this.limit = limit || 10; + this.map = {}; + this.keys = []; +}; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +LimitableMap.prototype.set = function (key, value) { + var map = this.map; + var keys = this.keys; + if (!hasOwnProperty.call(map, key)) { + if (keys.length === this.limit) { + var firstKey = keys.shift(); + delete map[firstKey]; + } + keys.push(key); + } + map[key] = value; +}; + +LimitableMap.prototype.get = function (key) { + return this.map[key]; +}; + +module.exports = LimitableMap; diff --git a/pool/shard000/JavaScript/0005578_password.client.controller.js b/pool/shard000/JavaScript/0005578_password.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..eff6b4b8cbbe23059a4d132b2aef53b38b76c46a --- /dev/null +++ b/pool/shard000/JavaScript/0005578_password.client.controller.js @@ -0,0 +1,45 @@ +'use strict'; + +angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$http', '$location', 'Authentication', + function($scope, $stateParams, $http, $location, Authentication) { + $scope.authentication = Authentication; + + //If user is signed in then redirect back home + if ($scope.authentication.user) $location.path('/'); + + // Submit forgotten password account id + $scope.askForPasswordReset = function() { + $scope.success = $scope.error = null; + $scope.clicked = 'processing request'; + + $http.post('/auth/forgot', $scope.credentials).success(function(response) { + // Show user success message and clear form + $scope.credentials = null; + $scope.success = response.message; + + }).error(function(response) { + // Show user error message and clear form + $scope.credentials = null; + $scope.error = response.message; + }); + }; + + // Change user password + $scope.resetUserPassword = function() { + $scope.success = $scope.error = null; + + $http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) { + // If successful show success message and clear form + $scope.passwordDetails = null; + + // Attach user profile + Authentication.user = response; + + // And redirect to the index page + $location.path('/password/reset/success'); + }).error(function(response) { + $scope.error = response.message; + }); + }; + } +]); diff --git a/pool/shard000/JavaScript/0005579_helper.js b/pool/shard000/JavaScript/0005579_helper.js new file mode 100644 index 0000000000000000000000000000000000000000..55d9d7a30b23dbe8650658f0f59f55eb50fd1054 --- /dev/null +++ b/pool/shard000/JavaScript/0005579_helper.js @@ -0,0 +1,46 @@ +'use strict'; + +const Promise = require('bluebird').Promise; + +class Cleaner { + + constructor(client) { + this.client = client; + this.empty = false; + } + + before() { + const self = this; + return self.client.redis.keysAsync('*') + .then((keys) => { + if (keys.length > 0) { + throw Error('Redis database not empty.'); + } + self.empty = true; + }); + } + + after() { + if (this.empty) { + return this.client.redis.flushdbAsync(); + } else { + console.log('Not flushing db because it was not empty.'); + return null; + } + } +} + +const stubDisposer = (obj, prop, stub) => { + const original = obj[prop]; + return Promise.try(() => { + obj[prop] = stub; + return stub; + }).disposer(() => { + obj[prop] = original; + }); +}; + +module.exports = { + Cleaner, + stubDisposer, +}; diff --git a/pool/shard000/JavaScript/0005581_pickmeup.js b/pool/shard000/JavaScript/0005581_pickmeup.js new file mode 100644 index 0000000000000000000000000000000000000000..b6f6ce8c86111c8631b79600d83aa7eee6722b20 --- /dev/null +++ b/pool/shard000/JavaScript/0005581_pickmeup.js @@ -0,0 +1,71 @@ +pushover = require('node-pushover'); + +// Pushover instance +var push = new pushover({ + token: '[api token]', + user: '[user key]' + }), + // Message sent to Pushover + pushoverMessage = { + title: 'Pick Me Up', + message: 'Hi, can you pick me up.' + }, + // States, used to notify user + state = { + 'fail': { + 'sent': false, + 'stateClass': 'error', + 'stateMessage': 'Failed to Send' + }, + 'success': { + 'sent': true, + 'stateClass': 'success', + 'stateMessage': 'Message Sent' + } + }, + // Set default notification + notification = state.success, + // Unique token to match query string + token = 'gu0crib7jev1gat0peJ5'; + +// Check user token is valid +function isValidToken(userToken) { + + if (userToken === token) { + return true; + } + + return false; + +}; + +// Send message using Pushover +function sendToPushover(req) { + + push.send(pushoverMessage.title, pushoverMessage.message, function (err, res) { + if (err) { + notification = state.fail; + } + req.io.emit('pickMeUp', notification); + }); + +}; + +module.exports = { + + // If user's token is valid, send message + sendMessage: function (app, userToken) { + + var validToken = isValidToken(userToken); + + app.io.route('connect', function (req) { + if (validToken) { + sendToPushover(req); + } else { + req.io.emit('pickMeUp', state.fail); + } + }); + + } + +}; diff --git a/pool/shard000/JavaScript/0005586_user.js b/pool/shard000/JavaScript/0005586_user.js new file mode 100644 index 0000000000000000000000000000000000000000..0c0b3722abbbf78cfb9ef79ea5576168978b5acc --- /dev/null +++ b/pool/shard000/JavaScript/0005586_user.js @@ -0,0 +1,71 @@ +define([ + 'soundcloud', + 'backbone', + 'c/favourites', + 'constants' +], function( + SC, + Backbone, + FavouritesCollection, + c +){ + + return Backbone.Model.extend({ + + defaults: { + favourites: null + }, + + fetch: function() { + var def = new $.Deferred(), + _this = this, + favourites = []; + + SC.connect(function() { + SC.get('/me', function(user) { + _this.set(user); + window.localStorage.setItem('scUser', JSON.stringify(user)); + console.log('User ' + _this.get('username') + ' fetched'); + + getFaves = function(userId, limit) { + var i = 0, count = 0, + pageSize = 200, + url = '/users/' + userId + '/favorites.json', + defs = [], + goGet = function(pageSize, offset, dfd) { + SC.get(url, { limit: pageSize, offset: offset }, function(resp) { + favourites = favourites.concat(resp); + dfd.resolve(); + // returning from the fn fixed the $.when block + return; + }); + }; + + while( i <= limit ) { + var d = new $.Deferred(); + goGet(pageSize, i, d); + defs.push(d.promise()); + i += pageSize; + count++; + } + + // return the array of deferreds + return defs; + }; + + var promises = getFaves(_this.get('id'), _this.get('public_favorites_count')); + $.when.apply($, promises).done(function() { + window.localStorage.setItem('favourites', JSON.stringify(favourites)); + _this.set('favourites', new FavouritesCollection()); + _this.get('favourites').reset(favourites); + console.log(_this.get('favourites').length + ' favourites fetched'); + + def.resolve(); + }); + }); + }); + + return def.promise(); + } + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005590_CodecSelection.js b/pool/shard000/JavaScript/0005590_CodecSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..e222ab23323637b510b5c10ea13f4e2ec2f0e4ec --- /dev/null +++ b/pool/shard000/JavaScript/0005590_CodecSelection.js @@ -0,0 +1,157 @@ + +import { getLogger } from '@jitsi/logger'; + +import * as JitsiConferenceEvents from '../../JitsiConferenceEvents'; +import CodecMimeType from '../../service/RTC/CodecMimeType'; +import { MediaType } from '../../service/RTC/MediaType'; +import browser from '../browser'; + +const logger = getLogger(__filename); + +/** + * This class handles the codec selection mechanism for the conference based on the config.js settings. + * The preferred codec is selected based on the settings and the list of codecs supported by the browser. + * The preferred codec is published in presence which is then used by the other endpoints in the + * conference to pick a supported codec at join time and when the call transitions between p2p and jvb + * connections. + */ +export class CodecSelection { + /** + * Creates a new instance for a given conference. + * + * @param {JitsiConference} conference the conference instance + * @param {*} options + * @param {string} options.disabledCodec the codec that needs to be disabled. + * @param {boolean} options.enforcePreferredCodec whether codec preference has to be + * enforced even when an endpoints that doesn't support the preferred codec joins the call. + * Falling back to the standard codec will be skipped when this option is true, endpoints + * that do not support the preferred codec may not be able to encode/decode video when this happens. + * @param {string} options.jvbCodec the codec that is preferred on jvb connection. + * @param {string} options.p2pCodec the codec that is preferred on p2p connection. + */ + constructor(conference, options) { + this.conference = conference; + this.options = options; + + // VP8 cannot be disabled and it will be the default codec when no preference is set. + this.disabledCodec = options.disabledCodec === CodecMimeType.VP8 + ? undefined + : this._getCodecMimeType(options.disabledCodec); + + // Check if the codec values passed are valid. + const jvbCodec = this._getCodecMimeType(options.jvbCodec); + const p2pCodec = this._getCodecMimeType(options.p2pCodec); + + this.jvbPreferredCodec = jvbCodec && this._isCodecSupported(jvbCodec) ? jvbCodec : CodecMimeType.VP8; + this.p2pPreferredCodec = p2pCodec && this._isCodecSupported(p2pCodec) ? p2pCodec : CodecMimeType.VP8; + logger.debug(`Codec preferences for the conference are JVB: ${this.jvbPreferredCodec}, + P2P: ${this.p2pPreferredCodec}`); + + if (this.jvbPreferredCodec === CodecMimeType.VP9 && !browser.supportsVP9()) { + this.jvbPreferredCodec = CodecMimeType.VP8; + } + + this.conference.on( + JitsiConferenceEvents.USER_JOINED, + () => this._selectPreferredCodec()); + this.conference.on( + JitsiConferenceEvents.USER_LEFT, + () => this._selectPreferredCodec()); + this.conference.on( + JitsiConferenceEvents._MEDIA_SESSION_STARTED, + session => this._onMediaSessionStarted(session)); + } + + /** + * Checks if a given string is a valid video codec mime type. + * + * @param {string} codec the codec string that needs to be validated. + * @returns {CodecMimeType|null} mime type if valid, null otherwise. + * @private + */ + _getCodecMimeType(codec) { + if (typeof codec === 'string') { + return Object.values(CodecMimeType).find(value => value === codec.toLowerCase()); + } + + return null; + } + + /** + * Checks if the given codec is supported by the browser. + * + * @param {CodecMimeType} preferredCodec codec to be checked. + * @returns {boolean} true if the given codec is supported, false otherwise. + * @private + */ + _isCodecSupported(preferredCodec) { + // Skip the check on FF and RN because they do not support the getCapabilities API. + // It is safe to assume both of them support all the codecs supported by Chrome. + if (browser.isFirefox() || browser.isReactNative()) { + return true; + } + + return window.RTCRtpReceiver + && window.RTCRtpReceiver.getCapabilities + && window.RTCRtpReceiver.getCapabilities('video').codecs + .some(codec => codec.mimeType.toLowerCase() === `video/${preferredCodec}`); + } + + /** + * Handles the {@link JitsiConferenceEvents._MEDIA_SESSION_STARTED} event. Codecs need to be + * configured on the media session that is newly created. + * + * @param {JingleSessionPC} mediaSession media session that started. + * @returns {void} + * @private + */ + _onMediaSessionStarted(mediaSession) { + const preferredCodec = mediaSession.isP2P ? this.p2pPreferredCodec : this.jvbPreferredCodec; + const disabledCodec = this.disabledCodec && this._isCodecSupported(this.disabledCodec) + ? this.disabledCodec + : null; + + this._selectPreferredCodec(mediaSession, preferredCodec, disabledCodec); + } + + /** + * Sets the codec on the media session based on the preferred codec setting and the supported codecs + * published by the remote participants in their presence. + * + * @param {JingleSessionPC} mediaSession session for which the codec selection has to be made. + * @param {CodecMimeType} preferredCodec preferred codec. + * @param {CodecMimeType} disabledCodec codec that needs to be disabled. + */ + _selectPreferredCodec(mediaSession = null, preferredCodec = null, disabledCodec = null) { + const session = mediaSession ? mediaSession : this.conference.jvbJingleSession; + const currentCodec = preferredCodec ? preferredCodec : this.jvbPreferredCodec; + let selectedCodec = currentCodec; + + if (session && !session.isP2P && !this.options.enforcePreferredCodec) { + const remoteParticipants = this.conference.getParticipants().map(participant => participant.getId()); + + for (const remote of remoteParticipants) { + const peerMediaInfo = session._signalingLayer.getPeerMediaInfo(remote, MediaType.VIDEO); + const peerCodec = peerMediaInfo?.codecType; + + if (peerCodec + && peerCodec !== currentCodec + && (peerCodec !== CodecMimeType.VP9 || browser.supportsVP9())) { + selectedCodec = peerCodec; + } + } + } + session && session.setVideoCodecs(selectedCodec, disabledCodec); + } + + /** + * Returns the preferred codec for the conference. The preferred codec for the JVB media session + * is the one that gets published in presence and a comparision is made whenever a participant joins + * or leaves the call. + * + * @returns {CodecMimeType} preferred codec. + */ + getPreferredCodec() { + return this.jvbPreferredCodec; + } +} diff --git a/pool/shard000/JavaScript/0005591_dhtmlxaccordion_deprecated.js b/pool/shard000/JavaScript/0005591_dhtmlxaccordion_deprecated.js new file mode 100644 index 0000000000000000000000000000000000000000..ec96cc93134dcf41984382df63d8fa108ffb91a3 --- /dev/null +++ b/pool/shard000/JavaScript/0005591_dhtmlxaccordion_deprecated.js @@ -0,0 +1,62 @@ +/* +Product Name: dhtmlxSuite +Version: 5.0 +Edition: Standard +License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact sales@dhtmlx.com +Copyright UAB Dinamenta http://www.dhtmlx.com +*/ + +/* deprecated */ +dhtmlXAccordion.prototype.setEffect = function(mode) { + // expand/collapse, dnd + // enabled for browsers which support html5 by default +}; +dhtmlXAccordion.prototype.setIcon = function(id, icon) { + this.cells(id).setIcon(icon); +}; +dhtmlXAccordion.prototype.clearIcon = function(id) { + this.cells(id).clearIcon(); +}; +dhtmlXAccordion.prototype.setActive = function(id) { + this.cells(id).open(); +}; +dhtmlXAccordion.prototype.isActive = function(id) { + return this.cells(id).isOpened(); +}; +dhtmlXAccordion.prototype.openItem = function(id) { + this.cells(id).open(); +}; +dhtmlXAccordion.prototype.closeItem = function(id) { + this.cells(id).close(); +}; +dhtmlXAccordion.prototype.moveOnTop = function(id) { + this.cells(id).moveOnTop(); +}; +dhtmlXAccordion.prototype.setItemHeight = function(h) { + this.cells(id).setHeight(h); +}; +dhtmlXAccordion.prototype.setText = function(id, text) { + this.cells(id).setText(text); +}; +dhtmlXAccordion.prototype.getText = function() { + return this.cells(id).getText(); +}; +dhtmlXAccordion.prototype.showItem = function(id) { + this.cells(id).show(); +}; +dhtmlXAccordion.prototype.hideItem = function(id) { + this.cells(id).hide(); +}; +dhtmlXAccordion.prototype.isItemHidden = function(id) { + return !this.cells(id).isVisible(); +}; +dhtmlXAccordion.prototype.loadJSON = function(data, callback) { + this.loadStruct(data, callback); +}; +dhtmlXAccordion.prototype.loadXML = function(data, callback) { + this.loadStruct(data, callback); +}; +dhtmlXAccordion.prototype.setSkinParameters = function(ofsBetween, ofsCont) { + if (ofsBetween != null) this.setOffset(ofsBetween); +}; + diff --git a/pool/shard000/JavaScript/0005592_menu.js b/pool/shard000/JavaScript/0005592_menu.js new file mode 100644 index 0000000000000000000000000000000000000000..4d10c1ddfb6ef4fcf2a1aefe280013c70a9e1145 --- /dev/null +++ b/pool/shard000/JavaScript/0005592_menu.js @@ -0,0 +1,203 @@ +var utils = require('utils'), + stringExt = require('utils/string-exts'), + _store = {}, + bkBukkit = org.bukkit.Bukkit, + bkSign = org.bukkit.block.Sign; + +/* + Define the signs module - signs are persistent + (that is - a menu sign will still be a menu after the + server has shut down and started up) plugins now have persistent state - Yay! +*/ +var signs = plugin("signs", { + /* + construct an interactive menu which can then be attached to a Sign. + */ + menu: function( + /* String */ label, + /* Array */ options, + /* Function */ onInteract, + /* Number */ defaultSelection ){}, + store: _store + }, + true); + +module.exports = signs; + +/* + redraw a menu sign +*/ +var _redrawMenuSign = function( p_sign, p_selectedIndex, p_displayOptions ) { + var optLen = p_displayOptions.length, + i, + text; + // the offset is where the menu window begins + var offset = Math.max( 0, Math.min( optLen-3, Math.floor( p_selectedIndex/3 ) * 3) ); + for ( i = 0;i < 3; i++ ) { + text = ""; + if ( offset+i < optLen ) { + text = p_displayOptions[offset+i]; + } + if ( offset+i == p_selectedIndex ) { + text = ('' + text).replace(/^ /,">"); + } + p_sign.setLine( i+1, text ); + } + p_sign.update( true ); +}; + +var _updaters = {}; +/* + construct an interactive menu to be subsequently attached to + one or more Signs. +*/ +signs.menu = function( /* String */ label, /* Array */ options, /* Function */ callback, /* Number */ selectedIndex ) { + + if ( typeof selectedIndex == "undefined" ) { + selectedIndex = 0; + } + // + // variables common to all instances of this menu can go here + // + var labelPadding = "---------------"; + var optionPadding = " "; + var i; + var paddedLabel = ( labelPadding + label + labelPadding) + .substr( ( ( label.length+30 ) / 2 ) - 7, 15 ); + var optLen = options.length; + var displayOptions = []; + for ( i = 0; i < options.length; i++ ) { + displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); + } + /* + this function is returned by signs.menu and when it is invoked it will + attach menu behaviour to an existing sign in the world. + signs.menu is for use by Plugin Authors. + The function returned by signs.menu is for use by admins/ops. + */ + var convertToMenuSign = function(/* Sign */ sign, save) { + var mouseLoc; + if (typeof save == "undefined") { + save = true; + } + /* + @deprecated start + all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter. + */ + if ( typeof sign == "undefined" ) { + mouseLoc = utils.getMousePos(); + if ( mouseLoc ) { + sign = mouseLoc.block.state; + if ( !( sign && sign.setLine ) ) { + throw new Error("You must first provide a sign!"); + } + } else { + throw new Error("You must first provide a sign!"); + } + } + /* + @deprecated end + */ + // + // per-sign variables go here + // + var cSelectedIndex = selectedIndex; + sign.setLine( 0, paddedLabel.bold() ); + var _updateSign = function( p_player, p_sign ) { + cSelectedIndex = ( cSelectedIndex + 1 ) % optLen; + _redrawMenuSign( p_sign, cSelectedIndex, displayOptions ); + var signSelectionEvent = { + player: p_player, + sign: p_sign, + text: options[ cSelectedIndex ], + number: cSelectedIndex + }; + callback( signSelectionEvent ); + }; + + /* + get a unique ID for this particular sign instance + */ + var signLoc = sign.block.location; + var menuSignSaveData = utils.locationToJSON( signLoc ); + var menuSignUID = JSON.stringify( menuSignSaveData ); + /* + keep a reference to the update function for use by the event handler + */ + _updaters[ menuSignUID ] = _updateSign; + + // initialize the sign + _redrawMenuSign( sign, cSelectedIndex, displayOptions ); + + /* + whenever a sign is placed somewhere in the world + (which is what this function does) + save its location for loading and initialization + when the server starts up again. + */ + if ( save ) { + if ( typeof _store.menus == "undefined") { + _store.menus = {}; + } + var signLocations = _store.menus[label]; + if ( typeof signLocations == "undefined" ) { + signLocations = _store.menus[label] = []; + } + signLocations.push( menuSignSaveData ); + } + return sign; + }; + + /* + a new sign definition - need to store (in-memory only) + its behaviour and bring back to life other signs of the + same type in the world. Look for other static signs in the + world with this same label and make dynamic again. + */ + + if ( _store.menus && _store.menus[label] ) { + var signsOfSameLabel = _store.menus[ label ]; + var defragged = []; + var len = signsOfSameLabel.length; + for ( i = 0; i < len; i++ ) { + var loc = signsOfSameLabel[i]; + var world = bkBukkit.getWorld(loc.world); + if ( !world ) { + continue; + } + var block = world.getBlockAt( loc.x, loc.y, loc.z ); + if ( block.state instanceof bkSign ) { + convertToMenuSign( block.state, false ); + defragged.push( loc ); + } + } + /* + remove data for signs which no longer exist. + */ + if ( defragged.length != len ) { + _store.menus[label] = defragged; + } + } + return convertToMenuSign; +}; + +// +// update it every time player interacts with it. +// +events.on( 'player.PlayerInteractEvent', function( listener, event ) { + /* + look up our list of menu signs. If there's a matching location and there's + a sign, then update it. + */ + + if ( ! event.clickedBlock.state instanceof bkSign ) { + return; + } + var evtLocStr = utils.locationToString(event.clickedBlock.location); + var signUpdater = _updaters[evtLocStr]; + if ( signUpdater ) { + signUpdater( event.player, event.clickedBlock.state ); + } +}); + + diff --git a/pool/shard000/JavaScript/0005593_canary.js b/pool/shard000/JavaScript/0005593_canary.js new file mode 100644 index 0000000000000000000000000000000000000000..55e73644f6b748e6374b5537a78cbc1c9d477cec --- /dev/null +++ b/pool/shard000/JavaScript/0005593_canary.js @@ -0,0 +1,122 @@ + +import * as fs from 'fs'; +import exec from 'child_process'; +import {XMLHttpRequest as xmhtrq} from 'xmlhttprequest'; + + + + + + + +// ======================================================================================== +// SOME SIMPLE CONVENIENCE FUNCTIONS +var uid = function(url) { + return url.replace(/\/+/g, '_').replace(/:/g, ''); +}; + +var uuid = function() { + return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); + return v.toString(16); + }); +}; + +if (typeof String.prototype.endsWith !== 'function') { + String.prototype.endsWith = function(suffix) { + return this.indexOf(suffix, this.length - suffix.length) !== -1; + }; +} +if (typeof String.prototype.startsWith !== 'function') { + String.prototype.startsWith = function(prefix) { + return this.indexOf(prefix, 0, this.length - prefix.length) !== -1; + }; +} + +var dated = function( delim, less ) { + if ( delim === undefined ) delim = ''; + if ( less === undefined ) less = 5; + var date = new Date(); + if ( less ) date.setDate(date.getDate() - less); + var dd = date.getDate(); + var mm = date.getMonth()+1; + var yyyy = date.getFullYear(); + if ( dd<10 ) dd = '0'+dd; + if ( mm<10 ) mm = '0'+mm; + return yyyy + delim + mm + delim + dd; +}; +var todayset = function() { + return 'daily' + dated(); +}; + +var eexec = function(cmd, callback) { + console.log('async exec ' + cmd); + var child = exec(cmd, function(err, out, code) { + console.log(err); + console.log(out); + console.log(code); + callback(null, out); + }); +}; +var aexec = Async.wrap(eexec); + + + + +// ======================================================================================== +// THE API ENDPOINTS, THAT CALL THE OTHER FUNCTIONS +API = new Restivus({ + prettyJson: true +}); +API.addRoute('', { + get: function() { + return { status: 'success', data: 'ContentMine API. Link to docs once they exist' }; + } +}); +API.addRoute('etl/:dailyset', { + // dailyset form should be like 2016-06-01 + post: function() { + etl(this.urlParams.dailyset); + return ''; + } +}); +// facts - actually use nginx to configure a direct ES search route safely +// catalogue - again use ES to configure a safe direct ES search onto catalogue METADATA (so store fulltext in separate index) +API.addRoute('retrieve', { + get: function() { + return {}; // TODO given a URL as query param, retrieve the content of the URL into the system somehow... could also accept data on POST + // if we do this, then the items content should be saved into a folder in the store named with some uuid, then can be extracted into an + // index with that uuid too, then facts could be retrieved from it + } +}); +API.addRoute('extract', { + get: function() { + return {}; // TODO extract the content of a given source - accept a dicts param to list which dicts to run, and a query param to identify the catalogue items to run it against + } +}); +API.addRoute('dictionary', { + get: function() { + return {}; // TODO return a list of the filenames in the dictionary directory + } +}); +API.addRoute('dictionary/:dict', { + get: function() { + return {}; // TODO read named dictionary from disk and return it as json + }, + post: function() { + return {}; // TODO if given a URL param or POST content, read it into the dictionary directory + }, + delete: function() { + return {}; // TODO delete the named dict (although if it is in our repo the next git pull would pull it back in) + } +}); +API.addRoute('store', { + get: function() { + return {}; // TODO provide access to normalised OA items stored on disk + // could also serve fulltexts of non-OA items if queried from inside cambridge. and if this would be useful for any reason + // this could probably also just be served by nginx configuration + } +}); + + + diff --git a/pool/shard000/JavaScript/0005596_gulpfile.js b/pool/shard000/JavaScript/0005596_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..fbe495e2199f1697a0862a2aad49ba84d4f6adbf --- /dev/null +++ b/pool/shard000/JavaScript/0005596_gulpfile.js @@ -0,0 +1,31 @@ +var sys = require('sys'); +var exec = require('child_process').exec; + +var gulp = require('gulp'); +var traceur = require('gulp-traceur'); +var sass = require('gulp-sass'); + +gulp.task('js', function() { + //Build Traceur + gulp.src('./src/**/*.js') + .pipe(traceur()) + .pipe(gulp.dest('./c/')); + + return gulp.src('./src/**/*.json') + .pipe(gulp.dest('./c/')); +}); + +gulp.task('css', function() { + //Build Sass + return gulp.src('./styles/*.scss') + .pipe(sass({ includePaths: ['styles/'] })) + .pipe(gulp.dest('./c/styles/')); +}); + +gulp.task('post-build', ['js', 'css'], function() { + exec("nw.exe ."); +}); + +gulp.task('default', function() { + gulp.start('js', 'css', 'post-build'); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005600_panorama_js_settings_dashboards.js b/pool/shard000/JavaScript/0005600_panorama_js_settings_dashboards.js new file mode 100644 index 0000000000000000000000000000000000000000..cf8a2b3b3205d03c502ff06d4887d6dabcb3de6c --- /dev/null +++ b/pool/shard000/JavaScript/0005600_panorama_js_settings_dashboards.js @@ -0,0 +1,247 @@ +/* show dashboard management window */ +Ext.define('TP.DashboardManagementWindow', { + extend: 'Ext.window.Window', + autoShow: true, + modal: true, + width: 800, + resizable: false, + title: 'Dashboard Management', + closeAction: 'destroy', + cls: 'dashboardmanagementwindow', + initComponent: function() { + var win = this; + win.xdata = {}; + win.callParent(); + win.startLoading = false; + + var listeners = { + activate: function(This, eOpts) { + var panel = This.up('panel').up('panel'); + // update grid content + if(This.loader && win.startLoading) { + This.loader.grid = This; + This.loader.xdata = panel.xdata; + This.loader.load(); + } + TP.dashboardsSettingGrid = This; + // reset filter + if(TP.dashboardsSettingWindow) { + var filterEl = Ext.getCmp('dashboardManagementFilterEl'); + var resetEl = Ext.getCmp('dashboardManagementResetBtn'); + if( (TP.dashboardsSettingGrid.tabConfig && TP.dashboardsSettingGrid.tabConfig.title.match(/Import/)) + || (TP.dashboardsSettingGrid.title && TP.dashboardsSettingGrid.title.match(/Import/)) + ) { + filterEl.hide(); + resetEl.hide(); + } else { + filterEl.show(); + resetEl.show(); + filterEl.setValue(''); + } + } + }, + beforeselect: function(This, record, index, eOpts) { + /* prevent selections */ + return false; + }, + edit: function(editor, el) { + if(el.value != el.originalValue) { + TP.toggleDashboardOption(el.record.data.id, el.field, el.value); + el.record.commit(); + } + }, + destroy: function(This, eOpts) { + delete TP.dashboardsSettingWindow; + return true; + }, + close: function(This, eOpts) { + This.destroy(); + return true; + }, + afterrender: function(This) { + win.startLoading = true; + if(This.loader) { + /* prevent tab switching directly after open which leads to js errors targetParent undef */ + win.mask("Loading"); + } + }, + reconfigure: function(This) { + win.unmask(); + } + } + /* My Dasboards */ + win.grid_my = Ext.create('Ext.grid.Panel', { + tabConfig: { + title: 'My', + tooltip: 'My Dashboards' + }, + columns: [], + listeners: listeners, + loader: Ext.create('TP.GridLoader', { + url: 'panorama.cgi?task=dashboard_list&list=my', + loadMask: true, + target: win + }), + plugins: readonly ? [] : [Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 })] + }); + win.items.get(0).add(win.grid_my); + + /* Public Dasboards */ + win.grid_public = Ext.create('Ext.grid.Panel', { + tabConfig: { + title: 'Public', + tooltip: 'Public Dashboards' + }, + columns: [], + listeners: listeners, + loader: Ext.create('TP.GridLoader', { + url: 'panorama.cgi?task=dashboard_list&list=public', + loadMask: true, + target: win + }), + plugins: readonly ? [] : [Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 })] + }); + win.items.get(0).add(win.grid_public); + + /* All Dasboards, Admins only */ + if(thruk_is_admin) { + win.grid_all = Ext.create('Ext.grid.Panel', { + tabConfig: { + title: 'All', + tooltip: 'All Dashboards' + }, + columns: [], + listeners: listeners, + loader: Ext.create('TP.GridLoader', { + url: 'panorama.cgi?task=dashboard_list&list=all', + loadMask: true, + target: win + }), + plugins: readonly ? [] : [Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 })], + bbar:[{ + xtype: 'button', + text: 'Cleanup Dashboards', + iconCls: 'clear-btn', + handler: function(This) { + This.setIconCls("wait-btn"); + This.mask("loading"); + Ext.Ajax.request({ + url: 'panorama.cgi?task=dashboards_clean', + method: 'POST', + callback: function(options, success, response) { + This.unmask(); + This.setIconCls("clear-btn"); + if(!success) { + if(response.status == 0) { + TP.Msg.msg("fail_message~~cleaning dashboards failed"); + } else { + TP.Msg.msg("fail_message~~cleaning dashboards failed: "+response.status+' - '+response.statusText); + } + } else { + var data = TP.getResponse(undefined, response); + if(data.num > 0) { + TP.Msg.msg("success_message~~cleaned "+data.num+" dashboards successful"); + This.up('panel').loader.load(); + } else { + TP.Msg.msg("success_message~~all dashboards are cleaned already"); + } + } + } + }); + } + }] + }); + win.items.get(0).add(win.grid_all); + } + + /* import / export */ + var tabpan = Ext.getCmp('tabpan'); + var tab = tabpan.getActiveTab(); + win.exportTab = TP.getExportTab({listeners: listeners, tab: tab}); + win.items.get(0).add(win.exportTab); + + win.items.get(0).setActiveTab(0); + }, + items: [{ + xtype: 'tabpanel', + height: 380, + items: [], + tabBar: { + items: [{ + xtype: 'tbfill' + }, { + xtype: 'textfield', + emptyText: 'filter dashboards', + width: 120, + closable: false, + id: 'dashboardManagementFilterEl', + fieldStyle: 'border-bottom: 1px solid #EAEAEA;', + fieldBodyCls: 'x-form-clear-trigger', + listeners: { + change: function(This) { + var clearBtn = Ext.getCmp('dashboardManagementResetBtn'); + var activeTab = This.up('window').items.getAt(0).getActiveTab(); + var store = activeTab.store; + if(This.value != undefined && This.value != '') { + clearBtn.enable(); + var val = This.value.toLowerCase(); + store.filterBy(function(rec, id) { + var found = false; + for(var key in rec.data) { + if(String(rec.data[key]).toLowerCase().match(val)) { found=true; } + } + return found; + }); + } else { + clearBtn.disable(); + store.clearFilter(); + } + } + } + }, { + xtype: 'button', + text: ' ', + width: 19, + border: 1, + style: 'padding: 0 0 5px;', + cls: 'x-form-clear-trigger', + id: 'dashboardManagementResetBtn', + disabled: true, + handler: function(This) { + var searchField = Ext.getCmp('dashboardManagementFilterEl'); + searchField.reset(); + }, + listeners: { + afterrender: function(This) { + window.setTimeout(function() { + var style = This.getEl().dom.style; + var left = Number(String(style.left).replace(/px$/, '')); + style.top = '-1px'; + style.borderBottom = '1px solid #EAEAEA'; + style.borderTop = '1px solid #B5B8C8'; + style.borderRight = '1px solid #B5B8C8'; + style.borderLeft = '0'; + style.left = left-2+'px'; + } , 100); + } + } + }] + } + }] +}); + +TP.dashboardsWindow = function() { + var win = Ext.create('TP.DashboardManagementWindow', {}); + TP.dashboardsSettingWindow = win; + TP.modalWindows.push(win); + + // somehow new tabbar elements occur when opening window again, so we just remove them + var toDelete = TP.dashboardsSettingWindow.items.getAt(0).tabBar.items.getCount() - 7; + if(toDelete > 0) { + for(var x = toDelete-1; x >= 0; x--) { + TP.dashboardsSettingWindow.items.getAt(0).tabBar.items.getAt(7+x).destroy(); + TP.dashboardsSettingWindow.items.getAt(0).tabBar.items.removeAt(7+x); + } + TP.dashboardsSettingWindow.items.getAt(0).tabBar.doLayout(); + } +} diff --git a/pool/shard000/JavaScript/0005602_settings-screen.js b/pool/shard000/JavaScript/0005602_settings-screen.js new file mode 100644 index 0000000000000000000000000000000000000000..c52c29aaabf765d807f6c82d08a1559d6f1fee04 --- /dev/null +++ b/pool/shard000/JavaScript/0005602_settings-screen.js @@ -0,0 +1,23 @@ +import startsWith from 'underscore.string/startsWith'; +import template from './settings-screen.html'; + +export default function init(ngModule) { + ngModule.directive('settingsScreen', $location => ({ + restrict: 'E', + transclude: true, + template, + controller($scope, currentUser) { + $scope.usersPage = startsWith($location.path(), '/users'); + $scope.groupsPage = startsWith($location.path(), '/groups'); + $scope.dsPage = startsWith($location.path(), '/data_sources'); + $scope.destinationsPage = startsWith($location.path(), '/destinations'); + $scope.snippetsPage = startsWith($location.path(), '/query_snippets'); + + $scope.showGroupsLink = currentUser.hasPermission('list_users'); + $scope.showUsersLink = currentUser.hasPermission('list_users'); + $scope.showDsLink = currentUser.hasPermission('admin'); + $scope.showDestinationsLink = currentUser.hasPermission('admin'); + $scope.showQuerySnippetsLink = currentUser.hasPermission('create_query'); + }, + })); +} diff --git a/pool/shard000/JavaScript/0005608_LinkedInSessionManager.android.js b/pool/shard000/JavaScript/0005608_LinkedInSessionManager.android.js new file mode 100644 index 0000000000000000000000000000000000000000..03f577db13e8c1c0e45c90ba460e462f1f74f41e --- /dev/null +++ b/pool/shard000/JavaScript/0005608_LinkedInSessionManager.android.js @@ -0,0 +1,39 @@ +const ReactNative = require('react-native'); + +const { + NativeModules, +} = ReactNative; + + +const { + RNLinkedInSessionManager, +} = NativeModules; + + +const LinkedInSDK = { + initSession(config) { + return RNLinkedInSessionManager.initSession(config); + }, + signIn(config) { + return LinkedInSDK.initSession(config) + .then(LinkedInSDK.normalizeToken); + }, + normalizeToken({expiresOn, ...token}) { + return { + expiresOn: new Date(expiresOn), + ...token, + }; + }, + getRequest(url) { + return RNLinkedInSessionManager.getRequest(url) + .then(({ + status, + data, + }) => ({ + status, + data: JSON.parse(data), + })); + }, +}; + +module.exports = LinkedInSDK; diff --git a/pool/shard000/JavaScript/0005609_util.js b/pool/shard000/JavaScript/0005609_util.js new file mode 100644 index 0000000000000000000000000000000000000000..b441b500a0991dfbfd8649d0a0c49052fe3d16b2 --- /dev/null +++ b/pool/shard000/JavaScript/0005609_util.js @@ -0,0 +1,255 @@ +// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- + +const Gio = imports.gi.Gio; +const Lang = imports.lang; +const Signals = imports.signals; + +const Batch = imports.gdm.batch; +const Fprint = imports.gdm.fingerprint; +const Main = imports.ui.main; +const Tweener = imports.ui.tweener; + +const PASSWORD_SERVICE_NAME = 'gdm-password'; +const FINGERPRINT_SERVICE_NAME = 'gdm-fingerprint'; +const FADE_ANIMATION_TIME = 0.16; + +const LOGIN_SCREEN_SCHEMA = 'org.gnome.login-screen'; +const FINGERPRINT_AUTHENTICATION_KEY = 'enable-fingerprint-authentication'; +const BANNER_MESSAGE_KEY = 'banner-message-enable'; +const BANNER_MESSAGE_TEXT_KEY = 'banner-message-text'; + +const LOGO_KEY = 'logo'; + +function fadeInActor(actor) { + if (actor.opacity == 255 && actor.visible) + return null; + + let hold = new Batch.Hold(); + actor.show(); + let [minHeight, naturalHeight] = actor.get_preferred_height(-1); + + actor.opacity = 0; + actor.set_height(0); + Tweener.addTween(actor, + { opacity: 255, + height: naturalHeight, + time: FADE_ANIMATION_TIME, + transition: 'easeOutQuad', + onComplete: function() { + this.set_height(-1); + hold.release(); + }, + }); + + return hold; +} + +function fadeOutActor(actor) { + if (!actor.visible || actor.opacity == 0) { + actor.opacity = 0; + actor.hide(); + return null; + } + + let hold = new Batch.Hold(); + Tweener.addTween(actor, + { opacity: 0, + height: 0, + time: FADE_ANIMATION_TIME, + transition: 'easeOutQuad', + onComplete: function() { + this.hide(); + this.set_height(-1); + hold.release(); + }, + }); + return hold; +} + +const ShellUserVerifier = new Lang.Class({ + Name: 'ShellUserVerifier', + + _init: function(client) { + this._client = client; + + this._settings = new Gio.Settings({ schema: LOGIN_SCREEN_SCHEMA }); + + this._cancellable = new Gio.Cancellable(); + + this._fprintManager = new Fprint.FprintManager(); + this._checkForFingerprintReader(); + }, + + begin: function(userName, hold) { + this._hold = hold; + this._userName = userName; + + if (userName) { + // If possible, reauthenticate an already running session, + // so any session specific credentials get updated appropriately + this._client.open_reauthentication_channel(userName, this._cancellable, + Lang.bind(this, this._reauthenticationChannelOpened)); + } else { + this._client.get_user_verifier(this._cancellable, Lang.bind(this, this._userVerifierGot)); + } + }, + + cancel: function() { + this._cancellable.cancel(); + + if (this._userVerifier) + this._userVerifier.call_cancel_sync(null); + }, + + clear: function() { + this._cancellable.cancel(); + + if (this._userVerifier) { + this._userVerifier.run_dispose(); + this._userVerifier = null; + } + }, + + answerQuery: function(serviceName, answer) { + this._userVerifier.call_answer_query(serviceName, answer, this._cancellable, null); + }, + + _checkForFingerprintReader: function() { + this._haveFingerprintReader = false; + + if (!this._settings.get_boolean(FINGERPRINT_AUTHENTICATION_KEY)) + return; + + this._fprintManager.GetDefaultDeviceRemote(Gio.DBusCallFlags.NONE, this._cancellable, Lang.bind(this, + function(device, error) { + if (!error && device) + this._haveFingerprintReader = true; + })); + }, + + _reauthenticationChannelOpened: function(client, result) { + try { + this._userVerifier = client.open_reauthentication_channel_finish(result); + this._connectSignals(); + this._beginVerification(); + + this._hold.release(); + } catch (e) { + // If there's no session running, or it otherwise fails, then fall back + // to performing verification from this login session + client.get_user_verifier(this._cancellable, Lang.bind(this, this._userVerifierGot)); + } + }, + + _userVerifierGot: function(client, result) { + this._userVerifier = client.get_user_verifier_finish(result); + this._connectSignals(); + this._beginVerification(); + + this._hold.release(); + }, + + _connectSignals: function() { + this._userVerifier.connect('info', Lang.bind(this, this._onInfo)); + this._userVerifier.connect('problem', Lang.bind(this, this._onProblem)); + this._userVerifier.connect('info-query', Lang.bind(this, this._onInfoQuery)); + this._userVerifier.connect('secret-info-query', Lang.bind(this, this._onSecretInfoQuery)); + this._userVerifier.connect('conversation-stopped', Lang.bind(this, this._onConversationStopped)); + this._userVerifier.connect('reset', Lang.bind(this, this._onReset)); + this._userVerifier.connect('verification-complete', Lang.bind(this, this._onVerificationComplete)); + }, + + _beginVerification: function() { + this._hold.acquire(); + + if (this._userName) { + this._userVerifier.call_begin_verification_for_user(PASSWORD_SERVICE_NAME, + this._userName, + this._cancellable, + Lang.bind(this, function(obj, result) { + obj.call_begin_verification_for_user_finish(result); + this._hold.release(); + })); + + if (this._haveFingerprintReader) { + this._hold.acquire(); + + this._userVerifier.call_begin_verification_for_user(FINGERPRINT_SERVICE_NAME, + this._userName, + this._cancellable, + Lang.bind(this, function(obj, result) { + obj.call_begin_verification_for_user_finish(result); + this._hold.release(); + })); + } + } else { + this._userVerifier.call_begin_verification(PASSWORD_SERVICE_NAME, + this._cancellable, + Lang.bind(this, function(obj, result) { + obj.call_begin_verification_finish(result); + this._hold.release(); + })); + } + }, + + _onInfo: function(client, serviceName, info) { + // We don't display fingerprint messages, because they + // have words like UPEK in them. Instead we use the messages + // as a cue to display our own message. + if (serviceName == FINGERPRINT_SERVICE_NAME && + this._haveFingerprintReader) { + this.emit('show-fingerprint-prompt'); + } else if (serviceName == PASSWORD_SERVICE_NAME) { + Main.notifyError(info); + } + }, + + _onProblem: function(client, serviceName, problem) { + // we don't want to show auth failed messages to + // users who haven't enrolled their fingerprint. + if (serviceName != PASSWORD_SERVICE_NAME) + return; + Main.notifyError(problem); + }, + + _onInfoQuery: function(client, serviceName, question) { + // We only expect questions to come from the main auth service + if (serviceName != PASSWORD_SERVICE_NAME) + return; + + this.emit('ask-question', serviceName, question, ''); + }, + + _onSecretInfoQuery: function(client, serviceName, secretQuestion) { + // We only expect secret requests to come from the main auth service + if (serviceName != PASSWORD_SERVICE_NAME) + return; + + this.emit('ask-question', serviceName, secretQuestion, '\u25cf'); + }, + + _onReset: function() { + this._userVerifier.run_dispose(); + this._userVerifier = null; + + this._checkForFingerprintReader(); + + this.emit('reset'); + }, + + _onVerificationComplete: function() { + this.emit('verification-complete'); + }, + + _onConversationStopped: function(client, serviceName) { + // if the password service fails, then cancel everything. + // But if, e.g., fingerprint fails, still give + // password authentication a chance to succeed + if (serviceName == PASSWORD_SERVICE_NAME) { + this.emit('verification-failed'); + } else if (serviceName == FINGERPRINT_SERVICE_NAME) { + this.emit('hide-fingerprint-prompt'); + } + }, +}); +Signals.addSignalMethods(ShellUserVerifier.prototype); diff --git a/pool/shard000/JavaScript/0005614_htmlHandler.js b/pool/shard000/JavaScript/0005614_htmlHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..a5a558c65bd2a9f671d2809a8ee51cade74123a9 --- /dev/null +++ b/pool/shard000/JavaScript/0005614_htmlHandler.js @@ -0,0 +1,19 @@ +// Show HTML +// This will take the data that is sent to it from the GUI and render on the overlay. +function showHtml(data){ + // HTML Packet... + // {"event":"html","html": HTML, "length": length, "removal": removal} + var HTML = data.html; + var length = parseInt(data.length) * 1000; + var mainClass = data.removal; + + // Throw HTML on page. + $('#wrapper').append(HTML); + + // In X time remove it. + setTimeout(function(){ + $('.'+mainClass).fadeOut('fast', function(){ + $('.'+mainClass).remove(); + }); + }, length); +} diff --git a/pool/shard000/JavaScript/0005615_prepare.js b/pool/shard000/JavaScript/0005615_prepare.js new file mode 100644 index 0000000000000000000000000000000000000000..b54d06ee88d3d1cf234cd8d7afdb45e017054b65 --- /dev/null +++ b/pool/shard000/JavaScript/0005615_prepare.js @@ -0,0 +1,20 @@ +'use strict'; + +var Task = require('./-task'); +var CordovaRawTask = require('../tasks/cordova-raw'); +var logger = require('../utils/logger'); + +module.exports = Task.extend({ + project: undefined, + verbose: false, + + run: function() { + logger.info('Running cordova prepare'); + var prepare = new CordovaRawTask({ + project: this.project, + rawApi: 'prepare', + }); + + return prepare.run({ verbose: this.verbose }); + } +}); diff --git a/pool/shard000/JavaScript/0005616_getPpOfMap.js b/pool/shard000/JavaScript/0005616_getPpOfMap.js new file mode 100644 index 0000000000000000000000000000000000000000..e341afd4d7a182d00b844321591ec549aa1b9a27 --- /dev/null +++ b/pool/shard000/JavaScript/0005616_getPpOfMap.js @@ -0,0 +1,42 @@ +/** + * Created by julia on 02.10.2016. + */ +var i18nBean = require('../utility/i18nManager'); +var t = i18nBean.getT(); +var cmd = 'pp'; +var logger = require('../utility/logger'); +var winston = logger.getT(); +var osuHelper = require('../utility/osu'); +var execute = function (message) { + osuHelper.calcPP(message, (err, result) => { + if (err) { + switch (err.type) { + case "api-body": + message.reply(t('pp.err.api-body', {lngs:message.lang})); + return; + case "osu-api": + message.reply(t('pp.err.osu-api', {lngs:message.lang})); + return; + case "unvalid-link": + message.reply(t('pp.err.unvalid-link', {lngs:message.lang})); + return; + case "no-link": + message.reply(t('pp.err.no-link', {lngs:message.lang})); + return; + default: + return; + } + } + message.reply(t('pp.success', { + lngs: message.lang, + interpolation: {escape: false}, + artist: result.beatmap.artist, + title: result.beatmap.title, + version: result.body.version, + accuracy: result.body.acc, + pp: result.body.pp, + mods: result.body.mods + })); + }); +}; +module.exports = {cmd: cmd, accessLevel: 0, exec: execute, cat: 'misc'}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005619_esnext.map.every.js b/pool/shard000/JavaScript/0005619_esnext.map.every.js new file mode 100644 index 0000000000000000000000000000000000000000..18cb6364ab4021b5517f5d9d4b2d31d8bcf342a0 --- /dev/null +++ b/pool/shard000/JavaScript/0005619_esnext.map.every.js @@ -0,0 +1,19 @@ +'use strict'; +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getMapIterator = require('../internals/get-map-iterator'); + +// `Map.prototype.every` method +// https://github.com/tc39/collection-methods +require('../internals/export')({ target: 'Map', proto: true, real: true, forced: require('../internals/is-pure') }, { + every: function every(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var step, entry; + while (!(step = iterator.next()).done) { + entry = step.value; + if (!boundFunction(entry[1], entry[0], map)) return false; + } return true; + } +}); diff --git a/pool/shard000/JavaScript/0005621_car.js b/pool/shard000/JavaScript/0005621_car.js new file mode 100644 index 0000000000000000000000000000000000000000..82ef5936e34171b423b958945dc930c594b741f4 --- /dev/null +++ b/pool/shard000/JavaScript/0005621_car.js @@ -0,0 +1,195 @@ +var Car = { + + load: function () { + "use strict"; + + this.addCar(); + this.editCar(); + this.deleteCar(); + this.comboListener(); + }, + + //Combo options for adding a new car + comboListener: function () { + + $("#yearSelect").change(function () { + var year = $(this).val(); + console.log("Year selected: "+ year); + + //Get all the makes from that year + $.ajax({ + type: "POST", + url: "/car/makeyear", + data:'year='+year, + success: function(data){ + + //Remove all the previous options + $('#carMake').empty() + + //Inject the makers into the Manufacturer box + data = $.parseJSON(data); + + $.each(data, function(k,v) { + + $("#carMake").append( + $('<option></option>').val(v.car_make).html(v.car_make) + ); + }); + + } + }); + }); + + //Select a manufacturer + $("#carMake").change(function () { + + var year = $("#yearSelect").val(); + var maker = $("#carMake").val(); + + //Get all the makes from that year + $.ajax({ + type: "POST", + url: "/car/modelmakeyear", + data:'year='+year+'&make='+maker, + success: function(data){ + + //Remove all the previous options + $('#carModel').empty() + + //Inject the makers into the Manufacturer box + data = $.parseJSON(data); + + $.each(data, function(k,v) { + + $("#carModel").append( + $('<option></option>').val(v.car_model).html(v.car_model) + ); + }); + + } + }); + }); + }, + + //Add a new car to garage + addCar: function () { + "use strict"; + + $('body').on('click', "#add-car-btn", function () { + + $.ajax({ + type: "POST", + url : "/car/add", + data : $("#add-car-form").serialize(), + success : function (response) { + + var rsp = $.parseJSON(response); + + if (rsp.status === 'success') { + + //Hide the Add Car Button + $("#add-car-btn").hide(); + + $("#add-car-response").html("<div class='card-panel light-green lighten-12'> \ + <span class='white-text'>"+ rsp.msg +"</span> \ + </div>"); + + //Refresh the page + window.setTimeout(function(){location.reload()},2000) + } else { + + $("#add-car-response").html("<div class='card-panel red lighten-1'> \ + <span class='white-text'>"+ rsp.msg +"</span> \ + </div>"); + } + } + }, "json"); + + return false; + }); + }, + + //Add a new car to garage + editCar: function () { + "use strict"; + + $('body').on('click', "#edit-car-btn", function () { + + $.ajax({ + type: "POST", + url : "/car/update", + data : $("#edit-car-form").serialize(), + success : function (response) { + + var rsp = $.parseJSON(response); + + if (rsp.status === 'success') { + + $("#edit-car-response").html("<div class='card-panel light-green lighten-12'> \ + <span class='white-text'>"+ rsp.msg +"</span> \ + </div>"); + + } else { + + $("#edit-car-response").html("<div class='card-panel red lighten-1'> \ + <span class='white-text'>"+ rsp.msg +"</span> \ + </div>"); + } + } + }, "json"); + + return false; + }); + }, + + //Delete Car + deleteCar: function () { + "use strict"; + + $('body').on('click', "#delete-car-btn", function () { + + var carData = 'vehicleid='+$(this).data('vehicleid'); + + $.ajax({ + type: "POST", + url : "/car/delete", + data : carData, + success : function (response) { + + var rsp = $.parseJSON(response); + + if (rsp.status === 'success') { + + $("#delete-car-btn").hide(); + + + $(".modal-footer").append("<div class='card-panel red lighten-1'> \ + <span class='white-text'>You have deleted the vehicle, updating your information. One moment.</span> \ + </div>"); + + //Redirect to the dashboard + window.setTimeout( + function(){ + location.assign('/dashboard'); + } ,2500 + ); + + } else { + + $("#delete-car-response").html("<div class='card-panel red lighten-1'> \ + <span class='white-text'>"+ rsp.msg +"</span> \ + </div>"); + } + } + }, "json"); + + return false; + }); + } +}; + +$(document).ready(function () { + "use strict"; + + Car.load(); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005622_Events.js b/pool/shard000/JavaScript/0005622_Events.js new file mode 100644 index 0000000000000000000000000000000000000000..e99af6d190e3b8e283147f2db206ee0b4e69dd68 --- /dev/null +++ b/pool/shard000/JavaScript/0005622_Events.js @@ -0,0 +1,226 @@ +/* +--- + +name: "Events" + +description: "" + +license: + - "[GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)" + - "[MIT License](http://opensource.org/licenses/mit-license.php)" + +requires: + - Core + - declare + +inspiration: + - "[MooTools](http://mootools.net)" + +provides: Events + +... +*/ + +/** @class atom.Events */ +declare( 'atom.Events', { + + /** @constructs */ + initialize: function (context) { + this.context = context || this; + this.locked = []; + this.events = {}; + this.actions = {}; + this.readyList = {}; + }, + + /** + * @param {String} name + * @return Boolean + */ + exists: function (name) { + var array = this.events[this.removeOn( name )]; + return !!(array && array.length); + }, + + /** + * @param {String} name + * @param {Function} callback + * @return Boolean + */ + add: function (name, callback) { + this.run( 'addOne', name, callback ); + return this; + }, + + /** + * @param {String} name + * @param {Function} [callback] + * @return Boolean + */ + remove: function (name, callback) { + if (typeof name == 'string' && !callback) { + this.removeAll( name ); + } else { + this.run( 'removeOne', name, callback ); + } + return this; + }, + + /** + * @param {String} name + * @param {Array} args + * @return atom.Events + */ + fire: function (name, args) { + args = args ? slice.call( args ) : []; + name = this.removeOn( name ); + + this.locked.push(name); + var i = 0, l, events = this.events[name]; + if (events) for (l = events.length; i < l; i++) { + events[i].apply( this.context, args ); + } + this.unlock( name ); + return this; + }, + + /** + * @param {String} name + * @param {Array} [args=null] + * @return atom.Events + */ + ready: function (name, args) { + name = this.removeOn( name ); + this.locked.push(name); + if (name in this.readyList) { + throw new Error( 'Event «'+name+'» is ready' ); + } + this.readyList[name] = args; + this.fire(name, args); + this.removeAll(name); + this.unlock( name ); + return this; + }, + + /** + * @param {String} name + * @param {Array} [args=null] + * @return atom.Events + */ + ensureReady: function (name, args) { + if (!(name in this.readyList)) { + this.ready(name, args); + } + return this; + }, + + + // only private are below + + /** @private */ + context: null, + /** @private */ + events: {}, + /** @private */ + readyList: {}, + /** @private */ + locked: [], + /** @private */ + actions: {}, + + /** @private */ + removeOn: function (name) { + return (name || '').replace(/^on([A-Z])/, function(full, first){ + return first.toLowerCase(); + }); + }, + /** @private */ + removeAll: function (name) { + var events = this.events[name]; + if (events) for (var i = events.length; i--;) { + this.removeOne( name, events[i] ); + } + }, + /** @private */ + unlock: function (name) { + var action, + all = this.actions[name], + index = this.locked.indexOf( name ); + + this.locked.splice(index, 1); + + if (all) for (index = 0; index < all.length; index++) { + action = all[index]; + + this[action.method]( name, action.callback ); + } + }, + /** @private */ + run: function (method, name, callback) { + var i = 0, l = 0; + + if (Array.isArray(name)) { + for (i = 0, l = name.length; i < l; i++) { + this[method](name[i], callback); + } + } else if (typeof name == 'object') { + for (i in name) { + this[method](i, name[i]); + } + } else if (typeof name == 'string') { + this[method](name, callback); + } else { + throw new TypeError( 'Wrong arguments in Events.' + method ); + } + }, + /** @private */ + register: function (name, method, callback) { + var actions = this.actions; + if (!actions[name]) { + actions[name] = []; + } + actions[name].push({ method: method, callback: callback }) + }, + /** @private */ + addOne: function (name, callback) { + var events, ready, context; + + name = this.removeOn( name ); + + if (this.locked.indexOf(name) == -1) { + ready = this.readyList[name]; + if (ready) { + context = this.context; + setTimeout(function () { + callback.apply(context, ready); + }, 0); + return this; + } else { + events = this.events; + if (!events[name]) { + events[name] = [callback]; + } else { + events[name].push(callback); + } + } + } else { + this.register(name, 'addOne', callback); + } + }, + /** @private */ + removeOne: function (name, callback) { + name = this.removeOn( name ); + + if (this.locked.indexOf(name) == -1) { + var events = this.events[name], i = events.length; + while (i--) if (events[i] == callback) { + events.splice(i, 1); + } + } else { + this.register(name, 'removeOne', callback); + } + } +}); + +// local alias +var Events = atom.Events; diff --git a/pool/shard000/JavaScript/0005627_op-lt_Parser.js b/pool/shard000/JavaScript/0005627_op-lt_Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..362289f4fa023df6f26a35d4d1fbff44636ea422 --- /dev/null +++ b/pool/shard000/JavaScript/0005627_op-lt_Parser.js @@ -0,0 +1,33 @@ +this.readOp_lt = function() { + var op = TOKEN_NONE, c = this.c, len = this.src.length; + c++; // the < + if (c < len) { + var ch = this.ch(c); + if (ch === CH_EQUALITY_SIGN) { + c++; + op = TOKEN_BINARY; + this.prec = PREC_COMP; + } else if (ch === CH_LESS_THAN) { + c++; + if (c < len) { + if (this.ch(c) === CH_EQUALITY_SIGN) { + c++; + op = TOKEN_OP_ASSIG; + this.prec = PREC_ASSIG; + } + } + if (op === TOKEN_NONE) { + op = TOKEN_BINARY; + this.prec = PREC_SH; + } + } + } + if (op === TOKEN_NONE) { + op = TOKEN_BINARY; + this.prec = PREC_COMP; + } + + this.setoff(c); + this.ttype = op; + this.traw = this.c0_to_c(); +}; diff --git a/pool/shard000/JavaScript/0005629_BrowserInfo.js b/pool/shard000/JavaScript/0005629_BrowserInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..304a853a2f94cbdb07b8885249f6c513e984975e --- /dev/null +++ b/pool/shard000/JavaScript/0005629_BrowserInfo.js @@ -0,0 +1,12 @@ +function userAgent(pattern) { + if (typeof window !== 'undefined' && window.navigator) { + return !!/*@__PURE__*/navigator.userAgent.match(pattern); + } +} + +export const IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i); +export const Edge = userAgent(/Edge/i); +export const FireFox = userAgent(/firefox/i); +export const Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i); +export const IOS = userAgent(/iP(ad|od|hone)/i); +export const ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i); diff --git a/pool/shard000/JavaScript/0005633_datepickerDirective.js b/pool/shard000/JavaScript/0005633_datepickerDirective.js new file mode 100644 index 0000000000000000000000000000000000000000..5dc6b0a0a4190519b0e6eb0758fa0dde2ca79457 --- /dev/null +++ b/pool/shard000/JavaScript/0005633_datepickerDirective.js @@ -0,0 +1,36 @@ +(function () { + 'use strict'; + + angular.module('app.directives.datepicker', []) + + .directive('ngDatePicker', ngDatePicker); + + ngDatePicker.$inject = []; + + function ngDatePicker() { + var directive = { + restrict: 'A', + require: 'ngModel', + link: linkFunc + }; + + return directive; + + function linkFunc(scope, element, attrs, ctrl) { + element.datepicker({ + changeYear: true, + changeMonth: true, + showWeek: false, + firstDay: 1, + dayNames: 'en', + dateFormat: 'dd/mm/yy', + onSelect: onSelectFunc + }); + + function onSelectFunc(date) { + ctrl.$setViewValue(date); + scope.$apply(); + } + } + } +})(); diff --git a/pool/shard000/JavaScript/0005636_IterationRunner.js b/pool/shard000/JavaScript/0005636_IterationRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..01963267c1dada07e423246f9990155a9bfb80a6 --- /dev/null +++ b/pool/shard000/JavaScript/0005636_IterationRunner.js @@ -0,0 +1,225 @@ +var jsface = require("jsface"), + Options = require('../utilities/Options'), + log = require('../utilities/Logger'), + Helpers = require('../utilities/Helpers'), + Globals = require('../utilities/Globals'), + EventEmitter = require('../utilities/EventEmitter'), + CollectionModel = require('../models/CollectionModel'), + FolderModel = require('../models/FolderModel'), + CollectionRunner = require("../runners/CollectionRunner"), + Errors = require('../utilities/ErrorHandler'), + fs = require('fs'), + path = require('path'), + JSON5 = require('json5'), + _und = require('underscore'), + ResponseExporter = require("../utilities/ResponseExporter"); +/** + * @class IterationRunner + * @param CollectionJson {JSON} Takes a JSON as the input + * @param Options {JSON} Set of options to pass to the collection runner + * @param numOfIterations {int} Number of times the iteration has to run + */ +var IterationRunner = jsface.Class([Options, EventEmitter], { + constructor: function(requestJSON, options) { + this.setOptions(options); + this.collection = this._getOrderedCollection(requestJSON); + this.collectionName = requestJSON.name; + if(!Globals.requestJSON) { + Globals.requestJSON = requestJSON; + } + this.runMode = requestJSON.runMode || "default"; + + //check if only a folder has to be run + if(options.folderName) { + this.folder = this._getFolderFromCollection(requestJSON, options.folderName); + if(!this.folder) { + Errors.terminateWithError('The folder ['+options.folderName+'] does not exist.'); + } + this.collection = this._getFolderRequestsFromCollection(this.collection, this.folder); + } + + if(!isNaN(options.delay) && options.delay%1===0) { + this.delay=options.delay; + } + else if(options.delay==null) { + this.delay=0; + } + else { + Errors.terminateWithError('The delay must be an integer'); + } + + // collection of environment jsons passed from datafile + this.dataVars = this._getJsonArraysFromFile(); + this.globalVars = this._getJsonArraysFromGlobalFile(); + + var iterationCount = this.getOptions().iterationCount; + if(iterationCount && this.dataVars.length && iterationCount>this.dataVars.length) { + log.warn("WARNING: The iterationCount is greater than the number of records in the data file. This could lead to unexpected results\n"); + } + + this.numOfIterations = iterationCount || this.dataVars.length || 1; + this.iteration = 0; + + // run the next iteration when the collection run is over + this.addEventListener('collectionRunnerOver', this._runNextIteration.bind(this)); + }, + + _getOrderedCollection: function(requestJSON) { + var collectionModel = new CollectionModel(requestJSON); + var orderedCollection = collectionModel.getOrderedRequests(this.getOptions()); + return orderedCollection; + }, + + _getFolderFromCollection: function(requestJSON, folderName) { + var folders = requestJSON.folders; + var folderNeeded = _und.find(folders, function(folder) {return folder.name===folderName;}); + if(!folderNeeded) { + return null; + } + var folderModel = new FolderModel(folderNeeded); + return folderModel; + }, + + _getFolderRequestsFromCollection: function(collection, folder) { + if(!folder || !folder.order) { + return []; + } + var retVal = []; + var folderOrders = folder.order; + _und.each(collection,function(request) { + if(folderOrders.indexOf(request.id)!==-1) { + retVal.push(request); + } + }); + return retVal; + }, + + _kvArrayToObject: function(array) { + var obj = {}; + _und.each(array,function(kv) { + obj[kv.key]=kv.value; + }); + return obj; + }, + + _objectToKvArray: function(obj) { + var arr=[]; + for (var property in obj) { + if (obj.hasOwnProperty(property)) { + arr.push({"key":property, "value":obj[property]}); + } + } + return arr; + }, + + // sets the global environment object property as the env vars + globals + dataFiles + _setGlobalEnvJson: function() { + if(typeof Globals.envJson.values==="undefined") { + Globals.envJson.values=[]; + } + + //add the globals (globalJSON, overriden by envJson) + if(this.globalVars && this.globalVars.length) { + Globals.globalJson.values = this.globalVars;//Helpers.augmentDataArrays(this.globalVars,Globals.envJson.values); + } + else { + Globals.globalJson={values:[]}; + } + + //add the dataFile vars (overrides everything else) + if (this.dataVars.length) { + var dataJson = { values: this.dataVars[this.iteration - 1] }; //data file + Globals.dataJson.values= dataJson.values; + } + }, + + _getJsonArraysFromGlobalFile: function() { + var globalFile = this.getOptions().globalJSON; + if(globalFile===null) { + return []; + } + return globalFile; +// var jsonArray = []; +// if (globalFile) { +// jsonArray = JSON5.parse(fs.readFileSync(globalFile, 'utf8')); +// } +// return jsonArray; + }, + + // parses the json from data file and sends it for transformation + _getJsonArraysFromFile: function() { + var dataFile = this.getOptions().dataFile; + var jsonArray = []; + if (dataFile) { + if (path.extname(dataFile) === ".json") { + // json file + jsonArray = JSON5.parse(fs.readFileSync(dataFile, 'utf8')); + } else { + // assumed csv file + jsonArray = []; + var headers; + var strContents = fs.readFileSync(dataFile, 'utf-8'); + + var array = Helpers.CSVUtil.csvToArray(strContents); + if(array && array.length>0) { + headers = array[0]; + + var numRows = array.length; + for(var i=1;i<numRows;i++) { + jsonArray.push(_und.object(headers, array[i])); + } + } + } + + var envJsonArray = _und.map(jsonArray, function(rawJson) { + return Helpers.transformToKeyValue(rawJson); + }, this); + return envJsonArray; + } + return jsonArray; + }, + + // logs the iteration count + _logStatus: function() { + log.note("\nIteration " + this.iteration + " of " + this.numOfIterations + "\n"); + }, + + // set the global envjson and then run the next iteration + _runNextIteration: function() { + if (this.iteration < this.numOfIterations) { + Globals.iterationNumber = ++this.iteration; + Globals.dataJson={"values":[]}; + var currentGlobalEnv = Globals.envJson; + this._setGlobalEnvJson(); + this._runCollection(); + Globals.envJson = currentGlobalEnv; + } else { + this._exportResponses(); + this.emit('iterationRunnerOver',Globals.exitCode); + if(Globals.updateMessage) { + console.log(Globals.updateMessage); + } + } + }, + + _runCollection: function() { + if (this.collection.length) { + this._logStatus(); + var runner = new CollectionRunner(this.collection, this.getOptions(), this.runMode); + runner.execute(); + } + }, + + _exportResponses: function() { + ResponseExporter.exportResults(); + }, + + /** + * Runs the iteration. Instantiates a new CollectionRunner and executes it + */ + execute: function() { + this._runNextIteration(); + } +}); + +module.exports = IterationRunner; diff --git a/pool/shard000/JavaScript/0005637_get.js b/pool/shard000/JavaScript/0005637_get.js new file mode 100644 index 0000000000000000000000000000000000000000..18160c6c01432836c09b35c3630b460a04f4f20c --- /dev/null +++ b/pool/shard000/JavaScript/0005637_get.js @@ -0,0 +1,41 @@ +const chai = require('chai'); +const chaiHttp = require('chai-http'); +const Promise = require('bluebird'); +const TestHelper = require('../../../../test-helper/'); + +const expect = chai.expect; + +chai.use(chaiHttp); + +describe('Integration - GET /users/login/token', function() { + let server; + const testHelper = new TestHelper(); + + before(function() { + this.timeout(30000); + return testHelper.getServer().then((s) => { + server = s; + return Promise.resolve(); + }); + }); + + after(function() { + return testHelper.cleanup(); + }); + + it('should return 501', function() { + return new Promise((resolve, reject) => { + chai.request(server) + .get('/users/login/token') + .set('Content-Type', 'application/vnd.api+json') + .end((err, res) => { + try { + expect(res).to.have.status(501); + } catch (e) { + return reject(e); + } + return resolve(); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005640_questionMethods.js b/pool/shard000/JavaScript/0005640_questionMethods.js new file mode 100644 index 0000000000000000000000000000000000000000..03a9024b5c987562e6dc86039b4e5caeaaa1192c --- /dev/null +++ b/pool/shard000/JavaScript/0005640_questionMethods.js @@ -0,0 +1,49 @@ +import { Meteor } from "meteor/meteor"; +import { Questions } from "../publishers/questionPublisher.js"; +import { QuestionsStatistics } from "../statistics/Statistics.js"; + +Meteor.methods({ + "questions.insert" (QMLtext, category) { + + var ok; + + Meteor.call("parser.check", QMLtext, function(error, result) { + debugger; + if(error){ + QzMessage.showText(0, error); + return false; + } + else + { + if(!result) + + ok= false; + else{ + var toInsert = { + owner: Meteor.userId(), + QMLtext, + category, + createdAt: new Date() + }; + + Questions.insert(toInsert,function(err,docsInserted){ + if(docsInserted) + QuestionsStatistics.insert({"_id": docsInserted, "rispCorrette" : 0 , "voltePresentata" : 0}); + }); + ok= true; + } + } + }); + return ok; + }, + + /*"questions.update" (questionID, QMLtext, category){ + Questions.update({'questionID': questionID}, {set {'QMLtext': QMLtext, 'category': category}}); + },*/ + + "questions.remove" (questionId) + { + return Questions.remove({"_id" : questionId}); + //QuestionsStatistics.remove(questionId); + } +}); diff --git a/pool/shard000/JavaScript/0005641_property.js b/pool/shard000/JavaScript/0005641_property.js new file mode 100644 index 0000000000000000000000000000000000000000..8fdda84fd21866af6b16cce31a3a2e3619c4fdc0 --- /dev/null +++ b/pool/shard000/JavaScript/0005641_property.js @@ -0,0 +1,12 @@ +import {PersistentConfig} from '../persistent-config'; +import {Util} from '../util'; + +export function Property(pathOrTarget, optPropertyKey, optDescriptor) { + let isDecorator = Util.isPropertyDecorator(...arguments); + let deco = function(target, propertyKey) { + let path = isDecorator ? optPropertyKey : pathOrTarget || optPropertyKey; + PersistentConfig.get(target).configureProperty(propertyKey, {path}); + }; + return isDecorator ? + deco(pathOrTarget, optPropertyKey, optDescriptor) : deco; +} diff --git a/pool/shard000/JavaScript/0005643_mm-affiliate_integration.js b/pool/shard000/JavaScript/0005643_mm-affiliate_integration.js new file mode 100644 index 0000000000000000000000000000000000000000..9399b2bfaa196ae7e28f95997bcaa34df5f6a89c --- /dev/null +++ b/pool/shard000/JavaScript/0005643_mm-affiliate_integration.js @@ -0,0 +1,137 @@ +/*! + * + * MemberMouse(TM) (http://www.membermouse.com) + * (c) MemberMouse, LLC. All rights reserved. + */ +var MM_AffiliateIntegrationViewJS = MM_Core.extend({ + + providerOptionsReset: function() { + jQuery("#provider_token").removeAttr("disabled"); + jQuery("#mm-affiliate-provider-options input").removeAttr("readonly"); + jQuery("#mm-affiliate-provider-options select").removeAttr("disabled"); + jQuery("#affiliate-provider-configure").removeAttr("readonly"); + jQuery("#mm-membership-to-profile").html(""); + jQuery("#mm-affiliate-provider-additional-options").hide("fast"); + jQuery("#reset").hide("fast"); + + jQuery("#affiliate-provider-configure").show("fast"); + }, + + showNewProviderOptions: function(form_data) { + + jQuery("#affiliate-provider-configure").show(); + jQuery("#mm-affiliate-provider-additional-options").hide(); + + var values = {}; + values.mm_action = "showProviderOptions"; + jQuery.each(form_data, function() { + if (values[this.name] !== undefined) { + if (!values[this.name].push) { + values[this.name] = [values[this.name]]; + } + values[this.name].push(this.value || ''); + } else { + values[this.name] = this.value || ''; + } + }); + + var module = this.module; + var method = "performAction"; + var action = 'module-handle'; + + var ajax = new MM_Ajax(false, module, action, method); + ajax.send(values, false, 'mmjs','updateProviderOptionsUI'); + }, + + showAdditionalOptionsDialog: function(form_data) { + var values = {}; + values.mm_action = "showAdditionalOptionsDialog"; + jQuery.each(form_data, function() { + if (values[this.name] !== undefined) { + if (!values[this.name].push) { + values[this.name] = [values[this.name]]; + } + values[this.name].push(this.value || ''); + } else { + values[this.name] = this.value || ''; + } + }); + + var module = this.module; + var method = "performAction"; + var action = 'module-handle'; + + var ajax = new MM_Ajax(false, module, action, method); + ajax.send(values, false, 'mmjs','updateAdditionalOptionsUI'); + }, + + providerOptionsSave: function(form_data) { + var values = {}; + values.mm_action = "saveProviderOptions"; + values['provider_token'] = jQuery("#provider_token").val(); + jQuery.each(form_data, function() { + if (values[this.name] !== undefined) { + if (!values[this.name].push) { + values[this.name] = [values[this.name]]; + } + values[this.name].push(this.value || ''); + } else { + values[this.name] = this.value || ''; + } + }); + + var module = this.module; + var method = "performAction"; + var action = 'module-handle'; + + var ajax = new MM_Ajax(false, module, action, method); + ajax.send(values, false, 'mmjs','updateStatus'); + }, + + updateStatus: function(data) { + if(data.type!='error'){ + alert("Provider settings saved successfully"); + } + else { + alert(data.message); + } + }, + + updateAdditionalOptionsUI: function(data) { + if(data.type!='error'){ + jQuery("#affiliate-provider-configure").hide("fast"); + jQuery("#reset").show("fast"); + jQuery("#provider_token").attr("disabled","disabled"); + jQuery("#mm-affiliate-provider-options input").attr("readonly","readonly"); + jQuery("#mm-affiliate-provider-options select").attr("disabled","disabled"); + jQuery("#affiliate-provider-configure").attr("readonly","readonly"); + jQuery("#mm-membership-to-profile").html(data.message); + jQuery("#mm-affiliate-provider-additional-options").show("slow"); + } + else { + alert(data.message); + } + }, + + updateProviderOptionsUI: function(data) { + if ((data.type!='error') && (typeof data.message != 'undefined') && (typeof data.message.dialog != 'undefined')) + { + jQuery("#mm-affiliate-provider-options").html(data.message.dialog); + jQuery("#mm-affiliate-provider-controls").html(data.message.controls); + } + else + { + if (data.type == 'error') + { + alert(data.message); + } + else + { + alert("There was an error retrieving the provider options"); + } + } + } + +}); + +var mmjs = new MM_AffiliateIntegrationViewJS("MM_AffiliateIntegrationView", "Affiliate Integration"); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005645_editableFieldBackdropDirective.js b/pool/shard000/JavaScript/0005645_editableFieldBackdropDirective.js new file mode 100644 index 0000000000000000000000000000000000000000..4c1c1d3a19bed8b958f975bc40884af9a0c97465 --- /dev/null +++ b/pool/shard000/JavaScript/0005645_editableFieldBackdropDirective.js @@ -0,0 +1,148 @@ +/* Copyright 2013-2016 Extended Mind Technologies Oy + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + 'use strict'; + + function editableFieldBackdropDirective() { + return { + restrict: 'A', + controller: ['$scope', '$element', function($scope, $element) { + $element.addClass('editable-field-backdrop'); + + var containerInfos = []; + var preventBackdropBubbleClick, preventContainerBubbleClick; + $scope.backdropActive = false; + + this.registerContainer = function(id, deactivateFn){ + var containerInfo = containerInfos.findFirstObjectByKeyValue('id', id); + if (containerInfo) { + // Overwrite id's existing values + containerInfo.deactivate = deactivateFn; + return; + } + containerInfos.push({ + id: id, + deactivate: deactivateFn + }); + }; + + this.unregisterContainer = function(id) { + var containerIndex = containerInfos.findFirstIndexByKeyValue('id', id); + if (containerIndex !== undefined){ + containerInfos.splice(containerIndex, 1); + } + }; + + function backdropClicked() { + if (preventBackdropBubbleClick) { + if (preventBackdropBubbleClick > Date.now() - 600){ + // Event bubbled from undesired click less than 600ms ago. Do nothing. + preventBackdropBubbleClick = false; + return; + } + preventBackdropBubbleClick = false; + } + + if (containerInfos && containerInfos.length > 0) { + + // First check that click did not hit one of the active containers + var foundActiveClicked = false; + for (var i = 0, len = containerInfos.length; i < len; i++) { + if (containerInfos[i].clicked && containerInfos[i].active) { + // reset clicked info + containerInfos[i].clicked = false; + foundActiveClicked = true; + } + } + if (foundActiveClicked) return; + + for (var j = 0, jLen = containerInfos.length; j < jLen; j++) { + if (containerInfos[j] && (!containerInfos[j].clicked && containerInfos[j].active)) { + // Clicked elsewhere than container for an active container, deactivate container. + // NOTE: Make sure container is not removed same time as looping containers. + containerInfos[j].deactivate(); + } + } + } + } + + this.activateContainer = function (id, blurBackdrop) { + if (event && (event.type === 'click' || event.type === 'focus')){ + // Function called in the middle of a click event. + // NOTE: It may be unsafe to stop event bubbling, so prevent bubbling locally to backdrop click + // event. event.stopPropagation() would be more reliable though if we were sure this + // function is not and will not be depended on click. Also in Chrome 48 + // event.timeStamp switched to using a float value, so use Date.now() which isn't as + // precise, but works. + var currentTime = Date.now(); + preventBackdropBubbleClick = currentTime; + preventContainerBubbleClick = currentTime; + } + + // activate container + var containerInfo = containerInfos.findFirstObjectByKeyValue('id', id); + if (containerInfo) containerInfo.active = true; + + // activate backdrop + $element[0].addEventListener('click', backdropClicked, false); + $scope.backdropActive = true; + $element.addClass('active'); + + if (blurBackdrop) { + // Add blur class to first child. + $element[0].firstElementChild.classList.add('blur'); + } + }; + + this.deactivateContainer = function(id) { + preventBackdropBubbleClick = false; + preventContainerBubbleClick = false; + + // mark container info deactivated + var containerInfo = containerInfos.findFirstObjectByKeyValue('id', id); + if (containerInfo) containerInfo.active = false; + + // deactivate backdrop + if ($scope.backdropActive){ + $element[0].removeEventListener('click', backdropClicked, false); + $scope.backdropActive = false; + $element.removeClass('active'); + $element[0].firstElementChild.classList.remove('blur'); + } + }; + + /* + * Editable field container clicked. + * + * Click event bubbles to backdrop where clicked information is used. + */ + this.notifyContainerClicked = function(id) { + if (preventContainerBubbleClick) { + if (preventContainerBubbleClick > Date.now() - 400){ + // Event bubbled from undesired click less than 400ms ago. Do nothing. + preventContainerBubbleClick = false; + return; + } + preventContainerBubbleClick = false; + } + + var containerInfo = containerInfos.findFirstObjectByKeyValue('id', id); + if (containerInfo) { + containerInfo.clicked = true; + } + }; + }] + }; +} +angular.module('common').directive('editableFieldBackdrop', editableFieldBackdropDirective); diff --git a/pool/shard000/JavaScript/0005648_fillin.js b/pool/shard000/JavaScript/0005648_fillin.js new file mode 100644 index 0000000000000000000000000000000000000000..1770d9b40d171174d2028ead1c52a207e8dc062a --- /dev/null +++ b/pool/shard000/JavaScript/0005648_fillin.js @@ -0,0 +1,22 @@ +'use strict'; + +describe('Controller: FillinCtrl', function () { + + // load the controller's module + beforeEach(module('infoApp')); + + var FillinCtrl, + scope; + + // Initialize the controller and a mock scope + beforeEach(inject(function ($controller, $rootScope) { + scope = $rootScope.$new(); + FillinCtrl = $controller('FillinCtrl', { + $scope: scope + }); + })); + + it('should attach a list of awesomeThings to the scope', function () { + expect(scope.awesomeThings.length).toBe(3); + }); +}); diff --git a/pool/shard000/JavaScript/0005651_HeaderCell.js b/pool/shard000/JavaScript/0005651_HeaderCell.js new file mode 100644 index 0000000000000000000000000000000000000000..0cf58a4b2865153c1a17fa914bfcd5730636c99e --- /dev/null +++ b/pool/shard000/JavaScript/0005651_HeaderCell.js @@ -0,0 +1,285 @@ +/** + * Copyright (C) 2005-2013 Alfresco Software Limited. + * + * This file is part of Alfresco + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. + */ + +/** + * + * @module alfresco/documentlibrary/views/layouts/HeaderCell + * @extends dijit/_WidgetBase + * @mixes dijit/_TemplatedMixin + * @mixes module:alfresco/core/Core + * @author Dave Draper + */ +define(["dojo/_base/declare", + "dijit/_WidgetBase", + "dijit/_TemplatedMixin", + "dojo/text!./templates/HeaderCell.html", + "alfresco/core/Core", + "dojo/_base/lang", + "dojo/dom-class", + "dojo/query", + "alfresco/misc/AlfTooltip"], + function(declare, _WidgetBase, _TemplatedMixin, template, AlfCore, lang, domClass, query, AlfTooltip) { + + return declare([_WidgetBase, _TemplatedMixin, AlfCore], { + + /** + * An array of the CSS files to use with this widget. + * + * @instance + * @type {object[]} + * @default [{cssFile:"./css/Cell.css"}] + */ + cssRequirements: [{cssFile:"./css/HeaderCell.css"}], + + /** + * The HTML template to use for the widget. + * + * @instance + * @type {String} + */ + templateString: template, + + /** + * Indicates whether or not this header can actually be used to trigger sort requests. + * + * @instance + * @type boolean + * @default false + */ + sortable: false, + + /** + * Indicate whether or not this cell is currently being used as the sort field. + * + * @instance + * @type boolean + * @default false + */ + usedForSort: false, + + /** + * Indicates whether or not the column headed by this cell is sorted in ascending order or not. + * This value is only relevant when the [usedForSort]{@link module:alfresco/documentlibrary/views/layouts/HeaderCell#usedForSort} + * attribute is true. + * + * @instance + * @type boolean + * @default false + */ + sortedAscending: false, + + /** + * The value to publish to sort on. + * + * @instance + * @type {string} + * @default null + */ + sortValue: null, + + /** + * The tool tip to display. + * + * @instance + * @type {string} + * @default null + */ + toolTipMsg: null, + + /** + * @instance + */ + postMixinProperties: function alfresco_documentlibrary_views_layouts_HeaderCell__postMixinProperties() { + if (this.label != null) + { + this.label = this.message(this.label); + } + this.currentItem = {}; + }, + + /** + * Calls [processWidgets]{@link module:alfresco/core/Core#processWidgets} + * + * @instance postCreate + */ + postCreate: function alfresco_documentlibrary_views_layouts_HeaderCell__postCreate() { + + this.alfSubscribe("ALF_DOCLIST_SORT", lang.hitch(this, "onExternalSortRequest")); + this.alfSubscribe("ALF_DOCLIST_SORT_FIELD_SELECTION", lang.hitch(this, "onExternalSortRequest")); + + if (this.sortable == false || this.usedForSort == false) + { + this.sortIcon("nil"); + } + else + { + this.sortIcon(this.sortedAscending == false ? "desc" : "asc"); + } + + if (this.toolTipMsg != null) + { + this.addToolTipMsg(); + } + }, + + /** + * Focuses the domNode. This has been added to support the dijit/_KeyNavContainer functions mixed into + * the [document library views]{@link module:alfresco/documentlibrary/views/AlfDocumentListView} to + * allow easier keyboard navigation. + * + * @instance + */ + focus: function alfresco_documentlibrary_views_layouts_HeaderCell__focus() { + this.domNode.focus(); + }, + + /** + * This function is called whenever the header cell is clicked. It publishes a request to + * resort the current data and updates its display + * + * @instance + * @param {object} evt The click event + */ + onSortClick: function alfresco_documentlibrary_views_layouts_HeaderCell__onSortClick(evt) { + if (this.sortable == true) + { + this.alfLog("log", "Sort request received"); + + // If currently NOT being used for sort then we start with ascending + if (this.usedForSort == false) + { + this.usedForSort = true; + this.sortedAscending = true; + this.sortIcon("asc"); + } + + // If we are already sorting on this column and direction is ascending then we want descending + else if (this.sortedAscending == true) + { + this.sortIcon("desc"); + this.sortedAscending = false; + } + + // Otherwise we want sort by ascending + else + { + this.sortIcon("asc"); + this.sortedAscending = true; + } + this.publishSortRequest(); + } + }, + + /** + * @instance + */ + publishSortRequest: function alfresco_documentlibrary_views_layouts_HeaderCell__publishSortRequest() { + this.alfPublish("ALF_DOCLIST_SORT", { + direction: (this.sortedAscending) ? "ascending" : "descending", + value: this.sortValue, + requester: this + }); + }, + + /** + * This handles external sort requests so that the header cell can match the current + * status. + * + * @instance + * @param {object} payload + */ + onExternalSortRequest: function alfresco_documentlibrary_views_layouts_HeaderCell__onExternalSortRequest(payload) { + var requester = lang.getObject("requester", false, payload); + if (requester != this) + { + var value = lang.getObject("value", false, payload); + if (value != null) + { + if (value == this.sortValue) + { + this.usedForSort = true; + this.sortIcon(this.sortedAscending == true ? "asc" : "desc"); + } + else + { + // A different field has been used for sorting, hide the sort icons and update the status... + this.usedForSort = false; + this.sortIcon("nil"); + } + } + + var direction = lang.getObject("direction", false, payload); + if (direction != null) + { + this.sortedAscending = (direction == "ascending"); + if (this.usedForSort == true) + { + this.sortIcon(this.sortedAscending == true ? "asc" : "desc"); + } + } + } + }, + + /** + * This controls the display of icons when using sort functionality. + * + * @instance + * @param {string} dir - asc, desc or nil + */ + sortIcon: function alfresco_documentlibrary_views_layouts_HeaderCell__sortIcon(dir) { + var hideClass = "hidden", + asn = this.ascendingSortNode, + dsn = this.descendingSortNode; + + switch(dir) + { + case "asc": + domClass.remove(asn, hideClass); + domClass.add(dsn, hideClass); + break; + + case "desc": + domClass.add(asn, hideClass); + domClass.remove(dsn, hideClass); + break; + + default: + domClass.add(asn, hideClass); + domClass.add(dsn, hideClass); + break; + } + }, + + /** + * This controls the display of a tool tip against the header cell label. + * + * @instance + */ + addToolTipMsg: function alfresco_documentlibrary_views_layouts_HeaderCell__addToolTipMsg() { + // Find the .label item within the domNode + var labelNode = query(".label", this.domNode); + var tip = new AlfTooltip({ + targetNode: labelNode, + label: this.message(this.toolTipMsg) + }); + this.alfLog("log", "Created HeaderCell tooltip with label '" + tip.label + "' for item '" + this.domNode + "'", this); + } + + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005653_spotify.js b/pool/shard000/JavaScript/0005653_spotify.js new file mode 100644 index 0000000000000000000000000000000000000000..8be16657df67b982d40d30e00feb3d2f2f6d51bf --- /dev/null +++ b/pool/shard000/JavaScript/0005653_spotify.js @@ -0,0 +1,33 @@ +var config = require(__dirname + '/../config.json') + +var sp = require('libspotify'); + +var session = new sp.Session({ + applicationKey: __dirname + '/../spotify_appkey.key' +}); + +module.exports = function (username, password, cb){ + + var downloadTrack = require(__dirname + '/download_track'), + downloadPlaylist = require(__dirname + '/download_playlist'), + getTrackByUrl = require(__dirname + '/get_track'); + + session.login(username, password); + + session.once('login', function(err) { + + cb(null, { + downloadTrack: downloadTrack(session), + downloadPlaylistByUrl: downloadPlaylist(session), + getTrackByUrl: getTrackByUrl(session) + }); + + }); + + session.on('error', function (err){ + cb(err); + session.close(); + process.exit(); + }); + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005654_ajax.js b/pool/shard000/JavaScript/0005654_ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..9af5bbc59ebcc993a6b4894a311586b838fe43a1 --- /dev/null +++ b/pool/shard000/JavaScript/0005654_ajax.js @@ -0,0 +1,80 @@ +M.local_panopto = { + Y : null, + transaction : [], + init : function(Y, courseid) { + var panopto = Y.one("#panopto-text"); + if (!panopto) { + return; + } + + var panoptofooter = Y.one("#panopto-footer"); + panopto.setHTML("Requesting data..."); + + Y.io(M.cfg.wwwroot + "/blocks/panopto/ajax.php", { + + timeout: 8000, + method: "GET", + data: { + sesskey: M.cfg.sesskey, + courseid: courseid + }, + on: { + success : function (x,o) { + // Process the JSON data returned from the server + try { + data = Y.JSON.parse(o.responseText); + } + catch (e) { + panopto.setHTML(M.str.block_panopto.ajax_json_error); + return; + } + + if (data.error) { + panopto.setHTML(M.str.block_panopto.ajax_data_error); + } else { + panopto.setHTML(data.text); + panoptofooter.setHTML(data.footer); + } + }, + + failure : function (x,o) { + if (o.statusText == "timeout") { + panopto.setHTML(M.str.block_panopto.ajax_busy); + } else { + panopto.setHTML(M.str.block_panopto.ajax_failure); + } + } + } + }); + }, + toggleHiddenLectures : function () { + var showAllToggle = document.getElementById("showAllToggle"); + var hiddenLecturesDiv = document.getElementById("hiddenLecturesDiv"); + + if(hiddenLecturesDiv.style.display == "block") { + hiddenLecturesDiv.style.display = "none"; + showAllToggle.innerHTML = M.str.block_panopto.show_all; + } else { + hiddenLecturesDiv.style.display = "block"; + showAllToggle.innerHTML = M.str.block_panopto.show_less; + } + }, + launchNotes : function (url) { + // Open empty notes window, then POST SSO form to it. + var notesWindow = window.open("", "PanoptoNotes", "width=500,height=800,resizable=1,scrollbars=0,status=0,location=0"); + document.SSO.action = url; + document.SSO.target = "PanoptoNotes"; + document.SSO.submit(); + + // Ensure the new window is brought to the front of the z-order. + notesWindow.focus(); + }, + startSSO : function (linkElem) { + document.SSO.action = linkElem.href; + document.SSO.target = "_blank"; + document.SSO.submit(); + + // Cancel default link navigation. + return false; + } +} diff --git a/pool/shard000/JavaScript/0005656_chapter-modal.js b/pool/shard000/JavaScript/0005656_chapter-modal.js new file mode 100644 index 0000000000000000000000000000000000000000..f52535f552dca976589e2bc02c56f02769c4580c --- /dev/null +++ b/pool/shard000/JavaScript/0005656_chapter-modal.js @@ -0,0 +1,94 @@ +define(function(require, exports, module) { + + var Validator = require('bootstrap.validator'); + var Notify = require('common/bootstrap-notify'); + require('jquery.sortable'); + + exports.run = function() { + + + var sortList = function($list) { + var data = $list.sortable("serialize").get(); + $.post($list.data('sortUrl'), {ids:data}, function(response){ + var lessonNum = chapterNum = unitNum = 0; + + $list.find('.item-lesson, .item-chapter').each(function() { + var $item = $(this); + if ($item.hasClass('item-lesson')) { + lessonNum ++; + $item.find('.number').text(lessonNum); + } else if ($item.hasClass('item-chapter-unit')) { + unitNum ++; + $item.find('.number').text(unitNum); + } else if ($item.hasClass('item-chapter')) { + chapterNum ++; + unitNum = 0; + $item.find('.number').text(chapterNum); + } + + }); + }); + }; + + var validator = new Validator({ + element: '#course-chapter-form', + autoSubmit: false + }); + + validator.addItem({ + element: '#chapter-title-field', + required: true + }); + + validator.on('formValidated', function(error, msg, $form) { + if (error) { + return ; + } + $('#course-chapter-btn').button('submiting').addClass('disabled'); + + $.post($form.attr('action'), $form.serialize(), function(html) { + + var id = '#' + $(html).attr('id'), + $item = $(id); + var $parent = $('#'+$form.data('parentid')); + var $panel = $('.lesson-manage-panel'); + $panel.find('.empty').remove(); + if ($item.length) { + $item.replaceWith(html); + Notify.success('信息已保存'); + } else { + if($parent.length){ + var add = 0; + $parent.nextAll().each(function(){ + if($(this).hasClass('item-chapter clearfix')){ + $(this).before(html); + add = 1; + return false; + } + + }); + if(add != 1 ) + $("#course-item-list").append(html); + + var $list = $("#course-item-list"); + sortList($list); + + }else{ + $("#course-item-list").append(html); + $(".lesson-manage-panel").find('.empty').remove(); + } + + Notify.success('添加成功'); + + } + $(id).find('.btn-link').tooltip(); + $form.parents('.modal').modal('hide'); + }); + + }); + + }; + + + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005657_IE8Respond.js b/pool/shard000/JavaScript/0005657_IE8Respond.js new file mode 100644 index 0000000000000000000000000000000000000000..4ce617a411e6fb4a8bb3c60dcecff12da16500b4 --- /dev/null +++ b/pool/shard000/JavaScript/0005657_IE8Respond.js @@ -0,0 +1,83 @@ +//IE8Respond.js +//Version:0.0.2 +//Author:Arun Kumar + +//Configuration +var nonResponsive = false; +var resizeEnd = false; + +//Check Jquery +if ("undefined" == typeof jQuery) { throw new Error("Script Requires jQuery"); } +else { + + //Variables + var mediaQueries = new Array(); + var jsMQ = new Array(); + var $currentCSS; + + // provide a resized event + var timer = window.setTimeout(function () { }, 0); + $(window).on('resize', function () { + resizeEnd ? (window.clearTimeout(timer), timer = window.setTimeout(function () { $(window).trigger("resized") }, 250)) : $(window).trigger("resized"); + }); + + + //Functions + var readRegEx = function (str, re) { + var resp = str.match(re); + null !== resp && resp.shift(); + return resp; + }; + + var parseMQs = function (str) { + var re = /(@media.(?!print)[^{]+\{[\s\S]+?}\s*})/g; + return readRegEx(str, re); + }; + + mediaQueries = $("style,link[rel='stylesheet']").map(function () { + if ($(this).is('style')) { + return parseMQs($(this).text()); + } + else { + var $href = $(this).attr('href'); + var result; + $.ajax({ url: $href, success: function (data) { result = data; }, type: "GET", async: false }); + + return parseMQs(result); + } + }); + + $.each(mediaQueries, function (index, value) { + var minWidth = readRegEx(value, /\(min-width:(.*?)px\)/); + minWidth = null !== minWidth ? parseInt(minWidth) : 0; + var maxWidth = readRegEx(value, /\(max-width:(.*?)px\)/); + var css = readRegEx(value, /@media[^{]+\{([\s\S]+?})\s*}/); + + jsMQ.push({ + min: minWidth, + max: maxWidth, + css: css + }) + }); + + var liveStyle = function () { + $("#jsStyle").remove(); + var $wWidth = $(window).width(); + $currentCSS = $jsMQ.map(function () { + if (null !== this.max) { + if ($wWidth > this.min && $wWidth < this.max) { + return this.css; + } + } else { + if ($wWidth > this.min) { + return this.css; + } + } + }).get().join(" "); + $('head').append("<style id=\"jsStyle\">" + $currentCSS + "</style>"); + } + + var $jsMQ = $(jsMQ); + liveStyle(); + nonResponsive || $(window).on("resized",liveStyle); +} diff --git a/pool/shard000/JavaScript/0005662_voteActions.js b/pool/shard000/JavaScript/0005662_voteActions.js new file mode 100644 index 0000000000000000000000000000000000000000..1a2c20b0410d077e398cafaa222a25df3296251d --- /dev/null +++ b/pool/shard000/JavaScript/0005662_voteActions.js @@ -0,0 +1,51 @@ +import axios from 'axios'; + +import { + UPVOTE, DOWNVOTE, SET_UPVOTE_LIST, SET_DOWNVOTE_LIST +} from '../constants'; + +const url = '/api/v1/recipes'; + +/** + * @description - Upvotes a recipe + * + * @export + * + * @param {Number} recipeId - Recipe ID + * + * @param {Number} userId - User ID + * + * @returns {object} dispatch - Dispatched action + */ +export function upvote(recipeId) { + return dispatch => axios.post(`${url}/${recipeId}/upvotes`) + .then((response) => { + const { recipe } = response.data; + dispatch({ + type: UPVOTE, + recipe + }); + }); +} + +/** + * @description - Downvotes a recipe + * + * @export + * + * @param {Number} recipeId - Recipe ID + * + * @param {Number} userId - User ID + * + * @returns {object} dispatch - Dispatched action + */ +export function downvote(recipeId) { + return dispatch => axios.post(`${url}/${recipeId}/downvotes`) + .then((response) => { + const { recipe } = response.data; + dispatch({ + type: DOWNVOTE, + recipe + }); + }); +} diff --git a/pool/shard000/JavaScript/0005663_requests-cache-service.js b/pool/shard000/JavaScript/0005663_requests-cache-service.js new file mode 100644 index 0000000000000000000000000000000000000000..cb222f0c215561358e973fe82950fdb375313e43 --- /dev/null +++ b/pool/shard000/JavaScript/0005663_requests-cache-service.js @@ -0,0 +1,46 @@ +import {Injectable} from 'app/app'; +import {HashGenerator} from 'common/hash-generator'; +import _ from 'lodash'; + +/** + * Provides functionality to reduce the REST calls made to the server. + */ +@Injectable() +export class RequestsCacheService { + + /** + * Hashes the passed parameters and uses them as a key in a provided map. The value used is the request made. + * Adds the calling REST function as unique string to the parameters before hashing to ensure proper work. + * It clones the results before return in order to serve different objects to the different callers. + * + * @param url to be used as part of the hash salt to ensure caller method uniqueness + * @param params to identify equal calls + * @param requestsMap map object, holds all active requests + * @param requestFunctionExecutor REST call function. Used as part of the hashSalt to ensure caller method uniqueness + * @param extendedMode true to handle nested objects with duplicates. When not provided defaults to true + * + * returns cashed promise + */ + cache(url, params, requestsMap, requestFunctionExecutor, extendedMode = true) { + let hashKey = HashGenerator.getHash(params, extendedMode, url + requestFunctionExecutor); + + if (requestsMap.has(hashKey)) { + return new Promise((resolve) => { + return requestsMap.get(hashKey).then(result => resolve(_.clone(result, true))); + }).catch((error) => { + throw error; + }); + } else { + let promise = requestFunctionExecutor(); + requestsMap.set(hashKey, promise); + return promise.then((result) => { + requestsMap.delete(hashKey); + return _.clone(result, true); + }) + .catch((error) => { + requestsMap.delete(hashKey); + throw error; + }); + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005666_DynamicPageUtility.js b/pool/shard000/JavaScript/0005666_DynamicPageUtility.js new file mode 100644 index 0000000000000000000000000000000000000000..716ce136cbd8b202fd6f032905ba8008ba264823 --- /dev/null +++ b/pool/shard000/JavaScript/0005666_DynamicPageUtility.js @@ -0,0 +1,114 @@ +(function () { + "use strict"; + + // Should be global + window.oDynamicPageUtil = { + getLabel: function (sText, sLabelFor) { + return new sap.m.Label({ + wrapping: true, + text: sText, + labelFor: sLabelFor + }); + }, + getSelectItem: function (iNumber) { + return new sap.ui.core.Item({ + text: "Content " + ++iNumber, + key: iNumber + }); + }, + getSelect: function (iCount) { + var aSelectItems = []; + + for (var i = 0; i < iCount; i++) { + aSelectItems.push(this.getSelectItem(i)); + } + + return new sap.m.Select({ + autoAdjustWidth: true, + items: aSelectItems + }); + }, + getLabelWithSelect: function (sValue) { + var oSelect = this.getSelect(10); + return new sap.ui.layout.VerticalLayout({ + content: [this.getLabel(sValue, oSelect), oSelect] + }); + }, + getLabelWithSelectCombo: function (iCount) { + var aLabelCombos = []; + + for (var i = 0; i < iCount; i++) { + aLabelCombos.push(this.getLabelWithSelect("Something Something" + i)); + } + + return aLabelCombos; + }, + getHeader: function () { + return new sap.f.DynamicPageHeader({ + pinnable: true, + content: [ + new sap.ui.layout.Grid({ + content: this.getLabelWithSelectCombo(6), + defaultSpan: "XL2 L3 M4 S6" + }) + ] + }); + }, + getTitle: function(oToggleFooterButton) { + return new sap.f.DynamicPageTitle({ + heading: [new sap.m.Title({text: "Some title", level: "H1", titleStyle: "H2", wrapping: true})], + snappedContent: [this.getLabel("Filtered 1042 items based on 'unknown' criteria")], + actions: [ + new sap.m.ToolbarSpacer(), + oToggleFooterButton, + new sap.m.Button({ + icon: "sap-icon://add", + tooltip: "add" + }), + new sap.m.Button({ + icon: "sap-icon://edit", + tooltip: "edit" + }), + new sap.m.Button({ + icon: "sap-icon://delete", + tooltip: "delete" + }) + ] + }); + }, + getFooter: function() { + return new sap.m.OverflowToolbar({ + content: [ + new sap.m.ToolbarSpacer(), + new sap.m.Button({ + text: "Accept", + type: "Accept" + }), + new sap.m.Button({ + text: "Reject", + type: "Reject" + }) + ] + }); + }, + getDynamicPage: function(bPreserveHeader, oTitle, oHeader, oContent, oFooter) { + return new sap.f.DynamicPage({ + preserveHeaderStateOnScroll: bPreserveHeader, + title: oTitle, + header: oHeader, + content: oContent, + footer: oFooter + }); + }, + getDynamicPageWithStickyHeader: function(bPreserveHeader, oTitle, oHeader, oContent, oFooter, oStickyHeaderProvider) { + return new sap.f.DynamicPage({ + preserveHeaderStateOnScroll: bPreserveHeader, + stickySubheaderProvider: oStickyHeaderProvider.getId(), + title: oTitle, + header: oHeader, + content: oContent, + footer: oFooter + }); + } + }; +}()); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005668_app.js b/pool/shard000/JavaScript/0005668_app.js new file mode 100644 index 0000000000000000000000000000000000000000..75fd3b4a09b2e6b29a3945252f35ada520327ff0 --- /dev/null +++ b/pool/shard000/JavaScript/0005668_app.js @@ -0,0 +1,68 @@ +'use strict'; + +var digApp = angular.module('digApp', [ + 'ngCookies', + 'ngResource', + 'ngSanitize', + 'ui.router', + 'ui.bootstrap', + 'elasticui', + 'digApp.directives', + 'digApp.services' +]) +.config(function($stateProvider, $urlRouterProvider, $locationProvider) { + $urlRouterProvider + .otherwise('/list'); + + $locationProvider.html5Mode(true); +}); + +angular.module('digApp.directives', []); +angular.module('digApp.services', []); + +angular.element(document).ready(function() { + var $http = angular.injector(['ng']).get('$http'); + + $http.get('/config') + .success(function(config) { + var euiHost = (config.euiHost || 'localhost') + ':' + (config.euiPort || 9200); + digApp.constant('euiHost', euiHost); + + var euiSearchIndex = (config.euiSearchIndex || 'dig'); + digApp.constant('euiSearchIndex', euiSearchIndex); + + var euiConfigs = (config.euiConfigs || { + facets: [], + listFields: [], + detailFields: [] + }); + digApp.constant('euiConfigs', euiConfigs); + + var simHost = (config.simHost || 'localhost') + ':' + (config.simPort || 3001); + digApp.constant('simHost', simHost); + + var blurImagesEnabled = (config.blurImagesEnabled !== undefined ? config.blurImagesEnabled : true); + digApp.constant('blurImagesEnabled', blurImagesEnabled); + + var blurImagesPercentage = config.blurImagesPercentage || 10; + digApp.constant('blurImagesPercentage', blurImagesPercentage); + + var appVersion = config.appVersion; + digApp.constant('appVersion', appVersion); + + angular.bootstrap(document, ['digApp']); + }) + .error(function() { + digApp.constant('euiHost', 'http://localhost:9200'); + digApp.constant('euiSearchIndex', 'dig'); + digApp.constant('euiConfigs', { + facets: [], + listFields: [], + detailFields: [] + }); + digApp.constant('simHost', 'http://localhost:3001'); + digApp.constant('blurImagesEnabled', true); + digApp.constant('blurImagesPercentage', 5); + digApp.constant('appVersion', '0.0.0'); + }); +}); diff --git a/pool/shard000/JavaScript/0005671_RoomBooking.js b/pool/shard000/JavaScript/0005671_RoomBooking.js new file mode 100644 index 0000000000000000000000000000000000000000..5c59247a24fc823eebd2a035d8fe8a8da8f19339 --- /dev/null +++ b/pool/shard000/JavaScript/0005671_RoomBooking.js @@ -0,0 +1,47 @@ +/* This file is part of Indico. + * Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). + * + * Indico 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. + * + * Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. + */ + +type("RoomListWidget", ["ListWidget"], + { + _drawItem: function(room) { + var self = this; + var roomData = room.get(); + + var removeButton = Widget.link(command(function() { + self.removeProcess(room.key, function(result) { + if (result) { + self.set(room, null); + } + }); + }, IndicoUI.Buttons.removeButton())); + return Html.div({style:{display: 'inline'}}, + Html.span({}, + Html.div({style: {cssFloat: "right", paddingRight: "10px"}},removeButton), + $B(Html.span(), self.useValue ? roomData : room.key) + )); + } + }, + + function(style, removeProcess, useValue) { + this.removeProcess = removeProcess; + this.useValue = useValue || false; + if (!exists(style)) { + style = "user-list"; + } + this.ListWidget(style); + } +); diff --git a/pool/shard000/JavaScript/0005673_InputTrigger.js b/pool/shard000/JavaScript/0005673_InputTrigger.js new file mode 100644 index 0000000000000000000000000000000000000000..6efd8ffb01c1e87acc657acf7d49d6e7d6bffa07 --- /dev/null +++ b/pool/shard000/JavaScript/0005673_InputTrigger.js @@ -0,0 +1,57 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; + +class InputTrigger extends Component { + static propTypes = { + prefixCls: PropTypes.string, + value: PropTypes.any, + placeholder: PropTypes.string, + onChange: PropTypes.func, + onClick: PropTypes.func, + keyword: PropTypes.string, + text: PropTypes.string, + }; + state = { + value: '', + }; + + componentDidMount() { + this.props.onChange({ + extraFilter: true, + }); + } + + componentWillReceiveProps(nextProps) { + this.setState({ + value: nextProps.keyword === null ? nextProps.value : nextProps.keyword, + }); + } + + shouldComponentUpdate(nextProps, nextState) { + return nextState.value !== this.state.value; + } + + inputChangeHandler = ev => { + this.props.onChange({ + keyword: ev.target.value, + }); + }; + + render() { + const { prefixCls, placeholder, keyword, text } = this.props; + + return ( + <input + ref={input => (this.input = input)} + className={`${prefixCls}-input`} + placeholder={placeholder} + type="text" + value={keyword === null ? text : keyword} + onChange={this.inputChangeHandler} + onClick={this.props.onClick} + /> + ); + } +} + +export default InputTrigger; diff --git a/pool/shard000/JavaScript/0005674_main.js b/pool/shard000/JavaScript/0005674_main.js new file mode 100644 index 0000000000000000000000000000000000000000..bcd98a3e9554ddf8a699a72ad0fd9f7555958a0b --- /dev/null +++ b/pool/shard000/JavaScript/0005674_main.js @@ -0,0 +1,84 @@ +$.extend($.tablesorter.themes.bootstrap, { + // these classes are added to the table. To see other table classes available, + // look here: http://twitter.github.com/bootstrap/base-css.html#tables + table: 'table table-bordered', + caption: 'caption', + header: 'bootstrap-header', // give the header a gradient background + footerRow: '', + footerCells: '', + icons: '', // add "icon-white" to make them white; this icon class is added to the <i> in the header + sortNone: 'fa fa-sort', + sortAsc: 'icon-chevron-up fa fa-sort-up', // includes classes for Bootstrap v2 & v3 + sortDesc: 'icon-chevron-down fa fa-sort-down', // includes classes for Bootstrap v2 & v3 + active: '', // applied when column is sorted + hover: '', // use custom css here - bootstrap class may not override it + filterRow: '', // filter row class + even: '', // odd row zebra striping + odd: '' // even row zebra striping +}); + +$(function () { + $("table.tablesorter").tablesorter({ + theme: "bootstrap", + headerTemplate: '{content} {icon}', + //widthFixed: true, + + widgets: [ "uitheme", "filter", "zebra" ], + widgetOptions: { + // using the default zebra striping class name, so it actually isn't included in the theme variable above + // this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden + zebra: ["even", "odd"] + } + }); + + $(document).on("click", "tbody.expand tr, table:has(tbody.expand) thead", function (e) { + + var info_box = $("tr#" + $(this).data('id')); + var was_hidden = (info_box.css('display')=='none') ; + console.log(was_hidden); + info_box.insertAfter(this); + $("tr.info").css('display', 'none'); + $("td.time").attr('rowspan', 1); + if (was_hidden) { + info_box.removeClass('filtered'); + info_box.css('display', 'table-row'); + $($(this).children()[0]).attr('rowspan', 2); + } + }) + + $('#myTable.infinite').infiniteScrollHelper({ + bottomBuffer: 10, + loadMore: function(page, done) { + // you should use the page argument to either select an anchor/href and load + // the contents of that url or make a call to an API that accepts a page number + + $.ajax({ + url: '/more', + type: 'POST', + data: { + page: page, + loadTime: $("#loadTime").data('time') + }, + success: function (data) { + $(data).appendTo("#table_body"); + console.log("loaded page" + page); + + done(); + } + }); + + /*$.get('/more', function(data) { + $(data).find('.items').appendTo('#my-element-to-watch'); + // call the done callback to let the plugin know you are done loading + done(); + }); + + // or an API perhaps + $.getJSON('http://myawesomeapi.com/data?p=' + page, function(data) { + // parse json data and create new html then append + + done(); + });*/ + } + }); +}); diff --git a/pool/shard000/JavaScript/0005677_content.js b/pool/shard000/JavaScript/0005677_content.js new file mode 100644 index 0000000000000000000000000000000000000000..f3431c1a97d62e8688ddeb388f75ae8a66e13a58 --- /dev/null +++ b/pool/shard000/JavaScript/0005677_content.js @@ -0,0 +1,79 @@ + +// enumeration of content types +var CONTENT_SUB_HEADER = 1; +var CONTENT_PARA_HEADER = 2; +var CONTENT_TEXT = 3; +var CONTENT_PREFORMATTED = 4; +var CONTENT_TABLE = 5; +var CONTENT_PLOT = 6; +var CONTENT_PLOT_TABLE = 7; +var CONTENT_BREAK = 8; + +function display_content (content) { + var display = $("#content"); + display.empty(); + var title = $("#title"); + title.empty(); + title.text(content.title); + var selection = $("#selectSection"); + selection.empty(); + var sections = content.sections; + display.data(sections); + for (var i_section = 0; i_section < sections.length; i_section++) { + console.log(sections[i_section].title); + selection.append($("<option/>").val(i_section).text( + sections[i_section].title)); + } + selection.change(function () { + var i_section = parseInt($("#selectSection").val()); + display_section(i_section); + }); + display_section(0); +} + +function display_section (i_section) { + var display = $("#content"); + display.empty(); + all_content = display.data(); + var section = all_content[i_section]; + display.append($("<h3/>").text(section.title)); + display.append($("<hr/>")); + i_graph = 0; + for (var i_content = 0; i_content < section.content.length; i_content++) { + var block = section.content[i_content]; + if (block.content_type == CONTENT_SUB_HEADER) { + display.append($("<h4/>").text(block.content)); + } else if (block.content_type == CONTENT_PARA_HEADER) { + display.append($("<h5/>").text(block.content)); + } else if (block.content_type == CONTENT_TEXT) { + display.append($("<p/>").text(block.content)); + } else if (block.content_type == CONTENT_PREFORMATTED) { + display.append($("<pre/>").text(block.content)); + } else if (block.content_type == CONTENT_TABLE) { + console.log("TABLE"); + var table = $("<table/>").attr("class", "data_display"); + for (var i_row = 0; i_row < block.content.rows.length; i_row++) { + var row = block.content.rows[i_row]; + var tr = $("<tr/>"); + table.append(tr); + if (i_row == 0) { + tr.attr("class", "header"); + } else { + tr.attr("class", "content"); + } + for (var i_col = 0; i_col < row.length; i_col++) { + tr.append($("<td/>").text(row[i_col]).attr("class", "data_cell")); + } + } + display.append(table); + } else if (block.content_type == CONTENT_PLOT) { + var graph_id = "graph" + i_graph; + display.append($("<div/>").attr("id", graph_id).attr("class", + "loggraph")); + var graph = new xtal.loggraph.Loggraph("#" + graph_id, [ block.content ], i_graph, + true); + i_graph++; + display.append($("<br/>")); + } + } +} diff --git a/pool/shard000/JavaScript/0005678_server.js b/pool/shard000/JavaScript/0005678_server.js new file mode 100644 index 0000000000000000000000000000000000000000..4c5c94bbd0e38043f9db04b31697fcfd47d20fb5 --- /dev/null +++ b/pool/shard000/JavaScript/0005678_server.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const express = require("express"); +const app = express(); +app.get("/", function (req, res) { + res.end("hello, world"); +}); +app.listen(3000, function () { + console.log("server is listening"); +}); +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005682_CorporatesApi.spec.js b/pool/shard000/JavaScript/0005682_CorporatesApi.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..33394de79b05bffab09faf0f70bfcac04c730a52 --- /dev/null +++ b/pool/shard000/JavaScript/0005682_CorporatesApi.spec.js @@ -0,0 +1,153 @@ +/** + * Open Payments Cloud Application API + * Open Payments Cloud API + * + * OpenAPI spec version: 1.0.0 + * + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenPaymentsCloudApplicationApi); + } +}(this, function(expect, OpenPaymentsCloudApplicationApi) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenPaymentsCloudApplicationApi.CorporatesApi(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('CorporatesApi', function() { + describe('corporatesIdCreate', function() { + it('should call corporatesIdCreate successfully', function(done) { + //uncomment below and update the code to test corporatesIdCreate + //instance.corporatesIdCreate(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesIdGet', function() { + it('should call corporatesIdGet successfully', function(done) { + //uncomment below and update the code to test corporatesIdGet + //instance.corporatesIdGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesIdUpdate', function() { + it('should call corporatesIdUpdate successfully', function(done) { + //uncomment below and update the code to test corporatesIdUpdate + //instance.corporatesIdUpdate(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesProfilesGet', function() { + it('should call corporatesProfilesGet successfully', function(done) { + //uncomment below and update the code to test corporatesProfilesGet + //instance.corporatesProfilesGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesProfilesIdGet', function() { + it('should call corporatesProfilesIdGet successfully', function(done) { + //uncomment below and update the code to test corporatesProfilesIdGet + //instance.corporatesProfilesIdGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesUsersGet', function() { + it('should call corporatesUsersGet successfully', function(done) { + //uncomment below and update the code to test corporatesUsersGet + //instance.corporatesUsersGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesUsersIdActivate', function() { + it('should call corporatesUsersIdActivate successfully', function(done) { + //uncomment below and update the code to test corporatesUsersIdActivate + //instance.corporatesUsersIdActivate(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesUsersIdCreate', function() { + it('should call corporatesUsersIdCreate successfully', function(done) { + //uncomment below and update the code to test corporatesUsersIdCreate + //instance.corporatesUsersIdCreate(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesUsersIdGet', function() { + it('should call corporatesUsersIdGet successfully', function(done) { + //uncomment below and update the code to test corporatesUsersIdGet + //instance.corporatesUsersIdGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('corporatesUsersIdUpdate', function() { + it('should call corporatesUsersIdUpdate successfully', function(done) { + //uncomment below and update the code to test corporatesUsersIdUpdate + //instance.corporatesUsersIdUpdate(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/pool/shard000/JavaScript/0005684_redisConfig.js b/pool/shard000/JavaScript/0005684_redisConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..4041982aa7136acf1215d55e96f1cdf81f238a03 --- /dev/null +++ b/pool/shard000/JavaScript/0005684_redisConfig.js @@ -0,0 +1,111 @@ +/** + * Copyright (c) 2017, salesforce.com, inc. + * All rights reserved. + * Licensed under the BSD 3-Clause license. + * For full license text, see LICENSE.txt file in the repo root or + * https://opensource.org/licenses/BSD-3-Clause + */ + +/** + * ./config/redisConfig.js + * + * Assigns each of the different redis uses cases to a particular redis + * instance, if configured, or falls back to the primary redis instance. + */ +'use strict'; // eslint-disable-line strict +const pe = process.env; // eslint-disable-line no-process-env +const DEFAULT_LOCAL_REDIS_URL = '//127.0.0.1:6379'; +const PRIMARY_REDIS = (pe.REDIS_URL || DEFAULT_LOCAL_REDIS_URL); +const perspectiveChannelName = 'focus'; +const botChannelName = 'imc'; + +let pubsubPerspectives = [PRIMARY_REDIS]; +if (pe.REDIS_PUBSUB_PERSPECTIVES) { + const arr = pe.REDIS_PUBSUB_PERSPECTIVES.split(',') + .map((r) => r.trim()) + .filter((r) => pe[r]) + .map((r) => pe[r]); + if (arr.length > 0) { + pubsubPerspectives = arr; + } +} + +module.exports = { + perspectiveChannelName, + botChannelName, + instanceUrl: { + /* + * Cache perspectives, lenses, etc. + */ + cache: pe.REDIS_CACHE && pe[pe.REDIS_CACHE] ? + pe[pe.REDIS_CACHE] : PRIMARY_REDIS, + + /* + * Used for coordinating clock job timing + */ + clock: pe.REDIS_CLOCK && pe[pe.REDIS_CLOCK] ? + pe[pe.REDIS_CLOCK] : PRIMARY_REDIS, + + /* + * Track generator changes to be sent in collector heartbeat response. + */ + heartbeat: pe.REDIS_HEARTBEAT && pe[pe.REDIS_HEARTBEAT] ? + pe[pe.REDIS_HEARTBEAT] : PRIMARY_REDIS, + + /* + * Keys for tracking rate limiter activity + */ + limiter: pe.REDIS_LIMITER && pe[pe.REDIS_LIMITER] ? + pe[pe.REDIS_LIMITER] : PRIMARY_REDIS, + + /* + * Array of redis instance url(s) for pubsub for perspective real-time + * events. + */ + pubsubPerspectives, + + /* + * PubSub for bots real-time events. + */ + pubsubBots: pe.REDIS_PUBSUB_BOTS && pe[pe.REDIS_PUBSUB_BOTS] ? + pe[pe.REDIS_PUBSUB_BOTS] : PRIMARY_REDIS, + + /* + * Kue job queue for work being delegated to worker dynos. + */ + queue: pe.REDIS_QUEUE && pe[pe.REDIS_QUEUE] ? + pe[pe.REDIS_QUEUE] : PRIMARY_REDIS, + + /* + * Transient data about socket connections from browsers with an open + * perspective, for logging activity=realtime. + */ + realtimeLogging: pe.REDIS_REALTIME_LOGGING && + pe[pe.REDIS_REALTIME_LOGGING] ? pe[pe.REDIS_REALTIME_LOGGING] : + PRIMARY_REDIS, + + /* + * SampleStore is the primary persistent store for samples, and an active + * cache for aspects and subjects. + */ + sampleStore: pe.REDIS_SAMPLE_STORE && pe[pe.REDIS_SAMPLE_STORE] ? + pe[pe.REDIS_SAMPLE_STORE] : PRIMARY_REDIS, + + /* + * Active browser sessions. + */ + session: pe.REDIS_SESSION && pe[pe.REDIS_SESSION] ? + pe[pe.REDIS_SESSION] : PRIMARY_REDIS, + }, + retryStrategy: { + /* Number of times to attempt to reconnect. Default 100. */ + attempt: +pe.REDIS_RETRY_ATTEMPT || 100, + + backoffFactor: +pe.REDIS_RETRY_BACKOFF_FACTOR || 100, + + backoffMax: +pe.REDIS_RETRY_BACKOFF_MAX || 3000, + + /* Time since the last successful connection. Default one hour. */ + totalRetryTime: +pe.REDIS_RETRY_TOTAL_RETRY_TIME || 3600000, + }, +}; diff --git a/pool/shard000/JavaScript/0005685_ember.js b/pool/shard000/JavaScript/0005685_ember.js new file mode 100644 index 0000000000000000000000000000000000000000..f1fde9e687d8efafcdba02847a21336bba43bd4b --- /dev/null +++ b/pool/shard000/JavaScript/0005685_ember.js @@ -0,0 +1,59 @@ +/*! Raven.js 3.22.2 (1b6187b) | github.com/getsentry/raven-js */ + +/* + * Includes TraceKit + * https://github.com/getsentry/TraceKit + * + * Copyright 2018 Matt Robenolt and other contributors + * Released under the BSD license + * https://github.com/getsentry/raven-js/blob/master/LICENSE + * + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Raven = global.Raven || {}, global.Raven.Plugins = global.Raven.Plugins || {}, global.Raven.Plugins.Ember = factory()); +}(this, (function () { 'use strict'; + +/** + * Ember.js plugin + * + * Patches event handler callbacks and ajax callbacks. + */ +function emberPlugin(Raven, Ember) { + Ember = Ember || window.Ember; // quit if Ember isn't on the page + + if (!Ember) return; + var _oldOnError = Ember.onerror; + + Ember.onerror = function EmberOnError(error) { + Raven.captureException(error); + + if (typeof _oldOnError === 'function') { + _oldOnError.call(this, error); + } + }; + + Ember.RSVP.on('error', function (reason) { + if (reason instanceof Error) { + Raven.captureException(reason, { + extra: { + context: 'Unhandled Promise error detected' + } + }); + } else { + Raven.captureMessage('Unhandled Promise error detected', { + extra: { + reason: reason + } + }); + } + }); +} + +var ember = emberPlugin; + +return ember; + +}))); diff --git a/pool/shard000/JavaScript/0005686_client.js b/pool/shard000/JavaScript/0005686_client.js new file mode 100644 index 0000000000000000000000000000000000000000..fd9ec8a28d11d03f3c2cf9f9de83237f878d3694 --- /dev/null +++ b/pool/shard000/JavaScript/0005686_client.js @@ -0,0 +1,82 @@ +/* */ +var util = require("util"), + net = require("net"), + tls = require("tls"), + crypto = require("crypto"), + url = require("url"), + driver = require("websocket-driver"), + API = require("./api"), + Event = require("./api/event"); +var DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443, + 'ws:': 80, + 'wss:': 443 +}, + SECURE_PROTOCOLS = ['https:', 'wss:']; +var Client = function(_url, protocols, options) { + options = options || {}; + this.url = _url; + this._driver = driver.client(this.url, { + maxLength: options.maxLength, + protocols: protocols + }); + ['open', 'error'].forEach(function(event) { + this._driver.on(event, function() { + self.headers = self._driver.headers; + self.statusCode = self._driver.statusCode; + }); + }, this); + var proxy = options.proxy || {}, + endpoint = url.parse(proxy.origin || this.url), + port = endpoint.port || DEFAULT_PORTS[endpoint.protocol], + secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0, + onConnect = function() { + self._onConnect(); + }, + originTLS = options.tls || {}, + socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS, + self = this; + originTLS.ca = originTLS.ca || options.ca; + this._stream = secure ? tls.connect(port, endpoint.hostname, socketTLS, onConnect) : net.connect(port, endpoint.hostname, onConnect); + if (proxy.origin) + this._configureProxy(proxy, originTLS); + API.call(this, options); +}; +util.inherits(Client, API); +Client.prototype._onConnect = function() { + var worker = this._proxy || this._driver; + worker.start(); +}; +Client.prototype._configureProxy = function(proxy, originTLS) { + var uri = url.parse(this.url), + secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0, + self = this, + name; + this._proxy = this._driver.proxy(proxy.origin); + if (proxy.headers) { + for (name in proxy.headers) + this._proxy.setHeader(name, proxy.headers[name]); + } + this._proxy.pipe(this._stream, {end: false}); + this._stream.pipe(this._proxy); + this._proxy.on('connect', function() { + if (secure) { + var options = { + socket: self._stream, + servername: uri.hostname + }; + for (name in originTLS) + options[name] = originTLS[name]; + self._stream = tls.connect(options); + self._configureStream(); + } + self._driver.io.pipe(self._stream); + self._stream.pipe(self._driver.io); + self._driver.start(); + }); + this._proxy.on('error', function(error) { + self._driver.emit('error', error); + }); +}; +module.exports = Client; diff --git a/pool/shard000/JavaScript/0005693_App.js b/pool/shard000/JavaScript/0005693_App.js new file mode 100644 index 0000000000000000000000000000000000000000..1a39d360f01d00569d33e1a79a193f754be5755e --- /dev/null +++ b/pool/shard000/JavaScript/0005693_App.js @@ -0,0 +1,149 @@ +/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ + +import './App.less'; +import React, { PropTypes } from 'react'; +import AppActions from '../../actions/AppActions'; +import AppStore from '../../stores/AppStore'; +import Header from '../Header'; +import ContentPage from '../ContentPage'; +import ContactPage from '../ContactPage'; +import EX2Browser from '../EX2Browser'; +import LoginPage from '../LoginPage'; +import RegisterPage from '../RegisterPage'; +import NotFoundPage from '../NotFoundPage'; +import Feedback from '../Feedback'; +import Footer from '../Footer'; +import setViewport from './setViewport'; + +const pages = { ContentPage, ContactPage, LoginPage, RegisterPage, NotFoundPage }; + +class App { + + static propTypes = { + path: PropTypes.string.isRequired, + viewport: PropTypes.object.isRequired, + onSetTitle: PropTypes.func.isRequired, + onSetMeta: PropTypes.func.isRequired, + onPageNotFound: PropTypes.func.isRequired + }; + + componentDidMount() { + window.addEventListener('popstate', this.handlePopState); + window.addEventListener('click', this.handleClick); + } + + componentWillUnmount() { + window.removeEventListener('popstate', this.handlePopState); + window.removeEventListener('click', this.handleClick); + } + + shouldComponentUpdate(nextProps) { + return this.props.path !== nextProps.path || + this.props.viewport !== nextProps.viewport; + } + + render() { + switch (this.props.path) { + + case '/contact': + this.props.onSetTitle(ContactPage.title); + this.component = <ContactPage />; + break; + + case '/test1': + this.props.onSetTitle('test 1'); + this.component = <EX2Browser />; + break; + + case '/login': + this.props.onSetTitle(LoginPage.title); + this.component = <LoginPage />; + break; + + case '/register': + this.props.onSetTitle(RegisterPage.title); + this.component = <RegisterPage />; + break; + + default: + let page = AppStore.getPage(this.props.path); + if (page) { + this.props.onSetTitle(page.title); + this.component = React.createElement(pages[page.component], page); + } else { + this.props.onSetTitle(NotFoundPage.title); + this.props.onPageNotFound(); + this.component = <NotFoundPage />; + } + } + + return ( + <div> + <Header /> + {this.component} + <Feedback /> + <Footer viewport={this.props.viewport} /> + </div> + ); + } + + handlePopState(event) { + AppActions.navigateTo(window.location.pathname, {replace: !!event.state}); + } + + handleClick(event) { + if (event.button === 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.defaultPrevented) { + return; + } + + // Ensure link + var el = event.target; + while (el && el.nodeName !== 'A') { + el = el.parentNode; + } + if (!el || el.nodeName !== 'A') { + return; + } + + // Ignore if tag has + // 1. "download" attribute + // 2. rel="external" attribute + if (el.getAttribute('download') || el.getAttribute('rel') === 'external') { + return; + } + + // Ensure non-hash for the same path + var link = el.getAttribute('href'); + if (el.pathname === location.pathname && (el.hash || link === '#')) { + return; + } + + // Check for mailto: in the href + if (link && link.indexOf('mailto:') > -1) { + return; + } + + // Check target + if (el.target) { + return; + } + + // X-origin + var origin = window.location.protocol + '//' + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + if (!(el.href && el.href.indexOf(origin) === 0)) { + return; + } + + // Rebuild path + var path = el.pathname + el.search + (el.hash || ''); + + event.preventDefault(); + AppActions.loadPage(path, () => { + AppActions.navigateTo(path); + }); + } + +} + +export default setViewport(App); diff --git a/pool/shard000/JavaScript/0005694_QuaternionKeyframeTrack.js b/pool/shard000/JavaScript/0005694_QuaternionKeyframeTrack.js new file mode 100644 index 0000000000000000000000000000000000000000..1471e712d8c2f70eec2a1a1ecae952496c32f396 --- /dev/null +++ b/pool/shard000/JavaScript/0005694_QuaternionKeyframeTrack.js @@ -0,0 +1,52 @@ +import { Quaternion } from '../../math/Quaternion.js'; +import { KeyframeTrack } from './KeyframeTrack.js'; + +/** + * Used for quaternion property track. + * @constructor + * @memberof zen3d + * @param {zen3d.Object3D} target + * @param {string} propertyPath + * @param {Array} times + * @param {Array} values + * @param {Boolean} interpolant + */ +function QuaternionKeyframeTrack(target, propertyPath, times, values, interpolant) { + KeyframeTrack.call(this, target, propertyPath, times, values, interpolant); +} + +QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), { + + constructor: QuaternionKeyframeTrack, + + valueTypeName: 'quaternion', + + getValue: function(t, outBuffer) { + var index = this._getLastTimeIndex(t), + times = this.times, + values = this.values, + key1 = times[index], + key2 = times[index + 1], + i = 0; + + if (this.interpolant) { + if (key2 !== undefined) { + var ratio = (t - key1) / (key2 - key1); + Quaternion.slerpFlat(outBuffer, 0, values, index * 4, values, (index + 1) * 4, ratio); + } else { + // just copy + for (i = 0; i < 4; i++) { + outBuffer[i] = values[index * 4 + i]; + } + } + } else { + // just copy + for (i = 0; i < 4; i++) { + outBuffer[i] = values[index * 4 + i]; + } + } + } + +}); + +export { QuaternionKeyframeTrack }; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005695_salary_work_time_model.js b/pool/shard000/JavaScript/0005695_salary_work_time_model.js new file mode 100644 index 0000000000000000000000000000000000000000..1c3384964af35fe819cbe7e2dfa86a50352ef70a --- /dev/null +++ b/pool/shard000/JavaScript/0005695_salary_work_time_model.js @@ -0,0 +1,71 @@ +const R = require("ramda"); +const DataLoader = require("dataloader"); +const { salarySchema } = require("./common_schemas"); +class SalaryWorkTimeModel { + constructor(manager) { + this.manager = manager; + this.collection = manager.db.collection("workings"); + + this.byCompanyLoader = new DataLoader(async names => { + const salaryWorkTimes = await this.findByCompanyNames(names); + + const toGroup = R.groupBy(x => x.company.name); + const group = toGroup(salaryWorkTimes); + const results = R.pipe( + R.flip(R.props)(group), + R.map(R.defaultTo([])) + )(names); + + return results; + }); + + this.byJobTitleLoader = new DataLoader(async job_titles => { + const salaryWorkTimes = await this.findByJobTitles(job_titles); + + const toGroup = R.groupBy(x => x.job_title); + const group = toGroup(salaryWorkTimes); + const results = R.pipe( + R.flip(R.props)(group), + R.map(R.defaultTo([])) + )(job_titles); + + return results; + }); + } + + async findByCompanyNames(names) { + // 特殊 find,為了給 dataloader 用 + return await this.collection + .find({ + status: "published", + "archive.is_archived": false, + "company.name": { $in: names }, + }) + .sort({ created_at: -1 }) + .toArray(); + } + + async findByJobTitles(job_titles) { + // 特殊 find,為了給 dataloader 用 + return await this.collection + .find({ + status: "published", + "archive.is_archived": false, + job_title: { $in: job_titles }, + }) + .sort({ created_at: -1 }) + .toArray(); + } + + async createSalaryWorkTime(salaryWorkTime) { + if (salaryWorkTime && salaryWorkTime.salary) { + const result = salarySchema.validate(salaryWorkTime.salary); + if (result.error) { + throw result.error; + } + } + return await this.collection.insertOne(salaryWorkTime); + } +} + +module.exports = SalaryWorkTimeModel; diff --git a/pool/shard000/JavaScript/0005696_ng-django-urls.js b/pool/shard000/JavaScript/0005696_ng-django-urls.js new file mode 100644 index 0000000000000000000000000000000000000000..d196e235817df02a10cafb0cd16cdb70199b0ecf --- /dev/null +++ b/pool/shard000/JavaScript/0005696_ng-django-urls.js @@ -0,0 +1,104 @@ +(function (angular, undefined) { + 'use strict'; + /* + module: ng.django.urls + Provide url reverse resolution functionality for django urls in angular + Usage: djangoUrl.reverse(url_name, args_or_kwargs) + + Examples: + - djangoUrl.reverse('home', [user_id: 2]); + - djangoUrl.reverse('home', [2]); + */ + var djngUrls = angular.module('ng.django.urls', []); + + djngUrls.provider('djangoUrl', function djangoUrlProvider() { + var reverseUrl = '/angular/reverse/'; + + this.setReverseUrl = function (url) { + reverseUrl = url; + }; + + this.$get = function () { + return new djangoUrl(reverseUrl); + } + } + ); + + var djangoUrl = function (reverseUrl) { + /* + Url-reversing service + */ + + //Functions from angular.js source, not public available + //See: https://github.com/angular/angular.js/issues/7429 + function forEachSorted(obj, iterator, context) { + var keys = sortedKeys(obj); + for (var i = 0; i < keys.length; i++) { + iterator.call(context, obj[keys[i]], keys[i]); + } + return keys; + } + + function sortedKeys(obj) { + var keys = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys.push(key); + } + } + return keys.sort(); + } + + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function (value, key) { + if (value === null || value === undefined) return; + if (angular.isObject(value)) { + value = angular.toJson(value); + } + parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + }); + return url + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); + } + + // Service public interface + this.reverse = function (url_name, args_or_kwargs) { + var url = buildUrl(reverseUrl, {djng_url_name: url_name}); + /* + Django wants arrays in query params encoded the following way: a = [1,2,3] -> ?a=1&a=2$a=3 + buildUrl function doesn't natively understand lists in params, so in case of a argument array + it's called iteratively, adding a single parameter with each call + + url = buildUrl(url, {a:1}) -> returns /url?a=1 + url = buildUrl(url, {a:2}) -> returns /url?a=1&a=2 + ... + */ + if (Array.isArray(args_or_kwargs)) { + forEachSorted(args_or_kwargs, function (value) { + url = buildUrl(url, {'djng_url_args': value}); + }); + return url; + } + /* + If there's a object of keyword arguments, a 'djng_url_kwarg_' prefix is prepended to each member + Then we can directly call the buildUrl function + */ + var params = {}; + forEachSorted(args_or_kwargs, function (value, key) { + params['djng_url_kwarg_' + key] = value; + }); + /* + If params is empty (no kwargs passed) return url immediately + Calling buildUrl with empty params object adds & or ? at the end of query string + E.g. buldUrl('/url/djng_url_name=home', {}) -> /url/djng_url_name=home& + */ + if (angular.equals(params, {})) { // If params is empty, no kwargs passed. + return url; + } + return buildUrl(url, params); + }; + }; + +}(window.angular)); + diff --git a/pool/shard000/JavaScript/0005699_join.js b/pool/shard000/JavaScript/0005699_join.js new file mode 100644 index 0000000000000000000000000000000000000000..9b470fb434c721da2dd5c279a4cbce0beaa73731 --- /dev/null +++ b/pool/shard000/JavaScript/0005699_join.js @@ -0,0 +1,30 @@ +var bot; + +module.exports.name = "sirc-joinchannel"; + +module.exports.init = function(b) { + bot = b; + channels = []; + bot.readDataFile('channels.txt', function(err, data) { + if(err) return console.log(err); + data.toString().split("\n").forEach(function(channel) { + if(channel.length > 0) { + bot.client.join(channel); + } + }); + }); +}; + +/* This simple module is partially meant to + * show off the {name: function} dict that + * can be used by a module to define commands + */ +module.exports.commands = { + join: function(channel) { + bot.client.join(channel); + bot.appendDataFile("channels.txt", channel + "\n", function(err) { + if(err) console.log(err); + }); + } +}; + diff --git a/pool/shard000/JavaScript/0005703_misc.js b/pool/shard000/JavaScript/0005703_misc.js new file mode 100644 index 0000000000000000000000000000000000000000..1096b6b3595087ce1d4a631d71cac587adc5d016 --- /dev/null +++ b/pool/shard000/JavaScript/0005703_misc.js @@ -0,0 +1,18 @@ +var util = require('../lib/util') + +module.exports = function (app) { + app.all('*', function (req, res, next) { + res.header('Access-Control-Allow-Origin', '*') + res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS') + res.header('Access-Control-Allow-Headers', 'Content-Type') + next() + }) + + app.get('/api/v1/context_all.jsonld', function (req, res) { + res.type('application/ld+json') + res.status(200).send(JSON.stringify({ '@context': util.context }, null, 2)) + return + }) + +// other routes.. +} diff --git a/pool/shard000/JavaScript/0005705_mozdef.js b/pool/shard000/JavaScript/0005705_mozdef.js new file mode 100644 index 0000000000000000000000000000000000000000..bf32963ea06ff073d7b42b5b6c5549b6f825c1f2 --- /dev/null +++ b/pool/shard000/JavaScript/0005705_mozdef.js @@ -0,0 +1,166 @@ +/* +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) 2014 Mozilla Corporation + +Contributors: +Jeff Bryner jbryner@mozilla.com +Anthony Verez averez@mozilla.com + */ + +if (Meteor.isClient) { + //defaults: + Meteor.startup(function () { + Session.set('verisfilter',''); + Session.set('alertsearchtext',''); + Session.set('attackerlimit','10'); + }); + + //helper functions for UI templates + //and other client javascript routines + dateOrNull=function(maybeDate){ + adate=moment(maybeDate); + if (adate.isValid()) { + return adate.toDate(); + }else{ + return null; + } + }; + + dateFormat=function(adate){ + mdate=moment(adate || null); + if (mdate.isValid()) { + dformat='MM/DD/YYYY hh:mm:ss A'; + return mdate.format(dformat); + }else{ + return ''; + } + }; + + //debug/testing functions + debugLog=function(logthis){ + if (typeof console !== 'undefined') { + console.log(logthis); + } + }; + + Template.hello.greeting = function () { + if (typeof console !== 'undefined') + console.log("mozdef starting"); + return "MozDef: the Mozilla defense platform"; + }; + + Template.hello.events({ + 'click' : function () { + // template data, if any, is available in 'this' + Session.set('displayMessage', 'Welcome & to mozdef.') + } + }); + + // loads kibana dashboards + Template.menu.kibanadashboards = function() { + Meteor.call('loadKibanaDashboards'); + return kibanadashboards.find(); + }; + + UI.registerHelper('uiDateFormat',function(adate){ + return dateFormat(adate); + }); + + //helper functions for handlebars + UI.registerHelper('now', function() { + return new Date(); + }); + + UI.registerHelper('mozdef',function(){ + //return the mozdef server settings object. + return mozdef + }); + + + UI.registerHelper('getAlertURL', function(alertid){ + //could be mongo id or es id + //assume mongo + if ( alerts.find({'_id':alertid}).count() >0 ){ + id=alerts.findOne({'_id':alertid}).esmetadata.id; + return(getSetting('rootURL') + '/alert/' + id); + }else{ + return(getSetting('rootURL') + '/alert/' + alertid); + } + }); + + UI.registerHelper('isselected',function(optionvalue,datavalue){ + if (optionvalue==datavalue){ + return 'selected' + }else{ + return '' + } + }); + + UI.registerHelper('eachSorted',function(context,options){ + var ret = ""; + + for(var i=0, j=context.length; i<j; i++) { + ret = ret + options.fn(context.sort()[i]); + } + + return ret; + }); + + UI.registerHelper('isEqual', function (var1,var2){ + //easy comparison operator for template engine + return var1 === var2; + }); + + UI.registerHelper('isNotEqual', function (var1,var2){ + //easy comparison operator for template engine + return var1 !== var2 + }); + + UI.registerHelper('isAnObject', function (var1){ + //help the template engine figure out objects for "each" iteration + return _.isObject(var1) + }); + + UI.registerHelper('objKeyValue', function (obj,yieldObject) { + //given an object, return key:value pairs + //for easy iteration. + + //decide whether to return objects natively: + yieldObject = typeof yieldObject !== 'undefined' ? yieldObject : true; + + return _.map(obj, function(i, k) { + if ( ! _.isObject(i) ) { + return {key: k, value: i}; + } else { + if (yieldObject) { + return { key: k, value: i}; + } else { + return { key: null, value: null}; + } + } + + }); + }); + + + //auto run to handle session variable changes + Deps.autorun(function() { + var message = Session.get('displayMessage'); + //console.log('Got new session message'); + if (message) { + var stringArray = message.split('&'); + //notify({ + // title : stringArray[0], + // content: stringArray[1] + //}); + if (typeof console !== 'undefined') + console.log(message) + Session.set('displayMessage', null); + } + }); + + + +}; diff --git a/pool/shard000/JavaScript/0005708_Widgets.js b/pool/shard000/JavaScript/0005708_Widgets.js new file mode 100644 index 0000000000000000000000000000000000000000..3071efecf1a0f8bcc8b33518080fd43ecb24c884 --- /dev/null +++ b/pool/shard000/JavaScript/0005708_Widgets.js @@ -0,0 +1,91 @@ +import _ from 'lodash'; +import uuid from 'uuid'; + +const widgets = (state = {} , action) => { + let widgetAreas; + switch(action.type){ + case 'LOAD_WIDGET_AREAS_SUCCESS': + return Object.assign({}, state, + {widgetAreas: action.widgetAreas} + ) + + case 'LOAD_WIDGETS_AVAILABLE_SUCCESS': + return Object.assign({}, state, + { widgetsAvailable: action.widgets } + ); + + case 'ADD_WIDGET_TO_WIDGET_AREA': + widgetAreas = _.map(state.widgetAreas, was => { + if (was.id === action.widgetAreaId) { + action.widget.id = uuid() + was.widgets.push(action.widget) + } + return was + }); + + return Object.assign({}, state, + {widgetAreas: widgetAreas} + ); + + case 'REMOVE_ALL_WIDGETS_FROM_WIDGET_AREA': + widgetAreas = _.map(state.widgetAreas, was => { + if (was.id === action.widgetAreaId){ + was.widgets = [] + } + return was + }); + + return Object.assign({}, state, + {widgetAreas: widgetAreas} + ); + + case 'REMOVE_SINGLE_WIDGET_FROM_WIDGET_AREA': + widgetAreas = _.map(state.widgetAreas, wa => { + if (wa.id === action.widgetAreaId) { + // remove single using _.filter + wa.widgets = _.filter(wa.widgets, w => ( w.id !== action.widgetId )) + } + return wa + }); + + return Object.assign({}, state, + {widgetAreas: widgetAreas} + ); + + case 'UPDATE_WIDGETS_ORDER': + widgetAreas = _.map(state.widgetAreas, wa => { + if(wa.id === action.widgetAreaId){ + wa.widgets = action.widgets + } + return wa + }); + + + return Object.assign({}, state, + {widgetAreas: widgetAreas} + ); + + case 'CREATE_ACTIVE_WIDGETS_INITIAL_VALUES': + let nodes = action.activeWidgets + let activeWidgetsInitials = {} + + _.forEach(nodes, node => { + let uuid = node.node.item.split("#")[1] + activeWidgetsInitials[uuid] = JSON.parse(JSON.parse(node.node.value)) + }); + + return {...state, activeWidgetsInitials} + + case 'SET_ALL_CATEGORY_LIST': + return {...state, allCategoryList: action.catList} + + case 'SET_WIDGET_DATA': + return {widgetData: action.widgetData} + + default: + return state + } +} + + +export default widgets; diff --git a/pool/shard000/JavaScript/0005711_webpack.config.js b/pool/shard000/JavaScript/0005711_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..d7552778f6d0f790e21e80d2b5fe664ecc6e992f --- /dev/null +++ b/pool/shard000/JavaScript/0005711_webpack.config.js @@ -0,0 +1,92 @@ +/// <binding ProjectOpened='Hot' /> +var path = require('path'); +var webpack = require('webpack'); +var HtmlWebpackPlugin = require('html-webpack-plugin'); +var pkg = require('./package.json'); + +// bundle dependencies in separate vendor bundle +var vendorPackages = Object.keys(pkg.dependencies).filter(function (el) { + return el.indexOf('font') === -1; // exclude font packages from vendor bundle +}); +var outputFileTemplateSuffix = '-' + pkg.version; + + +module.exports = function (env) { + + env = env || {}; + var isProd = env.NODE_ENV === 'production'; + + // Setup base config for all environments + var config = { + devtool: 'source-map', + resolve: { + extensions: ['.ts', '.tsx', '.js', '.jsx'] + }, + plugins: [ + new webpack.DefinePlugin({ + __API_URL__: JSON.stringify(process.env.API_URL || 'http://localhost:51407'), + 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || 'development') + }), + new HtmlWebpackPlugin({ + template: 'index.html' + }) + ], + module: { + rules: [ + { + test: /\.tsx?$/, + loader: 'awesome-typescript-loader', + include: __dirname + }, { + test: /\.css?$/, + use: ['style-loader', 'raw-loader'], + include: __dirname + } + ] + } + } + + // Set environment-specific properties to the config + if (isProd) { + config.entry = { + main: './app/index', + vendor: vendorPackages + }; + config.output = { + path: path.join(__dirname, 'dist'), + filename: '[name]' + outputFileTemplateSuffix + '.js', + chunkFilename: '[id]' + outputFileTemplateSuffix + '.js' + }; + config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ + name: 'vendor', + filename: 'vendor' + outputFileTemplateSuffix + '.js', + minChunks: Infinity + })); + } else { // dev + config.devServer = { + contentBase: './build', + host: 'localhost', + port: 3000 + }; + config.entry = { + main: [ + 'webpack-dev-server/client?http://localhost:3000', + 'webpack/hot/only-dev-server', + 'react-hot-loader/patch', + './app/index' + ], + vendor: vendorPackages + }; + config.output = { + path: path.join(__dirname, 'build'), + filename: '[name].js' + }; + config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ + name: 'vendor', + filename: 'vendor.js', + minChunks: Infinity + })) + } + + return config; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005713_slice_util.js b/pool/shard000/JavaScript/0005713_slice_util.js new file mode 100644 index 0000000000000000000000000000000000000000..c0aa6793647febed7053f9943baf9a166ffe3c9f --- /dev/null +++ b/pool/shard000/JavaScript/0005713_slice_util.js @@ -0,0 +1,150 @@ +"use strict"; +/** + * @license + * Copyright 2017 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. + * ============================================================================= + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var util = require("../util"); +function assertParamsValid(input, begin, size) { + util.assert(input.rank === begin.length, function () { return "Error in slice" + input.rank + "D: Length of begin " + begin + " must " + + ("match the rank of the array (" + input.rank + ")."); }); + util.assert(input.rank === size.length, function () { return "Error in slice" + input.rank + "D: Length of size " + size + " must " + + ("match the rank of the array (" + input.rank + ")."); }); + var _loop_1 = function (i) { + util.assert(begin[i] + size[i] <= input.shape[i], function () { return "Error in slice" + input.rank + "D: begin[" + i + "] + size[" + i + "] " + + ("(" + (begin[i] + size[i]) + ") would overflow input.shape[" + i + "] (" + input.shape[i] + ")"); }); + }; + for (var i = 0; i < input.rank; ++i) { + _loop_1(i); + } +} +exports.assertParamsValid = assertParamsValid; +/** Converts a binary mask to an array of axes. Used in stridedSlice(). */ +function maskToAxes(mask) { + var axes = []; + var axis = 0; + while (mask > 0) { + if (mask & 1) { + axes.push(axis); + } + mask /= 2; + axis++; + } + return axes; +} +exports.maskToAxes = maskToAxes; +/** Computes the output shape given the strided slice params. */ +function computeOutShape(begin, end, strides) { + var size = []; + for (var axis = 0; axis < begin.length; axis++) { + size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]); + } + return size; +} +exports.computeOutShape = computeOutShape; +function startForAxis(beginMask, startIndices, strides, inputShape, axis) { + // Begin with the specified index + var start = startIndices[axis]; + var stride = strides[axis] || 1; + // Check the axis bit from right of beginMask or the begin index is not set + // for the axis. + if (beginMask & 1 << axis || start == null) { + if (stride > 0) { + // Forward iteration - use the first element. These values will get + // clamped below (Note: We could have set them to 0 and axis_size-1, but + // use lowest() and max() to maintain symmetry with StopForAxis()) + start = Number.MIN_SAFE_INTEGER; + } + else { + // Backward iteration - use the last element. + start = Number.MAX_SAFE_INTEGER; + } + } + // Handle negative indices + var axisSize = inputShape[axis]; + if (start < 0) { + start += axisSize; + } + // Clamping + start = util.clamp(0, start, axisSize - 1); + return start; +} +exports.startForAxis = startForAxis; +function stopForAxis(endMask, stopIndices, strides, inputShape, axis) { + // Begin with the specified index + var stop = stopIndices[axis]; + var stride = strides[axis] || 1; + // Check the axis bit from right of endMask or if the stop index is not set + // for this axis. + if (endMask & (1 << axis) || stop == null) { + if (stride > 0) { + // Forward iteration - use the last element. These values will get + // clamped below + stop = Number.MAX_SAFE_INTEGER; + } + else { + // Backward iteration - use the first element. + stop = Number.MIN_SAFE_INTEGER; + } + } + // Handle negative indices + var axisSize = inputShape[axis]; + if (stop < 0) { + stop += axisSize; + } + // Clamping + // Because the end index points one past the last element, we need slightly + // different clamping ranges depending on the direction. + if (stride > 0) { + // Forward iteration + stop = util.clamp(0, stop, axisSize); + } + else { + // Backward iteration + stop = util.clamp(-1, stop, axisSize - 1); + } + return stop; +} +exports.stopForAxis = stopForAxis; +/** + * Returns true if the slice occupies a continous set of elements in the + * 'flat' space. + */ +function isSliceContinous(shape, begin, size) { + // Index of the first axis that has size > 1. + var firstNonOneAxis = size.length; + for (var i = 0; i < size.length; i++) { + if (size[i] > 1) { + firstNonOneAxis = i; + break; + } + } + for (var i = firstNonOneAxis + 1; i < size.length; i++) { + if (begin[i] > 0 || size[i] !== shape[i]) { + return false; + } + } + return true; +} +exports.isSliceContinous = isSliceContinous; +function computeFlatOffset(begin, strides) { + var flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1; + for (var i = 0; i < begin.length - 1; i++) { + flatOffset += begin[i] * strides[i]; + } + return flatOffset; +} +exports.computeFlatOffset = computeFlatOffset; +//# sourceMappingURL=slice_util.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005717_stories.js b/pool/shard000/JavaScript/0005717_stories.js new file mode 100644 index 0000000000000000000000000000000000000000..e78c7d918236a74b0222458d7cb17eea2cc923b4 --- /dev/null +++ b/pool/shard000/JavaScript/0005717_stories.js @@ -0,0 +1,121 @@ +import React from 'react' +import { ContributionCard } from './index' +import { Container, RocketIllustration } from 'kitten' +import { DocsPage } from 'storybook/docs-page' +import { action } from '@storybook/addon-actions' + +const argTypes = { + show: { + name: 'show', + description: 'If empty return null', + control: 'boolean', + }, + closeButtonLabel: { + name: 'closeButtonLabel', + description: 'Close button label', + control: 'text', + }, + borderColor: { + name: 'borderColor', + description: 'border color', + control: 'text', + }, + borderRadius: { + name: 'borderRadius', + description: 'border radius size', + control: { type: 'text', type: 'number' }, + }, + borderStyle: { + name: 'borderStyle', + description: 'border style', + control: 'text', + }, + onClose: { + name: 'close', + description: + 'Action when Close button is clicked. If null, no button is displayed.', + control: null, + }, + largeInput: { + name: 'largeInput', + description: 'Should the input be larger?', + control: 'boolean', + }, + largeTitle: { + name: 'ContributionCard.Title: largeTitle', + description: + 'When `ContributionCard.PillNumber` is hidden, the title can be more flex', + control: 'boolean', + }, +} + +const args = { + show: true, + closeButtonLabel: 'Close', + borderColor: 'var(--color-grey-400)', + borderRadius: 8, + borderStyle: 'solid', + onClose: action('onClose'), + largeInput: false, + largeTitle: false, +} + +export default { + component: ContributionCard, + title: 'Structure/Cards/ContributionCard', + parameters: { + docs: { + page: () => ( + <DocsPage filepath={__filename} importString="ContributionCard" /> + ), + }, + }, + decorators: [ + Story => ( + <div className="k-u-margin-top-quadruple"> + <Container className="k-u-margin-vertical-quadruple"> + <Story /> + </Container> + </div> + ), + ], + args, + argTypes, +} + +export const Default = ({ largeTitle, ...args }) => { + return ( + <ContributionCard {...args}> + <ContributionCard.Image> + <img src={`/kitten-${Math.floor(Math.random() * 10)}.jpg`} alt="" /> + </ContributionCard.Image> + + <ContributionCard.Title largeTitle={largeTitle}> + Lorem ipsum dolor sit amet. + </ContributionCard.Title> + + <ContributionCard.PillNumber value={0} min={0} max={100} /> + <ContributionCard.Amount>1005 €</ContributionCard.Amount> + </ContributionCard> + ) +} + +export const PetitPlus = (...args) => { + return ( + <ContributionCard {...args} onClose={null}> + <ContributionCard.Image className="k-u-hidden@xs-down"> + <RocketIllustration width={45} height={81} /> + </ContributionCard.Image> + + <ContributionCard.Title> + Un petit plus pour 900 care + <ContributionCard.Description> + Donnez encore plus de chances à ce projet de voir le jour. + </ContributionCard.Description> + </ContributionCard.Title> + + <ContributionCard.Input unit="€" /> + <ContributionCard.Action>Ajouter</ContributionCard.Action> + </ContributionCard> + ) +} diff --git a/pool/shard000/JavaScript/0005719_docs.js b/pool/shard000/JavaScript/0005719_docs.js new file mode 100644 index 0000000000000000000000000000000000000000..361da07eef1c4ac25c8e6ecb09abfbecb0689f3f --- /dev/null +++ b/pool/shard000/JavaScript/0005719_docs.js @@ -0,0 +1,23 @@ +import {EventAggregator} from 'aurelia-event-aggregator'; +import {bindable,Animator} from 'aurelia-framework'; + +export class Docs{ + + static inject = [Element,EventAggregator,Animator]; + constructor(element,ea,animator) { + this.element = element; + this.ea = ea; + this.animator = animator; + } + + attached(){ + this.ea.publish("page:ready"); + + + } + + detached(){ + + } + +} diff --git a/pool/shard000/JavaScript/0005720_anchor-is-valid.js b/pool/shard000/JavaScript/0005720_anchor-is-valid.js new file mode 100644 index 0000000000000000000000000000000000000000..85c86006a7c66b0a238b9960a3349e2f6b4cad95 --- /dev/null +++ b/pool/shard000/JavaScript/0005720_anchor-is-valid.js @@ -0,0 +1,125 @@ +'use strict'; + +var _jsxAstUtils = require('jsx-ast-utils'); + +var _schemas = require('../util/schemas'); + +/** + * @fileoverview Performs validity check on anchor hrefs. Warns when anchors are used as buttons. + * @author Almero Steyn + * + */ + +// ---------------------------------------------------------------------------- +// Rule Definition +// ---------------------------------------------------------------------------- + +var allAspects = ['noHref', 'invalidHref', 'preferButton']; + +var preferButtonErrorMessage = 'Anchor used as a button. Anchors are primarily expected to navigate. Use the button element instead. Learn more: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md'; + +var noHrefErrorMessage = 'The href attribute is required for an anchor to be keyboard accessible. Provide a valid, navigable address as the href value. If you cannot provide an href, but still need the element to resemble a link, use a button and change it with appropriate styles. Learn more: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md'; + +var invalidHrefErrorMessage = 'The href attribute requires a valid value to be accessible. Provide a valid, navigable address as the href value. If you cannot provide a valid href, but still need the element to resemble a link, use a button and change it with appropriate styles. Learn more: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md'; + +var schema = (0, _schemas.generateObjSchema)({ + components: _schemas.arraySchema, + specialLink: _schemas.arraySchema, + aspects: (0, _schemas.enumArraySchema)(allAspects, 1) +}); + +module.exports = { + meta: { + docs: { + url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/anchor-is-valid.md' + }, + schema: [schema] + }, + + create: function create(context) { + return { + JSXOpeningElement: function JSXOpeningElement(node) { + var attributes = node.attributes; + + var options = context.options[0] || {}; + var componentOptions = options.components || []; + var typeCheck = ['a'].concat(componentOptions); + var nodeType = (0, _jsxAstUtils.elementType)(node); + + // Only check anchor elements and custom types. + if (typeCheck.indexOf(nodeType) === -1) { + return; + } + + // Set up the rule aspects to check. + var aspects = options.aspects || allAspects; + + // Create active aspect flag object. Failing checks will only report + // if the related flag is set to true. + var activeAspects = {}; + allAspects.forEach(function (aspect) { + activeAspects[aspect] = aspects.indexOf(aspect) !== -1; + }); + + var propOptions = options.specialLink || []; + var propsToValidate = ['href'].concat(propOptions); + var values = propsToValidate.map(function (prop) { + return (0, _jsxAstUtils.getProp)(node.attributes, prop); + }).map(function (prop) { + return (0, _jsxAstUtils.getPropValue)(prop); + }); + // Checks if any actual or custom href prop is provided. + var hasAnyHref = values.filter(function (value) { + return value === undefined || value === null; + }).length !== values.length; + // Need to check for spread operator as props can be spread onto the element + // leading to an incorrect validation error. + var hasSpreadOperator = attributes.filter(function (prop) { + return prop.type === 'JSXSpreadAttribute'; + }).length > 0; + var onClick = (0, _jsxAstUtils.getProp)(attributes, 'onClick'); + + // When there is no href at all, specific scenarios apply: + if (!hasAnyHref) { + // If no spread operator is found and no onClick event is present + // it is a link without href. + if (!hasSpreadOperator && activeAspects.noHref && (!onClick || onClick && !activeAspects.preferButton)) { + context.report({ + node: node, + message: noHrefErrorMessage + }); + } + // If no spread operator is found but an onClick is preset it should be a button. + if (!hasSpreadOperator && onClick && activeAspects.preferButton) { + context.report({ + node: node, + message: preferButtonErrorMessage + }); + } + return; + } + + // Hrefs have been found, now check for validity. + var invalidHrefValues = values.filter(function (value) { + return value !== undefined && value !== null; + }).filter(function (value) { + return typeof value === 'string' && (!value.length || value === '#' || /^\W*?javascript/.test(value)); + }); + if (invalidHrefValues.length !== 0) { + // If an onClick is found it should be a button, otherwise it is an invalid link. + if (onClick && activeAspects.preferButton) { + context.report({ + node: node, + message: preferButtonErrorMessage + }); + } else if (activeAspects.invalidHref) { + context.report({ + node: node, + message: invalidHrefErrorMessage + }); + } + } + } + }; + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005723_tests.js b/pool/shard000/JavaScript/0005723_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..1f51bcbf272333186d535add6dd1c4d5f0001fcf --- /dev/null +++ b/pool/shard000/JavaScript/0005723_tests.js @@ -0,0 +1,66 @@ +/** + * Nodeunit functional tests. Requires internet connection to validate phantom + * functions correctly. + */ + +var childProcess = require('child_process') +var fs = require('fs') +var path = require('path') +var phantomjs = require('../lib/phantomjs') + + +exports.testDownload = function (test) { + test.expect(1) + test.ok(fs.existsSync(phantomjs.path), 'Binary file should have been downloaded') + test.done() +} + + +exports.testPhantomExecutesTestScript = function (test) { + test.expect(1) + + var childArgs = [ + path.join(__dirname, 'loadspeed.js'), + 'http://www.google.com/' + ] + + childProcess.execFile(phantomjs.path, childArgs, function (err, stdout, stderr) { + var value = (stdout.indexOf('msec') !== -1) + test.ok(value, 'Test script should have executed and returned run time') + test.done() + }) +} + + +exports.testPhantomExitCode = function (test) { + test.expect(1) + childProcess.execFile(phantomjs.path, [path.join(__dirname, 'exit.js')], function (err, stdout, stderr) { + test.equals(err.code, 123, 'Exit code should be returned from phantom script') + test.done() + }) +} + + +exports.testBinFile = function (test) { + test.expect(1) + + var binPath = process.platform === 'win32' ? + path.join(__dirname, '..', 'lib', 'phantom', 'phantomjs.exe') : + path.join(__dirname, '..', 'bin', 'phantomjs') + + childProcess.execFile(binPath, ['--version'], function (err, stdout, stderr) { + test.equal(phantomjs.version, stdout.trim(), 'Version should be match') + test.done() + }) +} + + +exports.testCleanPath = function (test) { + test.expect(5) + test.equal('/Users/dan/bin', phantomjs.cleanPath('/Users/dan/bin:./bin')) + test.equal('/Users/dan/bin:/usr/bin', phantomjs.cleanPath('/Users/dan/bin:./bin:/usr/bin')) + test.equal('/usr/bin', phantomjs.cleanPath('./bin:/usr/bin')) + test.equal('', phantomjs.cleanPath('./bin')) + test.equal('/Work/bin:/usr/bin', phantomjs.cleanPath('/Work/bin:/Work/phantomjs/node_modules/.bin:/usr/bin')) + test.done() +} diff --git a/pool/shard000/JavaScript/0005724_intro.js b/pool/shard000/JavaScript/0005724_intro.js new file mode 100644 index 0000000000000000000000000000000000000000..37ac66ff5ac93dac352920d26868a12c93df9840 --- /dev/null +++ b/pool/shard000/JavaScript/0005724_intro.js @@ -0,0 +1,84 @@ +var data=['<div style="position:absolute;background:url(\'clipboard.svg\');background-size:650px;width:650px;height:850px;"><form style="position:relative;margin:150px 0px 0px 60px;width:450px;font-family:\'Rock Salt\',cursive;font-size:20px;" action="myforensics_lab.php" method="post">DNA Barcode is a unique pattern of <input type="text" name="a1" size="8" value="', +'"> sequence specific of a living thing. In this technique, short, highly variable regions are of interest. The sequences are extracted from genomes located in <input type="text" size="10" name="a2" value="', +'"> for animals and <input type="text" size="10" name="a3" value="', +'"> for plants. These sequences must be amplified with <input type="text" size="25" name="a4" value="', +'">. For animals, a region of the gene named <input type="text" name="a5" value="', +'"> is studied...<br><input style="float:right" type="submit" name="OK" value="OK"></input></div></form>' +]; + +var emptybubble={'x':0,'y':0}; +var girl=[ +'I received the samples from the police...', +'Four samples come from animals and the tooth is human...', +'Don\'t know...', +'Yeees, that can solve my problem.', +'We need more details and know which gene to amplify and sequence ...', +'You want a coffee?<br>I\'m sorry, I have no coin', +'If you think you can solve my problem,<br>please read my clipboard and answer the questions.' +]; +var girlbubble={'x':-150,'y':-100}; + +var boy=[ +'Hmmmm...', +'And ? ...', +'Interesting! what can we do with the animal samples?', +'Maybe DNA barcoding can work...', +'We need to extract DNA and sequence some genes...', +'Hey you!<br>What are you waiting for?', +'Are you listening to us?<br> Do you have any idea about Sandy\'s problem?' +]; +var boybubble={'x':-10,'y':-80}; + +var statusboy=0; +var statusgirl=0; + +function dialog(ev,who) { + console.log(statusboy +" "+ statusgirl); + if (who=='clipboard') { + if (statusgirl==6) { + document.getElementById('bubble').innerHTML=''; + document.getElementById('bubble').style.left='0px'; + document.getElementById('bubble').style.top='0px'; + document.getElementById('popup').innerHTML=data; + } + else + myAlert(ev,'Hmmm... It\'s not very polite to read<br> her clipboard without her permission.',emptybubble); + } + else if (who=='girl') { + myAlert(ev,girl[statusgirl],girlbubble); + if (statusboy < (statusgirl+1) ) + statusboy++; + if (statusboy > 6) + statusboy=6; + } + else if (who=='boy') { + myAlert(ev,boy[statusboy],boybubble); + if (statusboy > statusgirl) + statusgirl++; + if (statusgirl > 6) + statusgirl=6; + } +} + + +function myAlert(ev,text,guy) { + ev = ev || window.event(); + console.log('myAlert '+text+' '+ev.clientX+' '+ev.clientY); + var bubble = document.getElementById('bubble'); + bubble.innerHTML='<p>'+text+'</p>'; + bubble.style.left= (ev.clientX + guy['x']) + 'px'; + bubble.style.top = (ev.clientY + guy['y']) + 'px'; +} + +function toClipboard(a1,a2,a3,a4,a5) { + document.getElementById('bubble').innerHTML=''; + document.getElementById('bubble').style.left='0px'; + document.getElementById('bubble').style.top='0px'; + document.getElementById('popup').innerHTML=data[0]+a1+data[1]+a2+data[2]+a3+data[3]+a4+data[4]+a5+data[5]; +} + +function doIt() { + // do nothing +} + + diff --git a/pool/shard000/JavaScript/0005728_answers.js b/pool/shard000/JavaScript/0005728_answers.js new file mode 100644 index 0000000000000000000000000000000000000000..47e1d92c3b4c605efa30b9bb4828f694e8985a07 --- /dev/null +++ b/pool/shard000/JavaScript/0005728_answers.js @@ -0,0 +1,14 @@ +angular.module('answers', []) + +.controller("answersCtrl", function($scope, $http, $location, SubsService) { + $scope.answers = {}; + $scope.getAnswers = function() { + $http.get('/answers') + .then(function(response) { + $scope.answers = response.data; + }); + }; + $scope.getAnswers(); + +}); + diff --git a/pool/shard000/JavaScript/0005731_mode-yaml.js b/pool/shard000/JavaScript/0005731_mode-yaml.js new file mode 100644 index 0000000000000000000000000000000000000000..f1650fc1c26ced522f4862c688415be3d80bc6d9 --- /dev/null +++ b/pool/shard000/JavaScript/0005731_mode-yaml.js @@ -0,0 +1,290 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. + * + * ***** END LICENSE BLOCK ***** */ + +ace.define('ace/mode/yaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/yaml_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/coffee'], function(require, exports, module) { + + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var YamlHighlightRules = require("./yaml_highlight_rules").YamlHighlightRules; +var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; +var FoldMode = require("./folding/coffee").FoldMode; + +var Mode = function() { + this.HighlightRules = YamlHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.foldingRules = new FoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + + this.$id = "ace/mode/yaml"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); + +ace.define('ace/mode/yaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { + + +var oop = require("../lib/oop"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var YamlHighlightRules = function() { + this.$rules = { + "start" : [ + { + token : "comment", + regex : "#.*$" + }, { + token : "list.markup", + regex : /^(?:-{3}|\.{3})\s*(?=#|$)/ + }, { + token : "list.markup", + regex : /^\s*[\-?](?:$|\s)/ + }, { + token: "constant", + regex: "!![\\w//]+" + }, { + token: "constant.language", + regex: "[&\\*][a-zA-Z0-9-_]+" + }, { + token: ["meta.tag", "keyword"], + regex: /^(\s*\w.*?)(\:(?:\s+|$))/ + },{ + token: ["meta.tag", "keyword"], + regex: /(\w+?)(\s*\:(?:\s+|$))/ + }, { + token : "keyword.operator", + regex : "<<\\w*:\\w*" + }, { + token : "keyword.operator", + regex : "-\\s*(?=[{])" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // multi line string start + regex : '[|>][-+\\d\\s]*$', + next : "qqstring" + }, { + token : "string", // single quoted string + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", // float + regex : /[+\-]?[\d_]+(?:(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?\b/ + }, { + token : "constant.numeric", // other number + regex : /[+\-]?\.inf\b|NaN\b|0x[\dA-Fa-f_]+|0b[10_]+/ + }, { + token : "constant.language.boolean", + regex : "(?:true|false|TRUE|FALSE|True|False|yes|no)\\b" + }, { + token : "invalid.illegal", // comments are not allowed + regex : "\\/\\/.*$" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + } + ], + "qqstring" : [ + { + token : "string", + regex : '(?=(?:(?:\\\\.)|(?:[^:]))*?:)', + next : "start" + }, { + token : "string", + regex : '.+' + } + ]}; + +}; + +oop.inherits(YamlHighlightRules, TextHighlightRules); + +exports.YamlHighlightRules = YamlHighlightRules; +}); + +ace.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { + + +var Range = require("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { + + +var oop = require("../../lib/oop"); +var BaseFoldMode = require("./fold_mode").FoldMode; +var Range = require("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var range = this.indentationBlock(session, row); + if (range) + return range; + + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1 || line[startLevel] != "#") + return; + + var startColumn = line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + line = session.getLine(row); + var level = line.search(re); + + if (level == -1) + continue; + + if (line[level] != "#") + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + var indent = line.search(/\S/); + var next = session.getLine(row + 1); + var prev = session.getLine(row - 1); + var prevIndent = prev.search(/\S/); + var nextIndent = next.search(/\S/); + + if (indent == -1) { + session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; + return ""; + } + if (prevIndent == -1) { + if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { + session.foldWidgets[row - 1] = ""; + session.foldWidgets[row + 1] = ""; + return "start"; + } + } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { + if (session.getLine(row - 2).search(/\S/) == -1) { + session.foldWidgets[row - 1] = "start"; + session.foldWidgets[row + 1] = ""; + return ""; + } + } + + if (prevIndent!= -1 && prevIndent < indent) + session.foldWidgets[row - 1] = "start"; + else + session.foldWidgets[row - 1] = ""; + + if (indent < nextIndent) + return "start"; + else + return ""; + }; + +}).call(FoldMode.prototype); + +}); diff --git a/pool/shard000/JavaScript/0005732_Tab.js b/pool/shard000/JavaScript/0005732_Tab.js new file mode 100644 index 0000000000000000000000000000000000000000..02fcfca76bcdca61f0747f8623f77c60d6392047 --- /dev/null +++ b/pool/shard000/JavaScript/0005732_Tab.js @@ -0,0 +1,14 @@ +import React from 'react' +import PropTypes from 'prop-types' + +// don't update a tab if it's currently hidden +const shouldUpdate = (prevProps, nextProps) => !nextProps.isActive + +const Tab = React.memo(({ children }) => <>{children}</>, shouldUpdate) +Tab.displayName = 'Tab' + +Tab.propTypes = { + children: PropTypes.node.isRequired, +} + +export default Tab diff --git a/pool/shard000/JavaScript/0005735_log.js b/pool/shard000/JavaScript/0005735_log.js new file mode 100644 index 0000000000000000000000000000000000000000..7b6534c10a30fd474986cb21d3ef0241c5ce89e9 --- /dev/null +++ b/pool/shard000/JavaScript/0005735_log.js @@ -0,0 +1,441 @@ +/** + * Source: log.js + * Copyright (c) 2013-2014 Oculus Info Inc. + * @fileOverview Aperture Logging API implementation + */ + +/* + * TODO Allow default appenders to be constructed based on config from server + */ + +/** + * @namespace Aperture logging API. Multiple appenders can be added to log to different + * destinations at a specified minimum log level. The logWindowErrors function can be + * configured to log unhandled JavaScript errors as well. Logging can be configured + * in the aperture config file (<a href="#constructor">see example</a>) or programmatically. + * + * @example + * // example aperture config file section + * aperture.log : { + * level : 'info', + * logWindowErrors : {log: true, preventDefault: true}, + * appenders : { + * consoleAppender : {level: 'info'}, + * notifyAppender : {level: 'error'} + * } + * } + */ +aperture.log = (function() { + + /** + * @class Logging level definitions + * @name aperture.log.LEVEL + */ + var LEVEL = + /** @lends aperture.log.LEVEL */ + { + /** @constant + * @description Error logging level */ + ERROR: 'error', + /** @constant + * @description Warn logging level */ + WARN: 'warn', + /** @constant + * @description Info logging level */ + INFO: 'info', + /** @constant + * @description Debug logging level */ + DEBUG: 'debug', + /** @constant + * @description 'Log' logging level */ + LOG: 'log', + /** @constant + * @description Turn off logging */ + NONE: 'none' + }, + + levelOrder = { + 'error': 5, + 'warn': 4, + 'info': 3, + 'debug': 2, + 'log': 1, + 'none': 0 + }, + + + // The list of active appenders + appenders = [], + + // The global logging level + globalLevel = LEVEL.INFO, + + // Log window errors too. + logWinErrs = false, + eatWinErrs = false, + otherWinErrHandler, + + // The current indentation level. + prefix = '', + eightSpaces = ' ', + + + /** + * @private + * Internal function that takes a format string and additional arguments + * and returns a single formatted string. Essentially a cheap version of + * sprintf. Parameters are referenced within the format string using {#} + * where # is the parameter index number, starting with 0. Parameter references + * may be repeated and may be in any order within the format string. + * + * Example: + * <pre> + * formatString('{0} is fun - use {0} more. {1} is boring', 'JavaScript', 'C'); + * </pre> + * + */ + formatString = function(message /*, params */) { + // Extract all but first arg (message) + var args = Array.prototype.slice.call(arguments, 1); + // Return string with all {digit} replaced with value from argument + return prefix + message.replace(/\{(\d+)\}/g, function(match, number) { + return typeof args[number] != 'undefined' ? + args[number] : + '{' + number + '}'; + }); + }, + + + + Appender = aperture.Class.extend( 'aperture.log.Appender', + /** @lends aperture.log.Appender# */ + { + /** + * @class Logging Appender base class.<br><br> + * + * @constructs + * @param {aperture.log.LEVEL} level The logging level threshold for this appender + */ + init : function(level) { + this.level = level || LEVEL.WARN; + }, + + /** + * Sets or gets the current global logging level + * @param {aperture.log.LEVEL} [l] the new appender level threshold. If value given, the + * threshold level is not changed and the current value is returned + * @param the current appender level threshold + */ + level : function(l) { + if( l !== undefined ) { + // Set new level if given one + this.level = l; + } + // Return current level + return this.level; + }, + + /** + * Log function called by the logging framework requesting that the + * appender handle the given data. In general this function should + * not be overridden by sub-classed Appenders, instead they should + * implement logString and logObjects + * @param {aperture.log.LEVEL} level level at which to log the message + * @param {Object|String} toLog data to log, see api.log for details. + */ + log : function( level, toLog ) { + // Check logging level + if( levelOrder[level] >= levelOrder[this.level] ) { + // Extract all arguments that are meant to be logged + var toLogArgs = Array.prototype.slice.call(arguments, 1); + // Is the first thing to log a string? + if( aperture.util.isString(toLog) ) { + // Log a string, assume is a format string if more args follow + // Create log message and call appender's log string function + this.logString( level, formatString.apply(null, toLogArgs) ); + + } else { + // Not a string, assume one or more objects, log as such + if( this.logObjects ) { + // Appender supports object logging + // Call logObjects with the level and an array of objects to log + this.logObjects( level, toLogArgs ); + } else { + // Appender doesn't support object logging + // Convert objects to a JSON string and log as such + var message = window.JSON? JSON.stringify( toLogArgs ) : + 'No window.JSON interface exists to stringify logged object. A polyfill like json2.js is required.'; + + this.logString( level, message ); + } + } + } + }, + + /** + * 'Abstract' function to log a given string message at the given level + * Appender sub-classes should implement this method to do something useful + * with the message + * @param {aperture.log.LEVEL} level the level of the message to log + * @param {String} message the message that should be logged as a string + */ + logString : function(level, message) {} + + /** + * 'Abstract' function to log javascript objects. Appender sub-classes + * may elect to implement this method if they can log objects in a useful + * way. If this method is not implemented, logString will be called + * with a string representation of the objects. + * <pre> + * logObjects : function(level, objects) {} + * </pre> + * @param {aperture.log.LEVEL} level the level of the entry to log + * @param {Object} ... the objects to log + */ + } ), + + /** + * Define the externally visible logging API + * @exports api as aperture.log + * @lends api + */ + api = { + /** + * Returns a list of the current logging appenders + * @returns an array of active appenders + */ + appenders : function() { + return appenders; + }, + + /** + * Adds an Appender instance to the set of active logging appenders + * @param {Appender} toAdd an appender instance to add + * @returns the added appender + */ + addAppender : function( toAdd ) { + appenders.push( toAdd ); + return toAdd; + }, + + /** + * Removes an Appender instance from the set of active logging appenders + * @param {Appender} toRemove an appender instance currently in the list + * of active appenders that should be removed + * @returns the removed appender + */ + removeAppender : function( toRemove ) { + appenders = aperture.util.without( appenders, toRemove ); + return toRemove; + }, + + /** + * Logs a message at the given level + * @param {aperture.log.LEVEL} level the level at which to log the given message + * @param {String|Object} message a message or object to log. + * The message may be a plain string, may be a format string followed by + * values to inject into the string, or may be one or more objects that should + * be logged as is. + * @param {String|Object} [...] additional objects to log or parameters + * for the format string contained in the message parameter. + */ + logAtLevel : function(level, message) { + // Only log if message level is equal to or higher than the global level + if( levelOrder[level] >= levelOrder[globalLevel] ) { + var args = arguments; + aperture.util.forEach(appenders, function(appender) { + // Call the appender's log function with the arguments as given + appender.log.apply(appender, args); + }); + } + }, + + /** + * Sets or gets the current global logging level + * @param {LEVEL} [l] if provided, sets the global logging level + * @returns {LEVEL} the global logging level, if a get, the old logging level if a set + */ + level : function(l) { + var oldLevel = globalLevel; + if( l !== undefined ) { + // Set new global level if given one + globalLevel = l; + } + // Return original global level + return oldLevel; + }, + + /** + * Returns true if configured to include the specified log level. + * @param {LEVEL} level + * @returns {Boolean} true if logging the specified level. + */ + isLogging : function(level) { + return levelOrder[level] >= levelOrder[globalLevel]; + }, + + /** + * If setting increments or decrements the indent by the specified number of spaces, + * otherwise returning the current indentation as a string of spaces. Zero may + * be supplied as an argument to reset the indentation to zero. + * + * @param {Number} [spaces] the number of spaces to increment or decrement, or zero to reset. + * @returns {String} the current indentation as a string. + */ + indent : function(spaces) { + if (arguments.length !== 0) { + if (spaces) { + if (spaces < 0) { + prefix = spaces < prefix.length? prefix.substring(0, prefix.length-spaces): ''; + } else { + while (spaces > 0) { + prefix += eightSpaces.substr(0, Math.min(spaces, 8)); + spaces-= 8; + } + } + } else { + prefix = ''; + } + } + + return prefix; + }, + + /** + * Specifies whether or not to intercept and log Javascript errors, or if no arguments + * are supplied returns true or false indicating the current state. + * + * @param {Boolean} [log] whether or not to log window errors. + * @param {Boolean} [preventDefault=false] whether or not to prevent the browser's default. + * + */ + logWindowErrors : function(log, preventDefault) { + if (log == null) { + return logWinErrs; + } + + // force it to a boolean. + log = !!log; + + if (logWinErrs !== log) { + logWinErrs = log; + eatWinErrs = !!preventDefault; + + if (logWinErrs) { + otherWinErrHandler = window.onerror; + window.onerror = onErr; + } else { + window.onerror = otherWinErrHandler; + otherWinErrHandler = undefined; + } + } + } + }; + + /** + * Logs a message at the "LEVEL.ERROR" level + * @name error + * @methodof aperture.log + * @param {String|Object} message a message or object to log. + * The message may be a plain string, may be a format string followed by + * values to inject into the string, or may be one or more objects that should + * be logged as is. + * @param {String|Object} [...] additional objects to log or parameters + * for the format string contained in the message parameter. + */ + + /** + * Logs a message at the "LEVEL.WARN" level + * @name warn + * @methodof aperture.log + * @param {String|Object} message a message or object to log. + * The message may be a plain string, may be a format string followed by + * values to inject into the string, or may be one or more objects that should + * be logged as is. + * @param {String|Object} [...] additional objects to log or parameters + * for the format string contained in the message parameter. + */ + + /** + * Logs a message at the "LEVEL.INFO" level + * @name info + * @methodof aperture.log + * @param {String|Object} message a message or object to log. + * The message may be a plain string, may be a format string followed by + * values to inject into the string, or may be one or more objects that should + * be logged as is. + * @param {String|Object} [...] additional objects to log or parameters + * for the format string contained in the message parameter. + */ + + /** + * Logs a message at the "LEVEL.LOG" level + * @name log + * @methodof aperture.log + * @param {String|Object} message a message or object to log. + * The message may be a plain string, may be a format string followed by + * values to inject into the string, or may be one or more objects that should + * be logged as is. + * @param {String|Object} [...] additional objects to log or parameters + * for the format string contained in the message parameter. + */ + + // Add a log method for each level to the api + aperture.util.forEach(LEVEL, function(value, key) { + // Create a method such as the following: + // api.info = log(level.INFO, args...) + api[value] = aperture.util.bind(api.logAtLevel, api, value); + }); + + // Expose 'abstract' base class + api.Appender = Appender; + + // Expose the log level definition + api.LEVEL = LEVEL; + + // Register for configuration events + // Configuration options allow + aperture.config.register('aperture.log', function(config) { + var logConfig = config['aperture.log']; + + // Set the global level + if( logConfig.level ) { + api.level( logConfig.level ); + } + + // log JS errors? + var winErrs = logConfig.logWindowErrors; + + if (winErrs) { + api.logWindowErrors( !!winErrs.log, winErrs.preventDefault ); + } + + // For all defined appenders... + aperture.util.forEach( logConfig.appenders, function(value, key) { + if (!key) { + return; + } + // the function will be an add fn that follows a particular format + key = 'add' + key.charAt(0).toUpperCase() + key.substr(1); + + // If an appender exists with the given key... + if( aperture.util.isFunction(aperture.log[key]) ) { + // Add it with the associated specification and start using it + aperture.log[key]( value ); + } + }); + }); + + function onErr(msg, url, line) { + api.error(msg + ' ' + url + ':' + line); + + // chain on + if (otherWinErrHandler) { + otherWinErrHandler.apply(this, arguments); + } + + return eatWinErrs; + } + + return api; +}()); diff --git a/pool/shard000/JavaScript/0005736_timezone.js b/pool/shard000/JavaScript/0005736_timezone.js new file mode 100644 index 0000000000000000000000000000000000000000..62ea880e23fcf8c149d6c24bd1b1a43abe549458 --- /dev/null +++ b/pool/shard000/JavaScript/0005736_timezone.js @@ -0,0 +1,51 @@ +/** +* DO NOT EDIT THIS FILE. +* See the following change record for more information, +* https://www.drupal.org/node/2815083 +* @preserve +**/ + +(function ($, Drupal) { + Drupal.behaviors.setTimezone = { + attach: function attach(context, settings) { + var $timezone = $(context).find('.timezone-detect').once('timezone'); + if ($timezone.length) { + var dateString = Date(); + + var matches = dateString.match(/\(([A-Z]{3,5})\)/); + var abbreviation = matches ? matches[1] : 0; + + var dateNow = new Date(); + var offsetNow = dateNow.getTimezoneOffset() * -60; + + var dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0); + var dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0); + var offsetJan = dateJan.getTimezoneOffset() * -60; + var offsetJul = dateJul.getTimezoneOffset() * -60; + + var isDaylightSavingTime = void 0; + + if (offsetJan === offsetJul) { + isDaylightSavingTime = ''; + } else if (Math.max(offsetJan, offsetJul) === offsetNow) { + isDaylightSavingTime = 1; + } else { + isDaylightSavingTime = 0; + } + + var path = 'system/timezone/' + abbreviation + '/' + offsetNow + '/' + isDaylightSavingTime; + $.ajax({ + async: false, + url: Drupal.url(path), + data: { date: dateString }, + dataType: 'json', + success: function success(data) { + if (data) { + $timezone.val(data); + } + } + }); + } + } + }; +})(jQuery, Drupal); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005738_ThemeProvider.js b/pool/shard000/JavaScript/0005738_ThemeProvider.js new file mode 100644 index 0000000000000000000000000000000000000000..d13c4406f2aef6141aa84df76b41973fc0cbd4e6 --- /dev/null +++ b/pool/shard000/JavaScript/0005738_ThemeProvider.js @@ -0,0 +1,53 @@ +import * as React from 'react'; +import PropTypes from 'prop-types'; +import { ThemeProvider as MuiThemeProvider } from '@material-ui/private-theming'; +import { exactProp } from '@material-ui/utils'; +import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine'; +import useTheme from './useTheme'; + +function InnerThemeProvider(props) { + const theme = useTheme(); + return ( + <StyledEngineThemeContext.Provider value={typeof theme === 'object' ? theme : {}}> + {props.children} + </StyledEngineThemeContext.Provider> + ); +} + +InnerThemeProvider.propTypes = { + /** + * Your component tree. + */ + children: PropTypes.node, +}; + +/** + * This component makes the `theme` available down the React tree. + * It should preferably be used at **the root of your component tree**. + */ +function ThemeProvider(props) { + const { children, theme: localTheme } = props; + + return ( + <MuiThemeProvider theme={localTheme}> + <InnerThemeProvider>{children}</InnerThemeProvider> + </MuiThemeProvider> + ); +} + +ThemeProvider.propTypes = { + /** + * Your component tree. + */ + children: PropTypes.node, + /** + * A theme object. You can provide a function to extend the outer theme. + */ + theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired, +}; + +if (process.env.NODE_ENV !== 'production') { + ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes); +} + +export default ThemeProvider; diff --git a/pool/shard000/JavaScript/0005739_endpoints.js b/pool/shard000/JavaScript/0005739_endpoints.js new file mode 100644 index 0000000000000000000000000000000000000000..269c041aa27123e8eb7de7ba17fbcef0f61286f4 --- /dev/null +++ b/pool/shard000/JavaScript/0005739_endpoints.js @@ -0,0 +1,107 @@ +var _ = require('underscore'); + +var __hasProp = {}.hasOwnProperty, + __extends = function (child, parent) { + for (var key in parent) { + if (__hasProp.call(parent, key)) child[key] = parent[key]; + } + function ctor() { + this.constructor = child; + } + + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + child.__super__ = parent.prototype; + return child; + }; + +module.exports = function (env, callback) { + var Endpoint, getEndpoints, jsonView, buildEndpoints; + Endpoint = (function (_super) { + __extends(Endpoint, _super); + + function Endpoint(filepath, content) { + this.filepath = filepath; + this.content = content; + } + + Endpoint.prototype.getFilename = function () { + return this.filepath.relative; + }; + + Endpoint.prototype.getView = function () { + return 'json'; + }; + + return Endpoint; + + })(env.plugins.Page); + /** + * Return all pages with metadata endpoint set to true + * @param contents + * @returns {Array} + */ + getEndpoints = function (contents) { + var page, _i, _len, _ref, _results; + _ref = contents._.directories; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + page = _ref[_i]; + if (page["index.md"] != null) { + _results.push(page["index.md"]); + } + } + return _results; + }; + + buildEndpoints = function (page) { + var content, filename, filepath, item, relative, _ref; + content = []; + _ref = page.parent; + for (filename in _ref) { + item = _ref[filename]; + if (item !== page) { + if (item instanceof env.ContentTree) { + content.push(item["index.md"]); + } else { + content.push(item); + } + } + } + relative = page.filepath.relative.replace(/\/index.md/, '') + '.json'; + filepath = { + relative: relative, + full: page.filepath.full.replace(/\/index.md/, '') + '.json' + }; + return this[relative] = new Endpoint(filepath, content); + }; + + jsonView = function (env, locals, contents, templates, callback) { + var content, obj; + content = (function () { + var _i, _len, _ref, _results; + _ref = this.content; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + obj = _ref[_i]; + if (obj instanceof env.plugins.MarkdownPage) { + _results.push(obj.serialize()); + } + } + return _results; + }).call(this); + return callback(null, new Buffer(JSON.stringify(content))); + }; + env.registerView('json', jsonView); + env.registerGenerator('endpoints', function (contents, callback) { + var rv = {}; + if (env.config.endpoints || false) { + rv.endpoints = {}; + _.forEach(getEndpoints(contents), buildEndpoints, rv.endpoints); + } + return callback(null, rv); + }); + env.plugins.Endpoint = Endpoint; + env.functions.getEndpoints = getEndpoints; + return callback(); +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005742_index.js b/pool/shard000/JavaScript/0005742_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4297256118dd49824990ec08f817ae1212fb897e --- /dev/null +++ b/pool/shard000/JavaScript/0005742_index.js @@ -0,0 +1,95 @@ +'use strict'; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const repo_manager_1 = require("./repo_manager"); +const package_kit_backend_1 = require("./backends/package_kit_backend"); +const brew_backend_1 = require("./backends/brew_backend"); +const chocolatey_backend_1 = require("./backends/chocolatey_backend"); +const fallback_backend_1 = require("./backends/fallback_backend"); +const util = require("./util"); +const repoManager = new repo_manager_1.default(); +const backends = [ + new package_kit_backend_1.default(), + new brew_backend_1.default(), + new chocolatey_backend_1.default(), + new fallback_backend_1.default() +].filter((backend) => backend.available); +let registeredPackages = new Map(); +function registerPackage(pkg) { + registeredPackages.set(pkg.name, pkg); +} +exports.registerPackage = registerPackage; +function isInstalled(packageInfo) { + return __awaiter(this, void 0, void 0, function* () { + const pkg = yield getPackage(packageInfo); + return pkg.targets.length && pkg.targets.every(util.checkExistence); + }); +} +exports.isInstalled = isInstalled; +function isUpgradable(packageInfo) { + return __awaiter(this, void 0, void 0, function* () { + const pkg = yield getPackage(packageInfo); + return pkg.backends.fallback + ? yield fallback_backend_1.default.isUpgradable({ name: pkg.name, version: pkg.version }, pkg.backends.fallback) + : false; + }); +} +exports.isUpgradable = isUpgradable; +function getInstallers(packageInfo) { + return __awaiter(this, void 0, void 0, function* () { + const pkg = yield getPackage(packageInfo); + const availableBackends = backends.filter((backend) => pkg.backends[backend.name]); + const results = yield Promise.all(availableBackends.map((backend) => backend.packageAvailable(pkg.backends[backend.name]))); + const actuallyAvailableBackends = availableBackends.filter((backend, i) => results[i]); + return actuallyAvailableBackends.map((backend) => new Installer(backend, pkg)); + }); +} +exports.getInstallers = getInstallers; +function addRepo(repo) { + repoManager.addRepo(repo); +} +exports.addRepo = addRepo; +function getFallbackPackagesPath() { + return fallback_backend_1.default.packagesPath; +} +exports.getFallbackPackagesPath = getFallbackPackagesPath; +function getPackage(packageInfo) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof (packageInfo) !== 'string') { + registerPackage(packageInfo); + return packageInfo; + } + return registeredPackages.has(packageInfo) + ? registeredPackages.get(packageInfo) + : yield repoManager.getPackage(packageInfo); + }); +} +class Installer { + get name() { + return this._backend.name; + } + get prettyName() { + return this._backend.prettyName; + } + constructor(backend, pkg) { + this._backend = backend; + this._package = pkg; + } + install(outputListener) { + return __awaiter(this, void 0, void 0, function* () { + const installed = yield isInstalled(this._package); + const basicInfo = { name: this._package.name, version: this._package.version }; + yield this._backend.install(basicInfo, this._package.backends[this._backend.name], outputListener || (() => { })); + return installed; + }); + } +} +exports.Installer = Installer; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005743_DisplayManager.js b/pool/shard000/JavaScript/0005743_DisplayManager.js new file mode 100644 index 0000000000000000000000000000000000000000..d5808bbe104b09bd0a8ba7efd34f3f3602e262cf --- /dev/null +++ b/pool/shard000/JavaScript/0005743_DisplayManager.js @@ -0,0 +1,154 @@ +function DisplayManager( canvas ) { + //Data + this._imageManager = new ImageManager(); + this._canvas = canvas; + this._context = this._canvas.getContext('2d'); + + //render + this.load = function () { + this._imageManager.load(); + } + this.loaded = function () { + return this._imageManager.loaded(); + } + this.render = function (playersRenderData) { + this._clearScreen(); + + var percent = 1; + + for (var i = 0; i < 1; i++) { + + this.renderPlayer((0) * percent, (0) * percent, percent, playersRenderData[i]); + } + + + }; + + this.renderPlayer = function (xOffset, yOffset, percent, playersRenderData) { + this._drawBlockArea(xOffset, yOffset, percent); + this._drawScore(xOffset, yOffset, percent, playersRenderData.score); + this._drawLevel(xOffset, yOffset, percent, playersRenderData.level); + this._drawBlocks(xOffset, yOffset, percent, playersRenderData.blocks, playersRenderData.blockInc, playersRenderData.selector); + + + + if(playersRenderData.selector != null) { + this._drawSelector(xOffset, yOffset, percent, playersRenderData.selector, playersRenderData.blockInc); + } + + }; + + + this._clearScreen = function () { + this._context.clearRect(0, 0, this._canvas.width, this._canvas.height); + }; + this._drawLevel = function (xOffset, yOffset, percent, level) { + var fontsize = 30 * percent; + + this._context.font = '' + fontsize + 'px Arial'; + this._context.fillStyle = 'white'; + this._context.fillText(level, (279) * percent + xOffset, (83) * percent + yOffset); + } + this._drawScore = function (xOffset, yOffset,percent, score) { + var fontsize = 30 * percent; + + this._context.font = ''+ fontsize + 'px Arial'; + this._context.fillStyle = 'white'; + this._context.fillText(score, (440) * percent + xOffset, (83) * percent + yOffset); + } + this._drawBlockArea = function (xOffset, yOffset, percent) { + + this._context.drawImage( + this._imageManager.layout, + xOffset + (247) * percent, + yOffset + (43) * percent, + (306) * percent, + (660) * percent + ); + } + this._drawSelector = function (xOffset, yOffset, percent, selector, blockInc) { + var startX = 250; + var startY = 650; + this._context.drawImage( + this._imageManager.selector, + xOffset + (startX + (selector.col - 1) * 50) * percent, + yOffset + (startY - (selector.row - 1) * 50 - blockInc) * percent, + (100) * percent, + (50) * percent + ); + } + this._drawBlocks = function (xOffset, yOffset, percent, blocks, blockInc, selector) { + var startX =250; + var startY = 650; + + for (var i = 0; i < blocks.length; i++) { + var selectorOffsetX = 0; + if(selector != null){ + if (selector.leftSelection === blocks[i] && blocks[i].state === BlockState.Swap){ + selectorOffsetX += selector.OFF_SET_PER_TICK * selector.ticks; + } + else if (selector.rightSelection === blocks[i] && blocks[i].state === BlockState.Swap) { + selectorOffsetX += -selector.OFF_SET_PER_TICK * selector.ticks; + } + } + + + + this.remove = true; + this.removeTick = 0; + this.startRemoveAtTick = 0; + this.fullRemoveAtTick = 0; + if (blocks[i].row === 0) + { + var yCutOff = 50 - blockInc; + this._context.drawImage( + this.getBlockImage(blocks[i]), + 0, + 0, + 50, + (50 - yCutOff), + xOffset + (startX + (blocks[i].col - 1) * 50 + selectorOffsetX) * percent, + yOffset + (startY - (blocks[i].row - 1) * 50 - blockInc) * percent, + (50) * percent, + (50 - yCutOff) * percent + ); + + + } + else + { + this._context.drawImage( + this.getBlockImage(blocks[i]), + xOffset + (startX + (blocks[i].col - 1) * 50 + selectorOffsetX) * percent, + yOffset + (startY - (blocks[i].row - 1) * 50 - blockInc) * percent, + (50) * percent, + (50) * percent + ); + } + + } + + } + this.getBlockImage = function (block) { + + if (block.state === BlockState.Remove) { + return this._imageManager.block; + } + + if (Color.Green == block.color) { + return this._imageManager.blockGreen; + } + if (Color.Blue == block.color) { + return this._imageManager.blockBlue; + } + if (Color.Red == block.color) { + return this._imageManager.blockRed; + } + if (Color.Purple == block.color) { + return this._imageManager.blockPurple; + } + if (Color.Yellow == block.color) { + return this._imageManager.blockYellow; + } + } +}; diff --git a/pool/shard000/JavaScript/0005745_lgt2xml.js b/pool/shard000/JavaScript/0005745_lgt2xml.js new file mode 100644 index 0000000000000000000000000000000000000000..c79247fc7e521f1a76b118818a3eec6c4e5811cb --- /dev/null +++ b/pool/shard000/JavaScript/0005745_lgt2xml.js @@ -0,0 +1,209 @@ +// ================================================================ +// Logtalk - Open source object-oriented logic programming language +// Release 2.44.1 +// +// Copyright (c) 1998-2012 Paulo Moura. All Rights Reserved. +// +// Logtalk is free software. You can redistribute it and/or modify +// it under the terms of the Artistic License 2.0 as published by +// the The Perl Foundation. +// +// 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 +// Artistic License 2.0 for more details. A copy of the license is +// provided in the "LICENSE.txt" file. +// ================================================================ + +if (ScriptEngineMajorVersion() < 5 || ScriptEngineMajorVersion() == 5 && ScriptEngineMinorVersion() < 6) { + WScript.Echo('Error! WSH 5.6 or later version needed for running this script.'); + WScript.Quit(1); +} + +var WshShell = new ActiveXObject("WScript.Shell"); + +var format = "xhtml"; +// var format = "html"; + +var directory = WshShell.CurrentDirectory; + +var index_file = "index.html"; +var index_title = "Entity documentation index"; + +if (WScript.Arguments.Unnamed.Length > 0) { + usage_help(); + WScript.Quit(0); +} + +var WshSystemEnv = WshShell.Environment("SYSTEM"); +var WshUserEnv = WshShell.Environment("USER"); + +var logtalk_home; +var logtalk_user; + +if (WshSystemEnv.Item("LOGTALKHOME")) + logtalk_home = WshSystemEnv.Item("LOGTALKHOME"); +else if (WshUserEnv.Item("LOGTALKHOME")) + logtalk_home = WshUserEnv.Item("LOGTALKHOME") +else { + WScript.Echo("Error! The environment variable LOGTALKHOME must be defined first!"); + usage_help(); + WScript.Quit(1); +} + +if (WshSystemEnv.Item("LOGTALKUSER")) + logtalk_user = WshSystemEnv.Item("LOGTALKUSER"); +else if (WshUserEnv.Item("LOGTALKUSER")) + logtalk_user = WshUserEnv.Item("LOGTALKUSER") +else { + WScript.Echo("Error! The environment variable LOGTALKUSER must be defined first!"); + usage_help(); + WScript.Quit(1); +} + +var f_arg = ""; +var i_arg = ""; +var t_arg = ""; + +if (WScript.Arguments.Named.Exists("f")) + f_arg = WScript.Arguments.Named.Item("f"); + +if (WScript.Arguments.Named.Exists("i")) + i_arg = WScript.Arguments.Named.Item("i"); + +if (WScript.Arguments.Named.Exists("t")) + t_arg = WScript.Arguments.Named.Item("t"); + +if (f_arg != "" && f_arg != "xhtml" && f_arg != "html") { + WScript.Echo("Error! Unsupported output format: " + f_arg); + WScript.Echo(""); + usage_help(); +} else if (f_arg != "") + format = f_arg; + +var FSObject = new ActiveXObject("Scripting.FileSystemObject"); + +if (i_arg != "") + index_file=i_arg; + +if (t_arg != "") + index_title=t_arg; + +if (!FSObject.FileExists(directory + "\\logtalk.dtd")) { + FSObject.CopyFile(logtalk_home + "\\xml\\logtalk.dtd", directory + "\\logtalk.dtd"); +} + +if (!FSObject.FileExists(directory + "\\custom.ent")) { + FSObject.CopyFile(logtalk_home + "\\xml\\custom.ent", directory + "\\custom.ent"); +} + +if (!FSObject.FileExists(directory + "\\logtalk.xsd")) { + FSObject.CopyFile(logtalk_home + "\\xml\\logtalk.xsd", directory + "\\logtalk.xsd"); +} + +if (!FSObject.FileExists(directory + "\\logtalk.css")) { + FSObject.CopyFile(logtalk_user + "\\xml\\logtalk.css", directory + "\\logtalk.css"); +} + +if (!FSObject.FileExists(directory + "\\lgtxml.xsl")) { + FSObject.CopyFile(logtalk_user + "\\xml\\lgtxml.xsl", directory + "\\lgtxml.xsl"); +} + +WScript.Echo(""); +WScript.Echo("generating index file..."); + +create_index_file(); + +WScript.Echo("index file generated"); +WScript.Echo(""); + +WScript.Quit(0); + +function usage_help() { + WScript.Echo(""); + WScript.Echo("This script generates an index for all the Logtalk XML files"); + WScript.Echo("documenting files in the current directory"); + WScript.Echo(""); + WScript.Echo("Usage:"); + WScript.Echo(" " + WScript.ScriptName + " [/f:format] [/i:index] [/t:title]"); + WScript.Echo(" " + WScript.ScriptName + " help"); + WScript.Echo(""); + WScript.Echo("Optional arguments:"); + WScript.Echo(" f - format of the index file (either xhtml or html; default is " + format + ")"); + WScript.Echo(" i - name of the index file (default is " + index_file + ")"); + WScript.Echo(" t - title to be used on the index file (default is " + index_title + ")"); + WScript.Echo(""); + WScript.Quit(1); +} + +function create_index_file() { + + var f = FSObject.CreateTextFile(index_file, true); + + switch (format) { + case "xhtml" : + f.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); + f.WriteLine("<?xml-stylesheet href=\"logtalk.css\" type=\"text/css\"?>"); + f.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); + f.WriteLine("<html lang=\"en\" xml:lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">"); + break; + case "html" : + f.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"); + f.WriteLine("<html>"); + break; + } + + f.WriteLine("<head>"); + f.WriteLine(" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>"); + f.WriteLine(" <title>" + index_title + ""); + f.WriteLine(" "); + f.WriteLine(""); + f.WriteLine(""); + f.WriteLine("

        " + index_title + "

        "); + f.WriteLine("
          "); + + var files = new Enumerator(FSObject.GetFolder(directory).Files); + + for (files.moveFirst(); !files.atEnd(); files.moveNext()) { + var file = files.item().name; + if (FSObject.GetExtensionName(file) == "xml") { + WScript.Echo(" indexing " + file); + var index = FSObject.GetBaseName(file).lastIndexOf("_"); + var pars = FSObject.GetBaseName(file).slice(index+1); + var entity = FSObject.GetBaseName(file).slice(0, index); + if (pars == 0) + f.WriteLine("
        • " + entity + "
        • "); + else + f.WriteLine("
        • " + entity + "/" + pars + "
        • "); + + } + } + + f.WriteLine("
        "); + + var today = new Date(); + var year = today.getFullYear(); + var month = today.getMonth() + 1; + if (month < 10) + month = "0" + month; + day = today.getDate(); + if (day < 10) + day = "0" + day; + strToday = year + "/" + month + "/" + day; + var hours = today.getHours(); + if (hours < 10) + hours = "0" + hours; + var mins = today.getMinutes(); + if (mins < 10) + mins = "0" + mins; + var secs = today.getSeconds(); + if (secs < 10) + secs = "0" + secs; + strTime = hours + ":" + mins + ":" + secs; + f.WriteLine("

        Generated on " + strToday + " - " + strTime + "

        "); + + f.WriteLine(""); + f.WriteLine(""); + + f.Close(); +} diff --git a/pool/shard000/JavaScript/0005747_ui.js b/pool/shard000/JavaScript/0005747_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..aac93b62fdec0269c2f2ae481b7cd796785705cd --- /dev/null +++ b/pool/shard000/JavaScript/0005747_ui.js @@ -0,0 +1,328 @@ +/*!(c) 2008-2010 Appcelerator, Inc. http://appcelerator.org + * Licensed under the Apache License, Version 2.0. Please visit + * http://license.appcelerator.com for full copy of the License. + **/ + +// A collection of JS patches for various UI functionality in Titanium + +// +// execute in anonymous function block so now variables leak into the +// global scope +// +(function() +{ + + // ensure that the window.opener property is set when we open a native + // window in the same domain as this window (assuming this window is a child) + if (Titanium.UI.getCurrentWindow().getParent()) + { + var d = Titanium.UI.getCurrentWindow().getParent().window.document; + // make sure in the same domain + if (typeof(d)!='undefined' && d.domain == document.domain) + { + window.opener = Titanium.UI.getCurrentWindow().getParent().window; + } + } + + window.onload=function() + { + // append the platform (osx, linux, win32) to the body so we can dynamically + // use platform specific CSS such as body.win32 div { } + var cn = (document.body.className || ''); + document.body.className = cn + (cn ? ' ': '') + Titanium.platform; + + // + // insert our user specific stylesheet in a generic way + // + var link = document.createElement('link'); + link.setAttribute('rel','stylesheet'); + link.setAttribute('href','ti://tiui/default.css'); + link.setAttribute('type','text/css'); + + + var headNodes = document.getElementsByTagName("head"); + if (headNodes && headNodes.length > 0) + { + var head = headNodes[0]; + // if we have children, insert at the top + if (head.childNodes.length > 0) + { + head.insertBefore(link,head.childNodes[0]); + } + else + { + head.appendChild(link); + } + } + else + { + // else we don't have a element, just insert + // in the body at the top + if (document.body.childNodes.length > 0) + { + document.body.insertBefore(link,document.body.childNodes[0]); + } + else + { + document.body.appendChild(link); + } + } + }; + + // + // override console.log to also send into our API logger + // + // patch from cb1kenobi + function replaceMethod(obj, methodName, newMethod) + { + var originalMethodName = methodName + "_orig"; + obj[originalMethodName] = obj[methodName]; + var fn = function() + { + newMethod.apply(null, arguments); + obj[originalMethodName].apply(obj, arguments); + }; + obj[methodName] = fn; + } + replaceMethod(console, "debug", function(msg) { Titanium.API.debug(msg); }); + replaceMethod(console, "log", function(msg) { Titanium.API.log(msg); }); + replaceMethod(console, "info", function(msg) { Titanium.API.info(msg); }); + replaceMethod(console, "warn", function(msg) { Titanium.API.warn(msg); }); + replaceMethod(console, "error", function(msg) { Titanium.API.error(msg); }); + + // Exchange the open() method for a version which ensures that a blank + // URL maps to app://__blank__ rather than about:blank. + var _oldOpenFunction = window.open; + window.open = function() + { + var newArgs = Array(); + if (arguments.length < 1 || arguments[0] == "about:blank") + { + newArgs[0] = "app://__blank__.html"; + } + else + { + newArgs[0] = arguments[0]; + } + + for (var i = 1; i < arguments.length; i++) + { + newArgs[i] = arguments[i]; + } + + return _oldOpenFunction.apply(window, newArgs); + } + + // + // UI Dialog class + // + /** + * @tiapi(property=True,name=UI.Window.isDialog,since=0.4) true if this window is a UI Dialog + */ + Titanium.UI.getCurrentWindow().isDialog = function() + { + return Titanium.UI.getCurrentWindow()._isDialog; + } + Titanium.UI.getCurrentWindow()._isDialog = false; + + /** + * @tiapi(method=True,name=UI.showDialog,since=0.4) create a UI dialog + * @tiarg(for=UI.showDialog,name=params,type=Object) options to pass in to create window + * @tiresult(for=UI.showDialog,type=UI.Dialog) dialog instance + */ + Titanium.UI.showDialog = function(params) + { + Titanium.API.debug("creating dialog with url: "+params.url); + var dialogWindow = Titanium.UI.createWindow(params); + + dialogWindow._dialogResult = null; + dialogWindow._dialogParameters = params.parameters || {}; + dialogWindow._isDialog = true; + dialogWindow._dialogCloseCallback = params.onclose || null; + + /** + * @tiapi(method=True,name=UI.Dialog.getDialogResult,since=0.4) get results from UI dialog + */ + dialogWindow.getDialogResult = function() + { + return dialogWindow._dialogResult; + } + + /** + * @tiapi(method=True,name=UI.Dialog.getDialogParameter,since=0.4) + * @tiapi Get an incoming UI dialog parameter + * @tiarg[string, name] Name of the parameter + * @tiarg[string, any] Default value of the parameter + * @tiresult[any] The parameter + */ + dialogWindow.getDialogParameter = function(name, defaultValue) + { + var v = dialogWindow._dialogParameters[name]; + return v || defaultValue; + }; + + + if (dialogWindow._dialogCloseCallback != null) + { + var originalClose = dialogWindow.close; + dialogWindow.close = function(result) + { + var onclose = dialogWindow._dialogCloseCallback; + dialogWindow._dialogResult = result || null; + originalClose(); + onclose(dialogWindow._dialogResult); + } + } + + dialogWindow.open(); + dialogWindow.show(); + return dialogWindow; + }; + + /** + * @tiapi(method=True,name=JSON.stringify,since=0.4) Convert a JavaScript object to a JSON string + * @tiarg(for=JSON.stringify,name=object,type=Object) JavaScript object to convert + * @tiresult(for=JSON.stringify,type=String) Returns the string representation of the object in JSON format + */ + + /** + * @tiapi(method=True,name=JSON.parse,since=0.4) Convert a JSON string to a JavaScript object + * @tiarg(for=JSON.parse,name=json,type=String) JSON string to convert + * @tiresult(for=JSON.parse,type=Object) Returns the object representation of the string + */ + if (!Titanium.JSON) + Titanium.JSON = window.JSON; + + // Enable titanium notifications as a fallback when platform + // native notifications are not available. + if (Titanium.UI.nativeNotifications == false) + { + var notification_windows = 1; + + function TitaniumNotification(window) + { + var self = this; + var width = 300; + var height = 80; + var showing = false; + var hideTimer = null; + + var properties = { + title: '', + message: '', + icon: '', + callback: null, + delay: 3000, + }; + + var mywindow = Titanium.UI.mainWindow.createWindow( + { + width:width, + height:height, + transparentBackground:true, + usingChrome:false, + toolWindow:true, + id:'notification_' + (notification_windows++), + visible:false, + topMost:true, + url:'app://blank' + }); + mywindow.open(); + + this.setTitle = function(value) + { + properties.title = value; + }; + + this.setMessage = function(value) + { + properties.message = value; + }; + + this.setIcon = function(value) + { + properties.icon = value; + }; + + this.setDelay = function(value) + { + properties.delay = value; + }; + this.setTimeout = this.setDelay; + + this.setCallback = function(value) + { + properties.callback = value; + }; + + this.show = function(animate,autohide) + { + showing = true; + if (hideTimer) + { + window.clearTimeout(hideTimer); + } + animate = (animate==null) ? true : animate; + autohide = (autohide==null) ? true : autohide; + mywindow.setX(window.screen.availWidth-width-20); + if (Titanium.platform == "osx" || Titanium.platform == 'linux') { + mywindow.setY(25); + } else if (Titanium.platform == "win32") { + mywindow.setY(window.screen.availHeight-height-10); + } + + var notificationClicked = function () + { + if (properties.callback) + properties.callback(); + self.hide(); + }; + + mywindow.callback = notificationClicked; + mywindow.setURL('ti://tiui/tinotification.html?' + + 'title=' + encodeURIComponent(properties.title) + + '&message=' + encodeURIComponent(properties.message) + + '&icon=' + encodeURIComponent(properties.icon)); + + mywindow.show(); + if (autohide) + { + hideTimer = window.setTimeout(function() + { + self.hide(); + },properties.delay + (animate ? 1000 : 0)); + } + }; + + this.hide = function(animate) + { + animate = (animate==null) ? true : animate; + showing = false; + if (hideTimer) + { + window.clearTimeout(hideTimer); + hideTimer=null; + } + mywindow.hide(animate); + mywindow.getParent().focus(); + }; + + this.configure = function(props) + { + for (attr in props) properties[attr] = props[attr]; + }; + }; + + Titanium.UI.createNotification = function() + { + var window = Titanium.UI.mainWindow.getDOMWindow(); + if (!window) + throw "Unable to get main window DOM!" + var n = new TitaniumNotification(window); + if (arguments.length == 1) + n.configure(arguments[0]); + return n; + } + } +})(); + diff --git a/pool/shard000/JavaScript/0005749_newlines.js b/pool/shard000/JavaScript/0005749_newlines.js new file mode 100644 index 0000000000000000000000000000000000000000..025692f941cce056d453b305690be12f7d537f86 --- /dev/null +++ b/pool/shard000/JavaScript/0005749_newlines.js @@ -0,0 +1,152 @@ +/** + * @license + * Copyright The Closure Library Authors. + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview Utilities for string newlines. + */ + + +/** + * Namespace for string utilities + */ +goog.provide('goog.string.newlines'); +goog.provide('goog.string.newlines.Line'); + +goog.require('goog.array'); + + +/** + * Splits a string into lines, properly handling universal newlines. + * @param {string} str String to split. + * @param {boolean=} opt_keepNewlines Whether to keep the newlines in the + * resulting strings. Defaults to false. + * @return {!Array} String split into lines. + */ +goog.string.newlines.splitLines = function(str, opt_keepNewlines) { + 'use strict'; + const lines = goog.string.newlines.getLines(str); + return goog.array.map(lines, function(line) { + 'use strict'; + return opt_keepNewlines ? line.getFullLine() : line.getContent(); + }); +}; + + + +/** + * Line metadata class that records the start/end indicies of lines + * in a string. Can be used to implement common newline use cases such as + * splitLines() or determining line/column of an index in a string. + * Also implements methods to get line contents. + * + * Indexes are expressed as string indicies into string.substring(), inclusive + * at the start, exclusive at the end. + * + * Create an array of these with goog.string.newlines.getLines(). + * @param {string} string The original string. + * @param {number} startLineIndex The index of the start of the line. + * @param {number} endContentIndex The index of the end of the line, excluding + * newlines. + * @param {number} endLineIndex The index of the end of the line, index + * newlines. + * @constructor + * @struct + * @final + */ +goog.string.newlines.Line = function( + string, startLineIndex, endContentIndex, endLineIndex) { + 'use strict'; + /** + * The original string. + * @type {string} + */ + this.string = string; + + /** + * Index of the start of the line. + * @type {number} + */ + this.startLineIndex = startLineIndex; + + /** + * Index of the end of the line, excluding any newline characters. + * Index is the first character after the line, suitable for + * String.substring(). + * @type {number} + */ + this.endContentIndex = endContentIndex; + + /** + * Index of the end of the line, excluding any newline characters. + * Index is the first character after the line, suitable for + * String.substring(). + * @type {number} + */ + + this.endLineIndex = endLineIndex; +}; + + +/** + * @return {string} The content of the line, excluding any newline characters. + */ +goog.string.newlines.Line.prototype.getContent = function() { + 'use strict'; + return this.string.substring(this.startLineIndex, this.endContentIndex); +}; + + +/** + * @return {string} The full line, including any newline characters. + */ +goog.string.newlines.Line.prototype.getFullLine = function() { + 'use strict'; + return this.string.substring(this.startLineIndex, this.endLineIndex); +}; + + +/** + * @return {string} The newline characters, if any ('\n', \r', '\r\n', '', etc). + */ +goog.string.newlines.Line.prototype.getNewline = function() { + 'use strict'; + return this.string.substring(this.endContentIndex, this.endLineIndex); +}; + + +/** + * Splits a string into an array of line metadata. + * @param {string} str String to split. + * @return {!Array} Array of line metadata. + */ +goog.string.newlines.getLines = function(str) { + 'use strict'; + // We use the constructor because literals are evaluated only once in + // < ES 3.1. + // See http://www.mail-archive.com/es-discuss@mozilla.org/msg01796.html + const re = RegExp('\r\n|\r|\n', 'g'); + let sliceIndex = 0; + let result; + const lines = []; + + while (result = re.exec(str)) { + const line = new goog.string.newlines.Line( + str, sliceIndex, result.index, result.index + result[0].length); + lines.push(line); + + // remember where to start the slice from + sliceIndex = re.lastIndex; + } + + // If the string does not end with a newline, add the last line. + if (sliceIndex < str.length) { + const line = + new goog.string.newlines.Line(str, sliceIndex, str.length, str.length); + lines.push(line); + } + + return lines; +}; diff --git a/pool/shard000/JavaScript/0005750_express.js b/pool/shard000/JavaScript/0005750_express.js new file mode 100644 index 0000000000000000000000000000000000000000..2a64a8b51f1e42d37ad4ba6a5f24bd4f3916badb --- /dev/null +++ b/pool/shard000/JavaScript/0005750_express.js @@ -0,0 +1,16 @@ + +var express = require('express') +var session = require('express-session') +var grant = require('../../').express() + + +express() + .use(session({secret: 'grant', saveUninitialized: true, resave: false})) + .use(grant(require('./config.json'))) + .get('/hello', (req, res) => { + res.end(JSON.stringify(req.session.grant.response, null, 2)) + }) + .get('/hi', (req, res) => { + res.end(JSON.stringify(req.session.grant.response, null, 2)) + }) + .listen(3000) diff --git a/pool/shard000/JavaScript/0005752_jquery.greybox.js b/pool/shard000/JavaScript/0005752_jquery.greybox.js new file mode 100644 index 0000000000000000000000000000000000000000..41bace8334c5bf0f5229da73e172aaa11f4d68cb --- /dev/null +++ b/pool/shard000/JavaScript/0005752_jquery.greybox.js @@ -0,0 +1,75 @@ +/************************* + Coppermine Photo Gallery + ************************ + Copyright (c) 2003-2016 Coppermine Dev Team + v1.0 originally written by Gregory DEMAR + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 3 + as published by the Free Software Foundation. + + ******************************************** + Coppermine version: 1.6.03 + $HeadURL$ +**********************************************/ + +/* Greybox Redux + * Required: http://jquery.com/ + * Written by: John Resig + * Based on code by: 4mir Salihefendic (http://amix.dk) + * License: LGPL (read more in LGPL.txt) + */ + +var GB_DONE = false; +var GB_HEIGHT = 400; +var GB_WIDTH = 600; + +function GB_show(caption, url, height, width) { + GB_HEIGHT = height || 400; + GB_WIDTH = width || 600; + if(!GB_DONE) { + $(document.body) + .append("
        " + + "\"\"
        "); + $("#GB_window img").click(GB_hide); + $("#GB_overlay").click(GB_hide); + $(window).resize(GB_position); + $(window).scroll(GB_position); + GB_DONE = true; + } + + $("#GB_frame").remove(); + $('#GBloading').show(); + $("#GB_window").append(""); + + $("#GB_caption").html(caption); + $("#GB_overlay").show(); + GB_position(); + + if(GB_ANIMATION) + $("#GB_window").slideDown("slow"); + else + $("#GB_window").show(); +} + +function GB_hide() { + $("#GB_window,#GB_overlay").hide(); +} + +function GB_position() +{ + var de = document.documentElement; + var h = self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; + var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; + var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body; + var dsocleft=document.all? iebody.scrollLeft : pageXOffset; + var dsoctop=document.all? iebody.scrollTop : pageYOffset; + + var height = h < GB_HEIGHT ? h - 32 : GB_HEIGHT; + var top = (h - height)/2 + dsoctop; + + $("#GB_window").css({width:GB_WIDTH+"px",height:height+"px", + left: ((w - GB_WIDTH)/2)+"px", top: top+"px" }); + $("#GB_frame").css("height",height - 32 +"px"); + $("#GB_overlay").css({height:h, top:dsoctop + "px", width:w}); +} diff --git a/pool/shard000/JavaScript/0005755_wp-seo-admin-310.js b/pool/shard000/JavaScript/0005755_wp-seo-admin-310.js new file mode 100644 index 0000000000000000000000000000000000000000..a2c84d91d11439066ff3e71f5cecdf2ea13b959e --- /dev/null +++ b/pool/shard000/JavaScript/0005755_wp-seo-admin-310.js @@ -0,0 +1,259 @@ +/* global wpseoAdminL10n */ +/* global ajaxurl */ +/* global setWPOption */ +/* global tb_remove */ +/* global YoastSEO */ +/* jshint -W097 */ +/* jshint -W003 */ +/* jshint unused:false */ +(function() { + 'use strict'; + + /** + * Detects the wrong use of variables in title and description templates + * + * @param {element} e + */ + function wpseoDetectWrongVariables( e ) { + var warn = false; + var error_id = ''; + var wrongVariables = []; + var authorVariables = [ 'userid', 'name', 'user_description' ]; + var dateVariables = [ 'date' ]; + var postVariables = [ 'title', 'parent_title', 'excerpt', 'excerpt_only', 'caption', 'focuskw', 'pt_single', 'pt_plural', 'modified', 'id' ]; + var specialVariables = [ 'term404', 'searchphrase' ]; + var taxonomyVariables = [ 'term_title', 'term_description' ]; + var taxonomyPostVariables = [ 'category', 'category_description', 'tag', 'tag_description' ]; + if ( e.hasClass( 'posttype-template' ) ) { + wrongVariables = wrongVariables.concat( specialVariables, taxonomyVariables ); + } + else if ( e.hasClass( 'homepage-template' ) ) { + wrongVariables = wrongVariables.concat( authorVariables, dateVariables, postVariables, specialVariables, taxonomyVariables, taxonomyPostVariables ); + } + else if ( e.hasClass( 'taxonomy-template' ) ) { + wrongVariables = wrongVariables.concat( authorVariables, dateVariables, postVariables, specialVariables ); + } + else if ( e.hasClass( 'author-template' ) ) { + wrongVariables = wrongVariables.concat( postVariables, dateVariables, specialVariables, taxonomyVariables, taxonomyPostVariables ); + } + else if ( e.hasClass( 'date-template' ) ) { + wrongVariables = wrongVariables.concat( authorVariables, postVariables, specialVariables, taxonomyVariables, taxonomyPostVariables ); + } + else if ( e.hasClass( 'search-template' ) ) { + wrongVariables = wrongVariables.concat( authorVariables, dateVariables, postVariables, taxonomyVariables, taxonomyPostVariables, [ 'term404' ] ); + } + else if ( e.hasClass( 'error404-template' ) ) { + wrongVariables = wrongVariables.concat( authorVariables, dateVariables, postVariables, taxonomyVariables, taxonomyPostVariables, [ 'searchphrase' ] ); + } + jQuery.each( wrongVariables, function( index, variable ) { + error_id = e.attr( 'id' ) + '-' + variable + '-warning'; + if ( e.val().search( '%%' + variable + '%%' ) !== -1 ) { + e.addClass( 'wpseo_variable_warning' ); + var msg = wpseoAdminL10n.variable_warning.replace( '%s', '%%' + variable + '%%' ); + if ( jQuery( '#' + error_id ).length ) { + jQuery( '#' + error_id ).html( msg ); + } + else { + e.after( '
        ' + msg + '
        ' ); + } + warn = true; + } + else { + if ( jQuery( '#' + error_id ).length ) { + jQuery( '#' + error_id ).remove(); + } + } + } + ); + if ( warn === false ) { + e.removeClass( 'wpseo_variable_warning' ); + } + } + + /** + * Sets a specific WP option + * + * @param {string} option The option to update + * @param {string} newval The new value for the option + * @param {string} hide The ID of the element to hide on success + * @param {string} nonce The nonce for the action + */ + function setWPOption( option, newval, hide, nonce ) { + jQuery.post( ajaxurl, { + action: 'wpseo_set_option', + option: option, + newval: newval, + _wpnonce: nonce + }, function( data ) { + if ( data ) { + jQuery( '#' + hide ).hide(); + } + } + ); + } + + /** + * Do the kill blocking files action + * + * @param {string} nonce + */ + function wpseoKillBlockingFiles( nonce ) { + jQuery.post( ajaxurl, { + action: 'wpseo_kill_blocking_files', + _ajax_nonce: nonce + }, function( data ) { + if ( data === 'success' ) { + jQuery( '#blocking_files' ).hide(); + } + else { + jQuery( '#block_files' ).html( data ); + } + } + ); + } + + /** + * Copies the meta description for the homepage + */ + function wpseoCopyHomeMeta() { + jQuery( '#og_frontpage_desc' ).val( jQuery( '#meta_description' ).val() ); + } + + /** + * Makes sure we store the action hash so we can return to the right hash + */ + function wpseoSetTabHash() { + var conf = jQuery( '#wpseo-conf' ); + if ( conf.length ) { + var currentUrl = conf.attr( 'action' ).split( '#' )[ 0 ]; + conf.attr( 'action', currentUrl + window.location.hash ); + } + } + + /** + * When the hash changes, get the base url from the action and then add the current hash + */ + jQuery( window ).on( 'hashchange', wpseoSetTabHash ); + + /** + * When the hash changes, get the base url from the action and then add the current hash + */ + jQuery( document ).on( 'ready', wpseoSetTabHash ); + + function wpseo_add_fb_admin() { + var target_form = jQuery( '#TB_ajaxContent' ); + + jQuery.post( + ajaxurl, + { + _wpnonce: target_form.find( 'input[name=fb_admin_nonce]' ).val(), + admin_name: target_form.find( 'input[name=fb_admin_name]' ).val(), + admin_id: target_form.find( 'input[name=fb_admin_id]' ).val(), + action: 'wpseo_add_fb_admin' + }, + function( response ) { + var resp = jQuery.parseJSON( response ); + + target_form.find( 'p.notice' ).remove(); + + switch ( resp.success ) { + case 1: + + target_form.find( 'input[type=text]' ).val( '' ); + + jQuery( '#user_admin' ).append( resp.html ); + jQuery( '#connected_fb_admins' ).show(); + tb_remove(); + break; + case 0 : + jQuery( resp.html ).insertAfter( target_form.find( 'h3' ) ); + break; + } + } + ); + } + + window.wpseoDetectWrongVariables = wpseoDetectWrongVariables; + window.setWPOption = setWPOption; + window.wpseoKillBlockingFiles = wpseoKillBlockingFiles; + window.wpseoCopyHomeMeta = wpseoCopyHomeMeta; + window.wpseo_add_fb_admin = wpseo_add_fb_admin; + window.wpseoSetTabHash = wpseoSetTabHash; + + jQuery( document ).ready( function() { + /* Fix banner images overlapping help texts */ + jQuery( '.screen-meta-toggle a' ).click( function() { + jQuery( '#sidebar-container' ).toggle(); + } + ); + + // events + jQuery( '#enablexmlsitemap' ).change( function() { + jQuery( '#sitemapinfo' ).toggle( jQuery( this ).is( ':checked' ) ); + } + ).change(); + + jQuery( '#breadcrumbs-enable' ).change( function() { + jQuery( '#breadcrumbsinfo' ).toggle( jQuery( this ).is( ':checked' ) ); + } + ).change(); + + jQuery( '#disable_author_sitemap' ).find( 'input:radio' ).change( function() { + if ( jQuery( this ).is( ':checked' ) ) { + jQuery( '#xml_user_block' ).toggle( jQuery( this ).val() === 'off' ); + } + } + ).change(); + + jQuery( '#cleanpermalinks' ).change( function() { + jQuery( '#cleanpermalinksdiv' ).toggle( jQuery( this ).is( ':checked' ) ); + } + ).change(); + + jQuery( '#wpseo-tabs' ).find( 'a' ).click( function() { + jQuery( '#wpseo-tabs' ).find( 'a' ).removeClass( 'nav-tab-active' ); + jQuery( '.wpseotab' ).removeClass( 'active' ); + + var id = jQuery( this ).attr( 'id' ).replace( '-tab', '' ); + jQuery( '#' + id ).addClass( 'active' ); + jQuery( this ).addClass( 'nav-tab-active' ); + } + ); + + jQuery( '#company_or_person' ).change( function() { + var companyOrPerson = jQuery( this ).val(); + if ( 'company' === companyOrPerson ) { + jQuery( '#knowledge-graph-company' ).show(); + jQuery( '#knowledge-graph-person' ).hide(); + } + else if ( 'person' === companyOrPerson ) { + jQuery( '#knowledge-graph-company' ).hide(); + jQuery( '#knowledge-graph-person' ).show(); + } + else { + jQuery( '#knowledge-graph-company' ).hide(); + jQuery( '#knowledge-graph-person' ).hide(); + } + } + ).change(); + + jQuery( '.template' ).change( function() { + wpseoDetectWrongVariables( jQuery( this ) ); + } + ).change(); + + // init + var activeTab = window.location.hash.replace( '#top#', '' ); + + // default to first tab + if ( activeTab === '' || activeTab === '#_=_' ) { + activeTab = jQuery( '.wpseotab' ).attr( 'id' ); + } + + jQuery( '#' + activeTab ).addClass( 'active' ); + jQuery( '#' + activeTab + '-tab' ).addClass( 'nav-tab-active' ); + + jQuery( '.nav-tab-active' ).click(); + } + ); +}()); diff --git a/pool/shard000/JavaScript/0005756_brix.js b/pool/shard000/JavaScript/0005756_brix.js new file mode 100644 index 0000000000000000000000000000000000000000..db52cc48b7e57d0aaf2304a214dd79084d379676 --- /dev/null +++ b/pool/shard000/JavaScript/0005756_brix.js @@ -0,0 +1,259 @@ +/** + * Brix配置类 组件框架入口类,在调用Brix组件的时候可以配置cdn地址,组件版本号等 + *
        Demo + *
        + * 引用: + * + * + * + * bx-config节点说明:
        + * autoConfig:自动配置包和map + * autoPagelet:自动渲染body节点下的所有bx-name组件 + * componentsPath:项目组件包路径 + * componentsTag:项目组件时间戳 + * importsPath:项目公用组件包路径 + * importsTag:项目公用组件时间戳 + * templateEngine: 模板引擎的包路径,brix内置mustache引擎,并做了扩展,详细看mu.js + * gallery:组件版本配置 + * tag:核心组件的时间戳 + * debug:是否启用非压缩版本 + * combine:是否启用combo功能 + * + * bx-config高级配置:
        + * fixed:对包路径的重写,多用在内部的版本管理(不清楚的不要配) + * @class Brix + */ +(function(S, Brix) { + var isReady = false; + var readyList = []; + var host = S.Env.host; + var location = host.location; + var debug = '@DEBUG@'; //区分src还是dist版本 + var tag = '@TAG@'; //KISSY包时间戳 + var version = '@VERSION@'; //版本号 + var isConfig = false; //是否已经配置过 + Brix = host[Brix] = host[Brix] || {}; + + //从KISSY源代码提取并改动适合brix的 + var simulatedLocation = new S.Uri(location.href); + + function returnJSON(s) { + if (s) { + return (new Function('return ' + s))(); + } else { + return {}; + } + } + + function getBaseInfo() { + // get base from current script file path + // notice: timestamp + var baseReg = /^(.*)(brix)(?:-min)?\.js[^\/]*/i, + baseTestReg = /(brix)(?:-min)?\.js/i, + comboPrefix, + comboSep, + scripts = host.document.getElementsByTagName('script'), + script = scripts[scripts.length - 1], + // can not use KISSY.Uri + // /??x.js,dom.js for tbcdn + src = script.src, + baseInfo = returnJSON(script.getAttribute('bx-config')); + + + if (location && (location.search || '').indexOf('bx-debug') !== -1) { + baseInfo.debug = true; + } + + comboPrefix = baseInfo.comboPrefix = baseInfo.comboPrefix || '??'; + comboSep = baseInfo.comboSep = baseInfo.comboSep || ','; + + var parts, + base, + index = src.indexOf(comboPrefix); + + // no combo + if (index == -1) { + base = src.replace(baseReg, '$1'); + } else { + base = src.substring(0, index); + // a.tbcdn.cn??y.js, ie does not insert / after host + // a.tbcdn.cn/combo? comboPrefix=/combo? + if (base.charAt(base.length - 1) != '/') { + base += '/'; + } + parts = src.substring(index + comboPrefix.length).split(comboSep); + S.each(parts, function(part) { + if (part.match(baseTestReg)) { + base += part.replace(baseReg, '$1'); + return false; + } + return undefined; + }); + } + //转换成绝对路径 + base = simulatedLocation.resolve(base).toString(); + //获取brix包base对应的路径 + base = base.substring(0, base.lastIndexOf('brix')); + + return S.mix({ + autoConfig: true, + base: base + }, baseInfo); + } + var defaultOptions = getBaseInfo(); + + S.mix(Brix, { + /** + * 初始化配置 + * @param {Object} options 配置对象,详见bx-config配置节点 + */ + config: function(options) { + if (isConfig) { + return; + } + isConfig = true; + options = S.merge({ + componentsPath: './', + importsPath: './', + templateEngine: 'brix/gallery/mu/', + debug: debug === '' ? false : true, + combine: false, //默认不开启combine + tag: tag == '@TAG@' ? '' : tag, + //路径修正,brix路径下存在其他文件夹 + fixed: version == '@VERSION@' ? 'src/' : version + '/', + gallery: { + //配置组件版本信息 + //dropdown:'1.0' + } + }, defaultOptions, options); + /** + * brix 的基础路径 + * @type {String} + */ + Brix.basePath = options.base; + /** + * 对包路径的重写 + * @type {String} + */ + Brix.fixed = options.fixed; + /** + * 模板引擎的包路径,内部使用 + * @type {String} + */ + Brix.templateEngine = options.templateEngine; + S.config({ + packages: [{ + name: "brix", + base: options.base, + combine: options.combine, + debug: options.debug, + tag: options.tag, + charset: "utf-8" + }, { + name: "components", + base: options.componentsPath, + combine: options.combine, + debug: options.debug, + tag: options.componentsTag || options.tag, + charset: "utf-8" + }, { + name: "imports", + base: options.importsPath, + combine: options.combine, + debug: options.debug, + tag: options.importsTag || options.tag, + charset: "utf-8" + }] + }); + S.config({ + map: [ + [/(.+brix\/)(gallery\/)(.+?)(\/.+?(?:-min)?\.(?:js|css))(\?[^?]+)?$/, function($0, $1, $2, $3, $4, $5) { + var str = $1 + options.fixed + $2 + $3; + if (options.gallery[$3]) { + str += '/' + options.gallery[$3]; + } + str += $4 + ($5 ? $5 : ''); + return str; + }], + [/(.+brix\/)(core.+?)((?:-min)?\.js)(\?[^?]+)?$/, function($0, $1, $2, $3, $4) { + var str = $1 + options.fixed; + str += $2 + $3 + ($4 ? $4 : ''); + return str; + }] + ] + }); + }, + /** + * 渲染完成后需要执行的函数 + * @param {Function} fn 执行的函数 + */ + ready: function(fn) { + if (isReady) { + fn.call(Brix); + } else { + readyList.push(fn); + } + }, + /** + * 触发ready添加的方法 + * @private + */ + _bx_fireReady: function() { + if (isReady) { + return; + } + isReady = true; + if (readyList) { + var fn, i = 0; + while (fn = readyList[i++]) { + fn.call(Brix); + } + readyList = null; + } + }, + /** + * 将bx-config节点转换成JSON格式 + * @param {String} s JSON字符串 + * @return {Object} JSON对象 + */ + returnJSON: function(s) { + return returnJSON(s); + }, + /** + * 根据模块相对路径获取绝对路径 + * @param {Object} module 模块的this + * @param {String} path 相对路径 + * @return {String} 绝对路径 + */ + absoluteFilePath: function(module, path) { + return new S.Uri(module.getFullPath()).resolve(path).toString(); + } + }); + if (defaultOptions.autoConfig) { + //自动配置 + Brix.config({}); + //自动实例化pagelet + //外部调用的S.ready注册的方法中可以直接用Brix.pagelet实例书写业务逻辑 + if (defaultOptions.autoPagelet) { + //延时执行,在打包后的能保证后面的模块已经载入 + S.later(function() { + S.use('brix/core/pagelet', function(S, Pagelet) { + S.ready(function() { + /** + * 配置autoPagelet时候,会在Brix的全局对象上挂载Pagelet的实例对象,模板为body + * @type {Brix.Pagelet} + */ + Brix.pagelet = new Pagelet({ + tmpl: 'body' + }); + Brix._bx_fireReady(); + }); + }); + }, 1); + return; + } + } + S.ready(function() { + Brix._bx_fireReady(); + }); +}(KISSY, 'Brix')); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005759_basic.js b/pool/shard000/JavaScript/0005759_basic.js new file mode 100644 index 0000000000000000000000000000000000000000..6b61e3152ecca2defe5b3889c638470026971d55 --- /dev/null +++ b/pool/shard000/JavaScript/0005759_basic.js @@ -0,0 +1,144 @@ +/** + * Basic routes. + * Author: GP. + * Version: 1.1 + * Release Date: 21-May-2014 + */ + +/** + * Module dependencies. + */ + +var config = require('../config/config'), + user = require('../utils/user'); + +/* + * Module exports. + */ + +module.exports = function(app) { + + /** + * GET '/' + */ + app.get(config.URL.MAIN, function(req, res) { + config.logger.info('QUIZ - MAIN - PAGE GET', { + username: (req.session.user) ? req.session.user.username : 'AnonymousUser' + }); + if (req.session.user) { + res.redirect(config.URL.QUIZ_MAIN); + } else { + res.render(config.TEMPL_LOGIN, { + tab: 'login' + }); + } + }); + + /** + * GET '/login' + */ + + app.get(config.URL.LOGIN, function(req, res) { + config.logger.info('LOGIN - PAGE GET'); + res.render(config.TEMPL_LOGIN, { + tab: 'login' + }); + }); + + /** + * POST '/login' + */ + + app.post(config.URL.LOGIN, function(req, res) { + var username = req.body.username; + config.logger.info('LOGIN - FORM POST', { + username: username, + auth_ldap: config.AUTH_USE_LDAP + }); + user.authenticate(username, req.body.password, function(err, user) { + if (user) { + req.session.regenerate(function() { + config.logger.info('LOGIN - SESSION REGENERATED SUCCESSFULLY', { + username: username + }); + //Custom session variables. + req.session.user = user; + req.session.is_admin = user.admin; + req.session.last_seen = user.last_seen; + req.session.success = 'Authenticated as ' + user.username; + res.redirect(config.URL.QUIZ_MAIN); + }); + } else { + config.logger.warn('LOGIN - LOGIN FAILED', { + username: username, + error: err.message + }); + req.session.error = err.message; + res.redirect(config.URL.LOGIN); + } + }); + }); + + /** + * GET '/logout' + */ + + app.get(config.URL.LOGOUT, function(req, res) { + config.logger.info('LOGOUT', { + username: req.session.user.username + }); + req.session.destroy(function() { + res.redirect(config.URL.MAIN); + }); + }); + + /** + * GET '/timeclosed' + */ + + app.get(config.URL.TIMECLOSED, user.requiredAuthentication, function(req, res) { + res.render(config.TEMPL_TIMECLOSED, { + start_time: config.QUIZ_START_TIME, + stop_time: config.QUIZ_STOP_TIME, + current_time: [new Date().getHours(), new Date().getMinutes()] + }); + }); + + /** + * GET '/faq' + */ + + app.get(config.URL.FAQ, function(req, res) { + res.render(config.TEMPL_FAQ, { + username: (req.session.user) ? req.session.user.username : null, + start_time: config.QUIZ_START_TIME, + stop_time: config.QUIZ_STOP_TIME + }); + }); + + /** + * GET '/feedback' + */ + + app.get(config.URL.FEEDBACK, user.requiredAuthentication, function(req, res) { + res.render(config.TEMPL_FEEDBACK); + }); + + /** + * POST '/feedback' + */ + + app.post(config.URL.FEEDBACK, user.requiredAuthentication, function(req, res) { + var username = req.session.user.username, + form_data = req.body; + form_data['user_agent'] = req.headers['user-agent']; + config.logger.info('FEEDBACK - FORM POST', { + username: username, + form_data: form_data + }); + user.saveFeedback(username, form_data); + res.render(config.TEMPL_FEEDBACK, { + 'form_submitted': true + }); + }); +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005762_index.js b/pool/shard000/JavaScript/0005762_index.js new file mode 100644 index 0000000000000000000000000000000000000000..436d190f45273b2d9be45edebab021d50b47b5f2 --- /dev/null +++ b/pool/shard000/JavaScript/0005762_index.js @@ -0,0 +1,50 @@ +export default function() { + 'ngInject'; + return { + restrict: 'E', + replace: true, + bindToController: true, + controller: Controller, + controllerAs: 'commentsCtrl', + scope: { + postId: "@" + }, + template: ` +
        + ` + }; + + function Controller($log, $scope, $element, $WPHCPost, $WPHCConfig) { + 'ngInject'; + + let depth = _.get($WPHCConfig, 'post.comments.depth') || 2; + let vm = this; + vm.postId = parseInt(vm.postId); + vm.comments = null; + + $WPHCPost.getComments(vm.postId).then(function(comments) { + var comment, parent; + if (!comments.lenght) { + vm.comments = []; + } + let commentsTemp = []; + for (let i = 0, len = comments.length; i < len; i++) { + comment = comments[i]; + commentsTemp[comment.id] = comment; + comment.children = []; + if (comment.parent === 0) { + comment.level = 1; + vm.comments.push(comment); + } else { + parent = commentsTemp[comment.parent]; + comment.level = parent.level + 1; + if (depth === parent.level) { + continue; + } + parent.children.push(comment); + } + } + // $log.debug('wphcComments:comments', vm.comments); + }); + } +} diff --git a/pool/shard000/JavaScript/0005763_index.js b/pool/shard000/JavaScript/0005763_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2e43fd8186131c3877e74770726515da22f44244 --- /dev/null +++ b/pool/shard000/JavaScript/0005763_index.js @@ -0,0 +1,44 @@ +'use strict'; +var postcss = require('postcss'); + +var Splitter = postcss.plugin('postcss-split', function (opts) { + var opts = opts || {}; + var pattern = opts.pattern || /FOLD/; + if (typeof opts.positive_match !== 'undefined') { + var positive_match = opts.positive_match; + } + else { + var positive_match = true; + } + return function (css, result) { + var newcss = postcss.root(); + css.eachRule(function (rule) { + if (rule.toString().match(pattern)){ + if (rule.parent.name != 'media'){ + rule.removeSelf(); + newcss.append(rule); + } else { + var mediaq_in_newcss = false; + newcss.eachAtRule('media', function (mediaq) { + if (mediaq.params == rule.parent.params) { + rule.removeSelf(); + mediaq.append(rule); + mediaq_in_newcss = true; + return false; + } + }); + if (!mediaq_in_newcss) { + var parent = rule.parent.clone(); + parent.eachRule(function(r) { r.removeSelf(); }); + rule.removeSelf(); + parent.append(rule); + newcss.append(parent); + } + } + } + }); + if(positive_match) + result.root = newcss; + }; +}); +module.exports = Splitter; diff --git a/pool/shard000/JavaScript/0005767_d3-hexbin.js b/pool/shard000/JavaScript/0005767_d3-hexbin.js new file mode 100644 index 0000000000000000000000000000000000000000..aebfd132ccf100d3752b5c59d2ba9651ee354c9c --- /dev/null +++ b/pool/shard000/JavaScript/0005767_d3-hexbin.js @@ -0,0 +1,122 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.d3 = global.d3 || {}))); +}(this, function (exports) { 'use strict'; + + var version = "0.2.1"; + + var thirdPi = Math.PI / 3; + var angles = [0, thirdPi, 2 * thirdPi, 3 * thirdPi, 4 * thirdPi, 5 * thirdPi]; + function pointX(d) { + return d[0]; + } + + function pointY(d) { + return d[1]; + } + + function hexbin() { + var x0 = 0, + y0 = 0, + x1 = 1, + y1 = 1, + x = pointX, + y = pointY, + r, + dx, + dy; + + function hexbin(points) { + var binsById = {}, bins = [], i, n = points.length; + + for (i = 0; i < n; ++i) { + if (isNaN(px = +x.call(null, point = points[i], i, points)) + || isNaN(py = +y.call(null, point, i, points))) continue; + + var point, + px, + py, + pj = Math.round(py = py / dy), + pi = Math.round(px = px / dx - (pj & 1) / 2), + py1 = py - pj; + + if (Math.abs(py1) * 3 > 1) { + var px1 = px - pi, + pi2 = pi + (px < pi ? -1 : 1) / 2, + pj2 = pj + (py < pj ? -1 : 1), + px2 = px - pi2, + py2 = py - pj2; + if (px1 * px1 + py1 * py1 > px2 * px2 + py2 * py2) pi = pi2 + (pj & 1 ? 1 : -1) / 2, pj = pj2; + } + + var id = pi + "-" + pj, bin = binsById[id]; + if (bin) bin.push(point); + else { + bins.push(bin = binsById[id] = [point]); + bin.x = (pi + (pj & 1) / 2) * dx; + bin.y = pj * dy; + } + } + + return bins; + } + + function hexagon(radius) { + var x0 = 0, y0 = 0; + return angles.map(function(angle) { + var x1 = Math.sin(angle) * radius, + y1 = -Math.cos(angle) * radius, + dx = x1 - x0, + dy = y1 - y0; + x0 = x1, y0 = y1; + return [dx, dy]; + }); + } + + hexbin.hexagon = function(radius) { + return "m" + hexagon(radius == null ? r : +radius).join("l") + "z"; + }; + + hexbin.centers = function() { + var centers = [], + j = Math.round(y0 / dy), + i = Math.round(x0 / dx); + for (var y = j * dy; y < y1 + r; y += dy, ++j) { + for (var x = i * dx + (j & 1) * dx / 2; x < x1 + dx / 2; x += dx) { + centers.push([x, y]); + } + } + return centers; + }; + + hexbin.mesh = function() { + var fragment = hexagon(r).slice(0, 4).join("l"); + return hexbin.centers().map(function(p) { return "M" + p + "m" + fragment; }).join(""); + }; + + hexbin.x = function(_) { + return arguments.length ? (x = _, hexbin) : x; + }; + + hexbin.y = function(_) { + return arguments.length ? (y = _, hexbin) : y; + }; + + hexbin.radius = function(_) { + return arguments.length ? (r = +_, dx = r * 2 * Math.sin(thirdPi), dy = r * 1.5, hexbin) : r; + }; + + hexbin.extent = function(_) { + return arguments.length ? (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1], hexbin) : [[x0, y0], [x1, y1]]; + }; + + return hexbin.radius(1); + } + + exports.version = version; + exports.hexbin = hexbin; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005768_FakeSocket.js b/pool/shard000/JavaScript/0005768_FakeSocket.js new file mode 100644 index 0000000000000000000000000000000000000000..0268131ce13c23b0331dc6b1b813134f41123236 --- /dev/null +++ b/pool/shard000/JavaScript/0005768_FakeSocket.js @@ -0,0 +1,32 @@ +// A fake socket for bot players +function FakeSocket(gameServer) { + this.server = gameServer; +} + +module.exports = FakeSocket; + +// Override + +FakeSocket.prototype.sendPacket = function(packet) { + // Fakes sending a packet + +}; + +FakeSocket.prototype.close = function(error) { + // Removes the bot + var len = this.playerTracker.cells.length; + for (var i = 0; i < len; i++) { + var cell = this.playerTracker.cells[0]; + + if (!cell) { + continue; + } + + this.server.removeNode(cell); + } + + var index = this.server.clients.indexOf(this); + if (index != -1) { + this.server.clients.splice(index, 1); + } +}; diff --git a/pool/shard000/JavaScript/0005769_settings.js b/pool/shard000/JavaScript/0005769_settings.js new file mode 100644 index 0000000000000000000000000000000000000000..4acc43a9cab754b5a1b0dcfd19b407d3745539a4 --- /dev/null +++ b/pool/shard000/JavaScript/0005769_settings.js @@ -0,0 +1,144 @@ +/*global define,dojo */ +/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */ +/* + | Copyright 2014 Esri + | + | 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. + */ +//============================================================================================================================// +define([ + "dojo/_base/declare", + "dojo/_base/lang", + "dojo/on", + "dojo/text!./templates/settings.html", + "dijit/_WidgetBase", + "dijit/_TemplatedMixin", + "dijit/_WidgetsInTemplateMixin", + "dojo/i18n!nls/localizedStrings", + "dojo/query", + "dojo/dom-class", + "dojo/topic", + "dojo/dom-construct", + "dojo/dom-geometry" + +], function (declare, lang, on, template, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, nls, query, domClass, topic, domConstruct, domGeom) { + + return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { + templateString: template, + flag: null, + nls: nls, + postCreate: function () { + this.domNode.title = nls.title.settingsBtnTitle; + this.own(on(this.settingsIcon, "click", lang.hitch(this, function () { + if (query(".esriCTSortByContainer")[0].children.length <= 0) { + var sortByTitle, sortMenu, listSortMenu, viewMbl, dateMbl; + sortByTitle = domConstruct.create('div', { "class": "esriCTSortByTitle" }, query(".esriCTSortByContainer")[0]); + domConstruct.create('div', { "class": "esriCTSortHeader", "innerHTML": nls.sortByTextMobile }, sortByTitle); + sortMenu = domConstruct.create('div', { "class": "esriCTSortMenu" }, sortByTitle); + listSortMenu = domConstruct.create('ul', {}, sortMenu); + viewMbl = domConstruct.create('li', { "class": "sortByViewMbl esriCTListSelected", "innerHTML": nls.viewTextMobile }, listSortMenu); + dateMbl = domConstruct.create('li', { "class": "sortByDateMbl", "innerHTML": nls.dateTextMobile }, listSortMenu); + this.own(on(viewMbl, "click", lang.hitch(this, function () { + topic.publish("sortByViews", query(".esriCTMenulbl")[0]); + domClass.remove(query(".esriCTListSelected")[0], "esriCTListSelected"); + domClass.add(query(".sortByViewMbl")[0], "esriCTListSelected"); + }))); + this.own(on(dateMbl, "click", lang.hitch(this, function () { + topic.publish("sortByDate", query(".esriCTMenulbl")[0]); + domClass.remove(query(".esriCTListSelected")[0], "esriCTListSelected"); + domClass.add(query(".sortByDateMbl")[0], "esriCTListSelected"); + }))); + } else { + domConstruct.empty(query(".esriCTSortByContainer")[0]); + } + this._slideLeftPanel(); + }))); + }, + + /** + * Slide in and out the left panel upon clicking the settings icon. Only for smart phone devices. + */ + _slideLeftPanel: function () { + query(".esriCTInnerLeftPanelBottom")[0].style.height = dojo.window.getBox().h + "px"; + if (query(".esriCTMenuTab")[0]) { + domClass.toggle(query(".esriCTMenuTab")[0], "esriCTShiftRight"); + } + if (query(".esriCTInnerLeftPanelTop")[0]) { + domClass.toggle(query(".esriCTInnerLeftPanelTop")[0], "esriCTShiftRight"); + } + if (query(".esriCTInnerLeftPanelBottom")[0]) { + domClass.remove(query(".esriCTInnerLeftPanelBottom")[0], "displayNone"); + domClass.toggle(query(".esriCTInnerLeftPanelBottom")[0], "esriCTInnerLeftPanelBottomShift"); + } + if (query(".esriCTSearchIcon")[0]) { + domClass.toggle(query(".esriCTSearchIcon")[0], "displayNone"); + domClass.toggle(query(".esriCTSearchItemInput")[0], "displayNone"); + domClass.toggle(query(".esriCTClearInput")[0], "displayNone"); + } + if (query(".esriCTInfoIcon")[0]) { + domClass.toggle(query(".esriCTInfoIcon")[0], "displayNone"); + } + if (query(".esriCTSearch")[0]) { + domClass.toggle(query(".esriCTSearch")[0], "displayNone"); + } + if (query(".esriCTRightPanel")[0]) { + domClass.toggle(query(".esriCTRightPanel")[0], "esriCTShiftRight"); + domClass.toggle(query(".esriCTRightPanel")[0], "esriCTShiftRightPanel"); + } + + if (query(".esriCTMenuTabLeft")[0]) { + if (domClass.contains(query(".esriCTMenuTabLeft")[0], "displayBlock")) { + domClass.replace(query(".esriCTMenuTabLeft")[0], "displayNone", "displayBlock"); + domClass.replace(query(".esriCTHomeIcon")[0], "displayNone", "displayBlock"); + + if (query(".esriCTSignIn")[0]) { + domClass.replace(query(".esriCTSignIn")[0], "displayNone", "displayBlock"); + } + domClass.add(query(".esriCTInnerRightPanel")[0], "displayNone"); + if (query(".esriCTNoResults")[0]) { + if (domClass.contains(query(".esriCTNoResults")[0], "displayBlockAll")) { + domClass.replace(query(".esriCTNoResults")[0], "displayNoneAll", "displayBlockAll"); + } + } + if (dojo.configData.values.showTagCloud) { + query(".esriCTPadding")[0].style.height = window.innerHeight - (domGeom.position(query(".sortByLabelMbl")[0]).h + domGeom.position(query(".esriCTCategoriesHeader")[0]).h + 40) + "px"; + } + if (domClass.contains(query(".esriCTItemSearch")[0], "displayBlockAll")) { + this.flag = true; + domClass.replace(query(".esriCTItemSearch")[0], "displayNoneAll", "displayBlockAll"); + } + if (dojo.sortBy !== dojo.configData.values.sortField) { + domClass.remove(query(".esriCTListSelected")[0], "esriCTListSelected"); + domClass.add(query(".sortByDateMbl")[0], "esriCTListSelected"); + } + } else { + domClass.replace(query(".esriCTMenuTabLeft")[0], "displayBlock", "displayNone"); + domClass.replace(query(".esriCTHomeIcon")[0], "displayBlock", "displayNone"); + if (query(".esriCTSignIn")[0]) { + domClass.replace(query(".esriCTSignIn")[0], "displayBlock", "displayNone"); + } + domClass.remove(query(".esriCTInnerRightPanel")[0], "displayNone"); + if (query(".esriCTNoResults")[0]) { + if (domClass.contains(query(".esriCTNoResults")[0], "displayNoneAll")) { + domClass.replace(query(".esriCTNoResults")[0], "displayBlockAll", "displayNoneAll"); + } + } + if (this.flag) { + domClass.replace(query(".esriCTItemSearch")[0], "displayBlockAll", "displayNoneAll"); + this.flag = false; + } + } + } + } + }); +}); diff --git a/pool/shard000/JavaScript/0005771_Highlighter.js b/pool/shard000/JavaScript/0005771_Highlighter.js new file mode 100644 index 0000000000000000000000000000000000000000..6f5711e0c67abaf915f8fe68d2cfee3cc2f5fa2a --- /dev/null +++ b/pool/shard000/JavaScript/0005771_Highlighter.js @@ -0,0 +1,333 @@ +/////////////////////////////////////////////////////////////////////////// +// Copyright © Esri. 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. +/////////////////////////////////////////////////////////////////////////// + +//====================================================================================================================// +define([ + 'dojo/_base/array', + 'dojo/_base/declare', + 'dojo/_base/lang', + 'dojo/Deferred', + 'esri/graphic', + 'esri/symbols/SimpleFillSymbol', + 'esri/symbols/SimpleLineSymbol', + 'esri/symbols/SimpleMarkerSymbol' + ], function ( + array, + declare, + lang, + Deferred, + Graphic, + SimpleFillSymbol, + SimpleLineSymbol, + SimpleMarkerSymbol + ) { + return declare([], { + + /** + * Constructor for class. + * @param {object} graphicsLayer Layer to which to add created graphics + * @memberOf Highlighter# + * @constructor + */ + constructor: function (chunkSize) { + this._drawingChunkSize = typeof chunkSize === 'number' ? chunkSize : 100; + }, + + /** + * Creates a graphic that can be used for highlighting. + * @param {object} item Graphic or geometry to be used to create highlight graphic + * @param {json} symbology Structure containing specifications for graphic to be created depending on type + * of graphic or geometry; see example below + * @return {object} Created graphic; only contains geometry of item + * @example + * symbology = { + * point: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * }, + * line: { + * lineColor: new Color('aqua'), + * lineWidth: 2 + * }, + * polygon: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * } + * } + * @memberOf Highlighter# + */ + createGraphic: function (item, symbology) { + var type, geometry, graphic = null, outlineSquareSize = 10; + + // Normalize graphic versus geometry + if (!item) { + return null; + } else if (item.geometry) { + geometry = item.geometry; + type = geometry.type; + } else { + geometry = item; + if (geometry.hasOwnProperty('x') && geometry.hasOwnProperty('y')) { + type = 'point'; + } else if (geometry.hasOwnProperty('paths')) { + type = 'polyline'; + } else if (geometry.hasOwnProperty('rings')) { + type = 'polygon'; + } else if (geometry.hasOwnProperty('points')) { + type = 'multipoint'; + } else { + return null; + } + } + + /** + * Gets a square bounding box that is one larger than the larger dimension of an item's symbol + * @param {object} item Item whose layer symbol is to be retrieved and bounded + * @param {number} defaultSize Pixel dimension of square bounding box if item does not have a layer + * @return {number} Pixel dimension of square bounding box + */ + function getPointSymbolSquareSize(item, defaultSize) { + var itemLayer, graphic, outlineSquareSize = defaultSize; + if (item.getLayer) { + itemLayer = item.getLayer(); + if (itemLayer) { + graphic = item.getLayer()._getSymbol(item); + if (graphic && !isNaN(graphic.width) && !isNaN(graphic.height)) { + outlineSquareSize = 1 + Math.max(graphic.width, graphic.height); + } + } + } + return outlineSquareSize; + } + + switch (type) { + case 'point': + // JSAPI does not want NaN coordinates + if (isNaN(geometry.x) || isNaN(geometry.y)) { + return null; + } + + // Update the outline size based on a graphic's symbol + outlineSquareSize = getPointSymbolSquareSize(item, outlineSquareSize); + + // Create the graphic + graphic = new Graphic(geometry, + new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, outlineSquareSize, + new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, + symbology.point.lineColor, symbology.point.lineWidth), + symbology.point.fillColor + ) + ); + break; + + case 'polyline': + graphic = new Graphic(geometry, + new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, + symbology.line.lineColor, symbology.line.lineWidth + ) + ); + break; + + case 'polygon': + graphic = new Graphic(geometry, + new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, + new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, + symbology.polygon.lineColor, symbology.polygon.lineWidth), + symbology.polygon.fillColor + ) + ); + break; + + case 'multipoint': + // Update the outline size based on a graphic's symbol + outlineSquareSize = getPointSymbolSquareSize(item, outlineSquareSize); + + // Create the graphic + graphic = new Graphic(geometry, + new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, outlineSquareSize, + new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, + symbology.point.lineColor, symbology.point.lineWidth), + symbology.point.fillColor + ) + ); + break; + } + + return graphic; + }, + + /** + * Highlights features in chunks to reduce impact on UI. + * @param {array} features Features to highlight + * @param {function} createAndAddGraphic Function to call to create a graphic and to add it to a layer + * @param {json} symbology Structure containing specifications for graphic to be created depending on type + * of graphic or geometry; see example below + * @param {object} layer Layer to receive graphics + * @param {function} setProgressPercentage Function to call with progress percentage + * @return {Deferred} Highlighting is done upon resolution + * @example + * symbology = { + * point: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * }, + * line: { + * lineColor: new Color('aqua'), + * lineWidth: 2 + * }, + * polygon: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * } + * } + * @memberOf Highlighter# + */ + highlightFeatures: function (features, createAndAddGraphic, symbology, layer, setProgressPercentage) { + var iChunk = 0, iFeatureStart = 0, numChunks, deferred = new Deferred(); + + if (features.length > 0) { + if (features.length <= this._drawingChunkSize) { + this._highlightFeatures(features, createAndAddGraphic, symbology, layer).then(function () { + deferred.resolve(true); + }); + + } else { + // Start a determinate progress bar + setProgressPercentage(0); + + numChunks = Math.ceil(features.length / this._drawingChunkSize); + setTimeout(lang.hitch(this, function () { + this._highlightFeaturesContinuation(features, + createAndAddGraphic, symbology, layer, setProgressPercentage, + this._drawingChunkSize, numChunks, + iChunk, iFeatureStart).then(function () { + deferred.resolve(true); + }); + }), 50); + } + } else { + deferred.resolve(true); + } + + return deferred; + }, + + /** + * Highlights features in chunks to reduce impact on UI. + * @param {array} features Features to highlight + * @param {function} createAndAddGraphic Function to call to create a graphic and to add it to a layer + * @param {json} symbology Structure containing specifications for graphic to be created depending on type + * of graphic or geometry; see example below + * @param {object} layer Layer to receive graphics + * @param {function} setProgressPercentage Function to call with progress percentage + * @param {number} chunkSize Number of features to highlight per chunk + * @param {number} numChunks Total number of chunks of features to highlight + * @param {number} iChunk 0-based chunk number + * @param {number} iFeatureStart 0-based index into list of features for this chunk to use + * @return {Deferred} Highlighting is done upon resolution + * @example + * symbology = { + * point: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * }, + * line: { + * lineColor: new Color('aqua'), + * lineWidth: 2 + * }, + * polygon: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * } + * } + * @memberOf Highlighter# + */ + _highlightFeaturesContinuation: function (features, createAndAddGraphic, symbology, layer, setProgressPercentage, + chunkSize, numChunks, iChunk, iFeatureStart) { + var iFeatureEnd, deferred = new Deferred(); + + if (iFeatureStart >= features.length) { + deferred.resolve(true); + return deferred; + } + + iFeatureEnd = Math.min(iFeatureStart + chunkSize, features.length); + this._highlightFeatures(features.slice(iFeatureStart, iFeatureEnd), + createAndAddGraphic, symbology, layer).then(lang.hitch(this, function () { + ++iChunk; + setProgressPercentage(100 * iChunk / numChunks); + + setTimeout(lang.hitch(this, function () { + this._highlightFeaturesContinuation(features, + createAndAddGraphic, symbology, layer, setProgressPercentage, + this._drawingChunkSize, numChunks, + iChunk, iFeatureEnd).then(function () { + deferred.resolve(true); + }); + }), 10); + })); + + return deferred; + }, + + /** + * Highlights a set of feature geometries. + * @param {array} features Features to highlight + * @param {function} createAndAddGraphic Function to call to create a graphic and to add it to a layer + * @param {json} symbology Structure containing specifications for graphic to be created depending on type + * of graphic or geometry; see example below + * @param {object} layer Layer to receive graphics + * @param {function} setProgressPercentage Function to call with progress percentage + * @return {Deferred} Highlighting of set of features is done upon resolution + * @example + * symbology = { + * point: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * }, + * line: { + * lineColor: new Color('aqua'), + * lineWidth: 2 + * }, + * polygon: { + * lineColor: new Color('aqua'), + * lineWidth: 2, + * fillColor: new Color([0, 255, 255, 0.1]) + * } + * } + * @memberOf Highlighter# + */ + _highlightFeatures: function (features, createAndAddGraphic, symbology, layer) { + var deferred = new Deferred(); + + array.forEach(features, function (feature) { + createAndAddGraphic(feature, symbology, layer); + }, this); + deferred.resolve(true); + + return deferred; + } + + }); + } +); diff --git a/pool/shard000/JavaScript/0005774_app.dev.js b/pool/shard000/JavaScript/0005774_app.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..dd429b1c15192c54fb8bfecdd8e8244b77e50520 --- /dev/null +++ b/pool/shard000/JavaScript/0005774_app.dev.js @@ -0,0 +1,49 @@ +import React from 'react' +import { createDevTools } from 'redux-devtools' +import LogMonitor from 'redux-devtools-log-monitor' +import DockMonitor from 'redux-devtools-dock-monitor' +import SliderMonitor from 'redux-slider-monitor' +import Inspector from 'redux-devtools-inspector' + +export const DevModule = (devToolsExtension) => { + return { + init : (ctx) => { + console.log('Initialize Dev Tools...') + if (__DEBUG__) { + if (typeof devToolsExtension === 'function') { + ctx.enhance(devToolsExtension()) + } + } + + if (__DEV__) { + ctx.enhance(DevTools.instrument()) + ctx.renderAssets = [...ctx.renderAssets, ] + } + }, + run : (ctx) => { + if (__DEV__) { + console.log('Run Dev Tools...') + let doRender = ctx.render + ctx.render = () => { + try { + doRender() + } catch (error) { + const RedBox = require('redbox-react').default + ctx.renderView() + } + } + } + } + } +} + +export const DevTools = createDevTools( + + + + + +) + +export default DevModule diff --git a/pool/shard000/JavaScript/0005775_Slider.stories.js b/pool/shard000/JavaScript/0005775_Slider.stories.js new file mode 100644 index 0000000000000000000000000000000000000000..479ae5c5fecc222586f3b27a7612319be35cadcc --- /dev/null +++ b/pool/shard000/JavaScript/0005775_Slider.stories.js @@ -0,0 +1,22 @@ +import { storiesOf } from "@storybook/react"; +import { withInfo } from "@storybook/addon-info"; +import KnobbedThemeProvider from "@hig/storybook/storybook-support/decorators/KnobbedThemeProvider"; + +import infoOptions from "./infoOptions"; +import renderStory from "./renderStory"; +import stories from "./stories"; + +const storybook = storiesOf("Forms|Slider", module); + +stories.forEach(({ description, getProps }) => { + storybook.add( + description, + withInfo({ + ...infoOptions, + propTablesExclude: [KnobbedThemeProvider] + })(() => { + const props = getProps(); + return renderStory(props); + }) + ); +}); diff --git a/pool/shard000/JavaScript/0005777_notifications.js b/pool/shard000/JavaScript/0005777_notifications.js new file mode 100644 index 0000000000000000000000000000000000000000..9a7ce1b40c103bbc4273c9223b9c74a9ec346067 --- /dev/null +++ b/pool/shard000/JavaScript/0005777_notifications.js @@ -0,0 +1,31 @@ +"use strict"; +$(document).ready(function () { + $('#notific8Test').on('click', function (event) { + var params = { + life: $('#notific8Life').find('option:selected').val(), + theme: $('#notific8Theme').val(), + sticky: $('#notific8Sticky').is(':checked'), + horizontalEdge: $('#notific8horizontal').find('option:selected').val(), + verticalEdge: $('#notific8vertical').find('option:selected').val() + }, + text = $('#notific8Text').val(), + $heading = $('#notific8Heading'); + + if ($.trim($heading.val()) !== '') { + params.heading = $heading.val(); + } + // show notification + $.notific8(text, params); + }); + $(".content .row").find('input').iCheck({ + checkboxClass: 'icheckbox_square-blue', + radioClass: 'iradio_square-blue', + increaseArea: '20%' // optional + }); + + $('[type="reset"]').on('click', function () { + setTimeout(function () { + $("input").iCheck("update"); + }, 10); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005779_app_controller.js b/pool/shard000/JavaScript/0005779_app_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..786bee55fa058ab41c25cf34e7026b69927e207f --- /dev/null +++ b/pool/shard000/JavaScript/0005779_app_controller.js @@ -0,0 +1,110 @@ +"use strict"; +Press = { + num: function (num) { + if (flagLastPress === "equally") { + AppSvc.reset(); + } + flagLastPress = 'num'; + if ((flagOperator) || (field === 0)) { + field = num; + flagOperator = false; + if (num === ".") { + field = "0."; + } + } else { + if (num === ".") { + if (field.toString().indexOf(".") != -1) { + return false; + } + } + field = field.toString() + num; + } + FieldSvc.renew(); + }, + operator: function (operator) { + switch (flagLastPress) { + case "num": + flagLastPress = 'operator'; + Save.values(); + AppSvc.changeCalculationString(operator, false); + if (secondVal !== undefined) { + AppSvc.calculationAction(Make.operatorWord(calculationString[calculationString.length - 3])); + } + Save.operator(operator); + break; + + case "operator": + calculationString.splice(-1, 1); + AppSvc.changeCalculationString(operator, true); + Save.operator(operator); + break; + + case "specialOperator": + calculationString.splice(-1, 1); + AppSvc.changeCalculationString(operator, true); + Save.operator(operator); + break; + + case "equally": + calculationString.splice(-1, 1); + flagLastPress = 'operator'; + Save.values(); + AppSvc.changeCalculationString(operator, true); + Save.operator(operator); + break; + } + }, + equally: function () { + if (operator !== undefined) { + Save.values(); + if (secondVal !== undefined) { + AppSvc.changeCalculationString("equally", false); + AppSvc.calculationAction(operator); + Save.operator(operator); + flagLastPress = "equally"; + } + } + }, + plusMinus: function () { + field = field - field * 2; + FieldSvc.renew(); + }, + percent: function () { + if ((operator !== undefined) && (flagLastPress == 'num')) { + field = (firstVal * parseFloat(field) / 100).toString(); + FieldSvc.renew(); + } + }, + reciproc: function () { + if (flagLastPress !== 'operator') { + flagLastPress = 'specialOperator'; + calculationString = ['1', '/', parseFloat(field), '=']; + field = 1 / field; + AppSvc.specialOperatorProcess(); + } + }, + squareRoot: function () { + if (flagLastPress !== 'operator') { + flagLastPress = 'specialOperator'; + calculationString = [parseFloat(field), '√', '=']; + field = Math.sqrt(field); + AppSvc.specialOperatorProcess(); + } + }, + backspace: function () { + if (!flagOperator) { + if ((field.toString().length <= 1)) { + field = 0; + } else { + field = field.toString().slice(0, -1) + } + FieldSvc.renew(); + } + }, + clearError: function () { + field = 0; + FieldSvc.renew(); + } +} + + diff --git a/pool/shard000/JavaScript/0005781_products.controller.js b/pool/shard000/JavaScript/0005781_products.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..06ddc118c19798f46cfad9f0ddbe3103f163655d --- /dev/null +++ b/pool/shard000/JavaScript/0005781_products.controller.js @@ -0,0 +1,64 @@ +/** + * @ngdoc object + * @name Bastion.products.controller:ProductsController + * + * @requires $scope + * @requires $location + * @requires Nutupane + * @requires Product + * @requires CurrentOrganization + * + * @description + * Provides the functionality specific to Products for use with the Nutupane UI pattern. + * Defines the columns to display and the transform function for how to generate each row + * within the table. + */ +angular.module('Bastion.products').controller('ProductsController', + ['$scope', '$location', 'Nutupane', 'Product', 'CurrentOrganization', + function ($scope, $location, Nutupane, Product, CurrentOrganization) { + + var params = { + 'organization_id': CurrentOrganization, + 'search': $location.search().search || "", + 'sort_by': 'name', + 'sort_order': 'ASC', + 'enabled': true, + 'paged': true + }; + + $scope.productsNutupane = new Nutupane(Product, params); + $scope.productTable = $scope.productsNutupane.table; + $scope.removeRow = $scope.productsNutupane.removeRow; + + $scope.productTable.closeItem = function () { + $scope.transitionTo('products.index'); + }; + + $scope.$on('productDelete', function (event, taskId) { + $scope.productDeletionTaskId = taskId; + }); + + $scope.unsetProductDeletionTaskId = function () { + $scope.productDeletionTaskId = undefined; + }; + + $scope.productTable.refresh = $scope.productsNutupane.refresh; + + $scope.table = $scope.productTable; + + $scope.mostImportantSyncState = function (product) { + var state = 'none'; + if (product['sync_summary'].pending > 0) { + state = 'pending'; + } else if (product['sync_summary'].error > 0) { + state = 'error'; + } else if (product['sync_summary'].warning > 0) { + state = 'warning'; + } else if (product['sync_summary'].success > 0) { + state = 'success'; + } + return state; + }; + + }] +); diff --git a/pool/shard000/JavaScript/0005784_createUserRoles.spec.js b/pool/shard000/JavaScript/0005784_createUserRoles.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..256f33204b3f7c7910f7df4ef3324476cada5983 --- /dev/null +++ b/pool/shard000/JavaScript/0005784_createUserRoles.spec.js @@ -0,0 +1,90 @@ +import { NOTEBOOK_CATEGORY, SITE_CATEGORY } from 'common/src/config/images'; +import createUserRoles from './createUserRoles'; + +describe('createUserRoles', () => { + it('returns empty object if resources still fetching', () => { + // Arrange + const fetching = true; + const value = []; + const usersProjectRoles = { fetching, value }; + const stacksArray = { fetching, value }; + const dataStorageArray = { fetching, value }; + + // Act + const userRoles = createUserRoles(usersProjectRoles, stacksArray, dataStorageArray); + + // Assert + expect(userRoles).toEqual({}); + }); + + it('create user roles from project roles and resources', () => { + // Arrange + const fetching = false; + const userId = 'user-1234'; + const projectKey = 'proj-1234'; + const usersProjectRoles = { + fetching, + value: [ + { + userId, + name: 'user name', + instanceAdmin: true, + dataManager: true, + catalogueRole: 'admin', + projectRoles: [{ + projectKey, + role: 'admin', + }], + }, + ], + }; + const stacksArray = { + fetching, + value: [ + { + projectKey, + category: NOTEBOOK_CATEGORY, + name: 'notebook name', + users: [userId], + }, + { + projectKey, + category: SITE_CATEGORY, + name: 'site name', + users: [userId], + }, + ], + }; + const dataStorageArray = { + fetching, + value: [ + { + projectKey, + name: 'storage name', + users: [userId], + }, + ], + }; + + // Act + const userRoles = createUserRoles(usersProjectRoles, stacksArray, dataStorageArray); + + // Assert + expect(userRoles).toEqual({ + 'user-1234': { + instanceAdmin: true, + dataManager: true, + catalogueRole: 'admin', + catalogueAdmin: true, + cataloguePublisher: false, + catalogueEditor: false, + projectAdmin: [projectKey], + projectUser: [], + projectViewer: [], + siteOwner: [{ projectKey, name: 'site name' }], + notebookOwner: [{ projectKey, name: 'notebook name' }], + storageAccess: [{ projectKey, name: 'storage name' }], + }, + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005786_jquery.fileinput.js b/pool/shard000/JavaScript/0005786_jquery.fileinput.js new file mode 100644 index 0000000000000000000000000000000000000000..3057a3a225cb38936133d6afad23693af4f1ca05 --- /dev/null +++ b/pool/shard000/JavaScript/0005786_jquery.fileinput.js @@ -0,0 +1,89 @@ +/** + * -------------------------------------------------------------------- + * jQuery customfileinput plugin + * Author: Scott Jehl, scott@filamentgroup.com + * Copyright (c) 2009 Filament Group + * licensed under MIT (filamentgroup.com/examples/mit-license.txt) + * -------------------------------------------------------------------- + */ +$.fn.customFileInput = function(){ + return $(this).each(function(){ + //apply events and styles for file input element + var fileInput = $(this) + .addClass('customfile-input') //add class for CSS + // .mouseover(function(){ upload.addClass('customfile-hover'); }) + // .mouseout(function(){ upload.removeClass('customfile-hover'); }) + .hover(function(){ upload.addClass('customfile-hover'); }, function(){ upload.removeClass('customfile-hover'); }) + .focus(function(){ + upload.addClass('customfile-focus'); + fileInput.data('val', fileInput.val()); + }) + .blur(function(){ + upload.removeClass('customfile-focus'); + $(this).trigger('checkChange'); + }) + .bind('disable',function(){ + fileInput.attr('disabled',true); + upload.addClass('customfile-disabled'); + }) + .bind('enable',function(){ + fileInput.removeAttr('disabled'); + upload.removeClass('customfile-disabled'); + }) + .bind('checkChange', function(){ + if(fileInput.val() && fileInput.val() != fileInput.data('val')){ + fileInput.trigger('change'); + } + }) + .bind('change',function(){ + //get file name + var fileName = $(this).val().split(/\\/).pop(); + //get file extension + var fileExt = 'customfile-ext-' + fileName.split('.').pop().toLowerCase(); + //update the feedback + uploadFeedback + .text(fileName) //set feedback text to filename + .removeClass(uploadFeedback.data('fileExt') || '') //remove any existing file extension class + .addClass(fileExt) //add file extension class + .data('fileExt', fileExt) //store file extension for class removal on next change + .addClass('customfile-feedback-populated'); //add class to show populated state + //change text of button + uploadButton.text('Change'); + uploadFeedback.ellipsis(true); + }) + .click(function(){ //for IE and Opera, make sure change fires after choosing a file, using an async callback + fileInput.data('val', fileInput.val()); + setTimeout(function(){ + fileInput.trigger('checkChange'); + },100); + upload.removeClass('customfile-focus'); + }); + + //create custom control container + var upload = $('
        '); + //create custom control button + var uploadButton = $('').appendTo(upload); + //create custom control feedback + var uploadFeedback = $('').appendTo(upload); + + //match disabled state + if(fileInput.is('[disabled]')){ + fileInput.trigger('disable'); + } + + + //on mousemove, keep file input under the cursor to steal click + upload + .mousemove(function(e){ + fileInput.css({ + 'left': e.pageX - upload.offset().left - fileInput.outerWidth() + 20, //position right side 20px right of cursor X) + 'top': e.pageY - upload.offset().top /* - $(window).scrollTop() */ - 3, + 'margin': 0 + }); + }) + .insertAfter(fileInput); //insert after the input + + fileInput.appendTo(upload); + + }); +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005790_entry.js b/pool/shard000/JavaScript/0005790_entry.js new file mode 100644 index 0000000000000000000000000000000000000000..c0c596e17f2c02272a637883e169613d7273fc0e --- /dev/null +++ b/pool/shard000/JavaScript/0005790_entry.js @@ -0,0 +1,87 @@ +/*eslint-env node */ +/*eslint no-console: 0*/ +var fs = require('fs'); +var path = require('path'); +var browserSync = require('browser-sync').create(); +var browserify = require('browserify'); +var watchify = require('watchify'); +var tsify = require('tsify'); + +var sourceFile = path.join(__dirname, 'src/main.ts'); +var outFile = path.join(__dirname, 'build/bundle.js'); + +//Browserify setup +var browserifyInstance = browserify({ + entries: [sourceFile], + cache: {}, + packageCache: {}, + plugin: [watchify, tsify], + debug: true //Enables sourcemaps +}); + +//Browser sync setup +browserSync.init({ + server: './' +}); + +//Browser sync watching of non-ts-files +browserSync.watch('index.html').on('change', browserSync.reload); +browserSync.watch('css/*.css').on('change', browserSync.reload); +browserSync.watch('src/IntervalWorker.js').on('change', () => { + copyFile('src/IntervalWorker.js', 'build/IntervalWorker.js', () => { + browserSync.reload('src/IntervalWorker.js'); + }); +}); + +//Bundling and reloading on bundling - fn triggered automatically on change in .ts-files due to watchify+tsify plugins +function bundle() { + browserifyInstance + .bundle() + .on('error', function (error) { + console.log('Err in fn bundle:', error.toString()); + }) + .pipe(fs.createWriteStream(outFile)); + + setTimeout(() => { + browserSync.reload(outFile);// To avoid unexpected end of input error in Chrome + }, 1000); +} + +browserifyInstance.on('update', bundle); + +//Initial bundling +bundle(); + +//Copy files from node modules +copyFile('node_modules/normalize.css/normalize.css', 'css/normalize.css', () => { }); + +//Copy js files +copyFile('src/IntervalWorker.js', 'build/IntervalWorker.js', () => { }); + +//Utility functions below here +function copyFile(source, target, cb) { + var cbCalled = false; + + var rd = fs.createReadStream(source); + rd.on('error', function (err) { + console.log('Error during copy. Read stream.', err.toString()); + done(err); + }); + var wr = fs.createWriteStream(target); + wr.on('error', function (err) { + console.log('Error during copy. Write stream.', err.toString()); + done(err); + }); + wr.on('close', function () { + console.log('Copy of', source, 'completed'); + done(); + }); + rd.pipe(wr); + + function done(err) { + if (!cbCalled) { + cb(err); + cbCalled = true; + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005791_AlgoliaSearchServer.js b/pool/shard000/JavaScript/0005791_AlgoliaSearchServer.js new file mode 100644 index 0000000000000000000000000000000000000000..42edcd29095293676daa6378a4b8a29a3386fe6e --- /dev/null +++ b/pool/shard000/JavaScript/0005791_AlgoliaSearchServer.js @@ -0,0 +1,78 @@ +'use strict'; + +// Some methods only accessible server side + +module.exports = AlgoliaSearchServer; + +var inherits = require('inherits'); + +var AlgoliaSearch = require('../../AlgoliaSearch'); + +function AlgoliaSearchServer(applicationID, apiKey, opts) { + // Default protocol is https: on the server, to avoid leaking admin keys + if (opts.protocol === undefined) { + opts.protocol = 'https:'; + } + + AlgoliaSearch.apply(this, arguments); +} + +inherits(AlgoliaSearchServer, AlgoliaSearch); + +/* + * Allow to use IP rate limit when you have a proxy between end-user and Algolia. + * This option will set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API Key having rate limits. + * @param adminAPIKey the admin API Key you can find in your dashboard + * @param endUserIP the end user IP (you can use both IPV4 or IPV6 syntax) + * @param rateLimitAPIKey the API key on which you have a rate limit + */ +AlgoliaSearchServer.prototype.enableRateLimitForward = function(adminAPIKey, endUserIP, rateLimitAPIKey) { + this._forward = { + adminAPIKey: adminAPIKey, + endUserIP: endUserIP, + rateLimitAPIKey: rateLimitAPIKey + }; +}; + +/* + * Disable IP rate limit enabled with enableRateLimitForward() function + */ +AlgoliaSearchServer.prototype.disableRateLimitForward = function() { + this._forward = null; +}; + +/* + * Specify the securedAPIKey to use with associated information + */ +AlgoliaSearchServer.prototype.useSecuredAPIKey = function(securedAPIKey, securityTags, userToken) { + this._secure = { + apiKey: securedAPIKey, + securityTags: securityTags, + userToken: userToken + }; +}; + +/* + * If a secured API was used, disable it + */ +AlgoliaSearchServer.prototype.disableSecuredAPIKey = function() { + this._secure = null; +}; + +AlgoliaSearchServer.prototype._computeRequestHeaders = function() { + var headers = AlgoliaSearchServer.super_.prototype._computeRequestHeaders.call(this); + + if (this._forward) { + headers['x-algolia-api-key'] = this._forward.adminAPIKey; + headers['x-forwarded-for'] = this._forward.endUserIP; + headers['x-forwarded-api-key'] = this._forward.rateLimitAPIKey; + } + + if (this._secure) { + headers['x-algolia-api-key'] = this._secure.apiKey; + headers['x-algolia-tagfilters'] = this._secure.securityTags; + headers['x-algolia-usertoken'] = this._secure.userToken; + } + + return headers; +}; diff --git a/pool/shard000/JavaScript/0005792_gbc.js b/pool/shard000/JavaScript/0005792_gbc.js new file mode 100644 index 0000000000000000000000000000000000000000..415df5221fd7781fda0cf1f342304fe3ed0c862b --- /dev/null +++ b/pool/shard000/JavaScript/0005792_gbc.js @@ -0,0 +1,50 @@ +"use strict"; + +var utils = require("../lib/utils"); + +var OPS = { + "0": { + "OP": "8CW", + "regex": /0(\d)([0-9a-f]{2})([0-9a-f]{4})/i, + "matches": [ "bank", "value", "address" ] + } +}; + +var activators = { + "A": 0x0001, + "B": 0x0002, + "SELECT": 0x0004, + "START": 0x0008, + "RIGHT": 0x0010, + "LEFT": 0x0020, + "UP": 0x0040, + "DOWN": 0x0080, + "RTRIGGER": 0x0100, + "LTRIGGER": 0x0200 +}; + +var processOP = function(type, code) { + var op = OPS[type]; + if(!op) return; + var response = { code: code, op: op.OP, data: {} }; + if(op.fn) { + op.fn(type, code, response); + return response; + } + var m = utils.match(code, op.regex); + for(var i = 0; i < m.length; i++) { + utils.addTo(response.data, op.matches[i], m[i]); + } + return response; +}; + +var parseGBC = function parseGBC(code) { + var type = code.match(/([0-9a-f]{1})/i)[1]; + var response = processOP(type, code); + return response; +}; + +module.exports = { + "name": "gbc", + "fn": parseGBC +}; diff --git a/pool/shard000/JavaScript/0005793_server.js b/pool/shard000/JavaScript/0005793_server.js new file mode 100644 index 0000000000000000000000000000000000000000..5bdbbaba0f26cf7bbe2895e1c445de26cea1842d --- /dev/null +++ b/pool/shard000/JavaScript/0005793_server.js @@ -0,0 +1,19 @@ +var express = require('express'), + http = require('http'); + +var app = express(), + port = process.env.PORT || 3000, + server; + +// Servce static assets +app.use('/dist', express.static(__dirname + '/dist')); + +// Routes - catch-all to return index.html +app.get('*', function (req, res) { + res.sendFile(__dirname + '/dist/index.html'); +}); + +server = http.createServer(app); +server.listen(port, function() { + console.log('app listenting on port: ' + port); +}); diff --git a/pool/shard000/JavaScript/0005797_configuration.js b/pool/shard000/JavaScript/0005797_configuration.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0f23b0e66138a6e63aa5ba15f77717a13d2956 --- /dev/null +++ b/pool/shard000/JavaScript/0005797_configuration.js @@ -0,0 +1,64 @@ +/** + * + */ + +'use strict'; + +var fs = require('fs'); +var URI = require('../node_modules/URIjs/src/URI.js'); + +/** + * + * @param {string} filename + * @returns {object} + */ +function read(filename) { + var configString, configObject; + try { + configString = fs.read(filename); + } catch (error) { + throw new Error('Unable to open configuration file "' + filename + '".'); + } + try { + configObject = JSON.parse(configString); + } catch (error) { + throw new Error('Unable to parse configuration file "' + filename + '".'); + } + configObject.baseUrl = configObject.baseUrl || ''; + configObject.paths = configObject.paths || []; + return configObject; +} + +/** + * + * @param {object} configuration + * @returns {Array} + */ +function buildImageScraperQueue(configuration) { + var baseUrl = new URI(configuration.baseUrl).normalize(), + queue = [], + i, path, selectors; + for (i = 0; i < configuration.paths.length; i++) { + if (typeof configuration.paths[i] === 'string') { + path = configuration.paths[i]; + selectors = []; + } else { + path = configuration.paths[i].path; + if (typeof configuration.paths[i].selectors === 'string') { + selectors = [configuration.paths[i].selectors]; + } else { + selectors = configuration.paths[i].selectors; + } + } + queue.push({ + url: new URI(path).absoluteTo(baseUrl).normalize().toString(), + selectors: selectors + }); + } + return queue; +} + +module.exports = { + read: read, + buildImageScraperQueue: buildImageScraperQueue +}; diff --git a/pool/shard000/JavaScript/0005800_type.wrapper.js b/pool/shard000/JavaScript/0005800_type.wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..da12902f25fe2cd8e212a7fe285be38ddcf5d86e --- /dev/null +++ b/pool/shard000/JavaScript/0005800_type.wrapper.js @@ -0,0 +1,105 @@ +/** + * Type Wrapper for Related posts lite + * + * Version: 1.0 + * Requires: jQuery v1.9+ + * + * Copyright (c) 2014 Ernest Marcinko + * Under MIT License (http://www.opensource.org/licenses/mit-license.php) + * + */ +(function($) { + + RplTypeWrapper = function(args) { + this.init(args); + } + + $.extend(RplTypeWrapper.prototype, { + // object variables + typeObject: '', // the current type + o : null, // the options + to : null, // the typeObject + + init: function(args) { + // do initialization here + this.o = $.extend({ + node : null, + type : 'slick', + titleSelector: '.rpl_title', + relevanceSelector: '.rpl_relevance', + visibleClass: 'rpl_visible' + }, args); + this.create(); + }, + + create: function() { + switch(this.o.type) { + case 'slick': + this.typeObject = this.create_slick(); + break; + default: + this.typeObject = this.create_slick(); + } + }, + + arrange: function(args) { + switch(this.o.type) { + case 'slick': + this.arrange_slick(args); + break; + default: + this.arrange_slick(args); + } + }, + + doSomething: function() { + // an example object method + alert('my name is '+this.widget_name); + }, + + /* SLIP-N-SLIDE START */ + + create_slick: function() { + var _this = this; + + // Creating the responsive object for the slick object paramater + var resp = []; + var w = $(this.o.elements, this.o.node).width(); + + for (var i=15;i>0;i--) { + var o = { + breakpoint : ((w+w/3)*i), + settings : { + slidesToShow: i, + slidesToScroll: i, + slide: _this.o.elements + } + }; + resp[i-1] = o; + } + + + + var sl = $(this.o.node).slick({ + infinite: false, + slidesToShow: 2, + slidesToScroll: 2, + slide: _this.o.elements, + responsive: resp + }); + + _debug = sl; + + return sl; + + }, + + arrange_slick: function(args) { + $(this.o.node).slickRefresh(); + } + + /* SLIP-N-SLIDE END */ + + }); + +})(jQuery); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005801_index.js b/pool/shard000/JavaScript/0005801_index.js new file mode 100644 index 0000000000000000000000000000000000000000..fe8f33125f2674bf741e707998632dd509b67e9d --- /dev/null +++ b/pool/shard000/JavaScript/0005801_index.js @@ -0,0 +1,68 @@ +// @flow +/** + * Copyright (c) 2016, Dirk-Jan Rutten + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import 'babel-polyfill' + +import express from 'express' +import graphqlHTTP from 'express-graphql' +import schema from './graphQL' +const app = express() +import { GraphQLError } from 'graphql/error' + +const environment = process.env.NODE_ENV + +var port: number +var errorFormatter + +switch (environment) { + case 'production': + port = 80 + errorFormatter = (error: GraphQLError) => ({ + message: error.message + }) + break + case 'development': + port = 3000 + errorFormatter = (error: GraphQLError) => ({ + message: error.message, + stack: error.stack.split('\n'), + locations: error.locations + }) + break + default: + + if (environment == null) throw new Error(`No environment has been specified, set one using NODE_ENV and set it equal to 'production' or 'development'`) + else throw new Error(`Unrecognized environment ${environment}`) +} + +/** + * The GraphiQL endpoint + */ +app.use(`/graphiql`, graphqlHTTP(req => ({ + schema: schema, + graphiql: true, + formatError: errorFormatter +}) +)) + +/** + * The GraphQL Endpoint + */ +app.use('/', graphqlHTTP(req => ({ + schema: schema, + graphiql: false, + pretty: environment !== 'production', + formatError: errorFormatter +}) +)) + +app.listen(port, function () { + console.log(`Server running on port ${port}`) +}) diff --git a/pool/shard000/JavaScript/0005803_index.js b/pool/shard000/JavaScript/0005803_index.js new file mode 100644 index 0000000000000000000000000000000000000000..11aa137be39f0eee7e0ac06c2afebf72b21d6a08 --- /dev/null +++ b/pool/shard000/JavaScript/0005803_index.js @@ -0,0 +1,77 @@ +import React, { Component } from 'react' +import { render } from 'react-dom' + +import { + Story, Viewer, Rooms, Room, Passage, Link, RoomTitle, RoomComponent, ContextTypes +} from '../' + +import '../styles/default.css' + +class Example extends Component { + render () { + return ( + + + + + + + + + + + + ) + } +} + +class DarkRoom extends Component { + static contextTypes = { + story: ContextTypes.StoryDataShape + } + + render () { + let { story } = this.context + + return ( +
        + + {story.data.turnedOnLight ? 'The room is dark again.' : 'You are in a dark room.'} + + + Turn on light +
        + ) + } +} + +class LightRoom extends Component { + static contextTypes = { + room: ContextTypes.RoomDataShape, + story: ContextTypes.StoryDataShape + } + + componentWillMount () { + let { room, story } = this.context + + room.data.visited = (room.data.visited ? room.data.visited + 1 : 1) + story.data.turnedOnLight = true + + room.updateData(room.data) + story.updateData(story.data) + } + render () { + let { room } = this.context + return ( +
        + + The room is now illuminated. You've turned on this light {room.data.visited} times. + + + Turn off light +
        + ) + } +} + +render(, document.getElementById('root')) diff --git a/pool/shard000/JavaScript/0005804_ng-email-list.js b/pool/shard000/JavaScript/0005804_ng-email-list.js new file mode 100644 index 0000000000000000000000000000000000000000..c9a5e2931b8d63c6c1fa14ef5a56e7b3ec47c1e0 --- /dev/null +++ b/pool/shard000/JavaScript/0005804_ng-email-list.js @@ -0,0 +1,88 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o', + 'link' : function ($scope, elem, attrs, model) { + + model.$validators.email = function (modelValue) { + if (model.$isEmpty(modelValue)) { + modelValue = []; + } + if (!angular.isArray(modelValue)) { + throw new Error('ng-email-list expects model to be an array.'); + } + if (modelValue === undefined) { + return true; + } + $scope.rejected = []; + angular.forEach(modelValue, function (email) { + if (!EMAIL_REX.test(email)) { + $scope.rejected.push(email); + } + }); + return $scope.rejected.length === 0; + }; + + if (attrs.repeat || angular.isDefined(attrs.norepeat)) { + console.log('repeats enabled'); + model.$validators.repeat = function (modelValue) { + if (model.$isEmpty(modelValue)) { + modelValue = []; + } + if (!angular.isArray(modelValue)) { + throw new Error('ng-email-list expects model to be an array.'); + } + $scope.repeat = []; + if (modelValue === undefined) { + return true; + } + //TODO make this = 0) { + pageNum = prev; + } else { + pageNum = next; + } + } else if (marginLeft - prev * width < next * width - marginLeft) { + pageNum = prev; + } else { + pageNum = next; + } + if (pageNum < 0) { + pageNum = 0; + } else if (pageNum >= childNum) { + pageNum = childNum - 1; + } + if (opt_distance) { + this.elem.style.transition = 'margin-left ' + + ExtendedLayout.BASE_TRANSITION_DURATION_ + 's'; + } else { + var transitionDuration = Math.abs(marginLeft - pageNum * width) / + ExtendedLayout.BASE_TRANSITION_DISTANCE_ * + ExtendedLayout.BASE_TRANSITION_DURATION_; + this.elem.style.transition = 'margin-left ' + + transitionDuration + 's ease-in'; + } + this.gotoPage(pageNum); + return pageNum; +}; + + +/** + * Update the category. + * + * @param {number} pageNum The page number to switch to. + */ +ExtendedLayout.prototype.updateCategory = function(pageNum) { + this.elem.style.transition = ''; + this.gotoPage(pageNum); +}; +}); // goog.scope diff --git a/pool/shard000/JavaScript/0005813_stock_out_item.js b/pool/shard000/JavaScript/0005813_stock_out_item.js new file mode 100644 index 0000000000000000000000000000000000000000..e2f074064dd6dbc616f9a7f7072f8964ff517d4c --- /dev/null +++ b/pool/shard000/JavaScript/0005813_stock_out_item.js @@ -0,0 +1,95 @@ +/** + * + */ +define(function (require, exports, module) { + + var zhCN = require('datatableZh'); + var editorCN = require('i18n'); + exports.index = function ($, itemTableId) { + var itemEditor = new $.fn.dataTable.Editor({ + ajax: { + create: { + type: 'POST', + url: '/admin/stock-out-item', + data: {_token: $('meta[name="_token"]').attr('content')}, + }, + edit: { + type: 'PUT', + url: '/admin/stock-out-item/_id_', + data: {_token: $('meta[name="_token"]').attr('content')}, + }, + remove: { + type: 'DELETE', + url: '/admin/stock-out-item/_id_', + data: {_token: $('meta[name="_token"]').attr('content')}, + } + }, + i18n: editorCN, + table: "#" + itemTableId, + idSrc: 'id', + fields: [ + { 'label': '商品', 'name': 'fmaterial_id', 'type': 'select', 'options': materials}, + {'label': '销售单位', 'name': 'fsale_unit',}, + {'label': '基本单位', 'name': 'fbase_unit',}, + {'label': '订单数量', 'name': 'fqty',}, + ] + }); + + var itemTable = $("#" + itemTableId).DataTable({ + dom: "Bfrtip", + language: zhCN, + processing: true, + serverSide: true, + select: true, + paging: true, + rowId: "id", + ajax: '/admin/stock-out-item/pagination', + columns: [ + {'data': 'id'}, + { + 'data': 'fstock_out_id', + render: function (data, type, full) { + if (full.stockout != null) + return full.stockout.fbill_no + else + return ""; + } + }, + { + 'data': 'fmaterial_id', + render: function (data, type, full) { + if (full.material != null) + return full.material.fname + else + return ""; + } + }, + {'data': 'fsale_unit'}, + {'data': 'fbase_unit'}, + {'data': 'fqty'}, + {'data': 'fbase_qty'}, + + ], + buttons: [ + // { text: '新增', action: function () { } }, + // { text: '编辑', className: 'edit', enabled: false }, + // { text: '删除', className: 'delete', enabled: false }, + {extend: "create", text: '新增', editor: itemEditor}, + {extend: "edit", text: '编辑', editor: itemEditor}, + {extend: "remove", text: '删除', editor: itemEditor}, + {extend: 'excel', text: '导出Excel'}, + {extend: 'print', text: '打印'}, + //{extend: 'colvis', text: '列显示'} + ] + }); + + // table.on( 'select', checkBtn).on( 'deselect', checkBtn); + // + // function checkBtn(e, dt, type, indexes) { + // var count = table.rows( { selected: true } ).count(); + // table.buttons( ['.edit', '.delete'] ).enable(count > 0); + // } + + } + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005814_ExpenseCtrl.js b/pool/shard000/JavaScript/0005814_ExpenseCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..0ae2c927404bb50e946522f88501bd19c18a6cc6 --- /dev/null +++ b/pool/shard000/JavaScript/0005814_ExpenseCtrl.js @@ -0,0 +1,125 @@ +'use strict'; +/** + * Created by AxelCollardBovy on 9/20/15. + * + * Expense Controller + */ +var universeControllers = angular.module('tripSplitterCloneControllers'); + +universeControllers.controller('ExpenseCtrl',['$scope', '$rootScope', 'ExpenseService', '$filter','UserService','$routeParams','TripService', + function($scope, $rootScope, ExpenseService, $filter,UserService,$routeParams,TripService) { + $scope.expense = {}; + $scope.expenses = []; + $scope.editing = false; + $scope.selectedTraveler = {}; + + $scope.users = []; + $scope.currentExpense = {}; + $scope.trip = {'id':$routeParams.tripId}; + + //var paginationHelper; + + $scope.list = function(pagination) { + ExpenseService.list(pagination, function(response) { + if (response.ok) { + var responseObject = JSON.parse(response.data); + + if (responseObject.page) { + $scope.expenses = responseObject.items; + paginationHelper.extendCallback(responseObject); + } else { + $scope.expenses = responseObject; + } + } + }, $rootScope.manageError); + }; + + $scope.listUsers = function() { + UserService.listUsers({}, function(response) { + if (response.ok){ + $scope.users = JSON.parse(response.data); + $scope.selectedTraveler = $scope.users[0]; + } + }, $rootScope.manageError); + }; + + $scope.edit = function(expense) { + $scope.editing = true; + + $scope.expense = expense; + + $scope.expenses.splice($scope.expenses.indexOf($scope.expense), 1); + }; + + $scope.modify = function() { + if ($scope.myForm.$valid) { + ExpenseService.modify($scope.expense, function(response) { + if (response.ok) { + // expense successfully edited + var par = JSON.parse(response.data); + + $scope.expenses.push(par); + + $rootScope.keepMessages = true; + $scope.initialize(); + } + }, this.errorManager); + } else { + $rootScope.showErrorMessage(i18n.t('commissionSchema.validation.numberFormat'), true); + } + }; + + $scope.clean = function() { + $scope.initialize(); + }; + + $scope.cancel = function() { + if ($scope.editing) { + + $scope.expense = {}; + $scope.editing = false; + } + + $scope.initialize(); + }; + + $scope.deleteExpense = function(expense){ + $('#deleteExpenseModal').modal('show'); + $scope.expense=expense; + }; + + $scope.remove = function() { + ExpenseService.remove($scope.expense, function(response) { + if (response.ok) { + $scope.expenses.splice($scope.expenses.indexOf($scope.expense), + 1); + $('#deleteExpenseModal').modal('hide'); + } + }, this.errorManager); + }; + + $scope.search = function(pagination) { + TripService.search($scope.trip, function(response) { + if (response.ok) { + $scope.trip = JSON.parse(response.data); + + } + }, $rootScope.manageError); + }; + + $scope.initialize = function() { + + $scope.editing = false; + $scope.expense = {}; + + if ($rootScope.canAccess('/configuration/expense:listExpense')) { + //$scope.list(); + //$scope.listUsers(); + $scope.search(); + } + + $rootScope.areErrorMessages = false; + }; + $scope.initialize(); + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005815_texture_test.js b/pool/shard000/JavaScript/0005815_texture_test.js new file mode 100644 index 0000000000000000000000000000000000000000..136300f8ddbc52d3a9dd4cafdeece0883c28967b --- /dev/null +++ b/pool/shard000/JavaScript/0005815_texture_test.js @@ -0,0 +1,28 @@ +var S = Shade; +var Models = Lux.Models; + +var gl; +var drawable; +var alive = true; + +////////////////////////////////////////////////////////////////////////////// + +function initWebgl() +{ + var tex = Lux.texture({ + src: "image.png", + onload: function() { Lux.Scene.invalidate(); } + }); + + var squareModel = Models.square(); + Lux.Scene.add(Lux.actor({ + model: squareModel, + appearance: { + position: squareModel.vertex, + color: S.texture2D(tex, squareModel.texCoord)}})); +} + +$().ready(function() { + gl = Lux.init(); + initWebgl(); +}); diff --git a/pool/shard000/JavaScript/0005816_safari-injected.js b/pool/shard000/JavaScript/0005816_safari-injected.js new file mode 100644 index 0000000000000000000000000000000000000000..a948b6d13cdde583fe3b49a72762953e55964de7 --- /dev/null +++ b/pool/shard000/JavaScript/0005816_safari-injected.js @@ -0,0 +1,12 @@ +var powerScrollDirection = 1; +var powerLastScrollTop = -1; +function handleMessage(msgEvent) { + if (msgEvent.name === "scroll") { + if (document.body.scrollTop == powerLastScrollTop) + powerScrollDirection = powerScrollDirection * -1; + powerLastScrollTop = document.body.scrollTop; + var amount = msgEvent.message * powerScrollDirection; + document.body.scrollTop = document.body.scrollTop + amount; + } +} +safari.self.addEventListener("message", handleMessage, false); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005817_FileUpload.js b/pool/shard000/JavaScript/0005817_FileUpload.js new file mode 100644 index 0000000000000000000000000000000000000000..91bbf555f58330935c6365237061b1aa5b50faa3 --- /dev/null +++ b/pool/shard000/JavaScript/0005817_FileUpload.js @@ -0,0 +1,122 @@ +Ext.define('TE.util.FileUpload', { + extend: 'Ext.window.Window', + title: 'Upload files', + id: 'file_upload_container', + modal: true, + closable: false, + width: 400, + editor: false, + + signalUploadComplete: function(info) { + var label = this.down('#file_upload_status'); + label.update('
        ' + info + '
        '); + }, + + items: [{ + id: 'FilesDropZone', + xtype: 'container', + height: 100, + border: false, + html: '
        Drop files here
        ', + ddGroup: 'filesDDGroup', + + style: { backgroundColor: '#fff', padding: '5px' }, + + listeners: { + afterrender: function () { + var dropTarget = this.getEl(); + var dropTargetEl = dropTarget.dom; + // var dropInnerZone = this.down('#upload_drop_zone'); + var me = this; + + function dragOver(event) { + dropTarget.setStyle('background-color', '#ccc'); + if (event.preventDefault) { + event.preventDefault(); + } + return false; + } + + function dragLeave(event) { + dropTarget.setStyle('background-color', '#fff'); + return true; + } + + // Cancel default behaviors to enable drag and drop + dropTargetEl.addEventListener('dragover', dragOver); + dropTargetEl.addEventListener('dragenter', dragOver); + dropTargetEl.addEventListener('dragleave', dragLeave); + + // When the user drops files onto the drop zone, + // capture the file references and immediately upload + dropTargetEl.addEventListener('drop', function (evt) { + dropTarget.setStyle('background-color', '#fff'); + + var files, datasetName; + + // Stop the browser's default behavior when + // dropping files in the viewable area + evt.stopPropagation(); + evt.preventDefault(); + + // Get the name of the selected data set + datasetName = "Multiview pictures"; + + // A reference to the files selected + files = evt.dataTransfer.files; + + // Currently, I have a separate library that holds + // reusable functions to access our public API + var win = Ext.getCmp('file_upload_container'); + var editor = win.editor; + editor.uploadFiles(datasetName, files, win); + + }, false); + } + } + },{ + xtype: 'container', + id: 'FilesField', + style: { padding: '5px' }, + + // Just adding a typical multipart file field here to a container + html: '
        or upload your files the traditional way...
        ', + + listeners: { + afterrender: function () { + + // This code is, essentially, the same as above + Ext.get('upload_files').on('change', function (evt) { + var files, datasetName; + + evt.stopPropagation(); + evt.preventDefault(); + + // Get the name of the selected data set + datasetName = "Multiview pictures"; + + // A reference to the files selected + files = evt.target.files; + + // Upload files to the server + var win = Ext.getCmp('file_upload_container'); + var editor = win.editor; + editor.uploadFiles(datasetName, files, win); + }); + } + } + },{ + xtype:'container', + id: 'file_upload_status', + html: '
        Ready to upload
        ', + width: 400 + }], + + buttons : [{ + text: 'Close', + iconCls: 'cancel-icon', + handler: function() { + this.up('window').close(); + } + }] +}); diff --git a/pool/shard000/JavaScript/0005819_cloud-key.js b/pool/shard000/JavaScript/0005819_cloud-key.js new file mode 100644 index 0000000000000000000000000000000000000000..79ac46b690f5b124b04d73deac49fd0fc44a3454 --- /dev/null +++ b/pool/shard000/JavaScript/0005819_cloud-key.js @@ -0,0 +1,43 @@ +define(function(require, exports, module) { + + exports.run = function() { + + var $form = $("#cloud-setting-form"); + + var $info = $("#key-license-info") + $.get($info.data('url'), function(html) { + $("#loading-text").hide(); + $info.html(html); + if ($info.find('.key-error-alert').length == 0) { + $("#key-rest-btn").removeClass('hide'); + } + }); + + $info.on('click', '.key-bind-btn', function() { + if (!confirm('授权域名一旦绑定就无法变更,您真的要绑定该授权域名吗?')) { + return ; + } + $(this).button('loading'); + $.post($(this).data('url'), function(response) { + + }, 'json').done(function() { + window.location.reload(); + }); + }); + + $form.on('click', '.save-copyright-btn', function() { + var $this = $(this); + $this.button('loading'); + + var params = {name: $('#field-copyrightName').val()}; + $.post($this.data('url'), params, function(){ + window.location.reload(); + }); + + + return false; + }); + + } + +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005821_DicewareApi.js b/pool/shard000/JavaScript/0005821_DicewareApi.js new file mode 100644 index 0000000000000000000000000000000000000000..f9cb09aba85a2984592f5120a72e34c167ecdf7c --- /dev/null +++ b/pool/shard000/JavaScript/0005821_DicewareApi.js @@ -0,0 +1,36 @@ +/** + * Created by andywalpole on 01/11/15. + */ +import JsonUrl from '../data/diceware'; +import DataCache from './dataCache'; + +class DicewareApi { + + static retrieveContent() { + + let content = JsonUrl; + let newMap = new Map(); + + for (let property in content) { + if (content.hasOwnProperty(property)) { + newMap.set(Number.parseInt(property, 10), content[property]); + } + } + + return newMap; + + } + + static setKeywordNum(input) { + this.keywordsNums = new DataCache(); + this.keywordsNums.cache = input; + } + + static getKeywordNum() { + return this.keywordsNums.cache; + } + +} + +export default DicewareApi; + diff --git a/pool/shard000/JavaScript/0005823_resizewatcher.js b/pool/shard000/JavaScript/0005823_resizewatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..d7e086587e66804e77a5b13f49cf8634279d38fb --- /dev/null +++ b/pool/shard000/JavaScript/0005823_resizewatcher.js @@ -0,0 +1,20 @@ +'use strict'; + +angular.module('heinzelmannchen') + .directive('resizeWatcher', function ($rootScope, $window) { + return { + restrict: 'A', + link: function postLink(scope, element, attrs) { + var width = $window.innerWidth; + var height = $window.innerHeight; + angular.element($window).bind('resize', function(){ + + if(width !== $window.innerWidth || height !== $window.innerHeight) { + $rootScope.$broadcast('updateGraph'); + } + width = $window.innerWidth; + height = $window.innerHeight; + }); + } + }; + }); diff --git a/pool/shard000/JavaScript/0005825_animate.js b/pool/shard000/JavaScript/0005825_animate.js new file mode 100644 index 0000000000000000000000000000000000000000..fd12ae4e7ecf2d08be8c60bf7430c6e548c3ef7b --- /dev/null +++ b/pool/shard000/JavaScript/0005825_animate.js @@ -0,0 +1,20 @@ +'use strict'; + +describe('Directive: animate', function () { + + // load the directive's module + beforeEach(module('rolApp')); + + var element, + scope; + + beforeEach(inject(function ($rootScope) { + scope = $rootScope.$new(); + })); + + it('should make hidden element visible', inject(function ($compile) { + element = angular.element(''); + element = $compile(element)(scope); + expect(element.text()).toBe('this is the animate directive'); + })); +}); diff --git a/pool/shard000/JavaScript/0005832_start-app.js b/pool/shard000/JavaScript/0005832_start-app.js new file mode 100644 index 0000000000000000000000000000000000000000..4d0ac621a78b9d0dbb1d12d9a0ad2e1606e8790e --- /dev/null +++ b/pool/shard000/JavaScript/0005832_start-app.js @@ -0,0 +1,29 @@ +/* global require */ + +var Application = require('<%= namespace %>/app')['default']; +var Router = require('<%= namespace %>/router')['default']; + +export default function startApp(attrs) { + var App; + + var attributes = Ember.merge({ + // useful Test defaults + rootElement: '#ember-testing', + LOG_ACTIVE_GENERATION:false, + LOG_VIEW_LOOKUPS: false + }, attrs); // but you can override; + + Router.reopen({ + location: 'none' + }); + + Ember.run(function(){ + App = Application.create(attributes); + App.setupForTesting(); + App.injectTestHelpers(); + }); + + App.reset(); + + return App; +} diff --git a/pool/shard000/JavaScript/0005834_index.js b/pool/shard000/JavaScript/0005834_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b23ed8defe732d9a547669a99e22a56ccfc7a83 --- /dev/null +++ b/pool/shard000/JavaScript/0005834_index.js @@ -0,0 +1,48 @@ +import React, { Component } from 'react' +import ReactDOM from 'react-dom' +import YTSearch from 'youtube-api-search' +import _ from 'lodash' + +import SearchBar from './components/search_bar' +import VideoList from './components/video_list' +import VideoDetail from './components/video_detail' + +const API_KEY = 'AIzaSyDJN1oayZjuG7SD3EUV-72cThreLHpo8i0' + + +class App extends Component { + + constructor(props){ + super(props) + this.state = { + videos: [], + selectedVideo: null + } + this.videoSearch("Surfboards") + } + + videoSearch(term){ + YTSearch({key: API_KEY, term: term}, (videos) => { + this.setState({ videos, selectedVideo: videos[0] }) + }) + } + + render(){ + + const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300) + + return( +
        + + + this.setState({selectedVideo}) } + /> +
        + ) + } +} + + +ReactDOM.render(, document.querySelector('.container')); diff --git a/pool/shard000/JavaScript/0005835_LyricsViewer_spec.js b/pool/shard000/JavaScript/0005835_LyricsViewer_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..da50652102dd3cf1c73628973214569c7aca943a --- /dev/null +++ b/pool/shard000/JavaScript/0005835_LyricsViewer_spec.js @@ -0,0 +1,173 @@ +/* eslint-disable no-unused-expressions */ + +import $ from 'jquery'; +import React from 'react'; +import { findDOMNode } from 'react-dom'; +import chai, { expect } from 'chai'; +import { mount } from 'enzyme'; + +import LyricsViewer from '../../../build/renderer/ui/components/generic/LyricsViewer'; +import mockSettings, { fakeSettings, getVars, mockEvent } from './_mockSettings'; + +chai.should(); + +describe('', () => { + let hooks; + let unhooks; + let opts; + + beforeEach(() => { + mockSettings(); + hooks = getVars().hooks; + unhooks = getVars().unhooks; + opts = { + attachTo: document.createElement('div'), + }; + }); + + it('should render the lyrics container', () => { + const component = mount(); + component.children().length.should.be.gt(0); + }); + + it('should hook into the PlaybackAPI events', () => { + mount(); + hooks['lyrics:show'].should.be.ok; + hooks['PlaybackAPI:change:lyrics'].should.be.ok; + hooks['PlaybackAPI:change:state'].should.be.ok; + hooks['PlaybackAPI:change:time'].should.be.ok; + hooks['settings:set:scrollLyrics'].should.be.ok; + }); + + it('should unhook the PlaybackAPI events when unmounting', () => { + mount().unmount(); + unhooks['lyrics:show'].should.be.ok; + unhooks['PlaybackAPI:change:lyrics'].should.be.ok; + unhooks['PlaybackAPI:change:state'].should.be.ok; + unhooks['PlaybackAPI:change:time'].should.be.ok; + unhooks['settings:set:scrollLyrics'].should.be.ok; + }); + + it('should show when recieving the show event', () => { + const component = mount(); + component.find('#lyrics_back.vis').length.should.be.equal(0); + mockEvent('lyrics:show'); + component.find('#lyrics_back.vis').length.should.be.equal(1); + }); + + it('should hide when the lyrics are clicked', () => { + const component = mount(); + component.find('#lyrics_back.vis').length.should.be.equal(0); + mockEvent('lyrics:show'); + component.find('#lyrics_back.vis').length.should.be.equal(1); + component.find('#lyrics_back').simulate('click'); + component.find('#lyrics_back.vis').length.should.be.equal(0); + }); + + it('should say loading lyrics when null lyrics are passed in', () => { + const component = mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', null); + const domNode = $(findDOMNode(component.instance())); + domNode.find('h1').text().should.be.equal('lyrics-loading-message'); + }); + + it('should should timeout if lyrics aren\'t found in 4 seconds', (done) => { + const component = mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', null); + const domNode = $(findDOMNode(component.instance())); + setTimeout(() => { + domNode.find('h1').text().should.be.equal('lyrics-failed-message'); + done(); + }, 4500); + }); + + it('should update the lyrics when a string of lyrics are passed in', () => { + const component = mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', null); + const domNode = $(findDOMNode(component.instance())); + domNode.find('h1').text().should.be.equal('lyrics-loading-message'); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + domNode.find('p').text().should.be.equal('new lyrics'); + }); + + it('should stop scrolling when settings change to false', () => { + const component = mount(, opts); + mockEvent('settings:set:scrollLyrics', false); + const domNode = $(findDOMNode(component.instance())); + expect(domNode.find('#lyrics p').attr('data-scroll')).to.be.equal(undefined); + }); + + it('should start scrolling when settings change to true', () => { + const component = mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + mockEvent('settings:set:scrollLyrics', true); + const domNode = $(findDOMNode(component.instance())); + expect(domNode.find('#lyrics p').attr('data-scroll')).to.be.equal('true'); + }); + + it('should start scrolling when the time changes', () => { + mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + mockEvent('PlaybackAPI:change:state', true); + mockEvent('settings:set:scrollLyrics', true); + mockEvent('PlaybackAPI:change:time', { + current: 1000, + total: 2000, + }); + }); + + it('should jump scrolling when the time jumps', () => { + mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + mockEvent('PlaybackAPI:change:state', true); + mockEvent('settings:set:scrollLyrics', true); + mockEvent('PlaybackAPI:change:time', { + current: 1000, + total: 20000, + }); + mockEvent('PlaybackAPI:change:time', { + current: 18000, + total: 20000, + }); + }); + + it('should stop animating when the music stops', () => { + mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + mockEvent('PlaybackAPI:change:state', true); + mockEvent('settings:set:scrollLyrics', true); + mockEvent('PlaybackAPI:change:time', { + current: 1000, + total: 2000, + }); + mockEvent('PlaybackAPI:change:state', false); + }); + + it('should not animate when the music isn\'t playing', () => { + mount(, opts); + mockEvent('PlaybackAPI:change:lyrics', 'new lyrics'); + mockEvent('PlaybackAPI:change:state', false); + mockEvent('settings:set:scrollLyrics', true); + mockEvent('PlaybackAPI:change:time', { + current: 1000, + total: 2000, + }); + }); + + it('should animate when the window is resized', () => { + mount(, opts); + window.dispatchEvent(new Event('resize')); + }); + + it('should update the styling in dark mode', () => { + fakeSettings('themeType', 'FULL'); + const component = mount(, opts); + component.find('#lyrics_progress').props().style.backgroundColor.should.be.equal('themeColor'); + }); + + it('should reset styling when the theme is disabled', () => { + fakeSettings('theme', false); + const component = mount(, opts); + component.find('#lyrics_progress').props().style.should.not.have.property('backgroundColor'); + }); +}); diff --git a/pool/shard000/JavaScript/0005839_controllers.js b/pool/shard000/JavaScript/0005839_controllers.js new file mode 100644 index 0000000000000000000000000000000000000000..7e545538991306e763340308ff576c2ace25a21a --- /dev/null +++ b/pool/shard000/JavaScript/0005839_controllers.js @@ -0,0 +1,103 @@ +angular.module('statistic') +.controller('StatsScoreCtrl', function ($scope, $rootScope, StatisticService, $ionicModal, SHOT_TYPES) { + //Always assign the nav bar title from the parent view, using the var name 'title' + $scope.title = 'Statistic'; + console.log('In StatsScoreCtrl'); + //var tempZoneStats1 = [12, 23, 35, 42, 53, 65, 71, 88, 93, 12, 11, 53, 93, 38, 52, 12, 58, 42, 18, 52, 82, 12, 60, 29, 100]; + //var tempZoneStats2 = [62, 23, 56, 29, 75, 95, 3, 35, 91, 30, 95, 11, 23, 87, 12, 98, 22, 69, 88, 12, 42, 35, 93, 72, 100]; + + var isAccuracyMode = true; + /* + StatisticService.zoneStat().then(function (result) { + zoneStats = result; + }) +*/ + + /* + StatisticService.heatMap().then(function (result) { + console.log('heatMapValue function from service', result); + }); + */ + + $ionicModal.fromTemplateUrl('templates/zone_stats_modal.html',function ($ionicModal) { + $scope.modal = $ionicModal; + }, { + scope: $scope, + animation: 'slide-in-up' + }) + + + $scope.scoreStats = function () { + isAccuracyMode = false; + $scope.header = 'Score Hit Map'; + $scope.content1 = 'Pink - Favorite score zone'; + $scope.content2 = 'Yellow - Avoided score zone'; + var element = document.getElementById('tabLeft'); + element.setAttribute('class', 'tab-item active'); + element.innerHTML = '

        Score

        '; + element = document.getElementById('tabRight'); + element.setAttribute('class','tab-item'); + element.innerHTML = '

        Accuracy

        '; + StatisticService.scoreHeatMap().then(function (result) { + $rootScope.$broadcast('createHitMapEvent_Y2P', result); + }); + } + + $scope.accuracyStats = function () { + isAccuracyMode = true; + $scope.header = 'Accuracy Hit Map'; + $scope.content1 = 'Red - High failure rate'; + $scope.content2 = 'Green - High success rate'; + var element = document.getElementById('tabLeft'); + element.setAttribute('class', 'tab-item'); + element.innerHTML = '

        Score

        '; + element = document.getElementById('tabRight'); + element.setAttribute('class','tab-item active'); + element.innerHTML = '

        Accuracy

        '; + StatisticService.accuracyHeatMap().then(function (result) { + $rootScope.$broadcast('createHitMapEvent_R2G', result); + }); + }; + + + $scope.$on('courtReadyForEvent', function (event, arg) { + console.log('In StatsScoreCtrl, received event', event); + $scope.header = 'Score Hit Map'; + $scope.content1 = 'Red - High failure rate'; + $scope.content2 = 'Green - High success rate'; + + StatisticService.accuracyHeatMap().then(function (result) { + $rootScope.$broadcast('createHitMapEvent_R2G', result); + }); + }); + + $scope.$on('recordShotEvent', function (event, arg) { + $scope.zone = []; + //console.log('Zone Stats', zoneStats); + + if (isAccuracyMode) { + StatisticService.zoneAccuracyStat(arg.value).then(function (result) { + Object.keys(result).forEach(function (key, index) { + $scope.zone.push({ + shottype: key, + shotrate: result[key]['accuracy'], + shotcount: result[key]['total'] + }); + }); + }); + } else { + StatisticService.zoneScoreStat(arg.value).then(function (result) { + for (var i = 0; i < result.length; i++) { + $scope.zone.push({ + shotcount: result[i]['shotCount'], + shottype: result[i]['shotType'], + shotposition: result[i]['shotPosition'] + }); + } + }); + } + $scope.accuracyModel = isAccuracyMode; + console.log('accuracy mode is on?', $scope.accuracyMode); + $scope.modal.show(); + }); +}); diff --git a/pool/shard000/JavaScript/0005840_tag_configuration_services.js b/pool/shard000/JavaScript/0005840_tag_configuration_services.js new file mode 100644 index 0000000000000000000000000000000000000000..3aaf3a38e9593012a449bbfc4a23edcef5014429 --- /dev/null +++ b/pool/shard000/JavaScript/0005840_tag_configuration_services.js @@ -0,0 +1,67 @@ +'use strict'; + +angular.module('alienUiApp').factory('tagConfigurationServices', ['$resource', + function($resource) { + + var TagConfigurationDAO = $resource('rest/tagconfigurations/:id'); + + var searchTagConfiguration = $resource('rest/tagconfigurations/search', {}, { + 'search': { + method: 'POST', + isArray: false, + headers: { + 'Content-Type': 'application/json; charset=UTF-8' + } + } + }); + + + var get = function(id) { + return TagConfigurationDAO.get({ + 'id': id + }).$promise.then(function(result) { + return result.data; + }); + }; + + var remove = function(id) { + return TagConfigurationDAO.remove({ + 'id': id + }).$promise.then(function(result) { + return result.data; + }); + }; + + var save = function(config) { + return TagConfigurationDAO.save({}, angular.toJson(config)).$promise.then(function(result) { + return result.data; + }); + }; + + var processValidationErrors = function(validationErrors) { + if (validationErrors) { + var errors = {}; + for (var i = 0; i < validationErrors.length; i++) { + var error = validationErrors[i]; + if (UTILS.isArrayDefinedAndNotEmpty(errors[error.error])) { + errors[error.error].push(error.path); + } else { + // TODO manage correctly server validation + errors[error.error] = [ + [error.path] + ]; + } + } + return errors; + } + }; + + return { + 'search': searchTagConfiguration.search, + 'get': get, + 'remove': remove, + 'save': save, + 'processValidationErrors': processValidationErrors + }; + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005842_vendorLinker.js b/pool/shard000/JavaScript/0005842_vendorLinker.js new file mode 100644 index 0000000000000000000000000000000000000000..d6a09ade8fe1f70b22b5f1c77456010882d4d080 --- /dev/null +++ b/pool/shard000/JavaScript/0005842_vendorLinker.js @@ -0,0 +1,116 @@ +'use strict'; + +/** + * Utility for linking vendor node modules with the application by exporting + * them to the IMA loader's modules. + */ +export class VendorLinker { + /** + * Initializes the vendor linker. + */ + constructor() { + /** + * Internal storage of loaded modules. + * + * @type {Map>} + */ + this._modules = new Map(); + + /** + * Internal storage of loaded IMA plugins. + * + * @type {Object[]} + */ + this._plugins = []; + } + + /** + * Sets the provided vendor node module to the internal registry of this + * vendor linker, and registers an IMA loader module of the same name, + * exporting the same values. + * + * @param {string} moduleName The name of the module. + * @param {Object} moduleValues Values exported from the module. + */ + set(moduleName, moduleValues) { + this._modules.set(moduleName, moduleValues); + + if (typeof moduleValues.$registerImaPlugin === 'function') { + this._plugins.push({ name: moduleName, module: moduleValues }); + } + + $IMA.Loader.register(moduleName, [], exports => ({ + setters: [], + execute: () => { + // commonjs module compatibility + exports('default', moduleValues); + // ES2015 module compatibility + for (let key of Object.keys(moduleValues)) { + exports(key, moduleValues[key]); + } + } + })); + } + + /** + * Returns the provided vendor node module from the internal registry of this + * vendor linker. + * + * @param {string} moduleName The name of the module. + * @param {?boolean} [imaInternalModule] + * @return {Object} moduleValues Values exported from the module. + */ + get(moduleName, imaInternalModule) { + if (!this._modules.has(moduleName) && !imaInternalModule) { + throw new Error( + `The module '${moduleName}' is not registered.` + + `Add the module to vendors in build.js` + ); + } + + return this._modules.get(moduleName); + } + + /** + * Clears all loaded modules and plugins from this vendor linker. + * + * @return {VendorLinker} This vendor linker. + */ + clear() { + this._modules.clear(); + this._plugins = []; + + return this; + } + + /** + * Binds the vendor modules loaded in this vendor linker to the + * {@code Vendor} sub-namespace of the provided namespace. + * + * @param {Namespace} ns The namespace to which the vendor modules should + * be bound. + */ + bindToNamespace(ns) { + let nsVendor = ns.namespace('vendor'); + for (let name of this._modules.keys()) { + let lib = this._modules.get(name); + + if (typeof lib.$registerImaPlugin === 'function') { + lib.$registerImaPlugin(ns); + } + + nsVendor[name] = lib; + } + } + + /** + * Returns the loaded IMA plugins as an array of export objects. + * + * @return {Array>} The loaded IMA plugins. + */ + getImaPlugins() { + return this._plugins; + } +} + +export default new VendorLinker(); diff --git a/pool/shard000/JavaScript/0005849_asset_path.js b/pool/shard000/JavaScript/0005849_asset_path.js new file mode 100644 index 0000000000000000000000000000000000000000..097002ee5c95994078222641c40a83b9ca24e5cb --- /dev/null +++ b/pool/shard000/JavaScript/0005849_asset_path.js @@ -0,0 +1,47 @@ +'use strict'; + +var should = require('chai').should(); + +describe('asset_path', function(){ + var Hexo = require('../../../lib/hexo'); + var hexo = new Hexo(__dirname); + var assetPathTag = require('../../../lib/plugins/tag/asset_path')(hexo); + var Post = hexo.model('Post'); + var PostAsset = hexo.model('PostAsset'); + var post; + + hexo.config.permalink = ':title/'; + + function assetPath(args){ + return assetPathTag.call(post, args.split(' ')); + } + + before(function(){ + return hexo.init().then(function(){ + return Post.insert({ + source: 'foo.md', + slug: 'foo' + }); + }).then(function(post_){ + post = post_; + + return PostAsset.insert({ + _id: 'bar', + slug: 'bar', + post: post._id + }); + }); + }); + + it('default', function(){ + assetPath('bar').should.eql('/foo/bar'); + }); + + it('no slug', function(){ + should.not.exist(assetPath('')); + }); + + it('asset not found', function(){ + should.not.exist(assetPath('boo')); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005850_productItem.js b/pool/shard000/JavaScript/0005850_productItem.js new file mode 100644 index 0000000000000000000000000000000000000000..de02d61e84a80cddb374346da50bfde386490a07 --- /dev/null +++ b/pool/shard000/JavaScript/0005850_productItem.js @@ -0,0 +1,45 @@ +var mongoose = require('mongoose') + , CommonModel = mongoose.model('ProductItem') + , utils = require('../../../lib/utils') + , wechatUtils = require('../../../lib/wechatUtils'); +var sha1 = require('sha1'); +exports.searchList = function(req, res) { + var crite = utils.setCriteriaParam(req.body); + var sortObj = utils.setSortParam(req.body); + CommonModel.count(crite, function(errors, count){ + if(errors){ + res.json({ + "success":false, + "msg":"查询过程中出错!", + "error":errors + }); + return; + } + CommonModel.queryList({rows:req.body.rows, page:req.body.page, criteria:crite, sort:sortObj}, function(err,list){ + utils.setQueryListResponse(err, req, res, list, count); + }); + }); +}; + +exports.findProductItemById = function(req, res){ + var id = req.param("_id"); + CommonModel.findOne({ _id:id}, function(err, doc){ + if(err) { + res.json({success:false, message:"内部错误!"}); + } + else { + res.json({success:true, productItem:doc}); + } + }); +}; + +exports.sharePruductById = function(req, res){ + var id = req.param("id"); + var timestr = Math.round(new Date().getTime()/1000); + var url = 'http://www.ncnll.com/shareProduct/'+id+"/"; + wechatUtils.getSignatureIfNotExist(function(obj, signature){ + console.log(signature) + res.render('share/shareIndex', { title: 'NCNLL', pageType:'share', timestr:timestr, signature:signature }); + }, url,timestr); + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005852_gulpfile.js b/pool/shard000/JavaScript/0005852_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..344afc27d1fe60a12ca0396af95a51f75434dc66 --- /dev/null +++ b/pool/shard000/JavaScript/0005852_gulpfile.js @@ -0,0 +1,12 @@ +var gulp = require('gulp'), + uglify = require('gulp-uglify'), + ngAnnotate = require('gulp-ng-annotate'), + rename = require('gulp-rename'); + +gulp.task('js', function () { + gulp.src('./barbarajs.js') + .pipe(ngAnnotate()) + .pipe(uglify()) + .pipe(rename({suffix: '.min'})) + .pipe(gulp.dest('.')); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005853_ticker.js b/pool/shard000/JavaScript/0005853_ticker.js new file mode 100644 index 0000000000000000000000000000000000000000..0281588a5552b973156e1ae7d0b8b5a3d1bbe99f --- /dev/null +++ b/pool/shard000/JavaScript/0005853_ticker.js @@ -0,0 +1,153 @@ +/* global describe, it */ + +'use strict'; + +var should = require('chai').should(); + +var pluginConfig = require('../config'); + + +var testedCurrencies = ['USD', 'EUR']; + + +// Checks structure and values of object returned by `.balance()` +function checkCurrency(results, currency) { + results.should.be.an('object'); + results.should.have.property(currency); + + var curr = results[currency]; + curr.should.be.an('object'); + curr.should.have.property('currency'); + curr.currency.should.equal(currency); + + curr.should.have.property('rates'); + + var rates = curr.rates; + rates.should.be.an('object'); + + rates.should.have.property('ask'); + var askRate = parseFloat(rates.ask); + isNaN(askRate).should.not.equal(true, 'The ask rate should be a float'); + + rates.should.have.property('bid'); + var bidRate = parseFloat(rates.bid); + isNaN(bidRate).should.not.equal(true, 'The bid rate should be a float'); + + askRate.should.be.at.least(bidRate); + + return rates; +} + + +// only test if ticker is declared to be working +if (pluginConfig.SUPPORTED_MODULES.indexOf('ticker') !== -1) { + describe(pluginConfig.NAME + ' Ticker', function() { + var tickerPlugin = require('../index'); + + // // NOTE: should be uncommented and adjusted when rate limiting is in place + // afterEach(function(done) { + // setTimeout(done, 1000); + // }); + + // NOTE: MAX timeout for each test + this.timeout(3000); + + // single supported currency fetch (as string) + it('should read ticker in \'' + testedCurrencies[0] + '\'', function(done) { + tickerPlugin.ticker(testedCurrencies[0], function(err, results) { + should.not.exist(err, 'There should be no error'); + should.exist(results); + + checkCurrency(results, testedCurrencies[0]); + + done(); + }); + }); + + + var tmpCurrency = testedCurrencies.length >= 2 ? + testedCurrencies[1] : + testedCurrencies[0]; + + // single supported currency fetch (as array) + it('should read ticker in [' + tmpCurrency + ']', function(done) { + tickerPlugin.ticker([tmpCurrency], function(err, results) { + should.not.exist(err, 'There should be no error'); + should.exist(results); + + checkCurrency(results, tmpCurrency); + + done(); + }); + }); + + + // will be used in following tests + var unsupportedCurrency = 'ABC'; + + // single *not* supported currency fetch + it('should fail to read ticker in ' + unsupportedCurrency, function(done) { + tickerPlugin.ticker([unsupportedCurrency], function(err, results) { + should.exist(err); + should.not.exist(results); + + done(); + }); + }); + + + // only make sense if there's more than one supported currency + if (testedCurrencies.length >= 2) { + // multiple supported currencies fetch + it('should read ticker in ' + testedCurrencies.join(', '), function(done) { + + tickerPlugin.ticker(testedCurrencies, function(err, results) { + should.not.exist(err, 'There should be no error'); + should.exist(results); + + for(var i in testedCurrencies) + checkCurrency(results, testedCurrencies[i]); + + done(); + }); + }); + + + // multiple supported and not supported currencies + var mix2Currencies = [unsupportedCurrency].concat(testedCurrencies); + it('should fail to read ticker in ' + mix2Currencies.join(', '), function(done) { + tickerPlugin.ticker(mix2Currencies, function(err, results) { + should.exist(err); + should.not.exist(results); + + done(); + }); + }); + } + + + // mix of supported AND not supported currencies + var mixCurrencies = [testedCurrencies[0], unsupportedCurrency]; + it('should fail to read ticker with ' + mixCurrencies.join(', '), function(done) { + tickerPlugin.ticker(mixCurrencies, function(err, results) { + should.exist(err); + should.not.exist(results); + + done(); + }); + }); + + + // ticker request with empty array + var emptyArray = []; + it('should fail to read ticker with empty array', function(done) { + tickerPlugin.ticker(emptyArray, function(err, results) { + should.exist(err); + should.not.exist(results); + + done(); + }); + }); + + }); +} diff --git a/pool/shard000/JavaScript/0005856_nested-form.js b/pool/shard000/JavaScript/0005856_nested-form.js new file mode 100644 index 0000000000000000000000000000000000000000..26e3ebb4e05971f55baa31feef7dcd748d9999b2 --- /dev/null +++ b/pool/shard000/JavaScript/0005856_nested-form.js @@ -0,0 +1,219 @@ +var kunstmaanbundles = kunstmaanbundles || {}; + +kunstmaanbundles.nestedForm = (function(window, undefined) { + + var init, setupForm, + addNewItem, delItem, + addNewBtn, addDelBtn, showOrHideActions, + updateSortkeys; + + + var newButtonHtml = ''; + var delButtonHtml = '' + + + init = function() { + $('.js-nested-form').each(function() { + var $form = $(this), + initialized = $form.data('initialized'); + + if(!initialized) { + setupForm($form); + $form.data('initialized', true); + } + }); + }; + + + // Initial Setup + setupForm = function($form) { + var sortable = $form.data('sortable'), + allowNew = $form.data('allow-new'), + allowDelete = $form.data('allow-delete'), + minItems = $form.data('min-items'), + maxItems = $form.data('max-items'), + $currentItems = $form.find('.js-nested-form__item'); + + // Set index + var totalItems = $currentItems.length; + $form.data('index', totalItems); + + // Add "New" button + if(allowNew) { + addNewBtn($form); + } + + // Add "Delete" button + if(allowDelete) { + $currentItems.each(function() { + addDelBtn($(this), $form); + }); + } + + // Make sure we have at least as many items than minimally required + if (minItems > 0 && minItems > totalItems) { + var newNeeded = minItems - totalItems; + + for (var i=0; i minItems) { + $delBtn.removeClass('hidden'); + } else { + $delBtn.addClass('hidden'); + } + }; + + + // Add "New" button + addNewBtn = function($form) { + var $newBtn = $(newButtonHtml); + + $form.append($newBtn); + + $newBtn.on('click', function() { + addNewItem($form); + }); + }; + + + // Add "Delete" button + addDelBtn = function($item, $form) { + var $actionBar = $item.find('.js-nested-form__item__header__actions'), + $delBtn = $(delButtonHtml); + + $actionBar.append($delBtn); + + $delBtn.on('click', function() { + delItem($(this), $form, $item) + }); + }; + + + // Add new item + addNewItem = function($form) { + var prototype = $form.data('prototype'), + currentIndex = $form.data('index'), + sortable = $form.data('sortable'); + + // Update prototype with new index + prototype = prototype.replace(/__name__/g, currentIndex); + + // Increase the index with one for the next item + $form.data('index', currentIndex + 1); + + // Make item template + if(sortable) { + var sortKey = $form.data('sortkey').replace(/__name__/g, currentIndex); + var $newItem = $('
        '); + } else { + var $newItem = $('
        '); + } + + $newItem.find('.js-nested-form__item__view').append(prototype); + + // Append before "New" button + var $newBtn = $form.find('.js-nested-form__add-btn'); + + $newBtn.before($newItem); + + // Add "Delete" button + addDelBtn($newItem, $form); + + // Init new rich editors + kunstmaanbundles.richEditor.init(); + + // Init new tooltips + kunstmaanbundles.tooltip.init(); + + // Init new colorpickers + kunstmaanbundles.colorpicker.init(); + + // Init Ajax Modals + kunstmaanbundles.ajaxModal.resetAjaxModals(); + + // Update sortkeys + if(sortable) { + updateSortkeys($form); + } + }; + + + // Delete item + delItem = function($btn, $form, $item) { + var delKey = $item.data('delete-key'), + sortable = $form.data('sortable'); + + // Set delKey + if(delKey) { + $form.append(''); + } + + // Remove item + $item.remove(); + + // Check that we need to show/hide the add/delete buttons + showOrHideActions($form); + + // Update sortkeys + if(sortable) { + updateSortkeys($form); + } + }; + + + // Update Sortkeys + updateSortkeys = function($form) { + var key = 0, + $currentItems = $form.find('.js-nested-form__item'); + + $currentItems.each(function() { + var fieldId = $(this).data('sortkey'); + + if (fieldId === undefined) { + return; + } + + $('#' + fieldId).val(key++); + }); + }; + + + return { + init: init + }; + +}(window)); diff --git a/pool/shard000/JavaScript/0005858_index.js b/pool/shard000/JavaScript/0005858_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b89b78cf78f822a5f06e34a32993490a757486 --- /dev/null +++ b/pool/shard000/JavaScript/0005858_index.js @@ -0,0 +1,25 @@ +const server = require('./server-ws2'); +const serverHttp = require('./server-http'); + +let inOpts = {}; + +try { + inOpts = process.argv[2] ? JSON.parse(process.argv[2]) : {}; +} catch (e) { + // eslint-disable-next-line no-console + console.log(process.argv); +} + +const opts = Object.assign( + { + port: 8881, + }, + inOpts +); +if (opts.server && opts.server === 'http') { + serverHttp.start(opts) + .then(() => console.log(`Coinstac HTTP server listening on port ${opts.port}`)); // eslint-disable-line no-console +} else { + server.start(opts) + .then(() => console.log(`Coinstac WS server listening on port ${opts.port}`)); // eslint-disable-line no-console +} diff --git a/pool/shard000/JavaScript/0005860_fatal.test.js b/pool/shard000/JavaScript/0005860_fatal.test.js new file mode 100644 index 0000000000000000000000000000000000000000..0b5845438bb50a9a66d7a2b720f35f8065529278 --- /dev/null +++ b/pool/shard000/JavaScript/0005860_fatal.test.js @@ -0,0 +1,30 @@ +import React from 'react'; +import renderer from 'react-test-renderer'; + +import Fatal from './fatal'; + +describe('Fatal', function () { + it('should exist; and should be a function', function () { + expect(typeof Fatal).toBe('function'); + }); + + it('should match the snapshot', function () { + const props = { + error: new Error('Fatal error.'), + model: { + props: 'might not actually exist', + }, + path: 'could be anything' + }; + + spyOn(console, 'error'); + + const component = renderer.create( + + ); + + let tree = component.toJSON(); + expect(tree).toMatchSnapshot(); + expect(console.error).lastCalledWith(props.error); + }); +}); diff --git a/pool/shard000/JavaScript/0005863_posts.js b/pool/shard000/JavaScript/0005863_posts.js new file mode 100644 index 0000000000000000000000000000000000000000..e3c5d963f7655d85e6539d974d2810a6c11d551d --- /dev/null +++ b/pool/shard000/JavaScript/0005863_posts.js @@ -0,0 +1,208 @@ +/** + * Created by urielbertoche on 5/10/2016. + */ + +var Post = require('../models/post'); +var Category = require('../models/category'); +var marked = require("marked"); +var moment = require("moment"); +var ObjectId = require('mongoose').Types.ObjectId; +var _ = require("underscore"); +var methods = {}; + +methods.add = {}; + +methods.add.get = function (req, res, next) { + res.render("../views/post/form", { }); +}; + +methods.add.post = function (req, res, next) { + var post_data = req.body; + if (post_data.title != "" && post_data.message != "") { + var post = new Post(); + post.author = req.user; + post.message = post_data.message; + post.title = post_data.title; + post.categories = post_data.categories; + + Category.find({ + _id: { + $in: post.categories + } + }).exec(function (err, categories) { + if (err) return next(err); + + var categories_list = []; + + for (var i = 0; i < categories.length; i++) { + var category = { + id: categories[i]._id, + text: categories[i].name + }; + + categories_list.push(category); + } + + post_data.categories = categories_list; + + //req.flash("info", "Cancelado para teste"); + //return res.render("post/form", {post: post_data}); + + post.save(function (err) { + if (err) + return next(err); + + req.flash("success", "Post criado com sucesso!"); + res.redirect("/post/list"); + }); + + }); + } + else { + req.flash("warning", "Titulo ou comentário não preenchido."); + res.redirect("/post/new"); + } +}; + +methods.view = function (req, res, next) { + var postId = req.params.id; + + var populateQuery = [ + { + path: 'author' + }, + { + path: 'unit', + select: 'managers' + }, + { + path: 'comments', + populate: { + path: 'author', + model: 'User' + } + } + ]; + + Post.findOne({_id: postId}).populate(populateQuery).exec(function (err, doc) { + if (err) + return next(err); + + console.log(doc); + + res.render("../views/post/view", {post: doc, md: marked, moment: moment}); + }); +}; + +methods.list = function (req, res, next) { + /* + * A principio um list basico e suficiente, mas futuramente precisaremos criar as views para casos diferentes, ex: + * mais visualizadas, mais curtidas, mais recentes, etc; + */ + + Post.find({}).populate("author").exec(function (err, docs) { + if (err) + return next(err); + + res.render("../views/post/list", {posts: docs, moment: moment}); + }); +}; + +methods.ajax = {}; + +methods.ajax.like = function (req, res, next) { + var postId = req.params.id; + + Post.findOne({_id: postId}).exec(function (err, doc) { + if (err) + return next(err); + + var index = _.findIndex(doc.likes, function(like) { return like._id == req.user.id; }); //indexOf(userId); + + if (index != -1) { + doc.likes.splice(index, 1); + } else { + doc.likes.push(req.user.id); + } + + doc.save(function (err, post) { + if (err) + return next(err); + + res.json(post); + }); + }); +}; + +methods.ajax.report = function (req, res, next) { + var postId = req.params.id; + + Post.findOne({_id: postId}).exec(function (err, doc) { + if (err) + return next(err); + + var index = _.findIndex(doc.reports, function(report) { return report._id == req.user.id; }); //indexOf(userId); + var reason = req.body.reason; + + if (reason == undefined) + reason = "Razão não informada."; + + if (index == -1) { + doc.reports.push({ + _id: req.user.id, + reason: reason + }); + } + + doc.save(function (err, post) { + if (err) + return next(err); + + res.json(post); + }); + }); +}; + +methods.ajax.comment = function (req, res, next) { + var postId = req.params.id; + var isUnitManager = false; + + var populateQuery = [ + { + path: 'unit', + select: 'managers' + }, + { + path: 'comments', + populate: { + path: 'user', + model: 'User', + select: 'name' + } + } + ]; + + Post.findOne({_id: postId}).populate(populateQuery).exec(function (err, doc) { + if (doc.unit != null) { + var index = _.findIndex(doc.unit.managers, function (manager) { return manager._id == req.user.id; }); + isUnitManager = index != -1; + } + + var comment = { + author: req.user, + message: req.body.message, + isAnswer: isUnitManager + }; + + doc.comments.push(comment); + + doc.save(function (err, post) { + if (err) + return next(err); + + res.json(post); + }); + }); +}; + +module.exports = methods; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005865_OptionInput.js b/pool/shard000/JavaScript/0005865_OptionInput.js new file mode 100644 index 0000000000000000000000000000000000000000..2db25148bd1045dd9e707970d25ae96e5c373efc --- /dev/null +++ b/pool/shard000/JavaScript/0005865_OptionInput.js @@ -0,0 +1,183 @@ +/* + * Copyright 2015 Alexander Pustovalov + * + * 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 _ from 'lodash'; +import React, { Component, PropTypes } from 'react'; + +class OptionInput extends Component { + + constructor(props) { + + super(props); + + let valueType = 'text'; + if(props.valueObject && _.isObject(props.valueObject)){ + var value = _.get(props.valueObject, props.path); + valueType = this.getTypeOfProperty(value); + } + let label = props.path.replace('.', ' / '); + this.state = { + valueObject: props.valueObject, + label: label, + propertyType: valueType + }; + + this.handleChangeInputValue = this.handleChangeInputValue.bind(this); + this.handleChangeCheckboxValue = this.handleChangeCheckboxValue.bind(this); + this.handleDelete = this.handleDelete.bind(this); + this.handleFocus = this.handleFocus.bind(this); + } + + getValueFromObject(){ + return _.get(this.state.valueObject, this.props.path); + } + + handleChangeInputValue(e) { + let value = null; + if(this.state.propertyType){ + if(this.state.propertyType === 'text'){ + value = this.refs.inputElement.value; + } else if(this.state.propertyType === 'checkbox'){ + value = this.refs.inputElement.checked; + } else if(this.state.propertyType === 'number'){ + value = parseFloat(this.refs.inputElement.value); + } + } + let valueObject = _.set({}, this.props.path, value); + this.setState({ + valueObject: valueObject + }); + e.persist(); + this.delayedChangeInputValue(e); + } + + handleChangeCheckboxValue(e) { + let value = null; + if(this.state.propertyType){ + if(this.state.propertyType === 'checkbox'){ + value = this.refs.inputElement.checked; + } + } + let valueObject = _.set({}, this.props.path, value); + this.setState({ + valueObject: valueObject + }); + if(this.props.onChangeValue){ + this.props.onChangeValue(valueObject); + } + + } + + handleDelete(e){ + if(this.props.onDeleteValue){ + this.props.onDeleteValue(this.props.path); + } + } + + handleFocus(){ + if(this.props.onSetFocus){ + this.props.onSetFocus(this.props.path); + } + } + + getTypeOfProperty(propertyValue){ + if(_.isString(propertyValue)) { + return 'text'; + } else if(_.isNumber(propertyValue)){ + return 'number'; + } else if(_.isBoolean(propertyValue)){ + return 'checkbox'; + } + } + + componentWillMount(){ + this.delayedChangeInputValue = _.debounce((e) => { + if(this.props.onChangeValue){ + this.props.onChangeValue(this.state.valueObject); + } + }, 1000); + } + + componentDidMount(){ + if(this.props.focused){ + let input = this.refs.inputElement; + if(this.state.propertyType !== 'checkbox') { + let len = input.value ? input.value.length : 0; + input.focus(); + input.setSelectionRange(len, len); + } else { + input.focus(); + } + } + } + + render() { + let element = null; + let style = { + height: '1.55em', paddingTop: '2px', paddingBottom: '2px' + }; + if(this.state.propertyType === 'checkbox') { + style.width = '1em'; + element = ( +
        + + +
        + ); + + } else if(this.state.propertyType === 'text' || this.state.propertyType === 'number') { + element = ( +
        + + +
        + ); + } + + return ( +
        +

        {this.state.label}

        + {element} +
        + ); + } + +} + +OptionInput.defaultProps = { + valueObject: null, + label: 'Option:' +}; + +module.exports = OptionInput; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005868_common.js b/pool/shard000/JavaScript/0005868_common.js new file mode 100644 index 0000000000000000000000000000000000000000..2cd31e283256e2647f6c341c68082421d1c22d5b --- /dev/null +++ b/pool/shard000/JavaScript/0005868_common.js @@ -0,0 +1,352 @@ +(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["common"],{ + +/***/ "./node_modules/@coreui/coreui-plugin-chartjs-custom-tooltips/js/custom-tooltips.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@coreui/coreui-plugin-chartjs-custom-tooltips/js/custom-tooltips.js ***! + \******************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * -------------------------------------------------------------------------- + * CoreUI Plugins - Custom Tooltips for Chart.js (v1.1.0): custom-tooltips.js + * Licensed under MIT (https://coreui.io/license) + * -------------------------------------------------------------------------- + */ + +function CustomTooltips(tooltipModel) { + // Add unique id if not exist + if (!this._chart.canvas.id) { + const _hex = 16 + const _multiply = 0x10000 + const _idMaker = () => ((1 + Math.random()) * _multiply | 0).toString(_hex) + const _canvasId = `_canvas${_idMaker() + _idMaker()}` + this._chart.canvas.id = this._chart.canvas.id || _canvasId + } + + const ClassName = { + ABOVE : 'above', + BELOW : 'below', + CHARTJS_TOOLTIP : 'chartjs-tooltip', + NO_TRANSFORM : 'no-transform', + TOOLTIP_BODY : 'tooltip-body', + TOOLTIP_BODY_ITEM : 'tooltip-body-item', + TOOLTIP_BODY_ITEM_COLOR : 'tooltip-body-item-color', + TOOLTIP_BODY_ITEM_LABEL : 'tooltip-body-item-label', + TOOLTIP_BODY_ITEM_VALUE : 'tooltip-body-item-value', + TOOLTIP_HEADER : 'tooltip-header', + TOOLTIP_HEADER_ITEM : 'tooltip-header-item' + } + + const Selector = { + DIV : 'div', + SPAN : 'span', + TOOLTIP : `${this._chart.canvas.id}-tooltip` + } + + let tooltip = document.getElementById(Selector.TOOLTIP) + + if (!tooltip) { + tooltip = document.createElement('div') + tooltip.id = Selector.TOOLTIP + tooltip.className = ClassName.CHARTJS_TOOLTIP + this._chart.canvas.parentNode.appendChild(tooltip) + } + + // Hide if no tooltip + if (tooltipModel.opacity === 0) { + tooltip.style.opacity = 0 + return + } + + // Set caret Position + tooltip.classList.remove(ClassName.ABOVE, ClassName.BELOW, ClassName.NO_TRANSFORM) + if (tooltipModel.yAlign) { + tooltip.classList.add(tooltipModel.yAlign) + } else { + tooltip.classList.add(ClassName.NO_TRANSFORM) + } + + // Set Text + if (tooltipModel.body) { + const titleLines = tooltipModel.title || [] + + const tooltipHeader = document.createElement(Selector.DIV) + tooltipHeader.className = ClassName.TOOLTIP_HEADER + + titleLines.forEach((title) => { + const tooltipHeaderTitle = document.createElement(Selector.DIV) + tooltipHeaderTitle.className = ClassName.TOOLTIP_HEADER_ITEM + tooltipHeaderTitle.innerHTML = title + tooltipHeader.appendChild(tooltipHeaderTitle) + }) + + const tooltipBody = document.createElement(Selector.DIV) + tooltipBody.className = ClassName.TOOLTIP_BODY + + const tooltipBodyItems = tooltipModel.body.map((item) => item.lines) + tooltipBodyItems.forEach((item, i) => { + const tooltipBodyItem = document.createElement(Selector.DIV) + tooltipBodyItem.className = ClassName.TOOLTIP_BODY_ITEM + + const colors = tooltipModel.labelColors[i] + + const tooltipBodyItemColor = document.createElement(Selector.SPAN) + tooltipBodyItemColor.className = ClassName.TOOLTIP_BODY_ITEM_COLOR + tooltipBodyItemColor.style.backgroundColor = colors.backgroundColor + + tooltipBodyItem.appendChild(tooltipBodyItemColor) + + if (item[0].split(':').length > 1) { + const tooltipBodyItemLabel = document.createElement(Selector.SPAN) + tooltipBodyItemLabel.className = ClassName.TOOLTIP_BODY_ITEM_LABEL + tooltipBodyItemLabel.innerHTML = item[0].split(': ')[0] + + tooltipBodyItem.appendChild(tooltipBodyItemLabel) + + const tooltipBodyItemValue = document.createElement(Selector.SPAN) + tooltipBodyItemValue.className = ClassName.TOOLTIP_BODY_ITEM_VALUE + tooltipBodyItemValue.innerHTML = item[0].split(': ').pop() + + tooltipBodyItem.appendChild(tooltipBodyItemValue) + } else { + const tooltipBodyItemValue = document.createElement(Selector.SPAN) + tooltipBodyItemValue.className = ClassName.TOOLTIP_BODY_ITEM_VALUE + tooltipBodyItemValue.innerHTML = item[0] + + tooltipBodyItem.appendChild(tooltipBodyItemValue) + } + + tooltipBody.appendChild(tooltipBodyItem) + }) + + tooltip.innerHTML = '' + + tooltip.appendChild(tooltipHeader) + tooltip.appendChild(tooltipBody) + } + + const positionY = this._chart.canvas.offsetTop + const positionX = this._chart.canvas.offsetLeft + + // Display, position, and set styles for font + tooltip.style.opacity = 1 + tooltip.style.left = `${positionX + tooltipModel.caretX}px` + tooltip.style.top = `${positionY + tooltipModel.caretY}px` +} + +/* harmony default export */ __webpack_exports__["default"] = (CustomTooltips); + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui-plugin-chartjs-custom-tooltips/js/index.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@coreui/coreui-plugin-chartjs-custom-tooltips/js/index.js ***! + \********************************************************************************/ +/*! exports provided: CustomTooltips */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _custom_tooltips__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./custom-tooltips */ "./node_modules/@coreui/coreui-plugin-chartjs-custom-tooltips/js/custom-tooltips.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomTooltips", function() { return _custom_tooltips__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + + + + + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui/js/src/utilities/get-style.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@coreui/coreui/js/src/utilities/get-style.js ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * -------------------------------------------------------------------------- + * CoreUI Utilities (v1.0.0): get-style.js + * Licensed under MIT (https://coreui.io/license) + * -------------------------------------------------------------------------- + */ + +const getStyle = (property, element = document.body) => { + const style = window.getComputedStyle(element, null).getPropertyValue(property).replace(/^\s/, '') + + return style +} + +/* harmony default export */ __webpack_exports__["default"] = (getStyle); + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgb.js": +/*!********************************************************************!*\ + !*** ./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgb.js ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * -------------------------------------------------------------------------- + * CoreUI Utilities (v2.0.0-beta.3): hex-to-rgb.js + * Licensed under MIT (https://coreui.io/license) + * -------------------------------------------------------------------------- + */ + +/* eslint-disable no-magic-numbers */ +const hexToRgb = (color) => { + const hex = color.replace('#', '') + const r = parseInt(hex.substring(0, 2), 16) + const g = parseInt(hex.substring(2, 4), 16) + const b = parseInt(hex.substring(4, 6), 16) + + const result = `rgba(${r}, ${g}, ${b}` + return result +} + +/* harmony default export */ __webpack_exports__["default"] = (hexToRgb); + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgba.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgba.js ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * -------------------------------------------------------------------------- + * CoreUI Utilities (v2.0.0-beta.3): hex-to-rgba.js + * Licensed under MIT (https://coreui.io/license) + * -------------------------------------------------------------------------- + */ + +/* eslint-disable no-magic-numbers */ +const hexToRgba = (color, opacity = 100) => { + const hex = color.replace('#', '') + const r = parseInt(hex.substring(0, 2), 16) + const g = parseInt(hex.substring(2, 4), 16) + const b = parseInt(hex.substring(4, 6), 16) + + const result = `rgba(${r}, ${g}, ${b}, ${opacity / 100}` + return result +} + +/* harmony default export */ __webpack_exports__["default"] = (hexToRgba); + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui/js/src/utilities/index.js": +/*!***************************************************************!*\ + !*** ./node_modules/@coreui/coreui/js/src/utilities/index.js ***! + \***************************************************************/ +/*! exports provided: getStyle, hexToRgb, hexToRgba, rgbToHex */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _get_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./get-style */ "./node_modules/@coreui/coreui/js/src/utilities/get-style.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getStyle", function() { return _get_style__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _hex_to_rgb__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hex-to-rgb */ "./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgb.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hexToRgb", function() { return _hex_to_rgb__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _hex_to_rgba__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hex-to-rgba */ "./node_modules/@coreui/coreui/js/src/utilities/hex-to-rgba.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hexToRgba", function() { return _hex_to_rgba__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _rgb_to_hex__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rgb-to-hex */ "./node_modules/@coreui/coreui/js/src/utilities/rgb-to-hex.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rgbToHex", function() { return _rgb_to_hex__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@coreui/coreui/js/src/utilities/rgb-to-hex.js": +/*!********************************************************************!*\ + !*** ./node_modules/@coreui/coreui/js/src/utilities/rgb-to-hex.js ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * -------------------------------------------------------------------------- + * CoreUI (v2.0.0-beta.3): rgb-to-hex.js + * Licensed under MIT (https://coreui.io/license) + * -------------------------------------------------------------------------- + */ + +/* eslint-disable no-magic-numbers */ +const rgbToHex = (color) => { + const rgb = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i) + const r = `0${parseInt(rgb[1], 10).toString(16)}` + const g = `0${parseInt(rgb[2], 10).toString(16)}` + const b = `0${parseInt(rgb[3], 10).toString(16)}` + + return (rgb && rgb.length === 4) ? `#${r.slice(-2)}${g.slice(-2)}${b.slice(-2)}` : '' +} + +/* harmony default export */ __webpack_exports__["default"] = (rgbToHex); + + +/***/ }), + +/***/ "./node_modules/ngx-bootstrap/utils/decorators.js": +/*!********************************************************!*\ + !*** ./node_modules/ngx-bootstrap/utils/decorators.js ***! + \********************************************************/ +/*! exports provided: OnChange */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OnChange", function() { return OnChange; }); +/*tslint:disable:no-invalid-this */ +function OnChange(defaultValue) { + var sufix = 'Change'; + return function OnChangeHandler(target, propertyKey) { + var _key = " __" + propertyKey + "Value"; + Object.defineProperty(target, propertyKey, { + get: function () { + return this[_key]; + }, + set: function (value) { + var prevValue = this[_key]; + this[_key] = value; + if (prevValue !== value && this[propertyKey + sufix]) { + this[propertyKey + sufix].emit(value); + } + } + }); + }; +} +/* tslint:enable */ +//# sourceMappingURL=decorators.js.map + +/***/ }) + +}]); +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005873_versionCtrl-spec.js b/pool/shard000/JavaScript/0005873_versionCtrl-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7a7d3a1cd98701278f4863890f1817ca24224170 --- /dev/null +++ b/pool/shard000/JavaScript/0005873_versionCtrl-spec.js @@ -0,0 +1,30 @@ +'use strict'; + +describe('Version Controller', function () { + beforeEach(module('smlHreg.version')); + + var scope, $httpBackend; + + beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) { + scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $controller('VersionCtrl', {$scope: scope}); + })); + + it('should retrieve application version', function () { + // given + $httpBackend.expectGET('api/version').respond({build: 'foo', date: 'bar', version: 'baz', branch: 'branch', buildNumber: 'buildnumber', buildUrl: 'buildUrl'}); + + // when + $httpBackend.flush(); + + // then + expect(scope.buildSha).toEqual('foo'); + expect(scope.buildDate).toEqual('bar'); + expect(scope.version).toEqual('baz'); + expect(scope.branch).toEqual('branch'); + expect(scope.buildNumber).toEqual('buildnumber'); + expect(scope.buildUrl).toEqual('buildUrl'); + + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005879_kata.js b/pool/shard000/JavaScript/0005879_kata.js new file mode 100644 index 0000000000000000000000000000000000000000..f35d842cf037fd53b96e48426c42e79a968ff07a --- /dev/null +++ b/pool/shard000/JavaScript/0005879_kata.js @@ -0,0 +1,18 @@ +import timeAgo from 'damals'; + +export default class Kata { + + constructor(kata, group) { + this.id = kata.id; + this.name = kata.name; + this.description = kata.description; + this.path = kata.path; + this.kataGroup = group; + this.releaseDate = new Date(kata.publishDateUTC); + this.releaseDateAgo = timeAgo(new Date(kata.publishDateUTC)); + } + + static fromRawKataData(rawKataData, kataGroup) { + return new Kata(rawKataData, kataGroup); + } +} diff --git a/pool/shard000/JavaScript/0005881_TestResponseHandler.js b/pool/shard000/JavaScript/0005881_TestResponseHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..22cbdffc22b066709477f351db24786f3a7eb97d --- /dev/null +++ b/pool/shard000/JavaScript/0005881_TestResponseHandler.js @@ -0,0 +1,198 @@ +var assert = require('assert'), + sinon = require('sinon'), + fs = require('fs'), + _und = require('underscore'), + JSON5 = require('json5'), + path = require('path'); + +var TestResponseHandler = require('../../src/responseHandlers/TestResponseHandler'), + Logger = require('../../src/utilities/Logger'), + ErrorHandler = require('../../src/utilities/ErrorHandler'), + Globals = require('../../src/utilities/Globals'), + Helpers = require('../../src/utilities/Helpers'); + +describe("TestResponseHandler", function() { + + beforeEach(function() { + var filePath = path.join(__dirname, '../', 'data', 'PostmanCollection.json'); + this.collectionJson = JSON5.parse(fs.readFileSync(filePath, 'utf8')); + this.request = this.collectionJson.requests[0]; + this.request.headers = "Accept-Language: En\nCache-Control: 123\nPragma: Akamai"; + this.request.dataMode = "params"; + this.request.data = [ + { "key": "name", "value": "alice", "type": "text" }, + { "key": "age", "value": "40", "type": "text" }]; + this.request.transformed = { + url: this.request.url, + headers: this.request.headers, + data: this.request.data, + }; + this.response = { + headers: { + 'server': 'nginx/1.1.19', + 'content-type': 'application/json', + 'content-length': '3', + 'connection': 'Keep-Alive', + 'age': '286' + }, + stats: {timeTaken: 100}, + statusCode: 200, + body: "{\"lol\": \"jhingalalal\"}" + }; + this.stub = sinon.stub(TestResponseHandler, '_logTestResults'); + this.loggerStub = sinon.stub(ErrorHandler, 'exceptionError'); + Globals.envJson = { values: [] }; + }); + + it("should run the test cases properly", function() { + this.request.tests = 'tests["statuscode is 200"] = responseCode.code === 200;\n\ntests["Content type is correct"] = responseHeaders["content-type"].has("application/json")'; + var parsedResult = {"statuscode is 200": true,"Content type is correct": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the sugar has properly", function() { + this.request.tests = 'tests["testcase1"] = "Sugar has me".has("Sugar")'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the tv4 validator properly", function() { + this.request.tests = 'tests["testcase1"] = tv4.validate({"message": "This is a message."}, {"message": "string"})'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the lodash properly", function() { + this.request.tests = 'tests["testcase1"] = _.isString(responseBody)'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the Backbone properly", function() { + this.request.tests = 'tests["testcase1"] = new Backbone.Model({a: "b"}).toJSON().a === "b"'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the xmlToJson properly", function() { + this.request.tests = 'tests["testcase1"] = xmlToJson("Success").a.b === "Success"'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should run the test cases with the Jquery properly", function() { + this.request.tests = 'tests["testcase1"] = $.isArray([])'; + var parsedResult = {"testcase1": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should catch exception for invalid code / test cases", function() { + this.request.tests = 'tests["throws exception"] = undefinedValue === 200;'; // this should throw an exception + TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert(this.loggerStub.called); + }); + + it("should run test cases on request object properly", function() { + this.request.tests = ''; + this.request.tests += 'tests["testcase1"] = request.url === "' + this.request.url + '";'; + this.request.tests += 'tests["testcase2"] = _.has(request.headers, "Cache-Control") === true;'; + this.request.tests += 'tests["testcase3"] = request.dataMode === "params";'; + this.request.tests += 'tests["testcase4"] = request.data.name === "alice";'; + this.request.tests += 'tests["testcase5"] = request.data.age == 40;'; + var parsedResult = {"testcase1": true, "testcase2": true, "testcase3": true, "testcase4": true, "testcase5": true}; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, parsedResult); + }); + + it("should get env variable properly", function() { + Globals.envJson = { + values: [ + { + "key": "url", + "value": "http://dump.getpostman.com", + "type": "text", + "name": "url" + }, + { + "key": "user_id", + "value": "1", + "type": "text", + "name": "user_id" + } + ] + }; + this.request.tests = ''; + this.request.tests += 'tests["testcase1"] = environment.url === "http://dump.getpostman.com";'; + this.request.tests += 'tests["testcase2"] = environment["user_id"] == 1;'; + var expectedResult = {"testcase1": true, "testcase2": true }; + var results = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results, expectedResult); + }); + + it("should set env variable properly", function() { + Globals.envJson = { + values: [ + { + "key": "url", + "value": "http://dump.getpostman.com", + "type": "text", + "name": "url" + }, + { + "key": "user_id", + "value": "1", + "type": "text", + "name": "user_id" + } + ] + }; + this.request.tests = 'postman.setEnvironmentVariable("url", "google.com"); postman.setEnvironmentVariable("id", "10");'; + var tests = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert(_und.contains(_und.pluck(Globals.envJson.values, 'key'), 'id')); + assert(_und.contains(_und.pluck(Globals.envJson.values, 'key'), 'url')); + assert(_und.contains(_und.pluck(Globals.envJson.values, 'value'), 'google.com')); + assert(_und.contains(_und.pluck(Globals.envJson.values, 'value'), '10')); + }); + + + it("should get and set env variable properly", function() { + Globals.envJson = { + values: [ + { + "key": "url", + "value": "http://dump.getpostman.com", + "type": "text", + "name": "url" + }, + { + "key": "user_id", + "value": "1", + "type": "text", + "name": "user_id" + } + ] + }; + this.request.tests = ''; + this.request.tests = 'postman.setEnvironmentVariable("url", "google.com");'; + this.request.tests += 'tests["testcase1"] = environment.url === "http://dump.getpostman.com";'; // not changed for the first time + var results1 = TestResponseHandler._runTestCases(null, this.response, this.response.body, this.request); + assert.deepEqual(results1, {"testcase1": true}); + + var another_request = _und.extend(this.request); // deep copy + another_request.tests = 'tests["testcase2"] = environment.url === "google.com";'; + var results2 = TestResponseHandler._runTestCases(null, this.response, this.response.body, another_request); + assert.deepEqual(results2, {"testcase2": true}); + }); + + afterEach(function() { + TestResponseHandler._logTestResults.restore(); + ErrorHandler.exceptionError.restore(); + }); +}); diff --git a/pool/shard000/JavaScript/0005882_Translate.spec.js b/pool/shard000/JavaScript/0005882_Translate.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8def603c208dc49cc2e0a7c0e366b65ffb8d86cb --- /dev/null +++ b/pool/shard000/JavaScript/0005882_Translate.spec.js @@ -0,0 +1,111 @@ +/* global describe, test, expect, beforeAll, beforeEach */ + +import React from 'react'; +import { mount, configure } from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; +import { setLocale, setTranslations, Translate } from '../../src'; + +describe('Translate.jsx', () => { + beforeAll(() => { + configure({ adapter: new Adapter() }); + setTranslations({ + en: { + application: { + title: 'Awesome app with i18n!', + hello: 'Hello, %{name}!', + }, + export: 'Export %{count} items', + export_0: 'Nothing to export', + export_1: 'Export %{count} item', + two_lines: ( +
        + Line 1 +
        + Line 2 +
        + ), + }, + nl: { + application: { + title: 'Toffe app met i18n!', + }, + }, + }); + }); + + describe(' component', () => { + beforeEach(() => { + setLocale('en'); + }); + + test('should handle translation', () => { + const component = mount(); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Awesome app with i18n!'); + }); + + test('should handle NL translation', () => { + setLocale('nl'); + const component = mount(); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Toffe app met i18n!'); + }); + + test('should handle locale switching', () => { + const component = mount(); + + expect(component.text()).toBe('Awesome app with i18n!'); + setLocale('nl'); + component.update(); + expect(component.text()).toBe('Toffe app met i18n!'); + }); + + test('should handle dynamic placeholder', () => { + const component = mount(); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Hello, Aad!'); + }); + + test('should handle pluralization', () => { + const component = mount(); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Nothing to export'); + + component.setProps({ count: 1 }); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Export 1 item'); + + component.setProps({ count: 4 }); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Export 4 items'); + }); + + test('should handle react element', () => { + const component = mount(); + + expect(component.type()).toBe(Translate); + expect(component.text()).toBe('Line 1Line 2'); + expect(component.html()).toBe('
        Line 1
        Line 2
        '); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0005883_automigrate.js b/pool/shard000/JavaScript/0005883_automigrate.js new file mode 100644 index 0000000000000000000000000000000000000000..cec373dfa27e000987ba028efeeb2fffba19b471 --- /dev/null +++ b/pool/shard000/JavaScript/0005883_automigrate.js @@ -0,0 +1,41 @@ +var app = require('../server'); + +var accounts = [ + { + email: 'foo@bar.com', + createdAt: new Date(), + lastModifiedAt: new Date() + }, + { + email: 'baz@qux.com', + createdAt: new Date(), + lastModifiedAt: new Date() + } +]; + +// this loads the accountDb configuration in ~/server/datasources.json +var dataSource = app.dataSources.AccountDb; + +// this automigrates the Account model +dataSource.automigrate('Account', function(err) { + if (err) throw err; + + // this loads the Account model from ~/common/models/Account.json + var Account = app.models.Account; + var count = accounts.length; + accounts.forEach(function(account) { + // insert new records into the Account table + Account.create(account, function(err, record) { + if (err) return console.log(err); + + console.log('Record created:', record); + + count--; + + if (count === 0) { + console.log('done'); + dataSource.disconnect(); + } + }); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005886_ThemeCustomClasses.controller.js b/pool/shard000/JavaScript/0005886_ThemeCustomClasses.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..0eb7b9af560ac19a25b9a4d5011db2b8ff113b18 --- /dev/null +++ b/pool/shard000/JavaScript/0005886_ThemeCustomClasses.controller.js @@ -0,0 +1,93 @@ +sap.ui.define([ + 'sap/ui/core/mvc/Controller', + 'sap/ui/model/json/JSONModel' + ], function(Controller, JSONModel) { + "use strict"; + + var ThemeCustomClassesController = Controller.extend("sap.ui.core.sample.ThemeCustomClasses.ThemeCustomClasses", { + + // ############################################### + // + // whole code in controller is irrelevant for sapTheme prefixed classes! + // only for sample display + // + // ############################################### + onInit: function () { + + var it = this; + // subscribe to theme change event + sap.ui.getCore().attachThemeChanged(this._reloadSample, it); + + var oThemeClasses = this._fetchClasses(); + + var oModel = new JSONModel(oThemeClasses); + this.getView().setModel(oModel); + }, + + onAfterRendering : function(){ + // special treatment for border styles + var aData = this.oView.getModel().oData.Styles; + aData.forEach(function(e,i){ + var elem = document.querySelectorAll('.sampling')[i]; + if (elem && e.border){ + elem.style.borderWidth = "1xp"; + elem.style.borderStyle = "solid"; + } + }); + }, + + _fetchClasses : function(){ + var sheets = document.styleSheets; + var themeClasses = {"Styles" : []}; + for (var i in sheets){ + if (sheets[i].cssRules){ + var x = sheets[i].cssRules; + for (var j in x){ + if (x[j].selectorText && x[j].selectorText.indexOf("sapTheme") > 0){ + var sCssRule = x[j].cssText.split('{')[1].split('}')[0]; + var bBorder = ( x[j].cssText.indexOf('border') > 0 ) ? true : false; + var sStyles = ""; + if (x[j].selectorText.indexOf(',') > 0){ + var aStyles = x[j].selectorText.split(','); + for (var k in aStyles){ + sStyles = aStyles[k].split('.')[1]; + if (sStyles.trim() === "sapContrast" || sStyles.trim() === "sapContrastPlus") { continue; } + themeClasses.Styles.push({"stylingString" : sCssRule, "styleClass" : sStyles, "style" : x[j].style, 'border' : bBorder }); + } + } else if (x[j].selectorText.split('.').length > 2){ + var aStyles = x[j].selectorText.split('.'); + for (var k in aStyles){ + sStyles += aStyles[k]; + sStyles += " "; + } + if (sStyles.trim() === "sapContrast" || sStyles.trim() === "sapContrastPlus") { continue; } + themeClasses.Styles.push({"stylingString" : sCssRule, "styleClass" : sStyles, "style" : x[j].style, 'border' : bBorder }); + } else { + sStyles = x[j].selectorText.split('.')[1]; + if (sStyles.trim() === "sapContrast" || sStyles.trim() === "sapContrastPlus") { continue; } + themeClasses.Styles.push({"stylingString" : sCssRule, "styleClass" : sStyles, "style" : x[j].style, 'border' : bBorder }); + } + } + } + } + } + return themeClasses; + }, + + _reloadSample : function(context){ + // wait until theme is changed + setTimeout(function() { + + // load sapTheme classes + var oThemeClasses = this._fetchClasses(); + + // reload the view + this.oView.setModel(new JSONModel(oThemeClasses)); + this.oView.invalidate(); + }.bind(this), 500); + } + }); + + return ThemeCustomClassesController; + +}); diff --git a/pool/shard000/JavaScript/0005888_SubmissionStateMapLockingSpec.js b/pool/shard000/JavaScript/0005888_SubmissionStateMapLockingSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..3770854a5b18d183ce088997847f75c4fb6924f5 --- /dev/null +++ b/pool/shard000/JavaScript/0005888_SubmissionStateMapLockingSpec.js @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2016 - present Instructure, Inc. + * + * This file is part of Canvas. + * + * Canvas 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, version 3 of the License. + * + * Canvas 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 . + */ + +define([ + 'underscore', + 'timezone', + 'jsx/gradebook/SubmissionStateMap' +], (_, tz, SubmissionStateMap) => { + const student = { + id: '1', + group_ids: ['1'], + sections: ['1'] + }; + + function createMap(opts={}) { + const defaults = { + hasGradingPeriods: false, + selectedGradingPeriodID: '0', + isAdmin: false + }; + + const params = { ...defaults, ...opts }; + return new SubmissionStateMap(params); + } + + function createAndSetupMap(assignment, opts={}) { + const map = createMap(opts); + const assignments = {}; + assignments[assignment.id] = assignment; + map.setup([student], assignments); + return map; + } + + // TODO: the spec setup above should live in a spec helper -- at the + // time this is being written a significant amount of work is needed + // to be able to require javascript files that live in the spec directory + + QUnit.module('SubmissionStateMap with no grading periods'); + + test('submission is locked for a student without assignment visibility', function() { + const assignment = { id: '1', effectiveDueDates: {}, only_visible_to_overrides: true }; + const map = createAndSetupMap(assignment, { hasGradingPeriods: false }); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('submission is unlocked for an assigned student', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: null, + grading_period_id: null, + in_closed_grading_period: false + }; + + const map = createAndSetupMap(assignment, { hasGradingPeriods: false }); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, false); + }); + + QUnit.module('SubmissionStateMap with grading periods and all grading periods selected', { + setup() { + this.DATE_IN_CLOSED_PERIOD = '2015-07-15'; + this.DATE_NOT_IN_CLOSED_PERIOD = '2015-08-15'; + this.mapOptions = { hasGradingPeriods: true, selectedGradingPeriodID: '0' }; + } + }); + + test('submission is locked for a student without assignment visibility', function() { + const assignment = { id: '1', effectiveDueDates: {}, only_visible_to_overrides: true }; + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('submission is locked for an assigned student with assignment due in a closed grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_IN_CLOSED_PERIOD, + grading_period_id: '1', + in_closed_grading_period: true + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('user is admin: submission is unlocked for an assigned student with assignment due in a closed grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_IN_CLOSED_PERIOD, + grading_period_id: '1', + in_closed_grading_period: true + }; + + const mapOptions = { ...this.mapOptions, isAdmin: true }; + const map = createAndSetupMap(assignment, mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, false); + }); + + test('submission is unlocked for an assigned student with assignment due outside of a closed grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_NOT_IN_CLOSED_PERIOD, + grading_period_id: '1', + in_closed_grading_period: false + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, false); + }); + + QUnit.module('SubmissionStateMap with grading periods and a non-closed grading period selected', { + setup() { + this.DATE_IN_SELECTED_PERIOD = '2015-07-15'; + this.DATE_NOT_IN_SELECTED_PERIOD = '2015-08-15'; + this.SELECTED_PERIOD_ID = '1'; + this.mapOptions = { hasGradingPeriods: true, selectedGradingPeriodID: this.SELECTED_PERIOD_ID }; + } + }); + + test('submission is locked for an assigned student with assignment due outside of the selected grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_NOT_IN_SELECTED_PERIOD, + grading_period_id: '2', + in_closed_grading_period: false + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('submission is unlocked for an assigned student with assignment due in the selected grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_IN_SELECTED_PERIOD, + grading_period_id: this.SELECTED_PERIOD_ID, + in_closed_grading_period: false + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, false); + }); + + QUnit.module('SubmissionStateMap with grading periods and a closed grading period selected', { + setup() { + this.DATE_IN_SELECTED_PERIOD = '2015-07-15'; + this.DATE_NOT_IN_SELECTED_PERIOD = '2015-08-15'; + this.SELECTED_PERIOD_ID = '1'; + this.mapOptions = { hasGradingPeriods: true, selectedGradingPeriodID: this.SELECTED_PERIOD_ID }; + } + }); + + test('submission is locked for an assigned student with assignment due outside of the selected grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_NOT_IN_SELECTED_PERIOD, + grading_period_id: '2', + in_closed_grading_period: false + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('submission is locked for an assigned student with assignment due in the selected grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_IN_SELECTED_PERIOD, + grading_period_id: this.SELECTED_PERIOD_ID, + in_closed_grading_period: true + }; + + const map = createAndSetupMap(assignment, this.mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, true); + }); + + test('user is admin: submission is unlocked for an assigned student with assignment due in the selected grading period', function() { + const assignment = { id: '1', effectiveDueDates: {} }; + assignment.effectiveDueDates[student.id] = { + due_at: this.DATE_IN_SELECTED_PERIOD, + grading_period_id: this.SELECTED_PERIOD_ID, + in_closed_grading_period: true + }; + + const mapOptions = { ...this.mapOptions, isAdmin: true }; + const map = createAndSetupMap(assignment, mapOptions); + const state = map.getSubmissionState({ user_id: student.id, assignment_id: assignment.id }); + equal(state.locked, false); + }); +}); diff --git a/pool/shard000/JavaScript/0005889_animevision.js b/pool/shard000/JavaScript/0005889_animevision.js new file mode 100644 index 0000000000000000000000000000000000000000..67024b8032a041277aaba2ffd02ed0d35f357c20 --- /dev/null +++ b/pool/shard000/JavaScript/0005889_animevision.js @@ -0,0 +1,92 @@ +var request = require('request'); +var cheerio = require('cheerio'); + +function animevision(url) { + this.url= url; +} + +animevision.prototype.comparador = function (list1,list2){ + var flist = new Array; + for (var i= 0; i < list1.length; i++){ + if (list1[i][1]) flist.push(list1[i]); + else flist.push(list2[i]); + } +return (flist); +}; +animevision.prototype.getEpisodios = function ($,q='.fullhd_dados_area') { + var flag = 0; + var final = new Array; + var animevision = this; + $(q).filter(function(){ + var ar = new Array; + var data = $(this); + var link = data.children().eq(2); + link.each(function(){ + var int = $(this).children('a'); + var aux =int.attr('href').trim().split("/"); + var dic = {nome : int.text() , link : int.attr('href').trim()}; + ar.push(aux[4]) + ar.push(dic); + }) + if (ar.length < 2) flag = 1; + final.push(ar); + }) + if (flag == 1 && q == ".fullhd_dados_area"){ + var aux = animevision.getEpisodios($,".hd_dados_area"); + final = animevision.comparador(final, aux); + } + return(final); + +}; + +animevision.prototype.gettitle = function ($) { + var saida; + $('.nome_item_media').filter(function(){ + var data = $(this); + var title = data.text(); + title = title.trim(); + saida = title; + }) + return (saida); +}; +animevision.prototype.getinfo = function ($) { + var saida; + $('.area_skin_anime').filter(function(){ + var data = $(this); + var info = data.children().eq(2).children().text(); + info = info.trim(); + saida = info; + }) + return (saida); +}; +animevision.prototype.getrelease = function ($) { + var saida = "0000"; + return (saida); +}; +animevision.prototype.getimage = function ($) { + var saida; + saida = $('.screen_capa_01').css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,''); + saida = "https://animesvision.com" +saida + return (saida); +}; + +animevision.prototype.start = function () { +json = { title : "", release : "", info : "", image : "", link : null}; +var animevision = this; +request(this.url, function(error, response, html){ + if(!error){ + var $ = cheerio.load(html); + json.title = animevision.gettitle($); + json.release = animevision.getrelease($); + json.info = animevision.getinfo($); + json.image = animevision.getimage($); + json.link = animevision.getEpisodios($); + } + else { + console.log("erro ao entar no site"); + return(false) + } +}) +return(json); +}; +module.exports = animevision; diff --git a/pool/shard000/JavaScript/0005890_main.js b/pool/shard000/JavaScript/0005890_main.js new file mode 100644 index 0000000000000000000000000000000000000000..67ef0b83cba086c357f32cff4a6b00374f5dae12 --- /dev/null +++ b/pool/shard000/JavaScript/0005890_main.js @@ -0,0 +1,76 @@ + +var delayFactor = 1.0; + +function addLines(lines) { + var styleClass = server.getRandomClass(lines.length); + $.each(lines, function() { + var text = this; + var newElem = $("

        "); + var textElem = $(" " + text + ""); + textElem.addClass(styleClass); + var serverName = "mis-01" + newElem.append("[" + moment().format("HH:mm:ss") + " " + serverName + " (UTC " + moment.utc().format("HH:mm") + ")]"); + newElem.append(textElem); + $("#body_console").prepend(newElem); + }); +} + + +function cullOldEntries() { + var scrollbackLimit = 250; + $("#body_console p").slice(scrollbackLimit).remove(); +} + + +var currentTimeoutId = undefined; +var counter = 0; +function doStuff() { + var delay = 5 + 2600 * Math.random() * Math.random() * Math.random() * Math.random(); + delay *= delayFactor; + currentTimeoutId = setTimeout(function() { + addLines(server.getRandomLines()); + counter++; + if(counter % 20 == 0) { + cullOldEntries(); + } + doStuff(); + }, delay); +} + +// When ready, go go go +$(function() { + if(window.location.search.match("controls")) { + $("#controls").show(); + } + doStuff(); + + $("#controls #turbo").click(function() { + if(delayFactor < 1.0) { + delayFactor = 1.0; + } else { + delayFactor = 0.00001; + } + }); + + var lastLineCount = counter; + var lastTime = moment(); + setInterval(function() { + var currentTime = moment(); + duration = currentTime - lastTime; + lps = (counter - lastLineCount) / (duration / 1000.0); + $("#controls #lps").text("" + Math.round(lps) + " L/S"); + lastTime = currentTime; + lastLineCount = counter; + }, 3000); + + $("#controls #play_pause").click(function () { + if(typeof currentTimeoutId != "undefined") { + clearTimeout(currentTimeoutId); + currentTimeoutId = undefined; + } + else { + doStuff(); + } + }); +}) + diff --git a/pool/shard000/JavaScript/0005891_MutinyAtCrastersKeep.js b/pool/shard000/JavaScript/0005891_MutinyAtCrastersKeep.js new file mode 100644 index 0000000000000000000000000000000000000000..c071d871a05c213ff0af43c24c3bbc4ed89df9c0 --- /dev/null +++ b/pool/shard000/JavaScript/0005891_MutinyAtCrastersKeep.js @@ -0,0 +1,33 @@ +const DrawCard = require('../../drawcard.js'); + +const _ = require('underscore'); + +class MutinyAtCrastersKeep extends DrawCard { + setupCardAbilities(ability) { + this.action({ + title: 'Discard character from play', + phase: 'dominance', + cost: ability.costs.sacrifice(card => + card.getType() === 'character' && card.getPrintedCost() === this.getHighestCharacterCost()), + target: { + cardCondition: card => card.location === 'play area' && card.controller !== this.controller && + card.getType() === 'character' + }, + handler: context => { + context.target.owner.discardCard(context.target); + this.game.addMessage('{0} plays {1} and sacrifices {2} to discard {3} from play', + context.player, this, context.costs.sacrifice, context.target); + } + }); + } + + getHighestCharacterCost() { + let charactersInPlay = this.controller.filterCardsInPlay(card => card.getType() === 'character' && card.hasPrintedCost()); + let costs = _.map(charactersInPlay, card => card.getPrintedCost()); + return _.max(costs); + } +} + +MutinyAtCrastersKeep.code = '06086'; + +module.exports = MutinyAtCrastersKeep; diff --git a/pool/shard000/JavaScript/0005892_integration.spec.js b/pool/shard000/JavaScript/0005892_integration.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..3dd9334c606aef6f1b017e1e8e9eed085e7425a6 --- /dev/null +++ b/pool/shard000/JavaScript/0005892_integration.spec.js @@ -0,0 +1,122 @@ +var chp = require('child_process'); +//var npm = require('npm'); +var path = require('path'); + +var expect = require('chai').expect; +var _ = require('lodash'); +var shelltest = require('shelltest'); + +var cliPath = 'bin/cli.js '; + +var subjectFile = 'origin.txt'; + +describe("lnkr", function() { + describe.skip("after installation", function() { + + before(function(done) { + npm.load(done); + }); + + before(function(done) { + //@todo npm refuses to install itself as dependency, tmp dir should be used for test + npm.commands.install(['lnkr'], done) + }); + + it("should provide npm executable as lnkr", function(done) { + var options = {}; + chp.execFile('node_modules/.bin/lnkr', options, done); + }); + }); + + it.skip("should provide cli executalbe", function(done) { + chp.execFile(cliPath, done); + }); + + describe("when launched without args", function() { + + it("should show usage info", function(done) { + + var expected = new RegExp('^' + _.escapeRegExp('usage:')); + + shelltest() + .cmd(cliPath) + .expect('stdout', expected) + .expect('stderr', '') + .expect(0) + .end(done); + }); + }); + + describe("after init", function() { + beforeEach(setupFixtures); + + //beforeEach(); + + it("should write, that lnkr has been initialized", function runInitCmd(done) { + + var expected = new RegExp('^' + _.escapeRegExp('lnkr has been initialized')); + + shelltest() + .cmd(cliPath + 'init') + .expect('stdout', expected) + .expect('stderr', '') + .expect(0) + .end(); + }); + + describe.skip(", after list", function() { + it("should show a message that lnkr has no revisions yet", function(done) { + }); + }); + describe.skip(", after adding a new revision", function() { + it("should show a message that a new revision has been added", function(done) { + }); + + + describe.skip(", after list", function() { + it("should show a message that lnkr has one revision", function(done) { + }); + }); + + describe.skip(", after adding of another revision", function() { + it("should show a message that the revision has been added", function(done) { + }); + + + describe.skip(", after list", function() { + it("should show a message that lnkr has two revisions", function(done) { + }); + }); + }); + }); + }); +}); + +function run() { + var args = [].slice.apply(arguments); + var callback = args.pop(); + var cwd = 'tmp'; //@todo create new tmp dir for each run + var options = { + timeout: 1000, + cwd: cwd + }; + var execPath = path.relative(cwd, cliPath); + chp.execFile(execPath, args, options, callback); +} + +function checkNoErrors(callback) { + return function callbackForNoErrors(error, stdout, stderr) { + console.log('res', { + error: error, + stdout: stdout, + stderr: stderr + }); + expect(error).to.not.exist; + expect(stderr).to.be.empty; + callback(stdout); + } +} + +function setupFixtures() { + //@todo inplmement copying fixtures +} diff --git a/pool/shard000/JavaScript/0005893_deleteManagedObject.js b/pool/shard000/JavaScript/0005893_deleteManagedObject.js new file mode 100644 index 0000000000000000000000000000000000000000..2ed12b9050d6ab0fce01f255dc2e9958e186728e --- /dev/null +++ b/pool/shard000/JavaScript/0005893_deleteManagedObject.js @@ -0,0 +1,29 @@ +var OpenIdm = require('../lib/openidm'); + +var openidm = new OpenIdm({ + host : 'localhost', + port : 8080, + userName : 'openidm-admin', + password : 'openidm-admin' +}); + +// Read managed object +var readed = openidm.get('managed/user/user001', function(err, data) { + if (err) { + console.log("Error: " + err.message); + console.log("Error: " + err.response.message); + return; + } + + // Delete managed object + var deleted = openidm.delete('managed/user/user001', data._rev, function(err, data) { + if (err) { + console.log("Error: " + err.message); + console.log("Error: " + err.response.message); + return ; + } + console.log(data); + }); + +}); + diff --git a/pool/shard000/JavaScript/0005895_main.js b/pool/shard000/JavaScript/0005895_main.js new file mode 100644 index 0000000000000000000000000000000000000000..f36aedb0fe403d497d5083032467c7bec962fe3d --- /dev/null +++ b/pool/shard000/JavaScript/0005895_main.js @@ -0,0 +1,44 @@ +// Require bootstrap and jquery +window.$ = window.jQuery = require('jquery'); + +// Load vue libs +import Vue from 'vue' +import App from './components/app.vue' +import vueResource from 'vue-resource' +import router from './router' + +/** + * tell vue to user vue resource + */ +Vue.use(vueResource) + +// Register global components +Vue.component('sidebar', require('./components/sidebar.vue')) +Vue.component('navbar', require('./components/navbar.vue')) +Vue.component('alert', require('./components/other/alert.vue')) +/** + * We'll register a HTTP interceptor to attach the "CSRF" header to each of + * the outgoing requests issued by this application. The CSRF middleware + * included with Laravel will automatically verify the header's value. + */ +Vue.http.interceptors.push((request, next) => { + request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken) + next() +}) + + +window.Event = new Vue(); + +// set custom configs +Vue.config.debug = true +Vue.http.options.root = "/api"; + +//extend vue to handle with routing +new Vue( + Vue.util.extend( + { + router + }, + App + ) +).$mount('#app') diff --git a/pool/shard000/JavaScript/0005896_DetailView.js b/pool/shard000/JavaScript/0005896_DetailView.js new file mode 100644 index 0000000000000000000000000000000000000000..be925dcfa5dc70ec5da883140fa735d1857d22a0 --- /dev/null +++ b/pool/shard000/JavaScript/0005896_DetailView.js @@ -0,0 +1,40 @@ + //Detail View Component Constructor +exports.DetailView = function() { + //create object instance, parasitic subclass of Observable + var self = Ti.UI.createView({ + backgroundColor:"#fff" + }); + + var table = Ti.UI.createTableView({ + data:[] + }); + self.add(table); + + table.addEventListener('click', function(e) { + self.fireEvent('detailSelected', { + name:e.rowData.name, + examples:e.rowData.examples + }); + }); + + self.addEventListener('itemSelected', function(e) { + var data = [], + parts = [], + i = 0, + len = e.objects.length; + + Ti.API.info(e.objects); + for (; i < len; i++) { + parts = e.objects[i].name.split("."); + data.push({ + title:parts[parts.length-1], + hasChild:true, + name:e.objects[i].name, + examples:e.objects[i].examples + }); + } + table.setData(data); + }); + + return self; +}; diff --git a/pool/shard000/JavaScript/0005901_Dashboard.notifications.js b/pool/shard000/JavaScript/0005901_Dashboard.notifications.js new file mode 100644 index 0000000000000000000000000000000000000000..da18a101aad002c3c197e3f444d5d9ce7661bb0f --- /dev/null +++ b/pool/shard000/JavaScript/0005901_Dashboard.notifications.js @@ -0,0 +1,237 @@ +/*! + * Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved. + * + * This software was developed by Webdetails and is provided under the terms + * of the Mozilla Public License, Version 2.0, or any later version. You may not use + * this file except in compliance with the license. If you need a copy of the license, + * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. + * + * Software distributed under the Mozilla Public License is distributed on an "AS IS" + * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to + * the license for the specific language governing your rights and limitations. + */ + +define([ + './Dashboard', + './Dashboard.notifications.ext', + './Popups', + '../Logger', + 'amd!../lib/underscore', + '../lib/jquery', + 'amd!../lib/jquery.blockUI' +], function(Dashboard, DashboardNotificationsExt, Popups, Logger, _, $) { + + /** + * A module representing an extension to Dashboard module for notifications. + * @module Dashboard.notifications + */ + Dashboard.implement({ + + /** + * Inits the notification module + * + * @method _initNotifications + * @private + * @for Dashboard + */ + _initNotifications: function() { + + /** + * Property with the registered error codes. By default, the QUERY_TIMEOUT and COMPONENT_ERROR code + * are registered and assigned to a specific error message + * @property ERROR_CODES + * @type Object + * @for Dashboard + */ + this.ERROR_CODES = { + 'QUERY_TIMEOUT' : { + msg: "Query timeout reached" + }, + "COMPONENT_ERROR" : { + msg: "Error processing component" + } + }; + }, + + /** + * Renders a blocking div that can be dragged + * + * @method blockUIwithDrag + * @for Dashboard + */ + blockUIwithDrag: function() { + if(typeof this.i18nSupport !== "undefined" && this.i18nSupport != null) { + // If i18n support is enabled process the message accordingly + // but we're just setting the same img + $.blockUI.defaults.message = '
        '; + } + + $.blockUI(); + var handle = $('
        '); + $("div.blockUI.blockMsg").prepend(handle); + $("div.blockUI.blockMsg").draggable({ + handle: "#blockUIDragHandle" + }); + }, + + /** + * Makes visible the progress indicator. By default, this is a draggable blocking div that shows a spinner + * + * @method showProgressIndicator + * @for Dashboard + */ + showProgressIndicator: function() { + $.blockUI && this.blockUIwithDrag(); + }, + + /** + * Hides the progress indicator. Optionally, resets the running calls counter + * + * @method hideProgressIndicator + * @param {Boolean} _true_ if the running calls counter should be reset, _false_ otherwise + * @for Dashboard + */ + hideProgressIndicator: function(force) { + if(force) { + this.resetRunningCalls(); + } + $.unblockUI && $.unblockUI(); + this.showErrorTooltip();// Dashboard.legacy + }, + + /** + * Given an error code, returns the registered error object associated with that code + * + * @method getErrorObj + * @param errorCode errorCode to translate + * @returns {*|{}} error object or the empty object if the code is not registered + * + * @for Dashboard + */ + getErrorObj: function(errorCode) { + return this.ERROR_CODES[errorCode] || {}; + }, + + /** + * Parses a server error response and creates an error object + * + * @method parseServerError + * @param resp Server response + * @param txtStatus Response status + * @param error Error object to encapsulate + * @returns {Object} an error object containing detailed error message + * + * @for Dashboard + * @deprecated + * @private + */ + parseServerError: function(resp, txtStatus, error) { + // NOTE: this method's signature matches the error callback of $.ajax({error: . }). + var regexs = [ + {match: /Query timeout/, msg: this.getErrorObj('QUERY_TIMEOUT').msg} + ]; + + var out = { + msg: this.getErrorObj('COMPONENT_ERROR').msg, + error: error, + errorStatus: txtStatus + }; + + var str = $('
        ').html(resp.responseText).find('h1').text(); + _.find(regexs, function(el) { + if(str.match(el.match)) { + out.msg = el.msg; + return true; + } + return false; + }); + + return out; + }, + + /** + * Handles a server error + * + * @method handleServerError + * @for Dashboard + */ + handleServerError: function() { + this.errorNotification(this.parseServerError.apply(this, arguments)); + this.trigger('cdf cdf:serverError', this); + this.resetRunningCalls(); + }, + + /** + * Displays an error notification + * + * @method errorNotification + * @param err Error message to display + * @param ph Optional html element where to attach the error notification + * + * @for Dashboard + */ + errorNotification: function(err, ph) { + if(ph) { + Popups.notificationsComponent.render($(ph), {title: err.msg, desc: ""}); + } else { + Popups.notificationsGrowl.render({ + title: err.msg, + desc: '' + }); + } + }, + + /** + * Default implementation for the login alert that pops up when we detect the user is no longer logged in. + * + * @method loginAlert + * @param newOpts Options for the login popup + * + * @for Dashboard + */ + loginAlert: function(newOpts) { + var opts = { + header: "Warning", + desc: "You are no longer logged in or the connection to the server timed out", + button: "Click to reload this page", + callback: function() { + window.location.reload(true); + } + }; + opts = _.extend({}, opts, newOpts); + + Popups.okPopup.show(opts); + this.trigger('cdf cdf:loginError', this); + }, + + /** + * Check if we're able to connect to the server correctly, using post to avoid cache + * + * @method checkServer + * @returns {Boolean} _true_ if able to connect, _false_ otherwise + * + * @for Dashboard + */ + checkServer: function() { + var retVal = false; + $.ajax({ + type: 'POST', + async: false, + dataType: 'json', + url: DashboardNotificationsExt.getPing(), + success: function(result) { + if(result && result.ping == 'ok') { + retVal = true; + } + else { + retVal = false; + } + }, + error: function() { + retVal = false; + } + }); + return retVal; + } + }); +}); diff --git a/pool/shard000/JavaScript/0005902_espresso_attendees_admin.js b/pool/shard000/JavaScript/0005902_espresso_attendees_admin.js new file mode 100644 index 0000000000000000000000000000000000000000..7487c9f369e657c245d119d3a2ede72fecbbb0e9 --- /dev/null +++ b/pool/shard000/JavaScript/0005902_espresso_attendees_admin.js @@ -0,0 +1,155 @@ +jQuery(document).ready(function($) { + + $.ajaxSetup ({ cache: false }); + + // clear firefox and safari cache + $(window).unload( function() {}); + + + $('#entries-per-page-btn').hide(); + + $('#entries-per-page-slct').on( 'change', function() { + var per_page = $(this).val(); + $('#per_page').val( per_page ); + var theForm = $(this).parents('form'); + var formURL = theForm.attr('action'); + formURL = formURL.replace( '&noheader=true', '' ); + theForm.attr( 'action', formURL ); + theForm.submit(); + }); + + + + $('.confirm-delete').click(function() { + var what = $(this).attr('rel'); + var answer = confirm( eei18n.confirm_delete ); + return answer; + }); + + $('.updated.fade').delay(5000).fadeOut(); + + + // generic click event for displaying and giving focus to an element and hiding control + $('.display-the-hidden').click(function() { + // get target element from "this" (the control element's) "rel" attribute + var item_to_display = $(this).attr("rel"); + var control = $(this); + // display the target's div container - use slideToggle or removeClass + $('#'+item_to_display+'-dv').slideToggle(500, function() { + // hide the control element + control.addClass('hidden'); + // display the target div's hide link + $('#hide-'+item_to_display).removeClass('hidden'); + // if hiding/showing a form input, then id of the form input must = item_to_display + //$('#'+item_to_display).focus(); // add focus to the target + }); + return false; + }); + + // generic click event for re-hiding an element and displaying it's display control + $('.hide-the-displayed').click(function() { + // get target element from "this" (the control element's) "rel" attribute + var item_to_hide = $(this).attr("rel"); + var control = $(this); + // hide the target's div container - use slideToggle or addClass + $('#'+item_to_hide+'-dv').slideToggle(500, function() { + //$('#'+item_to_hide+'-dv').delay(250).addClass('hidden'); + // hide the control element + control.addClass('hidden'); + // display the control element that toggles display of this element + $('#display-'+item_to_hide).removeClass('hidden'); + }); + return false; + }); + + + + $('.add_new_attendee').on( 'click', function( event ) { + event.preventDefault(); + + var goodToGo = validate_form_inputs(); + + if ( goodToGo === true ) { + $(this).parents('form').submit(); + } else { + + var errorMsg ='

        ' + goodToGo + '

        '; + + $('#att-admin-add-new-attendee-messages-dv').html( errorMsg ); + + $('body,html').animate({ scrollTop: 100 }, 500 ); + return false; + } + return false; + }); + + + + function validate_form_inputs() { + goodToGo = true; + $('#att-admin-add-new-attendee-frm .required').each( function( index ) { + + if( $( this ).val() == '' || $( this ).val() == 0 ) { + $( this ).addClass('requires-value').prev( '.validation-notice-dv' ).fadeIn(); + // set error messages + if ( goodToGo === true ) { + goodToGo = 'You need to answer all required questions before you can proceed.'; + } else if ( goodToGo == 'You must enter a valid email address.' ) { + goodToGo = 'You must enter a valid email address and answer all other required questions before you can proceed.'; + } + + } else { + + // is this field an email address ? + if ( $(this).attr('id') == 'ATT_email' ) { + + // grab the addy + var email_address = $(this).val(); + // send addy for validation + if ( validate_email_address( email_address )) { + // good email addy + $(this).removeClass('requires-value').prev( '.validation-notice-dv' ).fadeOut('fast'); + } else { + // set error messages + if ( goodToGo === true ) { + goodToGo = 'You must enter a valid email address.'; + } else if ( goodToGo == 'You need to answer all required questions before you can proceed.' ) { + goodToGo = 'You must enter a valid email address and answer all other required questions before you can proceed.'; + } + // bad email addy + $( this ).addClass('requires-value').prev( '.validation-notice-dv' ).html('You must enter a valid email address.').fadeIn(); + + } + + } else { + $(this).removeClass('requires-value').prev( '.validation-notice-dv' ).fadeOut(); + } + + } + + + $( this ).on( 'change', function() { + if( $( this ).val() != '' || $( this ).val() != 0 ) { + $( this ).removeClass('requires-value').prev( '.validation-notice-dv' ).fadeOut('fast'); + } + }); + + }); + + return goodToGo; + } + + + + /** + * validate_email_address + */ + function validate_email_address (email) { + var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; + return regex.test(email); + } + + + +}); + diff --git a/pool/shard000/JavaScript/0005905_index.js b/pool/shard000/JavaScript/0005905_index.js new file mode 100644 index 0000000000000000000000000000000000000000..162854e9c89af21f087909e63005df66077f1a0c --- /dev/null +++ b/pool/shard000/JavaScript/0005905_index.js @@ -0,0 +1,76 @@ +import transformES2015TemplateLiterals from "babel-plugin-transform-es2015-template-literals"; +import transformES2015Literals from "babel-plugin-transform-es2015-literals"; +import transformES2015FunctionName from "babel-plugin-transform-es2015-function-name"; +import transformES2015ArrowFunctions from "babel-plugin-transform-es2015-arrow-functions"; +import transformES2015BlockScopedFunctions from "babel-plugin-transform-es2015-block-scoped-functions"; +import transformES2015Classes from "babel-plugin-transform-es2015-classes"; +import transformES2015ObjectSuper from "babel-plugin-transform-es2015-object-super"; +import transformES2015ShorthandProperties from "babel-plugin-transform-es2015-shorthand-properties"; +import transformES2015DuplicateKeys from "babel-plugin-transform-es2015-duplicate-keys"; +import transformES2015ComputedProperties from "babel-plugin-transform-es2015-computed-properties"; +import transformES2015ForOf from "babel-plugin-transform-es2015-for-of"; +import transformES2015StickyRegex from "babel-plugin-transform-es2015-sticky-regex"; +import transformES2015UnicodeRegex from "babel-plugin-transform-es2015-unicode-regex"; +import checkES2015Constants from "babel-plugin-check-es2015-constants"; +import transformES2015Spread from "babel-plugin-transform-es2015-spread"; +import transformES2015Parameters from "babel-plugin-transform-es2015-parameters"; +import transformES2015Destructuring from "babel-plugin-transform-es2015-destructuring"; +import transformES2015BlockScoping from "babel-plugin-transform-es2015-block-scoping"; +import transformES2015TypeofSymbol from "babel-plugin-transform-es2015-typeof-symbol"; +import transformES2015ModulesCommonJS from "babel-plugin-transform-es2015-modules-commonjs"; +import transformES2015ModulesSystemJS from "babel-plugin-transform-es2015-modules-systemjs"; +import transformES2015ModulesAMD from "babel-plugin-transform-es2015-modules-amd"; +import transformES2015ModulesUMD from "babel-plugin-transform-es2015-modules-umd"; +import transformRegenerator from "babel-plugin-transform-regenerator"; + +export default function (context, opts = {}) { + const moduleTypes = ["commonjs", "amd", "umd", "systemjs"]; + let loose = false; + let modules = "commonjs"; + let spec = false; + + if (opts !== undefined) { + if (opts.loose !== undefined) loose = opts.loose; + if (opts.modules !== undefined) modules = opts.modules; + if (opts.spec !== undefined) spec = opts.spec; + } + + if (typeof loose !== "boolean") throw new Error("Preset es2015 'loose' option must be a boolean."); + if (typeof spec !== "boolean") throw new Error("Preset es2015 'spec' option must be a boolean."); + if (modules !== false && moduleTypes.indexOf(modules) === -1) { + throw new Error("Preset es2015 'modules' option must be 'false' to indicate no modules\n" + + "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'"); + } + + // be DRY + const optsLoose = { loose }; + + return { + plugins: [ + [transformES2015TemplateLiterals, { loose, spec }], + transformES2015Literals, + transformES2015FunctionName, + [transformES2015ArrowFunctions, { spec }], + transformES2015BlockScopedFunctions, + [transformES2015Classes, optsLoose], + transformES2015ObjectSuper, + transformES2015ShorthandProperties, + transformES2015DuplicateKeys, + [transformES2015ComputedProperties, optsLoose], + [transformES2015ForOf, optsLoose], + transformES2015StickyRegex, + transformES2015UnicodeRegex, + checkES2015Constants, + [transformES2015Spread, optsLoose], + transformES2015Parameters, + [transformES2015Destructuring, optsLoose], + transformES2015BlockScoping, + transformES2015TypeofSymbol, + modules === "commonjs" && [transformES2015ModulesCommonJS, optsLoose], + modules === "systemjs" && [transformES2015ModulesSystemJS, optsLoose], + modules === "amd" && [transformES2015ModulesAMD, optsLoose], + modules === "umd" && [transformES2015ModulesUMD, optsLoose], + [transformRegenerator, { async: false, asyncGenerators: false }], + ].filter(Boolean), // filter out falsy values + }; +} diff --git a/pool/shard000/JavaScript/0005912_test.js b/pool/shard000/JavaScript/0005912_test.js new file mode 100644 index 0000000000000000000000000000000000000000..4f6450cd0613c1eb44ee1df54a5c35f227113deb --- /dev/null +++ b/pool/shard000/JavaScript/0005912_test.js @@ -0,0 +1,182 @@ +/* nodeunit test for vdf.js */ +/*jshint multistr: true */ + +var vdf = require("./index"); + +/* De-serialization */ +var UNQUOTED_VDF = "\n\ + node \n\ + { \n\ + key value \n\ + } \n\ + ", + + QUOTED_VDF = " \n\ + \"node\" \n\ + { \n\ + \"key\" \"value\" \n\ + } \n\ + ", + + MACRO_UNQUOTED_VDF = " \n\ + node \n\ + { \n\ + key value [$MACRO] \n\ + } \n\ + ", + + MACRO_QUOTED_VDF = " \n\ + \"node\" \n\ + { \n\ + \"key\" \"value\" [$MACRO] \n\ + } \n\ + ", + + COMMENT_QUOTED_VDF = " \n\ + \"node\" \n\ + { \n\ + // Hi I'm a comment. \n\ + \"key\" \"value\" [$MACRO] \n\ + } \n\ + ", + + SUBNODE_QUOTED_VDF = " \n\ + \"node\" \n\ + { \n\ + \"subnode\" \n\ + { \n\ + \"key\" \"value\" \n\ + } \n\ + } \n\ + ", + + MIXED_VDF = " \n\ + node \n\ + { \n\ + \"key\" value \n\ + key2 \"value\" \n\ + \"key3\" \"value\" [$MACRO] \n\ + \n\ + // Comment \n\ + \"subnode\" [$MACRO] \n\ + { \n\ + key value \n\ + } \n\ + \n\ + \"key4\" \"value\" \n\ + } \n\ + ", + + /* Expectations */ + EXPECTED_UNQUOTED_VDF = { + "node": { + "key": "value" + } + }, + + EXPECTED_QUOTED_VDF = EXPECTED_UNQUOTED_VDF, + EXPECTED_MACRO_UNQUOTED_VDF = EXPECTED_UNQUOTED_VDF, + EXPECTED_MACRO_QUOTED_VDF = EXPECTED_UNQUOTED_VDF, + EXPECTED_COMMENT_QUOTED_VDF = EXPECTED_UNQUOTED_VDF, + + EXPECTED_SUBNODE_QUOTED_VDF = { + "node": { + "subnode": { + "key": "value" + } + } + }, + EXPECTED_MIXED_VDF = { + "node": { + "key": "value", + "key2": "value", + "key3": "value", + "subnode": { + "key": "value" + }, + "key4": "value" + } + }; + +/* Serialization */ +var SIMPLE_OBJ = EXPECTED_UNQUOTED_VDF, + + SUBNODE_OBJ = EXPECTED_SUBNODE_QUOTED_VDF, + + ARRAY_OBJ = { + "array": [ + "a", + "b", + "c"] + }, + + NUMERICAL_OBJ = { + "number": 1, + "number2": 2 + }, + + COMBINATION_OF_ABOVE_OBJ = { + "node": { + "key": "value", + "subnode": { + "key": "value" + }, + "array": ["a", "b", "c", 1, 2, 3], + "number": 1024 + } + }, + + /* Expectations */ + EXPECTED_SIMPLE_OBJ = SIMPLE_OBJ, + + EXPECTED_SUBNODE_OBJ = SUBNODE_OBJ, + + EXPECTED_ARRAY_OBJ = { + "array": { + "a": "1", + "b": "1", + "c": "1" + } + }, + + EXPECTED_NUMERICAL_OBJ = { + "number": "1", + "number2": "2" + }, + + EXPECTED_COMBINATION_OF_ABOVE_OBJ = { + "node": { + "key": "value", + "subnode": { + "key": "value" + }, + "array": { + "a": "1", + "b": "1", + "c": "1", + "1": "1", + "2": "1", + "3": "1" + }, + "number": "1024" + } + }; + +/* Tests */ +exports.deserialization = { + test_unquoted: function (test) { test.equal(JSON.stringify(EXPECTED_UNQUOTED_VDF), JSON.stringify(vdf.parse(UNQUOTED_VDF))); test.done(); }, + test_quoted: function (test) { test.equal(JSON.stringify(EXPECTED_QUOTED_VDF), JSON.stringify(vdf.parse(QUOTED_VDF))); test.done(); }, + test_macro_unquoted: function (test) { test.equal(JSON.stringify(EXPECTED_MACRO_UNQUOTED_VDF), JSON.stringify(vdf.parse(MACRO_UNQUOTED_VDF))); test.done(); }, + test_macro_quoted: function (test) { test.equal(JSON.stringify(EXPECTED_MACRO_QUOTED_VDF), JSON.stringify(vdf.parse(MACRO_QUOTED_VDF))); test.done(); }, + test_comment_quoted: function (test) { test.equal(JSON.stringify(EXPECTED_COMMENT_QUOTED_VDF), JSON.stringify(vdf.parse(COMMENT_QUOTED_VDF))); test.done(); }, + test_subnode_quoted: function (test) { test.equal(JSON.stringify(EXPECTED_SUBNODE_QUOTED_VDF), JSON.stringify(vdf.parse(SUBNODE_QUOTED_VDF))); test.done(); }, + test_mixed: function (test) { test.equal(JSON.stringify(EXPECTED_MIXED_VDF), JSON.stringify(vdf.parse(MIXED_VDF))); test.done(); } +}; + +exports.serialization = { + test_simple_object: function (test) { test.equal(JSON.stringify(EXPECTED_SIMPLE_OBJ), JSON.stringify(vdf.parse(vdf.dump(SIMPLE_OBJ)))); test.done(); }, + test_subnode_object: function (test) { test.equal(JSON.stringify(EXPECTED_SUBNODE_OBJ), JSON.stringify(vdf.parse(vdf.dump(SUBNODE_OBJ)))); test.done(); }, + test_array_object: function (test) { test.equal(JSON.stringify(EXPECTED_ARRAY_OBJ), JSON.stringify(vdf.parse(vdf.dump(ARRAY_OBJ)))); test.done(); }, + test_numerical_object: function (test) { test.equal(JSON.stringify(EXPECTED_NUMERICAL_OBJ), JSON.stringify(vdf.parse(vdf.dump(NUMERICAL_OBJ)))); test.done(); }, + test_combination_of_above: function (test) { test.equal(JSON.stringify(EXPECTED_COMBINATION_OF_ABOVE_OBJ), JSON.stringify(vdf.parse(vdf.dump(COMBINATION_OF_ABOVE_OBJ)))); test.done(); } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005915_index.js b/pool/shard000/JavaScript/0005915_index.js new file mode 100644 index 0000000000000000000000000000000000000000..122ee0adff85fff4338e691313ff0754a193ed64 --- /dev/null +++ b/pool/shard000/JavaScript/0005915_index.js @@ -0,0 +1,28 @@ +$im.modechange(function(event, mode) { + if (mode !== $im.mode.stitched) { + return; + } + + jQuery.each($im.scenes, function(i, scene) { + jQuery.each(scene.sprites, function(i, sprite) { + sprite.tween(3, {x: sprite.x + 3, y: sprite.y + 1}); + }); + }); +}); + +$im.ready(function() { + $im.logLevel = $im.infoLevel; + + var sprite = new imMatch.Sprite(), + scene = new imMatch.Scene(); + + sprite.setImage("taipei101"); + sprite.maxScalingFactor = 2; + sprite.minScalingFactor = 0.5; + + scene.addSprite(sprite); + + $im.addScene(scene); + + $im.run(null, "127.0.0.1"); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005917_login.js b/pool/shard000/JavaScript/0005917_login.js new file mode 100644 index 0000000000000000000000000000000000000000..b48ffa04c36ae3a96ce4bbd0ed5ab709ab0c4c17 --- /dev/null +++ b/pool/shard000/JavaScript/0005917_login.js @@ -0,0 +1,156 @@ +function change2White(_this){ + var text=_this; //输入搜索内容的文本框 + var btn=$('#search_btn_out'); //搜索按钮 + var div=$('#search_out'); //搜索所在的div + + div.attr('id','search_over'); + btn.attr('id','search_btn_over'); + text.id='search-input-over'; +} + +function change2Gray(_this){ + var text=_this; //输入搜索内容的文本框 + var btn=$('#search_btn_over'); //搜索按钮 + var div=$('#search_over'); //搜索所在的div + + div.attr('id','search_out'); + btn.attr('id','search_btn_out'); + text.id='search-input-out'; +} + +function changeSearchFocus(){ + var inptu=$('.search-tags-ipt'); + inptu.css('border-color','#999'); + inptu.css('color','black'); +} + +function changeSearchBlur(){ + $('.search-tags-ipt').css('border-color','#CCC'); +} + +var flag; +var chTelRe=false; //检查电话号码的标志 +var chPwdRe=false;//检查密码格式的标志 +var chNamRe=false;//检查名字的标志 +//显示登陆注册界面 +function showDiv(ad){ + $("#div").show(); + $("#bg").show(); + if(ad==1){ + showLogin(); + }else{ + showReg(); + } +} +//显示登陆的块 +function showLogin(){ + $("#loginform").show(); + $("#regform").hide(); + $("#div").css("height","360px"); + $("#bg").css("height","360px"); + $("#lo").attr("class","btn active1"); + $("#re").attr("class","btn"); +} +//显示注册的块 +function showReg(){ + $("#loginform").hide(); + $("#regform").show(); + $("#div").css("height","450px"); + $("#bg").css("height","450px"); + $("#lo").attr("class","btn"); + $("#re").attr("class","btn active1"); +} +//关闭登陆注册界面 +function closes(){ + $("#div").hide(); + $("#bg").hide(); +} +//登陆的函数 +function UserLogin(){ + var uname=$("#luname").val(); + var upwd=$("#lupwd").val(); + $.post("user_loginUser",{uName:uname,uPwd:upwd},function(data){ + if(data==1){ + location.href="zhuye.jsp"; + }else{ + $("#tishi").show(); + } + }); +} +//点击登陆界面输入框 +function ludian(){ + $("#tishi").hide(); +} +//检查电话号码的函数 +function ch_tel(){ + var chtel=$("#zctel").val(); + var reg=/^1[3-8]\d{9}$/; //验证电话号码的正则表达式 + if(reg.test(chtel)){ + $.post("user_chTel",{uTel:chtel},function(data){ + if(data==1){ + chTelRe=true; + $("#ditishi").hide(); + }else{ + chTelRe=false; + $("#ditishi").html("电话已存在"); + $("#ditishi").show(); + } + }); + }else{ + chTelRe=false; + $("#ditishi").html("电话格式不正确"); + $("#ditishi").show(); + } +} +//检查密码格式的函数 +function ch_pwd(){ + var upwd=$("#zcpwd").val(); + var reg=/^\S{6,16}$/;//验证密码的正则表达式 + if(!reg.test(upwd)){ + chPwdRe=false; + $("#pwtishi").html("密码格式不正确"); + $("#pwtishi").show(); + }else{ + chPwdRe=true; + $("#pwtishi").hide(); + } +} +//检查name的函数 +function ch_name(){ + var chnam=$("#zcname").val(); + var reg=/^\S{2,18}$/; //验证电话号码的正则表达式 + if(reg.test(chnam)){ + $.post("user_chName",{uName:chnam},function(data){ + if(data==1){ + chNamRe=true; + $("#natishi").hide(); + }else{ + chNamRe=false; + $("#natishi").html("名字已存在"); + $("#natishi").show(); + } + }); + }else{ + chNamRe=false; + $("#natishi").html("名字格式不正确"); + $("#natishi").show(); + } +} +//注册 +function user_addUsreInfo(){ + ch_tel(); + ch_name(); + ch_pwd(); + if(chTelRe&&chNamRe&&chPwdRe){ + var chtel=$("#zctel").val(); + var upwd=$("#zcpwd").val(); + var chnam=$("#zcname").val(); + $.post("user_addUsreInfo",{uName:chnam,uPwd:upwd,uTel:chtel},function(data){ + if(data==1){ + location.href="zhuye.jsp"; + }else{ + alert('失败提示','注册失败....','error'); + } + }); + } +} diff --git a/pool/shard000/JavaScript/0005918_fractal.js b/pool/shard000/JavaScript/0005918_fractal.js new file mode 100644 index 0000000000000000000000000000000000000000..1bc68f58e612232a3ee831135eef896402a158d8 --- /dev/null +++ b/pool/shard000/JavaScript/0005918_fractal.js @@ -0,0 +1,167 @@ +(function (exports) { + 'use strict'; + + /* Draw a mountain range */ + + function MountainFractal() { + this.rangeWidth = 1000; + this.mountainCount = 30; + this.iterations = 4; + this.minMountainWidth = 150; + this.maxMountainWidth = 200; + this.minMountainHeight = 25; + this.maxMountainHeight = 47; + this.hConstant = [0.1, 0.2, 0.3, 0.4]; // 0.1 (smooth), 1.0 (jagged) + this.variationUpper = 12; // upper limit for y variation + this.variationLower = -12; // lower limit for y variation + this.startPositionSegments = 30; + + return this; + } + + exports.MountainFractal = MountainFractal; + + MountainFractal.prototype = { + + setRangeParameters: function (width) { + this.rangeWidth = width; + this.mountainCount = Math.round(width / 60); + this.startPositionSegments = Math.round(this.mountainCount / 2); + }, + + randomInRange: function (lower, upper) { + /* Return a random number between lower & upper (inclusive). */ + if (upper < lower) { + var tmp = lower; + lower = upper; + upper = tmp; + } + return Math.floor((Math.random() * (upper - lower + 1)) + lower); + }, + + randomStartPosition: function (mountain, segments, end) { + /* Start position for mountain is randomly selected from within + * n segments along the range width. This attempts to prevent + * clustering of mountains than can occur if the start position + * is random across the whole range width. + */ + var segmentWidth = end / segments; + var startSegment = mountain % segments; + var startMin = Math.round(startSegment * segmentWidth); + var startMax = Math.round(startMin + segmentWidth - 1); + + return this.randomInRange(startMin, startMax); + }, + + midPoint: function (point1, point2, variationUpper, variationLower) { + /* Take a straight line represented by two points and return + * a mid-point with a random variation on the y-axis. + */ + var xPos = Math.round((point2[0] - point1[0]) / 2 + point1[0]); + var yPos; + if (point2[1] > point1[1]) { + yPos = ((point2[1] - point1[1]) / 2) + point1[1]; + } else { + yPos = ((point1[1] - point2[1]) / 2) + point2[1]; + } + yPos = Math.round(yPos + this.randomInRange(variationLower, variationUpper)); + + return [xPos, yPos]; + }, + + addMidPoints: function (points, variationUpper, variationLower) { + /* Add mid-point to a series of straight line segments */ + var numberOfMidPoints = points.length - 1, + newPoints = []; + for (var i = 0; i < numberOfMidPoints; i++) { + newPoints.push(points[i]); + newPoints.push(this.midPoint(points[i], points[i + 1], variationUpper, variationLower)); + } + newPoints.push(points[numberOfMidPoints]); + return newPoints; + }, + + generateMountain: function (start, width, height) { + var end = start + width; + var mid = Math.round(start + width / 2); + var points = [ + [start, 0], + [mid, height], + [end, 0] + ]; + var variationLower = this.variationLower; + var variationUpper = this.variationUpper; + // pick a random h constant from those available + var hConstant = this.hConstant[this.randomInRange(0, this.hConstant.length - 1)]; + + for (var i = 0; i < this.iterations; i++) { + points = this.addMidPoints(points, variationUpper, variationLower); + // change variation on each iteration + variationUpper = variationUpper * hConstant; + variationLower = variationLower * hConstant; + } + return points; + }, + + generateMountainRange: function () { + var mountains = []; + for (var i = 0; i < this.mountainCount; i++) { + var height = this.randomInRange(this.minMountainHeight, this.maxMountainHeight); + var width = this.randomInRange(this.minMountainWidth, this.maxMountainWidth); + var start = this.randomStartPosition(i, this.startPositionSegments, this.rangeWidth + 300); + + mountains[i] = this.generateMountain(start, width, height); + } + return mountains; + } + }; + + var waitForFinalEvent = (function () { + var timers = {}; + return function (callback, ms, uniqueId) { + if (!uniqueId) { + uniqueId = "Don't call this twice without a uniqueId"; + } + if (timers[uniqueId]) { + clearTimeout(timers[uniqueId]); + } + timers[uniqueId] = setTimeout(callback, ms); + }; + })(); + + var displayMountains = function (mountains) { + var svgNS = "http://www.w3.org/2000/svg"; + + var length = mountains.length, + polygons = document.createDocumentFragment(); + + for (var mountain = 0; mountain < length; mountain++) { + var polygon = document.createElementNS(svgNS, "polygon"); + polygon.setAttributeNS(null, 'points', mountains[mountain].join(' ')); + polygons.appendChild(polygon); + } + + var svgElement = document.getElementById('mountain-range'); + while (svgElement.firstChild) { + svgElement.removeChild(svgElement.firstChild); + } + svgElement.appendChild(polygons); + }; + + var refreshMountains = function () { + fractal.setRangeParameters(document.getElementById('banner').clientWidth); + displayMountains(fractal.generateMountainRange()); + }; + + + var fractal = new MountainFractal(); + + window.addEventListener('resize', function () { + waitForFinalEvent(function () { + refreshMountains(); + }, 500, "resize complete"); + }); + + refreshMountains(); + +})(this); diff --git a/pool/shard000/JavaScript/0005920_AboutArrays.js b/pool/shard000/JavaScript/0005920_AboutArrays.js new file mode 100644 index 0000000000000000000000000000000000000000..b6d0a4940ed925f0bff282e312da1257daf108a9 --- /dev/null +++ b/pool/shard000/JavaScript/0005920_AboutArrays.js @@ -0,0 +1,97 @@ +describe("About Arrays", function() { + + //We shall contemplate truth by testing reality, via spec expectations. + it("should create arrays", function() { + var emptyArray = []; + expect(typeof(emptyArray)).toBe[0]; //A mistake? - http://javascript.crockford.com/remedial.html + expect(emptyArray.length).toBe(0); + + var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]]; + expect(multiTypeArray[0]).toBe(0); + expect(multiTypeArray[2]).toBe("two"); + expect(multiTypeArray[3]()).toBe(3); + expect(multiTypeArray[4].value1).toBe(4); + expect(multiTypeArray[4]["value2"]).toBe(5); + expect(multiTypeArray[5][0]).toBe(6); + }); + + it("should understand array literals", function () { + var array = []; + expect(array).toEqual([]); + + array[0] = 1; + expect(array).toEqual([1]); + + array[1] = 2; + expect(array).toEqual([1, 2]); + + array.push(3); + expect(array).toEqual([1, 2, 3]); + }); + + it("should understand array length", function () { + var fourNumberArray = [1, 2, 3, 4]; + + expect(fourNumberArray.length).toBe(4); + fourNumberArray.push(5, 6); + expect(fourNumberArray.length).toBe(6); + + var tenEmptyElementArray = new Array(10); + expect(tenEmptyElementArray.length).toBe(10); + + tenEmptyElementArray.length = 5; + expect(tenEmptyElementArray.length).toBe(5); + }); + + it("should slice arrays", function () { + var array = ["peanut", "butter", "and", "jelly"]; + + expect(array.slice(0, 1)).toEqual['peanut', 'butter']; + expect(array.slice(0, 2)).toEqual['peanut', 'and']; + expect(array.slice(2, 2)).toEqual['and', 'and']; + expect(array.slice(2, 20)).toEqual['and', 'jelly']; + expect(array.slice(3, 0)).toEqual['jelly', 'peanut']; + expect(array.slice(3, 100)).toEqual['jelly', 100]; + expect(array.slice(5, 1)).toEqual[5, 'butter']; + }); + + it("should know array references", function () { + var array = [ "zero", "one", "two", "three", "four", "five" ]; + + function passedByReference(refArray) { + refArray[1] = "changed in function"; + } + passedByReference(array); + expect(array[1]).toBe["one"]; + + var assignedArray = array; + assignedArray[5] = "changed in assignedArray"; + expect(array[5]).toBe['five']; + + var copyOfArray = array.slice(); + copyOfArray[3] = "changed in copyOfArray"; + expect(array[3]).toBe['three']; + }); + + it("should push and pop", function () { + var array = [1, 2]; + array.push(3); + + expect(array).toEqual[1, 2, 3]; + + var poppedValue = array.pop(); + expect(poppedValue).toBe['pop']; + expect(array).toEqual[1, 2, 3]; + }); + + it("should know about shifting arrays", function () { + var array = [1, 2]; + + array.unshift(3); + expect(array).toEqual[3, 2, 1]; + + var shiftedValue = array.shift(); + expect(shiftedValue).toEqual[3]; + expect(array).toEqual[1, 2]; + }); +}); diff --git a/pool/shard000/JavaScript/0005921_navigation.js b/pool/shard000/JavaScript/0005921_navigation.js new file mode 100644 index 0000000000000000000000000000000000000000..a04c62f33a7a83d2ee6cc70f329b0f5d4a6ae795 --- /dev/null +++ b/pool/shard000/JavaScript/0005921_navigation.js @@ -0,0 +1,137 @@ +/** + * Module of navigation view. + * @module navigation + * @author Tanjo, Hiroyuki + */ + +// Indicate global objects for JSHint. +/*global define:false*/ + +define([ + 'backbone', + 'jquery' +], function (Backbone, $) { + + // Enable Strict Mode. + 'use strict'; + + /** + * Class of navigation view. + * @class Navigation + * @constructor + * @extends Backbone.View + */ + var Navigation = Backbone.View.extend({ + + /** + * Construct article view. + * @method initialize + */ + initialize: function () { + var self = this; + + // Events + this.model.on('change:loadedPage', function(application, number) { + self.render(number); + }); + $(window).on('scroll', function () { + self.renderSelected(); + }); + }, + + /** + * Render navigation to add or clear anchor. + * @method render + * @param {Number} number + * @return {Navigation} + */ + render: function (number) { + var $list = this.$('ul'), + $addItem; + + if (number === 0) { + $list.empty().css('right', 0); + } + else { + $addItem = $('
      • ' + number + '
      • '); + $addItem.click(function () { + var $target = $($(this).attr('data-anchor')); + $('html, body').animate({scrollTop: $target.offset().top - 43}, 400); + }); + $list.append($addItem); + this.renderSelected(); + this.renderPosition(); + } + return this; + }, + + /** + * Update selected item. + * @method renderSelected + * @return {Navigation} + */ + renderSelected: function () { + var selectedItemIndex = 0, + $listItem = this.$('li'), + $targetItem; + $listItem.each(function (index) { + var $target = $($(this).attr('data-anchor')); + if ($target.offset().top >= $(window).scrollTop() + 200) { + return false; // Break each(). + } + selectedItemIndex = index; + }); + $targetItem = $listItem.eq(selectedItemIndex); + if (!$targetItem.hasClass('current')) { + $listItem.removeClass('active'); + $targetItem.addClass('active'); + this.renderPosition(); + } + return this; + }, + + /** + * Update position of navigation. + * @method renderPosition + * @return {Navigation} + */ + renderPosition: function () { + var $targetItem = this.$('.active'), + $list, + activeRight, + navWidth, + targetWidth, + targetPosition, + visibleOffsetRight, + visibleOffsetLeft; + if ($targetItem.length === 1) { + $list = this.$('ul'); + activeRight = parseInt($list.css('right'), 10); + navWidth = this.$el.width(); + targetWidth = $targetItem.width(); + targetPosition = $targetItem.position().left; + visibleOffsetRight = activeRight - targetPosition; + visibleOffsetLeft = targetPosition + targetWidth; + if (activeRight < visibleOffsetLeft) { + activeRight = visibleOffsetLeft; + } + else if (navWidth - 80 < visibleOffsetRight) { + activeRight = navWidth - 80 + targetPosition; + } + $list.css('right', activeRight); + } + return this; + }, + + /** + * Scroll content area. + * @method scrollContent + */ + scrollContent: function () { + + } + }); + + return Navigation; + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005922_usatoday-provider.js b/pool/shard000/JavaScript/0005922_usatoday-provider.js new file mode 100644 index 0000000000000000000000000000000000000000..77e51bf8b53bd945e5c9404746281c7d24428701 --- /dev/null +++ b/pool/shard000/JavaScript/0005922_usatoday-provider.js @@ -0,0 +1,55 @@ +'use strict'; + +// MODULE DEPENDENCIES +var when = require('when'), + request = require('request'); + +// CONSTRUCTOR +function UsaTodayProvider(options) { + this.options = options; + this.provider = 'usatoday'; +} + +// #search +UsaTodayProvider.prototype.search = function (query, details) { + //if (details === 'false') { + var self = this; + var deferred = when.defer(); + var data = {}; + var items = []; + request({ + method: 'GET', + uri: 'http://' + self.options.hostname + self.options.basepath + '/' + encodeURIComponent(query) + '?api_key=' + self.options.apiKey + }, function (err, response, body) { + console.log('http://' + self.options.hostname + self.options.basepath + '/' + encodeURIComponent(query) + '?api_key=' + self.options.apiKey); + data = JSON.parse(body); + + items = data.MovieReviews; + + //TODO: comment out when done + //console.log(items); + + when.map(items, function (item) { + return { + title: item.MovieName, + provider: self.provider, + reviewDate: item.ReviewDate, + link: { + url: item.WebUrl, + text: 'Read the USA Today Review of ' + item.MovieName + } + }; + }).then( + function pass(allitems) { + deferred.resolve(allitems); + }, + function fail(err) { + deferred.reject(err); + } + ); + }); + return deferred.promise; + //} +}; + +module.exports = UsaTodayProvider; diff --git a/pool/shard000/JavaScript/0005923_state.js b/pool/shard000/JavaScript/0005923_state.js new file mode 100644 index 0000000000000000000000000000000000000000..642334e274c7e41ce18afc8fd2b0877390ec558a --- /dev/null +++ b/pool/shard000/JavaScript/0005923_state.js @@ -0,0 +1,71 @@ +/** + * @title joola + * @overview the open-source data analytics framework + * @copyright Joola Smart Solutions, Ltd. + * @license GPL-3.0+ + * + * Licensed under GNU General Public License 3.0 or later. + * Some rights reserved. See LICENSE, AUTHORS. + **/ + +'use strict'; + +var + joola = require('../joola'), + EventEmitter2 = require('eventemitter2').EventEmitter2; + +var state = new EventEmitter2({wildcard: true, newListener: true}); +state._id = 'state'; + +module.exports = exports = state; + +state.controls = { + 'core': {state: 'working', message: ''}, + 'runtime-redis': {state: null, message: null}, + 'socketio-redis': {state: null, message: null}, + 'test': {state: 'working', message: ''}, + 'config-redis': {state: null, message: null}, + 'subscriber': {state: null, message: null}, + 'publisher': {state: null, message: null}, + 'webserver-http': {state: null, message: null}, + 'webserver-https': {state: null, message: null}, + 'dispatch': {state: null, message: null} +}; + +state.set = function (control, state, details) { + if (!this.controls[control]) + this.controls[control] = {}; + + if (this.controls[control].state != state) { + if (state != 'working' && state != 'online') + joola.logger.warn('State for [' + control + '] changed to [' + state + ']: ' + details); + else if (this.controls[control].state) + joola.logger.debug('State for [' + control + '] changed to [' + state + ']: ' + details); + else + joola.logger.debug('State for [' + control + '] changed to [' + state + ']: ' + details); + this.controls[control].state = state; + this.controls[control].message = details; + } +}; + +var state_local = 'working'; +state.get = function () { + var self = this; + var result = + { + status: state_local, + controls: {} + }; + + Object.keys(state.controls).forEach(function (key) { + if (result.status != state.controls[key].state && state.controls[key].state && state.controls[key].state != 'working' && state.controls[key].state != 'online') { + result.status = 'failure'; + if (state.controls[key].state == 'stop') + result.status = 'stop'; + result.controls[key] = self.controls[key]; + } + else if (result.status == 'working' && state.controls[key].state != 'working') + result.status = state.controls[key].state; + }); + return result; +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005927_journ.js b/pool/shard000/JavaScript/0005927_journ.js new file mode 100644 index 0000000000000000000000000000000000000000..14db4efccbc969105345246bc5493cc60a6e01ed --- /dev/null +++ b/pool/shard000/JavaScript/0005927_journ.js @@ -0,0 +1,143 @@ +#!/usr/bin/env node +'use strict'; + +var APP = APP || {}; +APP.Journ = function (mode) { + + var Dater = require('./lib/dater'); + var api = require('./lib/api'); + + var dater = new Dater(); + + var HELP_FLAG = 'help'; + var NEW_FLAG = 'new'; + var SETUP_FLAG = 'setup'; + var CONFIG_FLAG = 'config'; + var WEEK_FLAG = 'w'; + var WRITE_FLAG = '.'; + var ADD_TASK_FLAG = '+'; + + //PRIVATE + var config = function () { + console.log("====== config ======"); + api.makeCfg(); + }; + + var setup = function () { + console.log("==== setup ===="); + var cfg = api.readCfg(); + api.makeFileSystem(cfg); + console.log("Create file system at: ", cfg.journdir, cfg); + }; + + var newDay = function () { + console.log("===== A New Day ===="); + api.makeToday(); + }; + + var pastWeekSummary = function (week, year) { + var cfg = api.readCfg(); + api.pastWeekSummary(cfg, week, year); + }; + + var currentWeekSummary = function (cfg) { + var cfg = cfg || api.readCfg(); + api.weekSummary(cfg); + } + + var showHelp = function () { + var cfg = api.readCfg(); + console.log("====== JOURN USAGE ======\n"); + console.log("journ ", "without args will display journal status."); + console.log("journ ", HELP_FLAG, " displays help."); + console.log("journ ", CONFIG_FLAG, " will create a .journ.cfg.json file."); + console.log("journ ", SETUP_FLAG, " creates the file system."); + console.log("journ ", WRITE_FLAG, " 'new entry' will append to the today.md."); + console.log("journ ", WEEK_FLAG, " '##' will create a summary for ## week."); + console.log("journ ", NEW_FLAG, " will archive today.md and start a new one."); + console.log("Your working directory is ", cfg.journdir); + console.log("\n"); + }; + + var showStatus = function () { + var cfg = api.readCfg(); + console.log("====== showStatus ======"); + console.log(cfg); + console.log("Current Week ", dater.weekOfYear()); + console.log("journ ", HELP_FLAG, " displays help."); + }; + + var write = function (arr) { + var cfg = api.readCfg(); + var newline = "* " + arr.join(" ") + "\n"; + api.writeTodayLog(cfg, newline); + }; + + var addTask = function (arr) { + var cfg = api.readCfg(); + var newline = "* [ ] " + arr.join(" ") + "\n"; + api.addTask(cfg, newline); + }; + + //PUBLIC + return { + config: config, + setup: setup, + newDay: newDay, + pastWeekSummary: pastWeekSummary, + showHelp : showHelp, + showStatus: showStatus, + currentWeekSummary: currentWeekSummary, + write: write, + addTask: addTask, + HELP_FLAG: HELP_FLAG, + NEW_FLAG: NEW_FLAG, + SETUP_FLAG: SETUP_FLAG, + CONFIG_FLAG: CONFIG_FLAG, + WRITE_FLAG: WRITE_FLAG, + ADD_TASK_FLAG: ADD_TASK_FLAG, + WEEK_FLAG: WEEK_FLAG + + } +}; + +if (process.env.NODE_ENV !== 'test') { + var Journ = new APP.Journ; + + /* journ {args} first arg is the node exe then the program, then args + * [ '/usr/local/bin/node', '/Users/kyle/code/journ/journ.js', { args } ] + */ + + if (process.argv.length > 2) { + var args = process.argv; + switch (args[2]) { + case Journ.CONFIG_FLAG: + Journ.config(); + break; + case Journ.SETUP_FLAG: + Journ.setup(); + break; + case Journ.HELP_FLAG: + Journ.showHelp(); + break; + case Journ.NEW_FLAG: + Journ.newDay(); + Journ.currentWeekSummary(); + break; + case Journ.WEEK_FLAG: + Journ.pastWeekSummary(args[3], args[4]); + break; + case Journ.WRITE_FLAG: + Journ.write(args.slice(3)); + break; + case Journ.ADD_TASK_FLAG: + Journ.addTask(args.slice(3)); + break; + default: + Journ.showHelp(); + } + } else { + Journ.showStatus(); + Journ.currentWeekSummary(); + } +} diff --git a/pool/shard000/JavaScript/0005930_sass.js b/pool/shard000/JavaScript/0005930_sass.js new file mode 100644 index 0000000000000000000000000000000000000000..883be1405ab50260b6450416d4b396dfc7b1f0bb --- /dev/null +++ b/pool/shard000/JavaScript/0005930_sass.js @@ -0,0 +1,53 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. + * + * ***** END LICENSE BLOCK ***** */ + +define(function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var SassHighlightRules = require("./sass_highlight_rules").SassHighlightRules; +var FoldMode = require("./folding/coffee").FoldMode; + +var Mode = function() { + this.HighlightRules = SassHighlightRules; + this.foldingRules = new FoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + this.lineCommentStart = "//"; + this.$id = "ace/mode/sass"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); diff --git a/pool/shard000/JavaScript/0005931_routeManager.spec.js b/pool/shard000/JavaScript/0005931_routeManager.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6436f2d6c924b3d5d73f2d284d23b2d2ed98552e --- /dev/null +++ b/pool/shard000/JavaScript/0005931_routeManager.spec.js @@ -0,0 +1,203 @@ +const {RouteManager} = require('../app/routeManager') +const {it} = require('jasmine-promise-wrapper') + +let mockProject +let querier + +beforeEach(() => { + querier = {} + mockProject = { + _project: { + renderers: { + testHandler1: { + render: jasmine.createSpy('testHandler1render', async () => ({body: 'body'})).and.callThrough(), + urlList: jasmine.createSpy('testHandler1urlList', () => [ + { + data: 'data@th1', + url: '/url-th1' + } + ]).and.callThrough() + }, + testHandler2: { + render: jasmine.createSpy('testHandler2render', async () => ({body: 'body'})).and.callThrough(), + urlList: jasmine.createSpy('testHandler2urlList', () => [ + { + data: 'data@th2', + url: '/url-th2' + } + ]).and.callThrough() + } + } + }, + querier: jasmine.createSpy('querier', () => querier).and.callThrough() + } +}) + +describe('RouteManager', () => { + describe('handledUrls', () => { + it('returns handled url list', async () => { + // add some duplicate urls to be able to test the feature + mockProject._project.renderers.testHandler1.urlList = jasmine.createSpy('testHandler1urlList', () => [ + { + data: 'data@th1', + url: '/url-th1' + }, + {url: '/duplicateUrl'} + ]).and.callThrough() + + // add some duplicate urls to be able to test the feature + mockProject._project.renderers.testHandler2.urlList = jasmine.createSpy('testHandler1urlList', () => [ + { + data: 'data@th2', + url: '/url-th2' + }, + {url: '/duplicateUrl'} + ]).and.callThrough() + + const routeManager = new RouteManager({project: mockProject}) + const output = await routeManager.handledUrls() + + expect(mockProject.querier).toHaveBeenCalledTimes(2) + + expect(Object.keys(output.duplicates).length).toEqual(1) + expect(output.duplicates['/duplicateUrl']).toEqual({handler: ['testHandler2', 'testHandler1']}) + expect(output.urls.length).toEqual(3) + expect(output.urls).toContain({ + data: 'data@th2', + handler: 'testHandler2', + url: '/url-th2' + }) + }) + }) + + describe('handle', () => { + it('handles a url', async () => { + const routeManager = new RouteManager({project: mockProject}) + spyOn(routeManager, 'handledUrls').and.callThrough() + + const output = await routeManager.handle({url: '/url-th1'}) + expect(output.body).toEqual('body') + + expect(routeManager.handledUrls).toHaveBeenCalledTimes(1) + expect(mockProject._project.renderers.testHandler1.render).toHaveBeenCalledTimes(1) + expect(mockProject._project.renderers.testHandler1.render).toHaveBeenCalledWith({ + data: 'data@th1', + querier, + url: '/url-th1' + }) + }) + + it('throws an error if a url is handled by more than one handler', async () => { + const routeManager = new RouteManager({project: mockProject}) + const duplicates = {'/duplicate': {handler: ['testHandler']}} + routeManager.handledUrls = async () => ({ + duplicates, + urls: [ + { + handler: 'testHandler2', + url: '/duplicate' + } + ] + }) + const errorTextSpy = spyOn(RouteManager, 'generateDuplicateUrlErrorText').and.returnValue('text') + + try { + await routeManager.handle({url: '/duplicate'}) + fail('should not get here') + } catch (e) { + expect(e).toEqual(jasmine.any(Error)) + expect(e.message).toEqual('text') + expect(errorTextSpy).toHaveBeenCalledTimes(1) + expect(errorTextSpy).toHaveBeenCalledWith(duplicates) + } + }) + + it('throws an if url is not handled (aka. 404)', async () => { + const routeManager = new RouteManager({project: mockProject}) + routeManager.handledUrls = async () => ({ + duplicates: {}, + urls: [ + { + handler: 'testHandler', + url: '/not-tested-url' + } + ] + }) + + try { + await routeManager.handle({url: '/404'}) + fail('should not get here') + } catch (e) { + expect(e).toEqual(jasmine.any(Error)) + expect(e.message).toEqual('404') + } + }) + }) + + describe('handleAll', () => { + it('handles all urls one by and and calls a function for each one of them', async () => { + const routeManager = new RouteManager({project: mockProject}) + routeManager._handledUrlsPerHandler = async () => ({ + testHandler1: [ + { + data: 'data@h1u1', + url: '/h1u1' + }, + { + data: 'data@h1u2', + url: '/h1u2' + } + ], + testHandler2: [ + { + data: 'data@h2u1', + url: '/h2u1' + }, + { + data: 'data@h2u2', + url: '/h2u2' + } + ] + }) + + const urlProcessFn = jasmine.createSpy('urlProcessFn', async () => '').and.callThrough() + await routeManager.handleAll({urlProcessFn}) + + expect(mockProject._project.renderers.testHandler1.render).toHaveBeenCalledTimes(2) + expect(mockProject._project.renderers.testHandler1.render).toHaveBeenCalledWith({ + data: 'data@h1u1', + querier, + url: '/h1u1' + }) + expect(mockProject._project.renderers.testHandler1.render).toHaveBeenCalledWith({ + data: 'data@h1u2', + querier, + url: '/h1u2' + }) + + expect(mockProject._project.renderers.testHandler2.render).toHaveBeenCalledTimes(2) + expect(mockProject._project.renderers.testHandler2.render).toHaveBeenCalledWith({ + data: 'data@h2u1', + querier, + url: '/h2u1' + }) + expect(mockProject._project.renderers.testHandler2.render).toHaveBeenCalledWith({ + data: 'data@h2u2', + querier, + url: '/h2u2' + }) + }) + }) + + describe('generateDuplicateUrlErrorText', () => { + it('generates a nice text that complains', () => { + const duplicates = { + '/url1': {handler: ['h1', 'h2']}, + '/url2': {handler: ['h2', 'h3']} + } + const msg = RouteManager.generateDuplicateUrlErrorText(duplicates) + expect(msg).toContain('/url1 is handled by h1, h2') + expect(msg).toContain('/url2 is handled by h2, h3') + }) + }) +}) diff --git a/pool/shard000/JavaScript/0005932_history.js b/pool/shard000/JavaScript/0005932_history.js new file mode 100644 index 0000000000000000000000000000000000000000..b4f90810412f270ed6ceddbd0683a95af5da4e5d --- /dev/null +++ b/pool/shard000/JavaScript/0005932_history.js @@ -0,0 +1,55 @@ +import axios, { parseCursor } from '@/base/api/axios' + +export default { + async get (id) { + return convert((await axios.get(`/api/history/${id}/`)).data) + }, + + async list (filter) { + const response = (await axios.get('/api/history/', { params: filter })).data + return { + ...response, + next: parseCursor(response.next), + results: convert(response.results), + } + }, + + async listMore (cursor) { + const response = (await axios.get(cursor)).data + return { + ...response, + next: parseCursor(response.next), + prev: parseCursor(response.prev), + results: convert(response.results), + } + }, +} + +export function convert (val) { + if (Array.isArray(val)) { + return val.map(convert) + } + else { + const date = new Date(val.date) + let payload = val.payload + if (payload) { + // convert some known payload dates + const dates = {}; + ['date', 'startDate', 'invitedAt', 'feedbackDue'].forEach(k => { + if (payload[k]) { + if (Array.isArray(payload[k])) { + dates[k] = payload[k].map(d => new Date(d)) + } + else { + dates[k] = new Date(payload[k]) + } + } + }) + payload = { + ...payload, + ...dates, + } + } + return { ...val, date, payload } + } +} diff --git a/pool/shard000/JavaScript/0005937_remove_empty_nodes.js b/pool/shard000/JavaScript/0005937_remove_empty_nodes.js new file mode 100644 index 0000000000000000000000000000000000000000..81d664e8f98b8f236405f87cd4663c5a594756b6 --- /dev/null +++ b/pool/shard000/JavaScript/0005937_remove_empty_nodes.js @@ -0,0 +1,36 @@ +/** + * Checks for nodes with no text inside and removes them + * + * @param {Element} node The element in which to cleanup + * @example + * wysihtml5.dom.removeEmptyNodes(element); + */ + +import { nodeList } from "../dom/node_list"; + +var removeEmptyNodes = function(node) { + var element = node.cloneNode(true); + var nodes = nodeList.toArray(element.childNodes); + for (var index = 0; index < nodes.length; index++) { + var node = nodes[index]; + if (node) { + var nodeContainsImage = node.nodeName == "IMG" || (node.nodeType == Node.ELEMENT_NODE && node.querySelector("img")); + var nodeHasTextContent = (node.textContent || "").trim(); + if (!nodeContainsImage && !nodeHasTextContent) { + var nodeContainsLineBreak = node.nodeName == "BR" || (node.nodeType == Node.ELEMENT_NODE && node.querySelector("br")); + + if (nodeContainsLineBreak) { + var totalLineBreaks = node.nodeType == Node.ELEMENT_NODE ? node.querySelectorAll("br").length : 1; + for (var lineBreakIndex = 0; lineBreakIndex < totalLineBreaks; lineBreakIndex++) { + element.insertBefore(document.createElement("br"), node); + } + } + + element.removeChild(node); + } + } + }; + return element; +}; + +export { removeEmptyNodes }; diff --git a/pool/shard000/JavaScript/0005938_dbLookup.js b/pool/shard000/JavaScript/0005938_dbLookup.js new file mode 100644 index 0000000000000000000000000000000000000000..a930e7f79f4aa0168b79f7d4d7c29b2980facfd0 --- /dev/null +++ b/pool/shard000/JavaScript/0005938_dbLookup.js @@ -0,0 +1,65 @@ +/* +This file is part of WebNES. + +WebNES 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. + +WebNES 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 WebNES. If not, see . +*/ + +this.Nes = this.Nes || {}; + +"use strict"; + + +var calculateSha1 = function( binaryArray, startIndex ) { + + try { + startIndex = startIndex || 0; + var r = new Rusha( binaryArray.length - startIndex ); + // Using a subarray doesn't work. Need to copy contents into a new array (bit shit but it works) + // var sha1 = r.digestFromArrayBuffer( binaryArray.subarray( startIndex ).buffer ).toUpperCase(); + var buf = []; + for ( var i=startIndex; i= 0) { + jQuery(this).addClass('need'); + } + else { + jQuery(this).removeClass('need'); + } +} + +function progo_set_shipping_country(html_form_id, form_id){ + var shipping_region = ''; + country = jQuery(("div#"+html_form_id+" select[class=current_country]")).val(); + + if(country == 'undefined'){ + country = jQuery("select[title='billingcountry']").val(); + } + + region = jQuery(("div#"+html_form_id+" select[class=current_region]")).val(); + if(/[\d]{1,}/.test(region)) { + shipping_region = "&shipping_region="+region; + } + + form_values = { + wpsc_ajax_action: "change_tax", + form_id: form_id, + shipping_country: country, + shipping_region: region + } + + jQuery.post( 'index.php', form_values, function(returned_data) { + eval(returned_data); + jQuery('.statelabel').each(function() { + if(jQuery(this).next().html() == '') { + jQuery(this).hide(); + } else { + jQuery(this).show();//.parents().show(); + if(jQuery(this).parent().next().hasClass('zip')) { + jQuery(this).next().children().css('width','54px'); + } + } + }); + }); + +} + +function progo_set_billing_country(html_form_id, form_id){ + var billing_region = ''; + country = jQuery(("div#"+html_form_id+" select[class=current_country]")).val(); + region = jQuery(("div#"+html_form_id+" select[class=current_region]")).val(); + if(/[\d]{1,}/.test(region)) { + billing_region = "&billing_region="+region; + } + + form_values = "wpsc_ajax_action=change_tax&form_id="+form_id+"&billing_country="+country+billing_region; + jQuery.post( 'index.php', form_values, function(returned_data) { + eval(returned_data); + jQuery('.statelabel').each(function() { + if(jQuery(this).next().html() == '') { + jQuery(this).hide(); + } else { + jQuery(this).show();//.parents().show(); + if(jQuery(this).parent().next().hasClass('zip')) { + jQuery(this).next().children().css('width','54px'); + } + } + }); + }); +} + +function progo_selectcheck( id, disabled ) { + var wpsc_checkout_table = jQuery('#region_select_'+ id).parents('.wpsc_checkout_table'); + + if(disabled == true ) { + wpsc_checkout_table.find('input.billing_region').attr('disabled', 'disabled'); + wpsc_checkout_table.find('input.shipping_region').attr('disabled', 'disabled'); + wpsc_checkout_table.find('.billing_region').parent().hide(); + wpsc_checkout_table.find('.shipping_region').parent().hide(); + } else { + wpsc_checkout_table.find('input.billing_region').removeAttr('disabled'); + wpsc_checkout_table.find('input.shipping_region').removeAttr('disabled'); + wpsc_checkout_table.find('.billing_region').parent().show(); + wpsc_checkout_table.find('.shipping_region').parent().show(); + } + var countrysel = jQuery('#wpsc_checkout_form_'+id); + if( countrysel.children().size() < 2 ) { + countrysel.hide().parent().prev().prev().hide(); + } +} + +jQuery(function($) { + $('#edit').change(function() { + $('#billing,#shipping').toggle(); + }); + $('form.pform input.req').bind('blur.progo',checkThisField); + $('form.pform select.req').bind('change.progo',checkThisField); + $('form.pform').bind('submit',checkReq); + $('.pform .current_country').trigger('change'); + + var editchx = $('#side .editchecks input:checkbox'); + if(editchx.size() > 0) { + editchx.click(function() { + var check = $(this).attr('checked'); + var show = 'payment'; + if(check) { + show = $(this).attr('name') == 'editbilling' ? 'billing' : 'shipping'; + } + $('#'+show).show().siblings('fieldset').hide(); + $(this).parent().siblings('label').children('input:checkbox').attr('checked',false); + }); + } + + if($('#features-flash').size() > 0) { + $('#features-flash').prev().find('a').each(function(i) { + $(this).click(function() { + $(this).parent().addClass('ison').siblings('.ison').removeClass('ison'); + var pname = $(this).attr('href'); + pname = pname.substr(pname.lastIndexOf('#')+1); + var flashvars = {}; + flashvars.productName = pname; + var params = {}; + params.menu = "false"; + params.wmode = "transparent"; + var attributes = {}; + swfobject.embedSWF(jacuzzi_swfpath, "features-flash", "275", "330", "9.0.0", false, flashvars, params, attributes); + return false; + }); + if(i==0) { + $(this).click(); + } + }); + } + + Cufon.replace('#slogan, #bodycontent h2, #bodycontent h3, #arrow', { + fontFamily: 'GillSans' + }); + Cufon.replace('#toparr', { + fontFamily: 'GillSans', + color: '-linear-gradient(#ffd243, #e8b525' + }); + Cufon.now(); + + $('#requestform .txt:eq(0)').focus(); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005942_test.cli.js b/pool/shard000/JavaScript/0005942_test.cli.js new file mode 100644 index 0000000000000000000000000000000000000000..a4afe40a345c7b00c399d584c3d3efc13df652da --- /dev/null +++ b/pool/shard000/JavaScript/0005942_test.cli.js @@ -0,0 +1,168 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var resolve = require( 'path' ).resolve; +var exec = require( 'child_process' ).exec; +var tape = require( 'tape' ); +var IS_BROWSER = require( '@stdlib/assert/is-browser' ); +var IS_WINDOWS = require( '@stdlib/assert/is-windows' ); +var EXEC_PATH = require( '@stdlib/process/exec-path' ); +var readFileSync = require( '@stdlib/fs/read-file' ).sync; + + +// VARIABLES // + +var fpath = resolve( __dirname, '..', 'bin', 'cli' ); +var opts = { + 'skip': IS_BROWSER || IS_WINDOWS +}; + + +// FIXTURES // + +var PKG_VERSION = require( './../package.json' ).version; + + +// TESTS // + +tape( 'command-line interface', function test( t ) { + t.ok( true, __filename ); + t.end(); +}); + +tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) { + var expected; + var cmd; + + expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), { + 'encoding': 'utf8' + }); + cmd = [ + EXEC_PATH, + fpath, + '--help' + ]; + + exec( cmd.join( ' ' ), done ); + + function done( error, stdout, stderr ) { + if ( error ) { + t.fail( error.message ); + } else { + t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' ); + t.strictEqual( stderr.toString(), expected+'\n', 'expected value' ); + } + t.end(); + } +}); + +tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) { + var expected; + var cmd; + + expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), { + 'encoding': 'utf8' + }); + cmd = [ + EXEC_PATH, + fpath, + '-h' + ]; + + exec( cmd.join( ' ' ), done ); + + function done( error, stdout, stderr ) { + if ( error ) { + t.fail( error.message ); + } else { + t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' ); + t.strictEqual( stderr.toString(), expected+'\n', 'expected value' ); + } + t.end(); + } +}); + +tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) { + var cmd = [ + EXEC_PATH, + fpath, + '--version' + ]; + + exec( cmd.join( ' ' ), done ); + + function done( error, stdout, stderr ) { + if ( error ) { + t.fail( error.message ); + } else { + t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' ); + t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' ); + } + t.end(); + } +}); + +tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) { + var cmd = [ + EXEC_PATH, + fpath, + '-V' + ]; + + exec( cmd.join( ' ' ), done ); + + function done( error, stdout, stderr ) { + if ( error ) { + t.fail( error.message ); + } else { + t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' ); + t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' ); + } + t.end(); + } +}); + +tape( 'the command-line interface prints the mapping of US state names to state capitals', opts, function test( t ) { + var expected; + var cmd; + + cmd = [ + EXEC_PATH, + fpath + ]; + + expected = readFileSync( resolve( __dirname, '..', 'data', 'data.csv' ) ); + + exec( cmd.join( ' ' ), done ); + + function done( error, stdout, stderr ) { + if ( error ) { + t.fail( error.message ); + } else { + stdout = stdout.toString(); + expected = expected.toString(); + t.strictEqual( stdout, expected, 'prints US state names and state capitals' ); + t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' ); + } + t.end(); + } +}); diff --git a/pool/shard000/JavaScript/0005946_main.js b/pool/shard000/JavaScript/0005946_main.js new file mode 100644 index 0000000000000000000000000000000000000000..eb7464dfa50e3567c353562f71661df1d450b54f --- /dev/null +++ b/pool/shard000/JavaScript/0005946_main.js @@ -0,0 +1,44 @@ +$(document).ready(function(){ + var cellWidth = 20; + var cellHeight = 30; + var mainSeqData; + var mainData; + var baseColors; + function ajax(url, func){ + $.ajax({ url: url, dataType: 'json', async: false, + success: function(ct){ func(ct); } }); + } + + function ajaxAsync(url, func){ + $.ajax({ url: url, dataType: 'json', async: true, + success: function(ct){ func(ct); } }); + } + + var mainSeqData, mainData; + var baseColors = {}; + /*baseColors['A'] = "#ff8787"; + baseColors['G'] = "#ffffaf"; + baseColors['C'] = "#afffaf"; + baseColors['T'] = "#87afff";*/ + ajax('exampleSeqData.json', function(msd){ mainSeqData = msd; }); + ajax('exampleMainData.json', function(md){ mainData = md; }); + ajax('baseColors.json', function(bc){ baseColors = bc; }); + + + var SeqViewer = new SeqView("canvasDiv1", mainSeqData["seqs"], mainData, cellWidth, cellHeight, baseColors); + + function init(){ + $(window).bind("resize", function(){ + SeqViewer.updateCanvas(); + SeqViewer.setUpSliders(); + SeqViewer.paint(); + }); + SeqViewer.setUp(); + SeqViewer.paint(); + } + init(); + + + + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005947_view_document_default.js b/pool/shard000/JavaScript/0005947_view_document_default.js new file mode 100644 index 0000000000000000000000000000000000000000..1875f1bbd0770a2385d87d895b4f94ef7c858c3f --- /dev/null +++ b/pool/shard000/JavaScript/0005947_view_document_default.js @@ -0,0 +1,57 @@ +(function ($) { + + // here we go! + $.view_document_default = function (element, options) { + + // plugin's default options + var defaults = { + totalPages:0, + totalItem:10, + tour_id:0, + visiblePages:5, + tour_methor:'', + dialog_class:'dialog-form-price', + task:'' + + + } + + // current instance of the object + var plugin = this; + + // this will hold the merged default, and user-provided options + plugin.settings = {} + + var $element = $(element), // reference to the jQuery version of DOM element + element = element; // reference to the actual DOM element + // the "constructor" method that gets called when the object is created + plugin.init = function () { + plugin.settings = $.extend({}, defaults, options); + $('.buid-information').insertBefore($('.vm_toolbar')); + + + } + + plugin.init(); + + } + + // add the plugin to the jQuery.fn object + $.fn.view_document_default = function (options) { + + // iterate through the DOM elements we are attaching the plugin to + return this.each(function () { + // if plugin has not already been attached to the element + if (undefined == $(this).data('view_document_default')) { + var plugin = new $.view_document_default(this, options); + $(this).data('view_document_default', plugin); + + } + + }); + + } + +})(jQuery); + + diff --git a/pool/shard000/JavaScript/0005954_app-replay.js b/pool/shard000/JavaScript/0005954_app-replay.js new file mode 100644 index 0000000000000000000000000000000000000000..fe814248147894fded05ffc6d51925e74f7c3817 --- /dev/null +++ b/pool/shard000/JavaScript/0005954_app-replay.js @@ -0,0 +1,282 @@ +import config from './config'; +import SlacController from './slac-controller'; +import ReplayRenderer from './view/replay-renderer'; +import { degreeToNormalisedHeading } from './util/motion'; + +/** + * Application object for replaying recorded data + * @type {Object} + */ +window.SlacApp = { + + bleEventIteration: 0, + motionEventIteration: 0, + + controller: undefined, + renderer: undefined, + + bleInterval: undefined, + motionInterval: undefined, + + lastUpdate: 0, + + startMotionTimestamp: 0, + currentMotionTimestamp: 0, + + startHeading: 0, + + distPlots: {}, + + errorPlot: {}, + + error: {avg: 0}, + + initialize() { + + //Reset all the timers and counters so that we can reuse this object + //on multiple runs + this.bleEventIteration = 0; + this.motionEventIteration = 0; + + this.lastUpdate = 0; + + this.startMotionTimestamp = 0; + this.currentMotionTimestamp = 0; + + this.startHeading = 0; + + this.error = {avg: 0}; + + if (typeof SlacJsData === 'undefined') { + console.error('No replay data found'); + } + + if (typeof SlacJsLandmarkPositions === 'undefined') { + console.error('No true landmark positions found'); + } + + if (typeof SlacJsStartingPosition === 'undefined') { + console.error('No starting position found'); + } + + if (config.replay.showVisualisation) + { + //Create a renderer for the canvas view + this.renderer = new ReplayRenderer('slacjs-map', SlacJsLandmarkPositions); + } + + //Create plot for the errors + //Only when we actually show the progress of the algorithm + if (config.replay.delayAlgorithm) { + this._initErrorPlot(); + } + }, + + start() { + + //Store the current heading + this.startHeading = SlacJsData.motion[0].heading; + + //Update the initial pose with the true starting position + config.particles.user.defaultPose.x = SlacJsStartingPosition.x; + config.particles.user.defaultPose.y = SlacJsStartingPosition.y; + + //Create a new controller + this.controller = new SlacController(config); + + //We hack the controller to update the BLE observations before we run the internal update function + this.controller.pedometer.onStep(() => { + + this._updateBleObservations(this.currentMotionTimestamp); + this.controller._update(); + + //Take the last observations and output the measurement error + //for the best particle + const user = this.controller.particleSet.userEstimate(); + + //Show the current error + this._calculateLandmarkError(); + }); + + //Add a listener to the sensor of the controller + this.controller.sensor.setEventListener((uid, name, event, msg) => { + + if (event != 'update') { + console.log(`[SLCAjs/sensor] ${uid} ${event}, message: "${msg}"`); + } + }); + + this.controller.start(); + + //Bind renderer to controller + this.controller.onUpdate((particles) => { + + if (config.replay.showVisualisation) + { + //Update the canvas + this.renderer.render(particles); + } + }); + + //Save the start time, we use this to determine which BLE events to send + this.lastUpdate = new Date().getTime(); + + //Run the algorithm real time or as fast as possible + if (config.replay.delayAlgorithm) { + this.motionInterval = setInterval(() => this._processMotionObservation(), config.replay.updateRate); + } + else { + + let hasNext = true; + + while (hasNext) { + hasNext = this._processMotionObservation() + } + } + }, + + /** + * Utility function that returns the true distance to a beacon given a x,y position + * @param {Number} x Location of user + * @param {Number} y Location of user + * @param {String} name Beacon name + * @return {Number} Distance + */ + distanceToBeacon(x, y, name) { + + const beacon = SlacJsLandmarkPositions[name]; + + const dx = x - beacon.x; + const dy = y - beacon.y; + + return Math.sqrt((dx * dx) + (dy * dy)); + }, + + /** + * Simulate a motion event + * @return {Boolean} + */ + _processMotionObservation() { + + if (this.motionEventIteration >= SlacJsData.motion.length) { + clearInterval(this.motionInterval); + + console.log('[SLACjs] Motion events finished'); + return false; + } + + const data = SlacJsData.motion[this.motionEventIteration]; + + if (this.startMotionTimestamp === 0) { + this.startMotionTimestamp = data.timestamp; + } + + this.controller.addMotionObservation( + data.x, data.y, data.z, + degreeToNormalisedHeading(data.heading, this.startHeading) + ); + + this.currentMotionTimestamp = data.timestamp; + this.motionEventIteration++; + + return true; + }, + + /** + * Process all BLE observations until timestamp + * @param {Number} timestamp + * @return {void} + */ + _updateBleObservations(timestamp) { + + let current; + + do { + current = SlacJsData.bluetooth[this.bleEventIteration]; + + this.bleEventIteration++; + + this.controller.addDeviceObservation(current.address, current.rssi, current.name); + } + while (current.timestamp <= timestamp); + }, + + /** + * Calculate the landmark error and show on screen + * @return {[type]} [description] + */ + _calculateLandmarkError() { + + const distArr = []; + let landmarkErrorsStr = ''; + + this.controller.particleSet.bestParticle().landmarks.forEach((l) => { + + const trueL = SlacJsLandmarkPositions[l.name]; + + const dist = Math.sqrt(Math.pow(trueL.x - l.x, 2) + Math.pow(trueL.y - l.y, 2)); + + distArr.push(dist); + this.error[l.name] = dist; + + landmarkErrorsStr += l.name + ': ' + dist + '
        '; + }); + + if (distArr.length > 0) { + $('.landmark-individual-error').html(landmarkErrorsStr); + + const avg = distArr.reduce(function(total, d) { return total + d; }, 0) / distArr.length; + + //Only update the plot when we actually show the progress of the algorithm + if (config.replay.delayAlgorithm) { + this.errorPlot.data.push(avg); + + this.errorPlot.plot.series[0].setData(this.errorPlot.data); + } + + $('.landmark-error').html(avg); + this.error.avg = avg; + } + }, + + /** + * Initialize the error plot + * @return {void} + */ + _initErrorPlot() { + + this.errorPlot = { + + data: [], + + plot: new Highcharts.Chart({ + chart: { + renderTo: 'error-plot' + }, + title: { + text: 'Error plot' + }, + xAxis: { + title: { + text: 'Time' + } + }, + yAxis: [ + { + title: { + text: 'Error' + }, + max: 4, + min: 1 + } + ], + series: [ + { + name: 'Error', + type: 'line' + } + ] + }) + } + } +}; diff --git a/pool/shard000/JavaScript/0005955_mario.js b/pool/shard000/JavaScript/0005955_mario.js new file mode 100644 index 0000000000000000000000000000000000000000..bad0fc3b089a7758c995270dd282c00116e2e923 --- /dev/null +++ b/pool/shard000/JavaScript/0005955_mario.js @@ -0,0 +1,55 @@ + +var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); + +function preload() { + + game.load.tilemap('mario', 'assets/tilemaps/maps/super_mario.json', null, Phaser.Tilemap.TILED_JSON); + game.load.image('tiles', 'assets/tilemaps/tiles/super_mario.png'); + game.load.image('player', 'assets/sprites/phaser-dude.png'); + +} + +var map; +var layer; +var p; +var cursors; + +function create() { + + game.stage.backgroundColor = '#787878'; + + map = game.add.tilemap('mario'); + + map.addTilesetImage('SuperMarioBros-World1-1', 'tiles'); + + layer = map.createLayer('World1'); + + layer.resizeWorld(); + + layer.wrap = true; + + cursors = game.input.keyboard.createCursorKeys(); + +} + +function update() { + + if (cursors.left.isDown) + { + game.camera.x -= 8; + } + else if (cursors.right.isDown) + { + game.camera.x += 8; + } + + if (cursors.up.isDown) + { + game.camera.y -= 8; + } + else if (cursors.down.isDown) + { + game.camera.y += 8; + } + +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005961_test_helper.js b/pool/shard000/JavaScript/0005961_test_helper.js new file mode 100644 index 0000000000000000000000000000000000000000..d61c089f269746957a0cf828c4291bfa05d6c966 --- /dev/null +++ b/pool/shard000/JavaScript/0005961_test_helper.js @@ -0,0 +1,63 @@ +//= require konacha_config +//= require sinon +//= require application + +// Prevent the router from manipulating the browser's URL. +App.Router.reopen({location: 'none'}); + +//**** Utility methods (for tests only - not for use in apps) *** + +var lookupStore = function() { + return App.__container__.lookup('store:main'); +} + +var lookupRouter = function() { + return App.__container__.lookup('router:main'); +} + +var appendView = function(view) { + Ember.run(function() { + view.append('#konacha'); + }); +}; + +//**** Global before / after *** + +// Sinon fake server +var server; + +// Stub out Konacha.reset() +Konacha.reset = Ember.K; + +beforeEach(function(done) { + // Fake XHR + server = sinon.fakeServer.create(); + + // Prevent automatic scheduling of runloops. For tests, we + // want to have complete control of runloops. + Ember.testing = true; + + Ember.run(function() { + // Advance App readiness, which was deferred when the app + // was created. + // + // This needs to be done here, after each iframe has been setup, + // instead of in a global `before`. + App.advanceReadiness(); + + // When App readiness promise resolves, setup is complete + App.then(function() { + done(); + }); + }); +}); + +afterEach(function() { + // Reset App + Ember.run(function() { + App.reset(); + }); + + // Restore XHR + server.restore(); +}); diff --git a/pool/shard000/JavaScript/0005964_VisibilityTimeoutValue.js b/pool/shard000/JavaScript/0005964_VisibilityTimeoutValue.js new file mode 100644 index 0000000000000000000000000000000000000000..8ef7bbbf8dfccd5bcc2b32dc44b4c1a828a530f4 --- /dev/null +++ b/pool/shard000/JavaScript/0005964_VisibilityTimeoutValue.js @@ -0,0 +1,41 @@ +'use strict'; + +const AError = require('./../../core/AzuriteError'), + Operations = require('./../../core/Constants').Operations.Queue, + ErrorCodes = require('./../../core/ErrorCodes'); + +/* + * Checks whether the visibility timeout value adheres to the specifications at + * https://docs.microsoft.com/en-us/rest/api/storageservices/update-message + * and https://docs.microsoft.com/en-us/rest/api/storageservices/get-messages + */ +class VisibilityTimeoutValue { + constructor() { + } + + validate({ request = undefined, operation = undefined, message = undefined }) { + if (operation === Operations.GET_MESSAGE) { + if (request.visibilityTimeout < 1 || request.visibilityTimeout > 60 * 60 * 24 * 7) { + throw new AError(ErrorCodes.OutOfRangeInput); + } + } + else { + if (request.visibilityTimeout < 0 || request.visibilityTimeout > 60 * 60 * 24 * 7) { + throw new AError(ErrorCodes.OutOfRangeInput); + } + if (operation === Operations.PUT_MESSAGE) { + if (request.now + request.visibilityTimeout > request.now + request.messageTtl) { + throw new AError(ErrorCodes.OutOfRangeInput); + } + } + if (operation === Operations.UPDATE_MESSAGE) { + if (request.now + request.visibilityTimeout > message.expirationTime) { + throw new AError(ErrorCodes.OutOfRangeInput); + } + } + + } + } +} + +module.exports = new VisibilityTimeoutValue(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005966_composition.js b/pool/shard000/JavaScript/0005966_composition.js new file mode 100644 index 0000000000000000000000000000000000000000..329b017eaa44fd2d10c12191f7b375c47b812e1c --- /dev/null +++ b/pool/shard000/JavaScript/0005966_composition.js @@ -0,0 +1,74 @@ +'use strict'; + +module.exports = function (math) { + var util = require('../../util/index'), + + BigNumber = math.type.BigNumber, + + isNumber = util.number.isNumber, + isInteger = util.number.isInteger; + + /** + * The composition counts of n into k parts. + * + * composition only takes integer arguments. + * The following condition must be enforced: k <= n. + * + * Syntax: + * + * math.composition(n, k) + * + * Examples: + * + * math.composition(5, 3); // returns 6 + * + * See also: + * + * combinations + * + * @param {Number | BigNumber} n Total number of objects in the set + * @param {Number | BigNumber} k Number of objects in the subset + * @return {Number | BigNumber} Returns the composition counts of n into k parts. + */ + math.composition = function composition (n, k) { + var arity = arguments.length; + if (arity != 2) { + throw new math.error.ArgumentsError('composition', arguments.length, 2); + } + + if ((isNumber(n) && isNumber(k)) || n instanceof BigNumber) { + + if (!isInteger(n) || n < 0 || !isInteger(k) || k < 0) { + throw new TypeError('Positive integer value expected in function composition'); + } + else if (k > n) { + throw new TypeError('k must be less than or equal to n'); + } + return math.combinations(n-1, k-1); + } + else if (n instanceof BigNumber) { + // make sure k is a BigNumber as well + // not all numbers can be converted to BigNumber + k = BigNumber.convert(k); + + if (!(k instanceof BigNumber) || !isPositiveInteger(n) || !isPositiveInteger(k)) { + throw new TypeError('Positive integer value expected in function composition'); + } + if (k.gt(n)) { + throw new TypeError('k must be less than n in function composition'); + } + return math.combinations(n.minus(1), k.minus(1)); + } else { + throw new TypeError('Integer values are expected in composition') + } + }; + + /** + * Test whether BigNumber n is a positive integer + * @param {BigNumber} n + * @returns {boolean} isPositiveInteger + */ + var isPositiveInteger = function(n) { + return n.isInteger() && n.gte(0); + }; + }; diff --git a/pool/shard000/JavaScript/0005968_products.js b/pool/shard000/JavaScript/0005968_products.js new file mode 100644 index 0000000000000000000000000000000000000000..c47df18ac7cefa5f9214edbc56145dae6b09296c --- /dev/null +++ b/pool/shard000/JavaScript/0005968_products.js @@ -0,0 +1,81 @@ +var express = require('express') + , Product = require('mongoose').model('Product') + , utils = require('custom_utils') + , errors = require('shared').errors; +var app = module.exports = express(); + +// Find all +app.get('/', function(req, res) { + Product.find({}, function(err, data) { + if( err || data == undefined) { + res.send( (err || errors.DATA_NOT_FOUND).toString() ); + } else { + res.json( data ); + } + }) +}); + +// Create a new product +app.post('/', utils.requiresAuthHeaders, function(req, res) { + if( !req.body ) { + return res.send(400, 'No data'); + } + + var product = new Product(req.body); + product.save(function(err, data) { + if( err || !data ) { + res.send(500, (err || errors.UNKNOWN_ERROR).toString() ); + } else { + res.json(201, data); + } + }) +}); + +// Find one by id or name +app.get('/:identifier', function(req, res) { + Product.findByIdOrName( req.param('identifier') , function respond(err, product) { + if( err || !product ) { + res.send(404, (err || errors.INVALID_CREDENTIALS).toString() ); + } else { + res.json(product); + } + }); +}); + +// Delete a product +app.delete('/:identifier', utils.requiresAuthHeaders, function(req, res) { + + Product.findByIdOrName( req.param('identifier') , function respond(err, product) { + if( err || !product ) { + return res.send(404, (err || errors.INVALID_CREDENTIALS ).toString() ); + } + + Product.remove({ _id: product._id }, function(err, data) { + if( err || !data ) { + res.send(500, (err || errors.UNKNOWN_ERROR).toString() ) + } else { + res.send('Product removed'); + } + }) + }); + +}); + +// Updates a product +app.patch('/:identifier', utils.requiresAuthHeaders, function(req, res) { + + Product.findByIdOrName( req.param('identifier') , function respond(err, product) { + if( err || !product ) { + return res.send(404, (err || errors.INVALID_CREDENTIALS ).toString() ); + } + + Product.findOneAndUpdate({ _id : product._id }, req.body || {}, function(err, product) { + if( err || !product ) { + res.send(500, (err || errors.UNKNOWN_ERROR).toString() ) + } else { + res.json(product); + } + }) + }); + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005969_vue.js b/pool/shard000/JavaScript/0005969_vue.js new file mode 100644 index 0000000000000000000000000000000000000000..828ed3d871e07b4dbe9a050335dcf4843212c24f --- /dev/null +++ b/pool/shard000/JavaScript/0005969_vue.js @@ -0,0 +1,35 @@ +'use strict'; + +const _ = require('lodash'); +const Vue = require('vue/dist/vue.common.js'); +const Vuex = require('vuex'); +Vue.use(Vuex); + +const Enums = require('billund-enums'); +const StateEnums = Enums.state; + +/** + * 创建store + * + * @param {Object} config - 配置 + * @param {Array} widgets - 对应的重要组件 + * @return {Object} + */ +function createStore(config, widgets) { + const storeData = config.storeData || {}; + const storeConfig = config.storeConfig || {}; + + const modules = {}; + (widgets || []).forEach((widget) => { + modules[`${StateEnums.PREFIX_WIDGET_OWN_STATE_KEY}${widget.id}`] = {}; + }); + + return new Vuex.Store(_.extend({}, storeConfig, { + state: storeData, + modules + })); +} + +module.exports = { + createStore +}; diff --git a/pool/shard000/JavaScript/0005971_container.js b/pool/shard000/JavaScript/0005971_container.js new file mode 100644 index 0000000000000000000000000000000000000000..4080be6e66885ce359f921feda5b11cbe60baf4d --- /dev/null +++ b/pool/shard000/JavaScript/0005971_container.js @@ -0,0 +1,75 @@ +/* + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHOR 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. + */ + +'use strict'; + +var bunyan = require('bunyan'); + +module.exports = function(config, logger) { + logger = logger || bunyan.createLogger({name: 'azure-cs-container'}); + + var build = function build(mode, system, containerDef, out, callback) { + logger.info('building'); + out.stdout('building'); + callback(null); + }; + + var deploy = function deploy(mode, target, system, containerDef, container, out, callback) { + logger.info('deploying'); + out.stdout('deploying'); + callback(null); + }; + + var undeploy = function undeploy(mode, target, system, containerDef, container, out, callback) { + logger.info('undeploying'); + out.stdout('undeploying'); + callback(null); + }; + + var start = function start(mode, target, system, containerDef, container, out, callback) { + logger.info('starting'); + out.stdout('starting'); + callback(null); + }; + + var stop = function stop(mode, target, system, containerDef, container, out, callback) { + logger.info('stopping'); + out.stdout('stopping'); + callback(null); + }; + + var link = function link(mode, target, system, containerDef, container, out, callback) { + logger.info('linking'); + out.stdout('linking'); + callback(null); + }; + + var unlink = function unlink(mode, target, system, containerDef, container, out, callback) { + logger.info('unlinking'); + out.stdout('unlinking'); + callback(null); + }; + + return { + build: build, + deploy: deploy, + start: start, + stop: stop, + link: link, + unlink: unlink, + undeploy: undeploy, + add: deploy, + remove: undeploy + }; +}; diff --git a/pool/shard000/JavaScript/0005974_piratebay.js b/pool/shard000/JavaScript/0005974_piratebay.js new file mode 100644 index 0000000000000000000000000000000000000000..c27c9603a8f66277d7708caaabff3038acffa14a --- /dev/null +++ b/pool/shard000/JavaScript/0005974_piratebay.js @@ -0,0 +1,176 @@ +'use strict'; + +var urlModule = require('url'), + utils = require('./../common/utils'); + +/** + * Parses the size of a torrent. + * + * @param {String} str - Size data that was retrieved from the torrent site. + * + * @returns {Number} Size of the torrent in bytes if `str` was parsed successfully, otherwise null. + */ +function parseSize(str) { + var data = str.match(/(\d+(?:\.\d+)?).*\b(.{2}B).*/); + return utils.fileSizeToBytes(parseInt(data[1], 10), data[2]); +} + +/** + * Parses a date from the current year. + * + * @param {Array} dateThisYear - Data that was parsed from the regex. + * @param {String} dateThisYear[0] - Complete match - ignored. + * @param {String} dateThisYear[1] - Month. + * @param {String} dateThisYear[2] - Day. + * @param {String} dateThisYear[3] - Hour. + * @param {String} dateThisYear[4] - Minute. + * + * @returns {Date} Parsed date. + */ +function parseDateThisYear(dateThisYear) { + return new Date( + new Date().getFullYear(), + parseInt(dateThisYear[1], 10) - 1, + parseInt(dateThisYear[2], 10), + parseInt(dateThisYear[3], 10), + parseInt(dateThisYear[4], 10) + ); +} + +/** + * Parses a date from the last year. + * + * @param {Array} dateOtherYear - Data that was parsed from the regex. + * @param {String} dateOtherYear[0] - Complete match - ignored. + * @param {String} dateOtherYear[1] - Month. + * @param {String} dateOtherYear[2] - Day. + * @param {String} dateOtherYear[3] - Year. + * + * @returns {Date} Parsed date. + */ +function parseDateLastYear(dateOtherYear) { + return new Date( + parseInt(dateOtherYear[3], 10), + parseInt(dateOtherYear[1], 10) - 1, + parseInt(dateOtherYear[2], 10), + 0, + 0 + ); +} + +/** + * Parses a date from today. + * + * @param {Array} dateOtherYear - Data that was parsed from the regex. + * @param {String} dateOtherYear[0] - Complete match - ignored. + * @param {String} dateOtherYear[1] - Hours. + * @param {String} dateOtherYear[2] - Minutes. + * + * @returns {Date} Parsed date. + */ +function parseDateToday(dateToday) { + var date = new Date(); + date.setHours(parseInt(dateToday[1], 10)); + date.setMinutes(parseInt(dateToday[2], 10)); + date.setSeconds(0); + date.setMilliseconds(0); + + return date; +} + +/** + * Parses a date. + * + * @param {String} str - Date data that was retrieved from the torrent site. + * + * @returns {Date} Parsed date if parsed successfully, null otherwise. + */ +function parseDate(str) { + var dateThisYear = str.match(/(\d{2})-(\d{2}).*;(\d{2}):(\d{2})/), + dateOtherYear = str.match(/(\d{2})-(\d{2}).*;(\d{4})/), + dateToday = str.match(/Today.*;(\d{2}):(\d{2})/); + + if (dateThisYear !== null) { + return parseDateThisYear(dateThisYear); + } else if (dateOtherYear !== null) { + return parseDateLastYear(dateOtherYear); + } else if (dateToday !== null) { + return parseDateToday(dateToday); + } + + return null; +} + +/** + * Parser constructor. Throws an error if no `url` is provided. + * + * @param {String} url - Is used by the torrent-site index to build the search URL. + * @param {Bunyan.Log} log - Logger instance. + */ +module.exports = function (url, log) { + if (!url || !url.toString()) { + throw new Error('Must provide valid URL'); + } + + this.url = 'http://' + url + '/search/'; + + /** + * Parses the torrent data. + * + * @param {String} html - HTML response from the search. + * @param {Number} season - Season which was searched for. + * @param {Number} episode - Episode which was searched for. + * + * @returns {Object} Torrent information if parsing was successful, null otherwise. Properties: + * {String} name - Name of the torrent. + * {Number} season - Season of the torrent. + * {Number} episode - Episode of the torrent. + * {Number} seeders - Seeders of the torrent. + * {Number} leechers - Leechers of the torrent. + * {Number} size - Size in bytes of the torrent. + * {Date} uploadDate - Date when the torrent was uploaded. + * {String} link - Link to the torrent. + */ + this.parseTorrentData = function (html, season, episode) { + try { + var magnetRegexp = / size) { + rest = array.slice(size); + } + array_func(first); + if (rest) { + (function() { Utils.splitAndDefer(rest, size, array_func, final_func) }).defer(); + } + else { + final_func.defer(); + } + } +} diff --git a/pool/shard000/JavaScript/0005980_SavePaymentInput.js b/pool/shard000/JavaScript/0005980_SavePaymentInput.js new file mode 100644 index 0000000000000000000000000000000000000000..848ed9301d3f2ce04e678491952cc18072188c80 --- /dev/null +++ b/pool/shard000/JavaScript/0005980_SavePaymentInput.js @@ -0,0 +1,65 @@ +import renderer from "react-test-renderer"; +import { SavePaymentInput } from "../"; + +const defaultProps = { + saveName: () => {}, + savedAccount: {}, + schedule: { start: null, }, + shouldSaveState: true, + payment: { + type: "ach", + }, + transactionType: "default", +}; + +const generateComponent = (additionalProps = {}) => { + const newProps = { + ...defaultProps, + ...additionalProps, + }; + return ; +}; + +it("renders default `Bank Account` if ach", () => { + const result = renderer.create(generateComponent()); + expect(result).toMatchSnapshot(); +}); + +it("renders default `Credit Card` if not ach", () => { + const result = renderer.create(generateComponent({ + payment: { + type: "cc", + }, + })); + expect(result).toMatchSnapshot(); +}); + +it("does not render if should not save state", () => { + const result = renderer.create(generateComponent({ + shouldSaveState: false, + })); + expect(result).toMatchSnapshot(); +}); + +it("does not render if using saved account", () => { + const result = renderer.create(generateComponent({ + savedAccount: { + id: "1", + }, + })); + expect(result).toMatchSnapshot(); +}); + +it("does not render if guest checkout", () => { + const result = renderer.create(generateComponent({ + transactionType: "guest", + })); + expect(result).toMatchSnapshot(); +}); + +it("does not render if scheduling", () => { + const result = renderer.create(generateComponent({ + schedule: { start: "now" }, + })); + expect(result).toMatchSnapshot(); +}); diff --git a/pool/shard000/JavaScript/0005981_settings.js b/pool/shard000/JavaScript/0005981_settings.js new file mode 100644 index 0000000000000000000000000000000000000000..2670dad29b32f83990e5d91fce0bd38c9f1d0425 --- /dev/null +++ b/pool/shard000/JavaScript/0005981_settings.js @@ -0,0 +1,33 @@ + +'use strict'; + +angular.module('mean.admin').factory('Settings', ['$http', + function($http) { + var get = function(callback) { + // Temporary - probably it should to be resource based. + $http.get('/api/admin/settings').success(function(data, status, headers, config) { + callback({ + success: true, + settings: data + }); + }). + error(function(data, status, headers, config) { + callback({ + success: false + }); + }); + }; + var update = function(settings, callback) { + $http.put('/api/admin/settings', settings).success(function(data, status, headers, config) { + callback(data); + }). + error(function(data, status, headers, config) { + callback(data); + }); + }; + return { + get: get, + update: update + }; + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005983_20140816022612-add-wallets-v2.js b/pool/shard000/JavaScript/0005983_20140816022612-add-wallets-v2.js new file mode 100644 index 0000000000000000000000000000000000000000..8418d29f3f13d24b4dfff2e7c685c9314a195d46 --- /dev/null +++ b/pool/shard000/JavaScript/0005983_20140816022612-add-wallets-v2.js @@ -0,0 +1,32 @@ +var dbm = require('stex').dbMigrate; +var type = dbm.dataType; + +exports.up = function(db, callback) { + db.createTable('wallets_v2', { + // core columns + id: { type: 'int', primaryKey: true, autoIncrement: true }, + lockVersion: { type: 'int', notNull: true }, + createdAt: { type: type.DATE_TIME, notNull: true }, + updatedAt: { type: type.DATE_TIME, notNull: true }, + // update authorization + walletId: { type: type.STRING, length: "255", notNull: true }, + publicKey: { type: type.STRING, length: "255", notNull: true }, + // login columns + username: { type: type.STRING, length: "255", notNull: true }, + salt: { type: type.STRING, length: "255", notNull: true }, + kdfParams: { type: type.TEXT, notNull: true }, + totpKey: { type: type.STRING, length: "255" }, + // Data columns + mainData: { type: type.TEXT, length:16777216 }, + keychainData: { type: type.TEXT, length:16777216 } + + }, function() { + db.addIndex('wallets_v2', 'username_unique', ['username'], true, function() { + db.addIndex('wallets_v2', 'walletId', ['walletId'], false, callback); + }); + }); +}; + +exports.down = function(db, callback) { + db.dropTable('wallets_v2', callback); +}; diff --git a/pool/shard000/JavaScript/0005985_generic.js b/pool/shard000/JavaScript/0005985_generic.js new file mode 100644 index 0000000000000000000000000000000000000000..8c192f40fc615eab4204850cb325dbf65b6a9de3 --- /dev/null +++ b/pool/shard000/JavaScript/0005985_generic.js @@ -0,0 +1,80 @@ +var express = require('express'); +var router = express.Router(); +var _ = require('lodash'); +var Q = require('q'); + +// get all +router.get('/:dataType', function (req, res) { + var collection = req.db.get(req.params.dataType); + + collection.find({}, function (err, docs) { + res.send(docs); + }); +}); + +// get by id +router.get('/:dataType/:_id', function (req, res) { + var collection = req.db.get(req.params.dataType); + + collection.findById( + req.params._id, + function (err, doc) { + if (doc) { + res.send(doc); + } else { + res.sendStatus(404); + } + }); +}); + +// create +router.post('/:dataType', function (req, res) { + var collection = req.db.get(req.params.dataType); + + collection.insert( + req.body, + function (err, doc) { + if (err) throw err; + + // notify all connected sockets + req.io.emit(req.params.dataType, { action: 'created', item: doc }); + + res.sendStatus(200); + }); +}); + +// update +router.put('/:dataType/:_id', function (req, res) { + var collection = req.db.get(req.params.dataType); + + collection.findAndModify( + { _id: req.params._id }, + { $set: req.body }, + { 'new': true }, + function (err, doc) { + if (err) throw err; + + // notify all connected sockets + req.io.emit(req.params.dataType, { action: 'updated', item: doc }); + + res.sendStatus(200); + }); +}); + +// delete +router.delete('/:dataType/:_id', function (req, res) { + var collection = req.db.get(req.params.dataType); + + collection.remove( + { _id: req.params._id }, + function (err) { + if (err) throw err; + + // notify all connected sockets + req.io.emit(req.params.dataType, { action: 'deleted', _id: req.params._id }); + + res.sendStatus(200); + }); +}); + +module.exports = router; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0005986_index.test.js b/pool/shard000/JavaScript/0005986_index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..cd456ffbf98f0f9564ab1e21331ee6833aa5d949 --- /dev/null +++ b/pool/shard000/JavaScript/0005986_index.test.js @@ -0,0 +1,75 @@ +const sinon = require('sinon') +const CCTalkParser = require('../') + +describe('CCTalkParser', () => { + it('constructs', () => { + new CCTalkParser() + }) + it('emits data for a default length message', () => { + const data = Buffer.from([2, 0, 1, 254, 217]) + const spy = sinon.spy() + const parser = new CCTalkParser() + parser.on('data', spy) + parser.write(data) + assert.equal(spy.callCount, 1) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 0, 1, 254, 217])) + }) + + it('emits data for a 7 byte length message', () => { + const parser = new CCTalkParser() + const spy = sinon.spy() + parser.on('data', spy) + parser.write(Buffer.from([2, 2, 1, 254, 1, 1, 217])) + assert.equal(spy.callCount, 1) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217])) + }) + + it('parses multiple length messages', () => { + const parser = new CCTalkParser() + const spy = sinon.spy() + parser.on('data', spy) + parser.write(Buffer.from([2, 2, 1])) + parser.write(Buffer.from([254, 1, 1])) + parser.write(Buffer.from([217, 2])) + parser.write(Buffer.from([0, 1, 254, 217])) + assert.equal(spy.callCount, 2) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217])) + assert.deepEqual(spy.getCall(1).args[0], Buffer.from([2, 0, 1, 254, 217])) + }) + it('parses a long message', () => { + const parser = new CCTalkParser() + const spy = sinon.spy() + parser.on('data', spy) + parser.write(Buffer.from([2, 2, 1, 254, 1, 1, 217, 2, 0, 1, 254, 217, 2, 2, 1, 251, 1, 1, 217, 2, 2, 1, 252, 1, 1, 217, 2, 0, 1, 253, 217])) + assert.equal(spy.callCount, 5) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217])) + assert.deepEqual(spy.getCall(1).args[0], Buffer.from([2, 0, 1, 254, 217])) + assert.deepEqual(spy.getCall(2).args[0], Buffer.from([2, 2, 1, 251, 1, 1, 217])) + assert.deepEqual(spy.getCall(3).args[0], Buffer.from([2, 2, 1, 252, 1, 1, 217])) + assert.deepEqual(spy.getCall(4).args[0], Buffer.from([2, 0, 1, 253, 217])) + }) + it('resets incomplete message after timeout', () => { + const spy = sinon.spy() + const clock = sinon.useFakeTimers(Date.now()) + const parser = new CCTalkParser(50) + parser.on('data', spy) + parser.write(Buffer.from([2, 2, 1])) + clock.tick(51) + parser.write(Buffer.from([2, 2, 1, 254, 1, 1, 217])) + assert.equal(spy.callCount, 1) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217])) + clock.restore() + }) + it('disabled message timeout', () => { + const spy = sinon.spy() + const clock = sinon.useFakeTimers(Date.now()) + const parser = new CCTalkParser(0) + parser.on('data', spy) + parser.write(Buffer.from([2, 2, 1])) + clock.tick(100) + parser.write(Buffer.from([254, 1, 1, 217])) + assert.equal(spy.callCount, 1) + assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217])) + clock.restore() + }) +}) diff --git a/pool/shard000/JavaScript/0005988_trailing-commas.js b/pool/shard000/JavaScript/0005988_trailing-commas.js new file mode 100644 index 0000000000000000000000000000000000000000..c913b8bde0fbc39b02003ab337ad2d9902dd189f --- /dev/null +++ b/pool/shard000/JavaScript/0005988_trailing-commas.js @@ -0,0 +1,44 @@ +/** + * Adds trailing commas to every object litteral and array. + */ +export default function(file, api, options) { + const j = api.jscodeshift; + + const objectHasNoTrailingComma = ({node}) => { + // Only transform objects that are on multiple lines. + if (node.properties.length === 0 || node.loc.start.line === node.loc.end.line) { + return false; + } + const lastProp = node.properties[node.properties.length - 1]; + return file.source.charAt(lastProp.end) !== ','; + }; + + const arrayHasNoTrailingComma = ({node}) => { + // Only transform arrays that are on multiple lines. + if (node.elements.length === 0 || node.loc.start.line === node.loc.end.line) { + return false; + } + const lastEle = node.elements[node.elements.length - 1]; + return file.source.charAt(lastEle.end) !== ','; + }; + + const forceReprint = ({node}) => { + node.original = null; + }; + + const root = j(file.source); + root + .find(j.ObjectExpression) + .filter(objectHasNoTrailingComma) + .forEach(forceReprint); + root + .find(j.ArrayExpression) + .filter(arrayHasNoTrailingComma) + .forEach(forceReprint); + + return root.toSource({ + ...options.printOptions, + trailingComma: true, + wrapColumn: 0, // Makes sure we write each values on a separate line. + }); +} diff --git a/pool/shard000/Python/0000006_fakeit.py b/pool/shard000/Python/0000006_fakeit.py new file mode 100644 index 0000000000000000000000000000000000000000..46a4d11f7c555475bbea8d27c81c3df044c0727a --- /dev/null +++ b/pool/shard000/Python/0000006_fakeit.py @@ -0,0 +1,24 @@ +from bottle import route, view, request, run, template +import socket +import json + + +@route('/') +def index(): + return template('index_template') + +@route('/ajax/send/location', method='POST') +def sendLocation(): + locationDict = request.json['location'] + deviceDict = request.json['device'] + deviceIP = deviceDict['ip'] + devicePorts = deviceDict['port'] + devicePortsList = devicePorts.split(',') + for port in devicePortsList: + sendLocation(locationDict,deviceIP,int(port)) + +def sendLocation(dict,ip,port): + message = json.dumps(dict) + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.sendto(message, (ip, port)) +run(host='localhost', port=8080, debug=True) diff --git a/pool/shard000/Python/0000013_air_utilities_test.py b/pool/shard000/Python/0000013_air_utilities_test.py new file mode 100644 index 0000000000000000000000000000000000000000..07a15d11449b7bd9d617b5c9ed952a61385e610f --- /dev/null +++ b/pool/shard000/Python/0000013_air_utilities_test.py @@ -0,0 +1,97 @@ +import unittest +import datetime +import json +import sys + +sys.path.append('..') +import sabre_dev_studio +import sabre_dev_studio.sabre_exceptions as sabre_exceptions + +''' +requires config.json in the same directory for api authentication + +{ + "sabre_client_id": -----, + "sabre_client_secret": ----- +} + +''' +class TestAirUtilities(unittest.TestCase): + def read_config(self): + raw_data = open('config.json').read() + + data = json.loads(raw_data) + + client_secret = data['sabre_client_secret'] + client_id = data['sabre_client_id'] + + return (client_id, client_secret) + + def setUp(self): + # Read from config + self.client_id, self.client_secret = self.read_config() + self.sds = sabre_dev_studio.SabreDevStudio() + self.sds.set_credentials(self.client_id, self.client_secret) + self.sds.authenticate() + + def test_alliance_request(self): + res = self.sds.alliance_lookup('*A') + + airline_data = res.alliance_info[0].airline_info + airline_codes = map(lambda rd: rd.airline_code, airline_data) + + self.assertIsNotNone(res) + + # This test should pass as long as Air Canada is in Star Alliance + # and the function works ;) + self.assertTrue('AC' in airline_codes) + + def test_equipment_lookup(self): + res = self.sds.equipment_lookup('CR9') + + self.assertEqual(res, 'CANADAIR REGIONAL') + + def test_multi_city_airport_lookup(self): + res = self.sds.multi_city_airport_lookup('GB') + codes = map(lambda c: c.code, res) + + self.assertTrue('LON' in codes) + + def test_multi_city_airport_lookup(self): + res = self.sds.countries_lookup('GB') + origin_names = map(lambda c: c.country_name, res.origin_countries) + destination_names = map(lambda c: c.country_name, res.destination_countries) + + self.assertTrue('United Kingdom' in origin_names) + self.assertTrue('United Kingdom' in destination_names) + + def test_city_pairs_lookup(self): + # SHOP + # Country -> Country + res = self.sds.city_pairs_lookup('shop', origin_country='US', + destination_country='CA') + locations = res.origin_destination_locations + pairs = map(lambda l: l.origin_destination_locations, locations) + + self.assertTrue('JFK-YYZ' in pairs) + + # HISTORICAL + # Region -> Region + res = self.sds.city_pairs_lookup('shop', origin_region='North America', + destination_region='Latin America') + locations = res.origin_destination_locations + pairs = map(lambda l: l.origin_destination_locations, locations) + + self.assertTrue('ATL-CUN' in pairs) + + # FORECAST + # Country -> Region + res = self.sds.city_pairs_lookup('shop', origin_country='US', + destination_region='Europe') + locations = res.origin_destination_locations + pairs = map(lambda l: l.origin_destination_locations, locations) + + self.assertTrue('SFO-LHR' in pairs) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard000/Python/0000018_gattaca.py b/pool/shard000/Python/0000018_gattaca.py new file mode 100644 index 0000000000000000000000000000000000000000..991d18c836225571669b96e3a062816fdaf26d89 --- /dev/null +++ b/pool/shard000/Python/0000018_gattaca.py @@ -0,0 +1,61 @@ +# gattaca +# facebbok puzzle #5 + +import sys +import logging + +logging.basicConfig(level=logging.DEBUG) + +def load_data(filename): + with open(filename) as f: + n = int(f.readline()) + #logging.debug('n is {n}'.format(n=n)) + get_line = lambda : f.readline().replace('\n','').replace('\r','') + dna = '' + gene_predict = [] + + for i in range(0,n/80): + dna += get_line() + if n%80 != 0: + dna += get_line() + + g = int(f.readline()) + + for i in range(0,g): + gene = tuple(f.readline().split()) + gene = int(gene[0]),int(gene[1]),int(gene[2]) + gene_predict.append(gene) + + gene_predict.sort() + return (n, dna, g, gene_predict) +def main(): + if len(sys.argv) < 2: sys.exit('Ops! need a file name as argument') + + n, dna, g, gene_predict = load_data(sys.argv[1]) + + logging.debug(' \n n is: {n} \n dna is: {dna} \n g is: {g} \n gene predicitions are: {gp}'. + format(n=n, dna=dna, g=g, gp=gene_predict)) + + scored = [] + chains_score = [] + logging.debug('possible chains down bellow:') + for i,gene in enumerate(gene_predict): + chain = [] + chain.append(gene) + last_gene = gene + for new_gene in gene_predict[i+1:]: + if new_gene[0] > last_gene[1]: + chain.append(new_gene) + last_gene = new_gene + score = 0 + for c in chain: + score += c[2] + chains_score.append(score) + logging.debug('{chain} -> {score}'.format(chain=chain, score=score)) + + chains_score.sort() + print 'biggest is', chains_score[-1] + + +if __name__=="__main__": + main() \ No newline at end of file diff --git a/pool/shard000/Python/0000024_Turing_Machine.py b/pool/shard000/Python/0000024_Turing_Machine.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba2a1ce8f1e228e71ce5cc19b9a9096a004f1ba --- /dev/null +++ b/pool/shard000/Python/0000024_Turing_Machine.py @@ -0,0 +1,106 @@ + +pre_tape = list(raw_input("Give me tape in starting position: ")) +tape = [] +tp = '' +for i in pre_tape: + tape.append(int(i)) +tape = tape + [0,0,0,0,0] +position = 0 +lookup = {} + +class instruction(object): +#"""This is the class that generates states given arbitrary machine instructions.""" + def __init__(self, (e, a, b, c, d, f, g, h, i, j)): + self.alpha = a + self.bravo = b + self.charlie = c + self.delta = d + self.echo = e + self.fox = f + self.golf = g + self.hotel = h + self.india = i + self.juliet = j + + + + def run(self): + global tape + global position + if tape[position] == self.alpha: + tape[position] = self.bravo + position = position + self.charlie + if self.delta == self.echo: + self.run() + elif self.delta == 'HALT': + pass + else: + lookup[self.delta].run() + elif tape[position] == self.golf: + tape[position] = self.hotel + position = position + self.india + if self.juliet == self.fox: + self.run() + elif self.juliet == 'HALT': + pass + else: + lookup[self.juliet].run() + global tp + for i in range(len(tape)): + tp = tp+str(tape[i]) + +counter = 1 + +tuples_list = [] +command_map = {'l': -1, 'r': 1, 'n': 0} + +while True: + print_input_1 = int(raw_input("What does state %d print when scanner sees 1, (or '2' if finished)? " % counter)) + if print_input_1 == 2: + break + move_input_1 = raw_input("Where does state %d send the scanner when it sees 1? " % counter) + + ns_input_1 = raw_input("What state does state %d call when scanner sees 1? " % counter) + + print_input_0 = int(raw_input("What does state %d print when scanner sees 0? " % counter)) + + move_input_0 = raw_input("Where does state %d send the scanner when it sees 0? " % counter) + + ns_input_0 = raw_input("What state does state %d call when scanner sees 0? " % counter) + + if print_input_1 != 2: + tuples_list.append((str(counter), + 1, + print_input_1, + command_map[move_input_1], + ns_input_1, + str(counter), + 0, + print_input_0, + command_map[move_input_0], + ns_input_0)) + counter += 1 + +#Need to instantiate classes. + +state_names_list = [] + +for i in range(len(tuples_list)): + state_names_list.append('state'+str(i + 1)) + +for i in range(len(tuples_list)): + globals()[state_names_list[i]] = instruction(tuples_list[i]) + +for i in range(len(tuples_list)): + lookup[tuples_list[i][0]] = globals()[state_names_list[i]] + + +print "Your input tape was", ''.join(pre_tape)+'00000' + +state1.run() + +new_tape=[] +for i in range(len(tape)): + new_tape.append(str(tape[i])) + +print "Your output tape is", ''.join(new_tape) diff --git a/pool/shard000/Python/0000027_0004_auto_20170904_2114.py b/pool/shard000/Python/0000027_0004_auto_20170904_2114.py new file mode 100644 index 0000000000000000000000000000000000000000..f80f102834b1c065c530897e0319a05d4b676c28 --- /dev/null +++ b/pool/shard000/Python/0000027_0004_auto_20170904_2114.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.4 on 2017-09-05 04:14 +from __future__ import unicode_literals + +import datetime +from django.db import migrations, models +from django.utils.timezone import utc + + +class Migration(migrations.Migration): + + dependencies = [ + ('twitterscheduler', '0003_auto_20170819_1514'), + ] + + operations = [ + migrations.AlterField( + model_name='profile', + name='last_sync_time', + field=models.DateTimeField(default=datetime.datetime(2017, 9, 5, 3, 44, 49, 328435, tzinfo=utc)), + ), + ] diff --git a/pool/shard000/Python/0000035_generate_hoptable.py b/pool/shard000/Python/0000035_generate_hoptable.py new file mode 100644 index 0000000000000000000000000000000000000000..14cf15eebff4356bf9c4e8324e8a13b10980a0b3 --- /dev/null +++ b/pool/shard000/Python/0000035_generate_hoptable.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# this will generate a random frsky compatible +# hop table and a random txid +# +import random +import textwrap + +random.seed() + +#get a random number for the txid +txid = random.randint(513, 65000) + +hoptable_ok = 0 + +#generate hoptable +hoptable_ok = 0 +while (hoptable_ok == 0): + #get random numbers for the hoptable calculation + channel_start = random.randint(0, 7) + channel_spacing = random.randint(64, 255-64) + + hoptable = [] + hop = channel_start + for i in range(47): + hoptable.append(hop) + hop = (hop + channel_spacing) % 235 + if (hop == 0) or (hop == 0x5A) or (hop == 0xDC): + hop = hop + 1 + + #verify that there is no hop more than one time + hoptable_ok = 1 + for x in range(235): + count = hoptable.count(x) + if (count > 1): + #invalid hoptable, try again + #print hoptable.count(x) + hoptable_ok = 0 + +#great, valid hoptable found +hoptable_s = (", ".join(hex(x) for x in hoptable)) + +print("/*"); +print(" Copyright 2016 fishpepper gmail.com"); +print(""); +print(" This program is free software: you can redistribute it and/or modify"); +print(" it under the terms of the GNU General Public License as published by"); +print(" the Free Software Foundation, either version 3 of the License, or"); +print(" (at your option) any later version."); +print(""); +print(" This program is distributed in the hope that it will be useful,"); +print(" but WITHOUT ANY WARRANTY; without even the implied warranty of"); +print(" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); +print(" GNU General Public License for more details."); +print(""); +print(" You should have received a copy of the GNU General Public License"); +print(" along with this program. If not, see ."); +print(""); +print(" author: fishpepper gmail.com"); +print("*/"); +print("#ifndef HOPTABLE_H_"); +print("#define HOPTABLE_H_"); +print(""); +print("#define FRSKY_DEFAULT_FSCAL_VALUE 0x00"); +print(""); +print("#define FRSYK_TXID (0x%04X)" % (txid)) +print("") +print("// hoptable was generated with start=%d, spacing=%d" % (channel_start, channel_spacing)) +print("#define FRSKY_HOPTABLE { \\") +for x in textwrap.wrap(hoptable_s): + print("%s \\" % (x)) +print("};"); +print("") +print("#endif // HOPTABLE_H_") diff --git a/pool/shard000/Python/0000037_Helper.py b/pool/shard000/Python/0000037_Helper.py new file mode 100644 index 0000000000000000000000000000000000000000..3e9ad8c822e3d49fe15a9dbb758ba653b7329502 --- /dev/null +++ b/pool/shard000/Python/0000037_Helper.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os +import fnmatch +from PyQt5 import QtCore + + +def parseXML(directory = '.', filetype = '*.xml', structure = 'Device'): + #TODO use a structure + root = [] + for structure in fnmatch.filter(os.listdir(directory), filetype): + f = QtCore.QFile(directory + '/' + structure) + if not f.open(QtCore.QIODevice.ReadOnly): + print( 'could not open', structure) + continue + reader = QtCore.QXmlStreamReader(f) + xmlDevice = [] + count = -1 + + while not reader.atEnd(): + if reader.readNext(): + if reader.isStartElement(): + count += 1 + attr = reader.attributes() + attr.append('Reader_Name', reader.name()) + attr.append('Name', os.path.splitext(os.path.basename(structure))[0]) + xmlDevice.append((count, attr)) + elif reader.isEndElement(): + count -= 1 + if reader.hasError(): + break + if reader.hasError(): + print( '') + print( 'ERROR at %s:%i' % (structure, reader.lineNumber())) + print( reader.errorString()) + print( '') + else: + root.append(xmlDevice) + shrunken = [] + for x in root: + shrink(shrunken, x) + + return shrunken + + +def shrink(ret = None, liste = None, index = 0): + while liste: + (level, item) = liste[0] + if level == 0: + newItem = [item] + liste = shrink(newItem, liste[1:], level) + ret.append(newItem) + elif level == index: + return liste + newItem = [item] + liste = shrink(newItem, liste[1:], level) + ret.append(newItem) + elif level > index: + newItem = [item] + liste = shrink(newItem, liste[1:], level) + ret.append(newItem) + else: + return liste + diff --git a/pool/shard000/Python/0000039_send_msg.py b/pool/shard000/Python/0000039_send_msg.py new file mode 100644 index 0000000000000000000000000000000000000000..173846acabdfb7562fbad6bf0cfc06a5d3a3e69c --- /dev/null +++ b/pool/shard000/Python/0000039_send_msg.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# -*-coding:utf-8-*- +# @Time : 2017/11/1 ~ 2019/9/1 +# @Author : Allen Woo +import time +from flask import request +from flask_babel import gettext +from flask_login import current_user + +from apps.app import mdbs +from apps.core.flask.reqparse import arg_verify +from apps.modules.message.process.user_message import insert_user_msg +from apps.modules.upload.process.tempfile import clean_tempfile +from apps.utils.send_msg.send_email import send_email +from apps.utils.format.obj_format import json_to_pyseq +from apps.utils.send_msg.send_message import send_mobile_msg +from apps.utils.text_parsing.text_parsing import richtext_extract_img + + +def send_msg(): + """ + 发送消息 + :return: + """ + + title = request.argget.all("title") + content = request.argget.all("content") + content_html = request.argget.all("content_html") + send_type = json_to_pyseq(request.argget.all("send_type", [])) + username = json_to_pyseq(request.argget.all("username", [])) + + s, r = arg_verify([(gettext(gettext("title")), title), + (gettext("content"), content_html), + (gettext("send type"), send_type), + (gettext("user name"), username)], + required=True) + if not s: + return r + + data = {"msg": "", "msg_type": "s"} + query = { + "is_delete": { + "$in": [ + False, 0, ""]}, "active": { + "$in": [ + True, 1]}} + if len(username) > 1 or username[0].lower() != "all": + # 不是发给全部用户 + query["username"] = {"$in": username} + + users = list( + mdbs["user"].db.user.find( + query, { + "_id": 1, "email": 1, "mphone_num": 1})) + + # 清理消息中的临时img + if "email" not in send_type: + # 删除所有上传的图片 + srcs = [] + else: + # 保留邮件内容中使用的图片 + srcs = richtext_extract_img(richtext=content_html) + imgs = clean_tempfile(user_id=current_user.str_id, + type="image", old_file=[], + keey_file=srcs) + if imgs: + # 保存邮件中上传的图片记录, 以便之后删除 + mdbs["sys"].db.sys_msg_img.insert({"time": time.time(), "imgs": imgs, + "send_user_id": current_user.str_id, + "title": title}) + for send_t in send_type: + if send_t == "on_site": + for user in users: + insert_user_msg( + user_id=user["_id"], + ctype="notice", + label="sys_notice", + title=title, + content={ + "text": content}, + is_sys_msg=True) + + if users: + data["msg"] = "{}. {}".format( + data["msg"], gettext("Station news success")) + else: + data["msg"] = "{}. {}".format( + data["msg"], gettext("No relevant user")) + data["msg_type"] = "w" + + elif send_t == "email": + to_emails = [] + for user in users: + to_emails.append(user["email"]) + if to_emails: + msg = { + "subject": title, + "recipients": to_emails, + "html_msg": content_html + } + send_email(msg=msg, ctype="nt") + + data["msg"] = "{}. {}".format( + data["msg"], gettext("Mail message is being sent")) + else: + data["msg"] = "{}. {}".format( + data["msg"], gettext("There is no such email address user")) + data["msg_type"] = "w" + + elif send_t == "sms": + # 发送短信 + to_mnumber = [] + for user in users: + if "mphone_num" in user: + to_mnumber.append(user["mphone_num"]) + + if to_mnumber: + send_mobile_msg(to_mnumber, content) + + data["msg"] = "{}. {}".format(data["msg"], gettext("SMS sent")) + else: + data["msg"] = "{}. {}".format( + data["msg"], gettext("No user mobile phone number was obtained")) + data["msg_type"] = "w" + + data["msg"] = data["msg"].strip(". ") + data["custom_status"] = 201 + return data diff --git a/pool/shard000/Python/0000047_postprocess-specific.py b/pool/shard000/Python/0000047_postprocess-specific.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf48dc4cf2e6256fb91ed5229ec589ff801f69d --- /dev/null +++ b/pool/shard000/Python/0000047_postprocess-specific.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# +####################################################################### +# +# +# postprocess-specific.py +# +# USAGE: ./postprocess-specific.py [--dont-reverse-Stransform] treebank.gld treebank.jmx < treebank.parsed +# +# Postprocess trees. +# Postprocess a tree against the original treebank tree, such that +# EVALB can compare the parsed tree with the original tree. +# +# WRITEME: Describe more specifically. +# +# +# $Id: postprocess-specific.py 1657 2006-06-04 03:03:05Z turian $ +# +# +####################################################################### +# Copyright (c) 2004-2006, New York University. All rights reserved +####################################################################### + + +from variables import * +import parsetree + +import sys + +if mysys == "Linux" and not profile: + try: + debug(1, "Linux detected... using psyco") + import psyco + psyco.full(memory=4096) + +# psyco.full() + +# psyco.log() +# psyco.full(memory=128) +# psyco.profile(0.05, memory=1024) +# psyco.profile(0.2) + + except: + debug(1, "Could not import psyco") + +elif not profile: + debug(1, "Uname gives %s... NOT using psyco" % (mysys)) +else: + debug(1, "Profiling...") + import hotshot, hotshot.stats + +def main(): + reverse_Stransform = True + if len(sys.argv) == 4: + assert(sys.argv[1]) == "--dont-reverse-Stransform" + reverse_Stransform = False + sys.argv = sys.argv[1:] + debug(1, "NOT reversing Stransform.") + + assert(len(sys.argv) == 3) + debug(1, "Opening files:\n\t%s\n\t%s\n" % (sys.argv[1], sys.argv[2])) + treebank_file = open(sys.argv[1]) + jmx_file = open(sys.argv[2]) + + sentence = 0 + for l in sys.stdin: + sentence += 1 + if not l: assert(0) + if l == "\n": + lt = treebank_file.readline() + lj = jmx_file.readline() + print + continue + + tree = parsetree.read_tree(l) + assert tree != None + + if duplicate_top_item: + assert(0) + # Add a second TOP label, s.t. we can raise punctuation + # above the first TOP label + node = parsetree.Node() + node.isleaf = 0 + node.label = "TOP" + node.children = [tree] + tree = parsetree.refresh(node) +# else: +# tree = parsetree.refresh(tree) + + lt = treebank_file.readline() + treebank_tree = parsetree.read_tree(lt) + assert treebank_tree != None + treebank_tree = parsetree.reverse_regularize(treebank_tree) + treebank_leaves = [(n.headword, n.headtag) for n in treebank_tree.leaves()] + del treebank_tree + + lj = jmx_file.readline() + jmx_tree = parsetree.read_tree(lj) + assert jmx_tree != None + jmx_tree = parsetree.reverse_regularize(jmx_tree) + jmx_leaves = [(n.headword, n.headtag) for n in jmx_tree.leaves()] + del jmx_tree + + tree = parsetree.reverse_regularize(tree) + treestr = tree.to_string() + tree = parsetree.reverse_regularize(tree) + assert treestr == tree.to_string() + + parsetree.postprocess(tree, origleaves=jmx_leaves, treebank_leaves=treebank_leaves, reverse_Stransform=reverse_Stransform) + print tree.to_string() + + if sentence % 100 == 0: + debug(1, "Sentence #%d done" % sentence) + else: + debug(2, "Sentence #%d done" % sentence) + + assert(not treebank_file.readline()) + assert(not jmx_file.readline()) + treebank_file.close() + jmx_file.close() + +if profile: + #prof = hotshot.Profile("oracle.prof", lineevents=1) + prof = hotshot.Profile("oracle.prof") + prof.runcall(main) + prof.close() + stats = hotshot.stats.load("oracle.prof") + stats.strip_dirs() + stats.sort_stats('time', 'calls') + stats.print_stats(20) +else: + main() diff --git a/pool/shard000/Python/0000048_setup.py b/pool/shard000/Python/0000048_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f5cc297cdf355c25e3238f0caddf3f37e60cdc --- /dev/null +++ b/pool/shard000/Python/0000048_setup.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +""" +paco +==== +Utility library for asynchronous coroutine-driven programming for Python +3.4. + +:copyright: (c) 2016-2018 Tomas Aparicio +:license: MIT +""" + +import os +import sys +from setuptools import setup, find_packages +from setuptools.command.test import test as TestCommand + +# Publish command +if sys.argv[-1] == 'publish': + os.system('python setup.py sdist upload') + sys.exit() + + +setup_requires = [] +if 'test' in sys.argv: + setup_requires.append('pytest') + + +def read_version(package): + with open(os.path.join(package, '__init__.py'), 'r') as fd: + for line in fd: + if line.startswith('__version__ = '): + return line.split()[-1].strip().strip("'") + + +# Get package current version +version = read_version('paco') + + +class PyTest(TestCommand): + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = ['tests/'] + self.test_suite = True + + def run_tests(self): + # import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.test_args) + sys.exit(errno) + + +with open('requirements-dev.txt', encoding='utf-8') as f: + tests_require = f.read().splitlines() +with open('README.rst', encoding='utf-8') as f: + readme = f.read() +with open('History.rst', encoding='utf-8') as f: + history = f.read() + + +setup( + name='paco', + version=version, + author='Tomas Aparicio', + author_email='tomas+python@aparicio.me', + description=( + 'Small utility library for coroutine-based ' + 'asynchronous generic programming' + ), + url='https://github.com/h2non/paco', + license='MIT', + long_description=readme + '\n\n' + history, + py_modules=['paco'], + zip_safe=False, + tests_require=tests_require, + packages=find_packages(exclude=['tests', 'examples']), + package_data={'': ['LICENSE', 'History.rst', 'requirements-dev.txt']}, + package_dir={'paco': 'paco'}, + include_package_data=True, + cmdclass={'test': PyTest}, + classifiers=[ + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'Operating System :: OS Independent', + 'Development Status :: 5 - Production/Stable', + 'Natural Language :: English', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Topic :: Software Development', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Programming Language :: Python :: Implementation :: CPython' + ], +) diff --git a/pool/shard000/Python/0000049_formdata.py b/pool/shard000/Python/0000049_formdata.py new file mode 100644 index 0000000000000000000000000000000000000000..a189fd12a981cdec08fa129343da9238f4a14159 --- /dev/null +++ b/pool/shard000/Python/0000049_formdata.py @@ -0,0 +1,136 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.pipeline import ClientRawResponse + +from .. import models + + +class Formdata(object): + + def __init__(self, client, config, serializer, deserializer): + + self._client = client + self._serialize = serializer + self._deserialize = deserializer + + self.config = config + + def upload_file( + self, file_content, file_name, custom_headers={}, raw=False, callback=None, **operation_config): + """ + Upload file + + :param file_content: File to upload. + :type file_content: object + :param file_name: File name to upload. Name has to be spelled exactly + as written here. + :type file_name: str + :param dict custom_headers: headers that will be added to the request + :param boolean raw: returns the direct response alongside the + deserialized response + :param callback: if provided, the runtime will call the callback while + streaming upload/download. If streaming upload, response kwarg will + be None + :type callback: Callable[[concurrent.futures.Future], None] or None + :rtype: object or (object, requests.response) or + concurrent.futures.Future + """ + # Construct URL + url = '/formdata/stream/uploadfile' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'multipart/form-data' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct form data + form_data_content = { + 'fileContent': file_content, + 'fileName': file_name, + } + + # Construct and send request + request = self._client.post(url, query_parameters) + response = self._client.send_formdata( + request, header_parameters, form_data_content, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._client.stream_download(response, callback) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def upload_file_via_body( + self, file_content, file_name, custom_headers={}, raw=False, callback=None, **operation_config): + """ + Upload file + + :param file_content: File to upload. + :type file_content: object + :param file_name: File name to upload. Name has to be spelled exactly + as written here. + :type file_name: str + :param dict custom_headers: headers that will be added to the request + :param boolean raw: returns the direct response alongside the + deserialized response + :param callback: if provided, the runtime will call the callback while + streaming upload/download. If streaming upload, response kwarg will + be None + :type callback: Callable[[concurrent.futures.Future], None] or None + :rtype: object or (object, requests.response) or + concurrent.futures.Future + """ + # Construct URL + url = '/formdata/stream/uploadfile' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/octet-stream' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct body + body_content = self._client.stream_upload(file_content, callback) + + # Construct and send request + request = self._client.put(url, query_parameters) + response = self._client.send( + request, header_parameters, body_content, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._client.stream_download(response, callback) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized diff --git a/pool/shard000/Python/0000050_forms.py b/pool/shard000/Python/0000050_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..8807d6abbe813782d2be4754ed1a4b9bbf1f8dbf --- /dev/null +++ b/pool/shard000/Python/0000050_forms.py @@ -0,0 +1,42 @@ +from django.forms import ModelForm +from django.db import transaction +from django.db import models +from django.forms import ModelForm, PasswordInput +from django.forms.models import inlineformset_factory +from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm +from django.contrib.auth import get_user_model +from django.forms import ValidationError + +from django import forms +from django.core.validators import validate_email +from django.core.exceptions import ValidationError +from models import User, UserProfile + + +class UserForm(forms.ModelForm): + class Meta: + model = User + fields = ["username", "email", "password"] + widgets = {'password': forms.PasswordInput(), } + + +class UserProfileForm(forms.Form): + dob = forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y")) + + class Meta: + model = UserProfile + fields = ["dob"] + + def __init__(self, *args, **kwargs): + super(UserProfileForm, self).__init__(*args, **kwargs) + self.fields["dob"] = forms.DateField() + + +class EditUserProfileForm(forms.Form): + class Meta: + model = UserProfile + fields = ["dob"] + + def __init__(self): + super(EditUserProfileForm, self).__init__(*args, **kwargs) + self.fields["dob"] = forms.DateField() \ No newline at end of file diff --git a/pool/shard000/Python/0000051_descargavideos.py b/pool/shard000/Python/0000051_descargavideos.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd3639a4a4395e80c1f18316a83ea68534342e1 --- /dev/null +++ b/pool/shard000/Python/0000051_descargavideos.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +#------------------------------------------------------------ +# pelisalacarta - XBMC Plugin +# Conector para descargavideos +# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ +#------------------------------------------------------------ + +import urlparse,urllib2,urllib,re +import os + +from core import scrapertools +from core import logger +from core import config + +def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): + logger.info("tvalacarta.servers.descargavideos get_video_url(page_url='%s')" % page_url) + + param = urllib.urlencode({"web":page_url}) + data = scrapertools.cache_page("http://www.descargavideos.tv/?"+param) + logger.info("data="+data) + url = scrapertools.get_match(data,'href="/player/\?img\=[^\&]+&ext=[^\&]+&video=([^"]+)"') + url = urllib.unquote(url) + + video_urls = [] + video_urls.append( [ "["+get_real_server_name(page_url)+"]" , url ] ) + + for video_url in video_urls: + logger.info("[descargavideos.py] %s - %s" % (video_url[0],video_url[1])) + + return video_urls + +def get_real_server_name(page_url): + + real_server_name = "descargavideos" + + if "rtve.es" in page_url: + real_server_name = "rtve" + + return real_server_name + +# Encuentra vídeos del servidor en el texto pasado +def find_videos(data): + encontrados = set() + devuelve = [] + + return devuelve diff --git a/pool/shard000/Python/0000054_j3_cpu.py b/pool/shard000/Python/0000054_j3_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1b9d87dce77025e864100e1694a21f3787f506 --- /dev/null +++ b/pool/shard000/Python/0000054_j3_cpu.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +""" +Display the CPU usage. + +Configuration parameters: + - cache_timeout : seconds between rate checks (default: 1) + - colorize : true to colorize output (default: True) + - set color thresholds via rate_good/degraded/bad + - format : display format (default: 'CPU {icon}') + - mode : display mode (default: 'max') + - 'max' to display just the CPU with max usage + - 'avg' to display the average usage of all CPUs + - 'all' to display each individual CPU + - rate_good : threshold above which display is colorized as good (default: 10) + - rate_degraded : threshold above which display is colorized as degraded (default: 40) + - rate_bad : threshold above which display is colorized as bad (default: 90) +""" + +from __future__ import division # python2 compatibility +from time import time + +import math +import re + +BLOCKS = [' ','_','▁','▂','▃','▄','▅','▆','▇','█'] + +class Py3status: + # available configuration parameters + cache_timeout = 1 + colorize = True + format = 'CPU {icon}' + mode = 'max' + rate_good = 10 + rate_degraded = 40 + rate_bad = 90 + + # internal state + last_time = None + last_stats = None + + def _get_stats(self): + stats = [] + with open('/proc/stat') as f: + for line in f.readlines(): + if re.search(r'^cpu\d', line): + cols = line.split() + stats.append({ + 'total': sum(map(int, cols[1:])), + 'idle': int(cols[4]), + }) + return stats + + def j3_cpu(self, i3s_output_list, i3s_config): + # calculate the difference in seconds between last check and now + now = time() + last_time = self.last_time or now + self.last_time = now + diff_time = now - last_time + if diff_time < 1: diff_time = 1 + + stats = self._get_stats() + last_stats = self.last_stats or stats + self.last_stats = stats + + all_percent = [] + max_percent = 0 + sum_total = 0 + sum_idle = 0 + + # calculate cpu used since last check + for index, cpu in enumerate(stats): + last_cpu = last_stats[index] + total = cpu['total'] - last_cpu['total'] + idle = cpu['idle'] - last_cpu['idle'] + sum_total += total + sum_idle += idle + + percent = 100 - 100 * idle / (total or 1) + all_percent.append(percent) + if max_percent < percent: + max_percent = percent + + if self.mode == 'max': + color_rate = max_percent + icon = BLOCKS[int(math.ceil(max_percent/100*len(BLOCKS))) - 1] + elif self.mode == 'avg': + avg_percent = 100 - 100 * sum_idle / (sum_total or 1) + color_rate = avg_percent + icon = BLOCKS[int(math.ceil(avg_percent/100*len(BLOCKS))) - 1] + else: + avg_percent = 100 - 100 * sum_idle / (sum_total or 1) + color_rate = avg_percent + icon = '' + for percent in all_percent: + icon += BLOCKS[int(math.ceil(percent/100*len(BLOCKS))) - 1] + + color = None + if self.colorize: + if color_rate > self.rate_bad: + color = i3s_config['color_bad'] + elif color_rate > self.rate_degraded: + color = i3s_config['color_degraded'] + elif color_rate > self.rate_good: + color = i3s_config['color_good'] + + return { + 'cached_until': now + self.cache_timeout, + 'color': color, + 'full_text': self.format.format(icon=icon), + } + +if __name__ == "__main__": + from time import sleep + x = Py3status() + config = { + 'color_good': '#00FF00', + 'color_degraded': '#FFFF00', + 'color_bad': '#FF0000', + } + while True: + #print(x.j3_cpu([], config)['full_text']) + print(x.j3_cpu([], config)) + sleep(1) diff --git a/pool/shard000/Python/0000058_LattegtkModel.py b/pool/shard000/Python/0000058_LattegtkModel.py new file mode 100644 index 0000000000000000000000000000000000000000..353a8ded978e63e06fd8f20c8edd196ae1797121 --- /dev/null +++ b/pool/shard000/Python/0000058_LattegtkModel.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +from latte import latte, Analyzer + + + +class LattegtkModel(): + """ The model of Lattegtk. + Stores the application data such as logs and options. + + The class exposes: + self.entries : Latte's logs + self.total_time : The total time counted in the retrieved logs + self.get_option() : Retrieves the value of an option + self.update_option() : Updates the value of an option + self.update() : Updates self.entries and self.total_time + """ + + def __init__(self): + self._options = {} + self._analyzer = self._init_analyzer() + self.entries = self._fetch_entries() + self.total_time = self._fetch_total_time() + + def _options_list(self): + """ Generates an options list using self._options. The analyzer requires + options to be in list form. + Also, adds '--graphical' to options so that the analyzer returns + the logs. + """ + options_list = [] + for key in self._options: + options_list.append(key) + options_list.append(self._options[key]) + options_list.append('--graphical') + return options_list + + def _init_analyzer(self): + """ Inits Latte's analyzer. """ + return Analyzer.Analyzer( + latte.Latte().config, + latte.Latte().get_session(), + self._options_list()) + + def _fetch_entries(self): + """ Fetches data from Latte using Latte's analyzer. + This is used to fetch new data after the options have been changed, + since the analyzer generates data on the options that are passed + to it at that moment, new options mean also a new Analyzer instance + is needed. + """ + self._analyzer = self._init_analyzer() + self._logs = self._analyzer.analyze() + parsed = [] + for row in self._logs: + row_dict = {} + group_option = self.get_option('-g') + if group_option == 'instance': + row_dict['title'] = row[3] + elif group_option == 'class': + row_dict['title'] = row[2] + else: + row_dict['title'] = row[0] + row_dict['raw_time'] = row[1] + row_dict['time'] = self._analyzer.normalize_time(row[1]) + parsed.append( row_dict ) + return parsed + + def _fetch_total_time(self): + """ Returns the total time of the logs. """ + return self._analyzer.get_total_time(self._logs) + + def update(self): + """ Updates self.entries and self.total_time. + This should be used to update the model after options have been + updated with self.update_option(). + """ + self.entries = self._fetch_entries() + self.total_time = self._fetch_total_time() + + def get_option(self, option): + """ Get an option's value. """ + if self._options.has_key(option): + return self._options[option] + return None + + def update_option(self, option, value): + """ Update an option's value. """ + self._options[option] = value diff --git a/pool/shard000/Python/0000063_init__.py b/pool/shard000/Python/0000063_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..461bc6ca2bb919dd032c3253fdf066bfe99d9abd --- /dev/null +++ b/pool/shard000/Python/0000063_init__.py @@ -0,0 +1,67 @@ +import sqlite3 +import hashlib + +#db = sqlite3.connect(':memory:') # Base de datos en memoria +def cifrar_password(password): + cifrado = hashlib.sha512(password.encode('utf-8')).hexdigest() + return cifrado + +db = sqlite3.connect('prueba') # Base de datos en un archivo +db.create_function('cifrar', 1, cifrar_password) +cursor = db.cursor() +#cursor.execute('''CREATE TABLE clave(id INTEGER PRIMARY KEY, +# email TEXT, password TEXT)''') +usuario = input("Correo: ") +password = input("Password: ") +cursor.execute('''INSERT INTO clave(email, password) VALUES + (?,cifrar(?))''', (usuario, password)) +db.commit() + +#cursor.execute('''SELECT id, nombre FROM usuario''') +#resultado = cursor.fetchall() +#for fila in resultado: +# print("{0} : {1}".format(fila[0], fila[1])) + +# id = input("ID de usuario a eliminar: ") +# for fila in resultado: +# if int(id) == int(fila[0]): +# cursor.execute('''DELETE FROM usuario WHERE id = ?''', +# (id,)) +# db.commit() + +# id = input("ID de usuario a modificar: ") +# for fila in resultado: +# if int(id) == int(fila[0]): +# nuevo_nombre = input("Nombre Nuevo: ") +# cursor.execute('''UPDATE usuario SET nombre = ? WHERE +# id = ?''', (nuevo_nombre, id)) +# db.commit() + +# cursor.execute('''CREATE TABLE usuario(id INTEGER PRIMARY KEY, nombre TEXT, +# telefono TEXT, email TEXT UNIQUE, password TEXT)''') +# db.commit() +# cursor.execute('''DROP TABLE usuario''') +# db.commit() + +# nombre = input("Nombre: ") +# telefono = input("Telefono: ") +# email = input("Email: ") +# password = input("Password: ") + +# cursor.execute('''INSERT INTO usuario(nombre, telefono, email, password) +# VALUES(?,?,?,?)''', (nombre, telefono, email, password)) +# cursor.execute('''INSERT INTO usuario(nombre, telefono, email, +# password) VALUES(:nombre, :telefono, :email, +# :password)''', +# {'nombre':nombre, 'telefono':telefono, +# 'email':email, 'password':password}) +# db.commit() + +# usuarios = [("Juan","2323222","juan2@juan.org","12345"), +# ("Maria","4352122","maria2@maria.com","maria123"), +# ("Pedro","7773345","pedro2@juan.org","p3dr0")] +# cursor.executemany('''INSERT INTO usuario(nombre, telefono, email, +# password) VALUES (?,?,?,?)''', usuarios) +# db.commit() + +# db.close() \ No newline at end of file diff --git a/pool/shard000/Python/0000068_configure_packages.py b/pool/shard000/Python/0000068_configure_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..e9132677f80dd2ed3ce49d419122f1d55ea350f9 --- /dev/null +++ b/pool/shard000/Python/0000068_configure_packages.py @@ -0,0 +1,101 @@ +""" +Package resource configuration class. + +Copyright 2010 Kelsey Hightower +Kelsey Hightower + +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 2 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, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA + +module for configuring package resources on RedHat based distros. +requires the yum python module +""" + +import subprocess +import sys +import time +import yum + +class ConfigurePackages: + def __init__(self, packages): + self.packages = packages + self.in_sync = 0 + self.oo_sync = 0 + self.failed = 0 + + def configure(self): + print "\033[1;36m- Configuring Packages\033[1;m" + runtime_start = time.time() + # Setup YumBase + yb = yum.YumBase() + # Run in quite mode + yb.preconf.debuglevel = 0 + yb.preconf.errorlevel = 0 + yb.doTsSetup() + yb.doRpmDBSetup() + # Setup YumCLI + sys.path.append('/usr/share/yum-cli') + import cli + ybc = cli.YumBaseCli() + # Run in quite mode + ybc.preconf.debuglevel = 0 + ybc.preconf.errorlevel = 0 + # Assume yes to prevent Yum from prompting [Y/N] + ybc.conf.assumeyes = True + ybc.doTsSetup() + ybc.doRpmDBSetup() + pkg_list = list([package for package in self.packages]) + create_pkg_list = [] + remove_pkg_list = [] + for package in self.packages: + if yb.isPackageInstalled(package): + if self.packages[package]['action'] == 'create': + self.in_sync += 1 + if self.packages[package]['action'] == 'remove': + remove_pkg_list.append(package) + if not yb.isPackageInstalled(package): + if self.packages[package]['action'] == 'create': + create_pkg_list.append(package) + if self.packages[package]['action'] == 'remove': + self.in_sync += 1 + doTransaction = False + if create_pkg_list: + self.create(ybc,create_pkg_list) + doTransaction = True + if remove_pkg_list: + self.remove(ybc,remove_pkg_list) + doTransaction = True + if doTransaction: + ybc.buildTransaction() + ybc.doTransaction() + # Collect Stats + runtime_end = time.time() + runtime = (runtime_end - runtime_start) + stats = { + 'runtime': runtime, + 'in_sync': self.in_sync, + 'oo_sync': self.oo_sync, + 'failed' : self.failed + } + return stats + + def create(self,ybc,create_pkg_list): + print " Packages out of sync: %s" % create_pkg_list + ybc.installPkgs(create_pkg_list) + self.oo_sync += len(create_pkg_list) + + def remove(self,ybc,remove_pkg_list): + ybc.erasePkgs(remove_pkg_list) + self.oo_sync += len(remove_pkg_list) diff --git a/pool/shard000/Python/0000072_ehangman.py b/pool/shard000/Python/0000072_ehangman.py new file mode 100644 index 0000000000000000000000000000000000000000..a8748c1b68920c5185d0a501da98252d89799538 --- /dev/null +++ b/pool/shard000/Python/0000072_ehangman.py @@ -0,0 +1,71 @@ +""" Hangman Game (v1.0) + Name: + Date: + """ + +# imported modules go here + +def load_file(filename): + """ Function to return a word list from a plain text file; + Note: You will need to open the file, read and append + each line to an array (or list), close the file and + then return the array. + """ +## word_list = [] +## +## file = open(filename, "r") +## temp = file.readlines() +## +## for item in temp: +## word_list.append(item.replace("\n", "").lower()) +## +## file.close() +## +## print(word_list) +## return word_list + + word_list = [] + + with open(filename, "r") as file: + temp = file.readlines() + + for item in temp: + word_list.append(item.replace("\n", "").lower()) + + print(word_list) + return word_list + + +def select_word(word_list): + """ Function to return a random word from an array of words; + Note: You will need to import the random module and use + random.randint() to select a random index in the array. + """ + # your code goes here + return word + +def find_character(char, word): + """ Function to return the position(s) of a character in word; + Note: This should return the index of the character as an integer, + if the character is not found, it should return a value of -1 + """ + # your code goes here + return char_pos + +# do you need any other functions or procedures? + +def main(): + """ Note: This is your main function and should contain your game loop. + """ + filename = "word_list.txt" + attempts_remaining = 10 + # do you need any other variables? + + word_list = load_file(filename) +## word = select_word(word_list) + + # your code goes here + + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0000073_sinc.py b/pool/shard000/Python/0000073_sinc.py new file mode 100644 index 0000000000000000000000000000000000000000..44512231efc1ca67d105c4c5ffef4a6f751a212d --- /dev/null +++ b/pool/shard000/Python/0000073_sinc.py @@ -0,0 +1,40 @@ +# Copyright 2019,2020,2021 Sony Corporation. +# Copyright 2021 Sony Group Corporation. +# +# 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 nnabla.functions as F + +from .utils import no_grad, get_output + + +def sinc_backward(inputs): + """ + Args: + inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function. + kwargs (dict of arguments): Dictionary of the corresponding function arguments. + + Return: + list of Variable: Return the gradients wrt inputs of the corresponding function. + """ + dy = inputs[0] + x0 = inputs[1] + m0 = F.not_equal_scalar(x0, 0) + m0 = no_grad(m0) + y0 = get_output(x0, "Sinc") + + dx0 = dy * (F.cos(x0) - y0) / x0 + c0 = F.constant(0, x0.shape) + dx0 = F.where(m0, dx0, c0) + return dx0 diff --git a/pool/shard000/Python/0000074_opcode_14.py b/pool/shard000/Python/0000074_opcode_14.py new file mode 100644 index 0000000000000000000000000000000000000000..b75aca9815a7491834b3dcc38198aca7fde92446 --- /dev/null +++ b/pool/shard000/Python/0000074_opcode_14.py @@ -0,0 +1,80 @@ +# (C) Copyright 2018-2020 by Rocky Bernstein +# +# 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 2 +# 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, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +""" +CPython 1.4 bytecode opcodes + +This is used in bytecode disassembly. This is similar to the +opcodes in Python's dis.py library. +""" + +# This is used from outside this module +from xdis.cross_dis import findlabels + +import xdis.opcodes.opcode_15 as opcode_15 +from xdis.opcodes.base import ( + init_opdata, + def_op, + extended_format_RETURN_VALUE, + name_op, + varargs_op, + finalize_opcodes, + format_extended_arg, + # Although these aren't used here, they are exported + update_pj2, +) + +version = 1.4 +python_implementation = "CPython" + +l = locals() +init_opdata(l, opcode_15, version) + +# 1.4 Bytecodes not in 1.5 +def_op(l, "UNARY_CALL", 14) +def_op(l, "BINARY_CALL", 26) +def_op(l, "RAISE_EXCEPTION", 81) +def_op(l, "BUILD_FUNCTION", 86) +varargs_op(l, "UNPACK_ARG", 94) # Number of arguments expected +varargs_op(l, "UNPACK_VARARG", 99) # Minimal number of arguments +name_op(l, "LOAD_LOCAL", 115) +varargs_op(l, "SET_FUNC_ARGS", 117) # Argcount +varargs_op(l, "RESERVE_FAST", 123) # Number of local variables + +update_pj2(globals(), l) + +opcode_arg_fmt = {"EXTENDED_ARG": format_extended_arg} + +finalize_opcodes(l) + +def findlinestarts(co, dup_lines=False): + code = co.co_code + n = len(code) + offset = 0 + while offset < n: + op = code[offset] + offset += 1 + if op == l["opmap"]["SET_LINENO"] and offset > 0: + lineno = code[offset] + code[offset + 1] * 256 + yield (offset - 1, lineno) + pass + if op >= l["HAVE_ARGUMENT"]: + offset += 2 + pass + pass + +opcode_extended_fmt = { + "RETURN_VALUE": extended_format_RETURN_VALUE, +} diff --git a/pool/shard000/Python/0000075_test_newcomposition2.py b/pool/shard000/Python/0000075_test_newcomposition2.py new file mode 100644 index 0000000000000000000000000000000000000000..e687ad8a599deb098d4fe4adc13690845bb42259 --- /dev/null +++ b/pool/shard000/Python/0000075_test_newcomposition2.py @@ -0,0 +1,152 @@ + +from GestureAgents.AppRecognizer import AppRecognizer + +from GestureAgentsTUIO.Gestures2D.RecognizerTap import RecognizerTap +from RecognizerDT_Test import build_and_register_DT +from RecognizerTT_Test import build_and_register_TT +from RecognizerT_Test import RecognizerT_Test +from recognizer_testing import t_r, t_rs + +events_tap = [ + ('f', 1, (0.5, 0.5), ( + (0, 'in'), + (0.1, 'out'))), + # ('f', 2, (0.5, 0.5), ( + # (0.3, 'in'), + # (0.4, 'out'))), +] + +events_2tap = [ + ('f', 1, (0.5, 0.5), ( + (0, 'in'), + (0.1, 'out'))), + ('f', 2, (0.5, 0.5), ( + (0.3, 'in'), + (0.4, 'out'))), +] + + +class FeatureTapTestCase1(t_r( + events_tap, + RecognizerTap, + ("newTap",), 1, + AppRecognizerClass=AppRecognizer)): + pass + + +class FeatureTapTestCase2(t_r( + events_2tap, + RecognizerTap, + ("newTap",), 2, + AppRecognizerClass=AppRecognizer)): + pass + +events_3tap = [ + ('f', 1, (0.5, 0.5), ( + (0, 'in'), + (0.1, 'out'))), + ('f', 2, (0.5, 0.5), ( + (0.2, 'in'), + (0.3, 'out'))), + ('f', 3, (0.5, 0.5), ( + (0.4, 'in'), + (0.5, 'out'))), +] + + +# Test Composition sharing sub-gestures +#Test 1: 2 recognizers share a sub recognzer (Tap) + + +RecognizerDT1 = build_and_register_DT() +RecognizerTT1 = build_and_register_TT() +RecognizerDT2 = build_and_register_DT(RecognizerT_Test) +RecognizerTT2 = build_and_register_TT(RecognizerT_Test) + + +class TapTestCase(t_r(events_3tap, RecognizerTap, ("newTap",), 3, AppRecognizerClass=AppRecognizer)): + pass + + +class DoubleTapTestCase(t_r(events_3tap, RecognizerDT1, ("newDoubleTap",), 1, AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapTestCase(t_r(events_3tap, RecognizerTT1, ("newTripleTap",), 1, AppRecognizerClass=AppRecognizer)): + pass + + +class DoubleTapTestCase2(t_r(events_3tap, RecognizerDT2, ("newDoubleTap",), 1, AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapTestCase2(t_r(events_3tap, RecognizerTT2, ("newTripleTap",), 1, AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapWinsOverDoubleTapTestCase(t_rs(events_3tap, + [(RecognizerDT1, ("newDoubleTap",), 0), + (RecognizerTT1, ("newTripleTap",), 1)], AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapWinsOverDoubleTapTestCase2(t_rs(events_3tap, + [(RecognizerDT2, ("newDoubleTap",), 0), + (RecognizerTT2, ("newTripleTap",), 1)], AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapWinsOverDoubleTapTestCaseMixed1(t_rs(events_3tap, + [(RecognizerDT1, ("newDoubleTap",), 0), + (RecognizerTT2, ("newTripleTap",), 1)], AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapWinsOverDoubleTapTestCaseMixed1b(t_rs(events_3tap, + [(RecognizerTT2, ("newTripleTap",), 1), + (RecognizerDT1, ("newDoubleTap",), 0)], AppRecognizerClass=AppRecognizer)): + pass + + +class TripleTapWinsOverDoubleTapTestCaseMixed2(t_rs(events_3tap, + [(RecognizerDT2, ("newDoubleTap",), 0), + (RecognizerTT1, ("newTripleTap",), 1)], AppRecognizerClass=AppRecognizer)): + pass + +class TripleTapWinsOverDoubleTapTestCaseMixed2b(t_rs(events_3tap, + [(RecognizerTT1, ("newTripleTap",), 1), + (RecognizerDT2, ("newDoubleTap",), 0)], AppRecognizerClass=AppRecognizer)): + pass + +events_nodtap = [ + ('f', 1, (0.5, 0.5), ( + (0, 'in'), + (0.1, 'out'))), + ('f', 2, (0.5, 0.5), ( + (0.8, 'in'), + (0.9, 'out'))), +] + + +class DoubleTapTestCase3(t_r(events_nodtap, + RecognizerDT1, + ("newDoubleTap",), 0, + AppRecognizerClass=AppRecognizer)): + pass + + +events_nodtap2 = [ + ('f', 1, (0.5, 0.5), ( + (0, 'in'), + (0.1, 'out'))), + ('f', 2, (0.7, 0.7), ( + (0.2, 'in'), + (0.3, 'out'))), +] + + +class DoubleTapTestCase4(t_r(events_nodtap2, + RecognizerDT1, + ("newDoubleTap",), 0, + AppRecognizerClass=AppRecognizer)): + pass \ No newline at end of file diff --git a/pool/shard000/Python/0000076_imperative_grad.py b/pool/shard000/Python/0000076_imperative_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..5bebccced3b4456f90f319b19956e0caca1ed050 --- /dev/null +++ b/pool/shard000/Python/0000076_imperative_grad.py @@ -0,0 +1,76 @@ +# Copyright 2017 The TensorFlow 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. +# ============================================================================== +"""Code for backpropagation using the tape utilities.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.util import compat + +VSpace = collections.namedtuple("VSpace", [ + "aggregate_fn", "num_elements_fn", "zeros_fn", "ones_fn", "graph_shape_fn" +]) + + +def imperative_grad(tape, + target, + sources, + output_gradients=None, + sources_raw=None, + unconnected_gradients=UnconnectedGradients.NONE): + """Computes gradients from the imperatively defined tape on top of the stack. + + Works by filtering the tape, computing how many downstream usages are of each + tensor and entry, and repeatedly applying backward functions until we have + gradients for all sources. + + Args: + tape: the gradient tape which stores the trace. + target: either a Tensor or list of Tensors to be differentiated. + sources: list of Tensors for which we want gradients + output_gradients: if not None, a list of gradient provided for each Target, + or None if we are to use the target's computed downstream gradient. + sources_raw: if not None, a list of the source python objects from which the + sources were generated. Should have the same length as sources. Only needs + to be populated if unconnected_gradients is 'zero'. + unconnected_gradients: determines the value returned if the target and + sources are unconnected. When 'none' the value returned is None wheras when + 'zero' a zero tensor in the same shape as the sources is returned. + + Returns: + the gradient wrt each of the sources. + + Raises: + ValueError: if the arguments are invalid. + RuntimeError: if something goes wrong. + """ + try: + unconnected_gradients = UnconnectedGradients(unconnected_gradients) + except ValueError: + raise ValueError( + "Unknown value for unconnected_gradients: %r" % unconnected_gradients) + + return pywrap_tensorflow.TFE_Py_TapeGradient( + tape._tape, # pylint: disable=protected-access + target, + sources, + output_gradients, + sources_raw, + compat.as_str(unconnected_gradients.value)) diff --git a/pool/shard000/Python/0000079_all_checks.py b/pool/shard000/Python/0000079_all_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..416ac79f4bf2f2d8d705be1946c76604da3410b3 --- /dev/null +++ b/pool/shard000/Python/0000079_all_checks.py @@ -0,0 +1,34 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dev_tools import ( + check_incremental_coverage, + check_pylint, + check_pytest_with_coverage, + check_typecheck, +) + + +pylint = check_pylint.LintCheck() +typecheck = check_typecheck.TypeCheck() +pytest = check_pytest_with_coverage.TestAndPrepareCoverageCheck() +incremental_coverage = check_incremental_coverage.IncrementalCoverageCheck( + pytest) + +ALL_CHECKS = [ + pylint, + typecheck, + pytest, + incremental_coverage, +] diff --git a/pool/shard000/Python/0000087_split_concoct_bins.py b/pool/shard000/Python/0000087_split_concoct_bins.py new file mode 100644 index 0000000000000000000000000000000000000000..857a9804dece9d22107748cd1def138b4d5f3fb6 --- /dev/null +++ b/pool/shard000/Python/0000087_split_concoct_bins.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python2.7 +# Takes in the clustering_gt1000.csv file from CONCOCT binning, and splits the contigs into propper bins +# Usage: +# ./script clustering_gt1000.csv assembly_file.fa out_folder + +import sys, os + +print "Loading in the bins that the contigs belong to..." +bins={} +for line in open(sys.argv[1]): + bins[line.strip().split(",")[0]] = line.strip().split(",")[1] + + +print "Going through the entire assembly and splitting contigs into their respective bin file..." +current_bin="" +for line in open(sys.argv[2]): + if line.startswith(">"): + if current_bin!="": f.close() + if line[1:-1] in bins: current_bin="bin."+bins[line[1:-1]]+".fa" + else: current_bin="unbinned.fa" + f = open(sys.argv[3]+"/"+current_bin,'a') + f.write(line) +print "Done!" + + + + diff --git a/pool/shard000/Python/0000088_messages.py b/pool/shard000/Python/0000088_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..40ea0e4a31c9bcca1aebc3de2645a03d568d2416 --- /dev/null +++ b/pool/shard000/Python/0000088_messages.py @@ -0,0 +1,174 @@ +import datetime + +from flask import render_template + +from keyvalue import SiteKey, check_key_exists, new_key +from sql import upsert, doupsert, doquery, Tree +from mail import send_mail +from memoize import memoize_with_expiry, cache_persist, long_cache_persist +from utility import obfuscate, deobfuscate +import users +import items + +privatemessage_cache = dict() +class PrivateMessage(object): + @classmethod + @memoize_with_expiry(privatemessage_cache, cache_persist) + def create(cls, messageid): + return cls(messageid) + + def __init__(self, messageid): + sql = 'select * from messages where uid = %(uid)s;' + result = doquery(sql, {'uid': messageid}) + + try: + self.uid = result[0][0] + self.uid_obfuscated = obfuscate(result[0][0]) + self.from_uid = result[0][1] + self.to_uid = result[0][2] + self.subject = result[0][3] + self.message = result[0][4] + self.status = result[0][5] # trade status, None for PMs + self.parentid = result[0][6] + self.parentid_obfuscated = obfuscate(result[0][6]) + self.sent = result[0][7] + + self.from_user = users.SiteUser.create(users.user_by_uid(self.from_uid)).username + self.to_user = users.SiteUser.create(users.user_by_uid(self.to_uid)).username + except IndexError: + raise NoItem(messageid) + + def parent(self): + if self.parentid > 0: + return PrivateMessage.create(self.parentid) + + def setstatus(self, status): + if self.uid > 0: + self.status = status + sql = "update messages set status = %(status)s where uid = %(uid)s;" + result = doquery(sql, {"uid": self.uid, "status": status}) + else: + return None + + def read(self, userid): + new_key("messagereadstatus_{}_{}".format(self.uid, userid), '') + + def unread(self, userid): + o = SiteKey("messagereadstatus_{}_{}".format(self.uid, userid)) + o.delete() + + def read_status(self, userid): + return check_key_exists("messagereadstatus_{}_{}".format(self.uid, userid)) + + def delete(self, userid): + new_key("messagedeletestatus_{}_{}".format(self.uid, userid), '') + + def undelete(self, userid): + o = SiteKey("messagedeletestatus_{}_{}".format(self.uid, userid)) + o.delete() + + def delete_status(self, userid): + return check_key_exists("messagedeletestatus_{}_{}".format(self.uid, userid)) + + @memoize_with_expiry(privatemessage_cache, cache_persist) + def replies(self): + ret = list() + + sql = 'select * from messages where parent = %(uid)s;' + result = doquery(sql, {"uid": self.uid}) + + for reply in result: + pm = PrivateMessage.create(reply[0]) + ret.append(pm) + + return ret + +def send_pm(fromuserid, touserid, subject, message, status, parent): + # FIXME: parent id validation + sent = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") + sql = "insert into messages (fromuserid, touserid, subject, message, parent, sent, status) values (%(fromuserid)s, %(touserid)s, %(subject)s, %(message)s, %(parent)s, %(sent)s, %(status)s);" + doquery(sql, { 'fromuserid': fromuserid, 'touserid': touserid, 'subject': subject, 'message': message, 'parent': parent, 'sent': sent, 'status': status }) + + sql = "select uid from messages where fromuserid=%(fromuserid)s and touserid=%(touserid)s and sent=%(sent)s;" + messageid = doquery(sql, { 'fromuserid': fromuserid, 'touserid': touserid, 'sent': sent })[0][0] + + email_user = users.SiteUser.create(users.user_by_uid(touserid)) + from_user = users.SiteUser.create(users.user_by_uid(fromuserid)) + + message = render_template('email/pm_notify.html', to_user=email_user, email=email_user.email, from_user=from_user, message=message, status=status, parent=parent, messageid=obfuscate(messageid)) + + subject = '[Scarfage] (PM) ' + subject + send_mail(recipient=email_user.email, subject=subject, message=message) + + return messageid + +class TradeItem(object): + def __init__(self, itemid): + self.uid = itemid + self.itemid = 0 + self.messageid = 0 + self.userid = 0 + self.acceptstatus = 0 + + def setstatus(self, status): + if self.uid > 0: + self.acceptstatus = status + + sql = "update tradelist set acceptstatus = %(status)s where uid = %(uid)s;" + return doquery(sql, { "uid": self.uid, "status": status }) + + def accept(self): + return self.setstatus(tradeitemstatus['accepted']) + + def reject(self): + return self.setstatus(tradeitemstatus['rejected']) + +tradeitemstatus = {'unmarked': 0, 'rejected': 1, 'accepted': 2} +tradestatus = {'reserved': 0, 'active_trade': 1, 'complete_trade': 2, 'settled_trade': 3, 'rejected_trade': 4, 'cancelled_trade': 5} +trademessage_cache = dict() +class TradeMessage(PrivateMessage): + @classmethod + @memoize_with_expiry(trademessage_cache, cache_persist) + def create(cls, messageid): + return cls(messageid) + + def __init__(self, messageid): + super(self.__class__, self).__init__(messageid) + self.tradeitemstatus = tradeitemstatus + self.tradestatus = tradestatus + + self.items = [] + + sql = 'select * from tradelist where messageid = %(uid)s;' + result = doquery(sql, {"uid": messageid}) + + complete = True + for item in result: + ti = TradeItem(item[0]) + ti.itemid = item[1] + ti.messageid = item[2] + ti.userid = item[3] + ti.acceptstatus = item[4] + ti.item = items.SiteItem.create(ti.itemid) + ti.user = users.SiteUser.create(users.user_by_uid(ti.userid)) + + self.items.append(ti) + + if (ti.acceptstatus != tradeitemstatus['accepted']): + complete = False + + if complete == True and self.status < tradestatus['settled_trade']: + self.status = tradestatus['complete_trade'] + + def settle(self): + return self.setstatus(tradestatus['settled_trade']) + + def reject(self): + return self.setstatus(tradestatus['rejected_trade']) + + def cancel(self): + return self.setstatus(tradestatus['cancelled_trade']) + +def add_tradeitem(itemid, messageid, userid, acceptstatus): + sql = "insert into tradelist (itemid, messageid, userid, acceptstatus) values (%(itemid)s, %(messageid)s, %(userid)s, %(acceptstatus)s);" + doquery(sql, { 'itemid': itemid, 'messageid': messageid, 'userid': userid, 'acceptstatus': acceptstatus }) diff --git a/pool/shard000/Python/0000096_dl_cleanup.py b/pool/shard000/Python/0000096_dl_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..1acb0495827b5ff05c4a982a528dc7aa5bd6a59e --- /dev/null +++ b/pool/shard000/Python/0000096_dl_cleanup.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +""" +# OpenWrt download directory cleanup utility. +# Delete all but the very last version of the program tarballs. +# +# Copyright (C) 2010-2015 Michael Buesch +# Copyright (C) 2013-2015 OpenWrt.org +""" + +from __future__ import print_function + +import sys +import os +import re +import getopt + +# Commandline options +opt_dryrun = False + + +def parseVer_1234(match, filepath): + progname = match.group(1) + progversion = (int(match.group(2)) << 64) |\ + (int(match.group(3)) << 48) |\ + (int(match.group(4)) << 32) |\ + (int(match.group(5)) << 16) + return (progname, progversion) + +def parseVer_123(match, filepath): + progname = match.group(1) + try: + patchlevel = match.group(5) + except IndexError as e: + patchlevel = None + if patchlevel: + patchlevel = ord(patchlevel[0]) + else: + patchlevel = 0 + progversion = (int(match.group(2)) << 64) |\ + (int(match.group(3)) << 48) |\ + (int(match.group(4)) << 32) |\ + patchlevel + return (progname, progversion) + +def parseVer_12(match, filepath): + progname = match.group(1) + try: + patchlevel = match.group(4) + except IndexError as e: + patchlevel = None + if patchlevel: + patchlevel = ord(patchlevel[0]) + else: + patchlevel = 0 + progversion = (int(match.group(2)) << 64) |\ + (int(match.group(3)) << 48) |\ + patchlevel + return (progname, progversion) + +def parseVer_r(match, filepath): + progname = match.group(1) + progversion = (int(match.group(2)) << 64) + return (progname, progversion) + +def parseVer_ymd(match, filepath): + progname = match.group(1) + progversion = (int(match.group(2)) << 64) |\ + (int(match.group(3)) << 48) |\ + (int(match.group(4)) << 32) + return (progname, progversion) + +def parseVer_GIT(match, filepath): + progname = match.group(1) + st = os.stat(filepath) + progversion = int(st.st_mtime) << 64 + return (progname, progversion) + +extensions = ( + ".tar.gz", + ".tar.bz2", + ".tar.xz", + ".orig.tar.gz", + ".orig.tar.bz2", + ".orig.tar.xz", + ".zip", + ".tgz", + ".tbz", + ".txz", +) + +versionRegex = ( + (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)\.(\d+)"), parseVer_1234), # xxx-1.2.3.4 + (re.compile(r"(.+)[-_](\d\d\d\d)-?(\d\d)-?(\d\d)"), parseVer_ymd), # xxx-YYYY-MM-DD + (re.compile(r"(.+)[-_]([0-9a-fA-F]{40,40})"), parseVer_GIT), # xxx-GIT_SHASUM + (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)(\w?)"), parseVer_123), # xxx-1.2.3a + (re.compile(r"(.+)[-_](\d+)_(\d+)_(\d+)"), parseVer_123), # xxx-1_2_3 + (re.compile(r"(.+)[-_](\d+)\.(\d+)(\w?)"), parseVer_12), # xxx-1.2a + (re.compile(r"(.+)[-_]r?(\d+)"), parseVer_r), # xxx-r1111 +) + +blacklist = [ + ("linux", re.compile(r"linux-\d.*")), + ("gcc", re.compile(r"gcc-.*")), + ("wl_apsta", re.compile(r"wl_apsta.*")), + (".fw", re.compile(r".*\.fw")), + (".arm", re.compile(r".*\.arm")), + (".bin", re.compile(r".*\.bin")), + ("rt-firmware", re.compile(r"RT[\d\w]+_Firmware.*")), +] + +class EntryParseError(Exception): pass + +class Entry: + def __init__(self, directory, filename): + self.directory = directory + self.filename = filename + self.progname = "" + self.fileext = "" + + for ext in extensions: + if filename.endswith(ext): + filename = filename[0:0-len(ext)] + self.fileext = ext + break + else: + print(self.filename, "has an unknown file-extension") + raise EntryParseError("ext") + for (regex, parseVersion) in versionRegex: + match = regex.match(filename) + if match: + (self.progname, self.version) = parseVersion( + match, directory + "/" + filename + self.fileext) + break + else: + print(self.filename, "has an unknown version pattern") + raise EntryParseError("ver") + + def getPath(self): + return (self.directory + "/" + self.filename).replace("//", "/") + + def deleteFile(self): + path = self.getPath() + print("Deleting", path) + if not opt_dryrun: + os.unlink(path) + + def __ge__(self, y): + return self.version >= y.version + +def usage(): + print("OpenWrt download directory cleanup utility") + print("Usage: " + sys.argv[0] + " [OPTIONS] ") + print("") + print(" -d|--dry-run Do a dry-run. Don't delete any files") + print(" -B|--show-blacklist Show the blacklist and exit") + print(" -w|--whitelist ITEM Remove ITEM from blacklist") + +def main(argv): + global opt_dryrun + + try: + (opts, args) = getopt.getopt(argv[1:], + "hdBw:", + [ "help", "dry-run", "show-blacklist", "whitelist=", ]) + if len(args) != 1: + usage() + return 1 + except getopt.GetoptError as e: + usage() + return 1 + directory = args[0] + + if not os.path.exists(directory): + print("Can't find dl path", directory) + return 1 + + for (o, v) in opts: + if o in ("-h", "--help"): + usage() + return 0 + if o in ("-d", "--dry-run"): + opt_dryrun = True + if o in ("-w", "--whitelist"): + for i in range(0, len(blacklist)): + (name, regex) = blacklist[i] + if name == v: + del blacklist[i] + break + else: + print("Whitelist error: Item", v,\ + "is not in blacklist") + return 1 + if o in ("-B", "--show-blacklist"): + for (name, regex) in blacklist: + sep = "\t\t" + if len(name) >= 8: + sep = "\t" + print("%s%s(%s)" % (name, sep, regex.pattern)) + return 0 + + # Create a directory listing and parse the file names. + entries = [] + for filename in os.listdir(directory): + if filename == "." or filename == "..": + continue + for (name, regex) in blacklist: + if regex.match(filename): + if opt_dryrun: + print(filename, "is blacklisted") + break + else: + try: + entries.append(Entry(directory, filename)) + except EntryParseError as e: + pass + + # Create a map of programs + progmap = {} + for entry in entries: + if entry.progname in progmap.keys(): + progmap[entry.progname].append(entry) + else: + progmap[entry.progname] = [entry,] + + # Traverse the program map and delete everything but the last version + for prog in progmap: + lastVersion = None + versions = progmap[prog] + for version in versions: + if lastVersion is None or version >= lastVersion: + lastVersion = version + if lastVersion: + for version in versions: + if version is not lastVersion: + version.deleteFile() + if opt_dryrun: + print("Keeping", lastVersion.getPath()) + + return 0 + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/pool/shard000/Python/0000099_utils.py b/pool/shard000/Python/0000099_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..85a327612b89782d672db4c7b3a62f4feb7f984a --- /dev/null +++ b/pool/shard000/Python/0000099_utils.py @@ -0,0 +1,20 @@ +def create_instance(client, name, image_name, flavor_name, network_name, key_name): + """ An instance of Cloud OS is made. + + Args: + client: Cloud OS client. + name: Instance name. + image_name: Instance image name. + flavor_name: Instance flavor_name. + network_name: Instance attach network_name. + key_name: Security key name. + Returns: + client.servers.server: instance + """ + image = client.images.find(name=image_name) + flavor = client.flavors.find(name=flavor_name) + net = client.networks.find(label=network_name) + nics = [{'net-id': net.id}] + instance = client.servers.create( + name=name, image=image, flavor=flavor, key_name=key_name, nics=nics) + return instance diff --git a/pool/shard000/Python/0000100_conf.py b/pool/shard000/Python/0000100_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..6347e850a935d69cff750dc3e31aff5d96757e64 --- /dev/null +++ b/pool/shard000/Python/0000100_conf.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('../')) + + +# -- Project information ----------------------------------------------------- + +project = 'neuropythy' +copyright = '2018, Noah C. Benson' +author = 'Noah C. Benson' + +# The short X.Y version +version = '' +# The full version, including alpha/beta/rc tags +release = '' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['.templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['.build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['.static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'neuropythydoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'neuropythy.tex', 'neuropythy Documentation', + 'Noah C. Benson', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'neuropythy', 'neuropythy Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'neuropythy', 'neuropythy Documentation', + author, 'neuropythy', 'One line description of project.', + 'Miscellaneous'), +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + + +# -- Extension configuration ------------------------------------------------- diff --git a/pool/shard000/Python/0000101_run_main_gj01.py b/pool/shard000/Python/0000101_run_main_gj01.py new file mode 100644 index 0000000000000000000000000000000000000000..c07234fbd4064e488b24a03fb8e7fc3172f957fb --- /dev/null +++ b/pool/shard000/Python/0000101_run_main_gj01.py @@ -0,0 +1,116 @@ +# flake8: noqa + +import os +import sys +# 将repostory的目录i,作为根目录,添加到系统环境中。 +ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) +sys.path.append(ROOT_PATH) +print(f'append {ROOT_PATH} into sys.path') + +from vnpy.event import EventEngine + +from vnpy.trader.engine import MainEngine +from vnpy.trader.ui import MainWindow, create_qapp + +#from vnpy.gateway.binancef import BinancefGateway +# from vnpy.gateway.bitmex import BitmexGateway +# from vnpy.gateway.futu import FutuGateway +# from vnpy.gateway.ib import IbGateway +# from vnpy.gateway.ctp import CtpGateway +# from vnpy.gateway.ctptest import CtptestGateway +# from vnpy.gateway.mini import MiniGateway +# from vnpy.gateway.sopt import SoptGateway +# from vnpy.gateway.minitest import MinitestGateway +# from vnpy.gateway.femas import FemasGateway +# from vnpy.gateway.tiger import TigerGateway +# from vnpy.gateway.oes import OesGateway +# from vnpy.gateway.okex import OkexGateway +# from vnpy.gateway.huobi import HuobiGateway +# from vnpy.gateway.bitfinex import BitfinexGateway +# from vnpy.gateway.onetoken import OnetokenGateway +# from vnpy.gateway.okexf import OkexfGateway +# from vnpy.gateway.okexs import OkexsGateway +# from vnpy.gateway.xtp import XtpGateway +# from vnpy.gateway.hbdm import HbdmGateway +# from vnpy.gateway.tap import TapGateway +# from vnpy.gateway.tora import ToraGateway +# from vnpy.gateway.alpaca import AlpacaGateway +# from vnpy.gateway.da import DaGateway +# from vnpy.gateway.coinbase import CoinbaseGateway +# from vnpy.gateway.bitstamp import BitstampGateway +# from vnpy.gateway.gateios import GateiosGateway +# from vnpy.gateway.bybit import BybitGateway +from vnpy.gateway.gj import GjGateway + +# from vnpy.app.cta_crypto import CtaCryptoApp +from vnpy.app.cta_stock import CtaStockApp +# from vnpy.app.csv_loader import CsvLoaderApp +# from vnpy.app.algo_trading import AlgoTradingApp +# from vnpy.app.cta_backtester import CtaBacktesterApp +# from vnpy.app.data_recorder import DataRecorderApp +# from vnpy.app.tick_recorder import TickRecorderApp +# from vnpy.app.risk_manager import RiskManagerApp +# from vnpy.app.script_trader import ScriptTraderApp +# from vnpy.app.rpc_service import RpcServiceApp +# from vnpy.app.spread_trading import SpreadTradingApp +# from vnpy.app.portfolio_manager import PortfolioManagerApp + + +def main(): + """""" + qapp = create_qapp() + + event_engine = EventEngine() + + main_engine = MainEngine(event_engine) + + main_engine.add_gateway(GjGateway, 'gj01') + #main_engine.add_gateway(CtpGateway) + # main_engine.add_gateway(CtptestGateway) + # main_engine.add_gateway(MiniGateway) + # main_engine.add_gateway(SoptGateway) + # main_engine.add_gateway(MinitestGateway) + # main_engine.add_gateway(FemasGateway) + # main_engine.add_gateway(IbGateway) + # main_engine.add_gateway(FutuGateway) + #main_engine.add_gateway(BitmexGateway) + # main_engine.add_gateway(TigerGateway) + # main_engine.add_gateway(OesGateway) + # main_engine.add_gateway(OkexGateway) + # main_engine.add_gateway(HuobiGateway) + # main_engine.add_gateway(BitfinexGateway) + # main_engine.add_gateway(OnetokenGateway) + # main_engine.add_gateway(OkexfGateway) + # main_engine.add_gateway(HbdmGateway) + # main_engine.add_gateway(XtpGateway) + # main_engine.add_gateway(TapGateway) + # main_engine.add_gateway(ToraGateway) + # main_engine.add_gateway(AlpacaGateway) + # main_engine.add_gateway(OkexsGateway) + # main_engine.add_gateway(DaGateway) + # main_engine.add_gateway(CoinbaseGateway) + # main_engine.add_gateway(BitstampGateway) + # main_engine.add_gateway(GateiosGateway) + #main_engine.add_gateway(BybitGateway) + + #main_engine.add_app(CtaStrategyApp) + main_engine.add_app(CtaStockApp) + #main_engine.add_app(CtaBacktesterApp) + # main_engine.add_app(CsvLoaderApp) + # main_engine.add_app(AlgoTradingApp) + # main_engine.add_app(DataRecorderApp) + #main_engine.add_app(TickRecorderApp) + # main_engine.add_app(RiskManagerApp) + # main_engine.add_app(ScriptTraderApp) + # main_engine.add_app(RpcServiceApp) + # main_engine.add_app(SpreadTradingApp) + #main_engine.add_app(PortfolioManagerApp) + + main_window = MainWindow(main_engine, event_engine) + main_window.showMaximized() + + qapp.exec() + + +if __name__ == "__main__": + main() diff --git a/pool/shard000/Python/0000102_autoencoder.py b/pool/shard000/Python/0000102_autoencoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8c52e2f3eb9af8f1b2c8fe691a853a6327c08303 --- /dev/null +++ b/pool/shard000/Python/0000102_autoencoder.py @@ -0,0 +1,38 @@ +""" +AutoEncoder Models should be comparable. +""" + +from model_base import * + +class H2OAutoEncoderModel(ModelBase): + """ + Class for Binomial models. + """ + def __init__(self, dest_key, model_json): + super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) + + def anomaly(self,test_data): + """ + Return the reconstruction error for an AutoEncoder models + """ + if not test_data: raise ValueError("Must specify test data") + # cbind the test_data vecs together and produce a temp key + test_data_key = H2OFrame.send_frame(test_data) + # get the anomaly + j = H2OConnection.post_json("Predictions/models/" + self._key + "/frames/" + test_data_key, reconstruction_error=True) + # extract the frame data + anomaly_frame_key = j["model_metrics"][0]["predictions"]["key"]["name"] + anomaly_frame_meta = h2o.frame(anomaly_frame_key)["frames"][0] + # create vecs by extracting vec_keys, col length, and col names + vec_keys = anomaly_frame_meta["vec_keys"] + rows = anomaly_frame_meta["rows"] + cols = [col["label"] for col in anomaly_frame_meta["columns"]] + vecs = H2OVec.new_vecs(zip(cols, vec_keys), rows) + # remove test_data + h2o.remove(test_data_key) + # return new H2OFrame object + return H2OFrame(vecs=vecs) + +class H2OAutoEncoderModelMetrics(object): + def __init__(self, metric_json): + self._metric_json = metric_json \ No newline at end of file diff --git a/pool/shard000/Python/0000103_edit_handlers.py b/pool/shard000/Python/0000103_edit_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..421135d4f9926f7ab6515247133f7552e6b863de --- /dev/null +++ b/pool/shard000/Python/0000103_edit_handlers.py @@ -0,0 +1,133 @@ +from django.conf import settings +from django.conf.urls import url +from django.db import models +from django.urls import reverse +from django.utils.html import format_html, format_html_join + +from wagtail.admin.edit_handlers import BaseChooserPanel +from wagtail.core import hooks + +from .widgets import AdminModelChooser +from .views import ModelChooserView, ModelChosenView + + +class ModelChooserPanel(BaseChooserPanel): + object_type_name = 'model' + widget_class = None + model = None + chooser_view = None + chosen_view = None + + def widget_overrides(self): + return {self.field_name: self.widget_class} + + @classmethod + def register_with_wagtail(cls): + @hooks.register('register_admin_urls') + def register_admin_urls(): + return cls.get_admin_urls_for_registration() + + @hooks.register('insert_editor_js') + def insert_editor_js(): + return cls.get_editor_js_for_registration() + + @classmethod + def get_admin_urls_for_registration(cls): + return ( + url(r'^{}/chooser/$'.format(cls.model._meta.model_name), cls.chooser_view.as_view(), + name='{}_chooser'.format(cls.model._meta.model_name)), + url(r'^{}/chooser/(?P\d+)/$'.format(cls.model._meta.model_name), cls.chosen_view.as_view(), + name='{}_chosen'.format(cls.model._meta.model_name)), + ) + + @classmethod + def get_editor_js_for_registration(cls): + js_files = cls.get_editor_js_files() + + js_includes = format_html_join( + '\n', '', + ((settings.STATIC_URL, filename) for filename in js_files) + ) + return js_includes + format_html( + """ + + """, + cls.model._meta.object_name, + reverse('{}_chooser'.format(cls.model._meta.model_name)) + ) + + @classmethod + def get_editor_js_files(cls): + return [ + 'wagtailmodelchooser/js/model-chooser.js', + ] + + +def register_chooser_for_model( + model, widget_class=None, widget_attrs={}, chooser_panel_base_class=None, chooser_view=None, + chooser_view_attrs={}, chosen_view=None, chosen_view_attrs={}, title_field='title'): + + # Ensure the model is well defined + assert issubclass(model, models.Model), "model must be a subclass of Django's models.Model" + + # Build the chooser panel class + class_name = model._meta.object_name + + # Check or build the widget class + if widget_class: + if not getattr(widget_class, 'model', None) == model: + raise AssertionError("Incorrect model attribute for {}: '{}.{}' is expected".format( + widget_class.__name__, model.__module__, model.__name__)) + else: + defaults = { + 'model': model, + 'title_field': title_field, + } + defaults.update(**widget_attrs) + widget_class = type(str('Admin{}Chooser'.format(class_name)), (AdminModelChooser,), defaults) + + # Check or build the chooser view + if chooser_view: + if not getattr(chooser_view, 'model', None) == model: + raise AssertionError("Incorrect model attribute for {}: '{}.{}' is expected".format( + chooser_view.__name__, model.__module__, model.__name__)) + assert hasattr(chooser_view, 'title_field'), "chooser_view must define 'title_field'" + assert hasattr(chooser_view, 'model_chooser_url_name'), "chooser_view must define 'model_chooser_url_name'" + assert hasattr(chooser_view, 'model_chosen_url_name'), "chooser_view must define 'model_chosen_url_name'" + else: + defaults = { + 'model': model, + 'ordering': ['-pk'], + 'title_field': title_field, + 'model_chooser_url_name': '{}_chooser'.format(model._meta.model_name), + 'model_chosen_url_name': '{}_chosen'.format(model._meta.model_name), + } + defaults.update(**chooser_view_attrs) + chooser_view = type(str('{}ChooserView'.format(class_name)), (ModelChooserView,), defaults) + + # Check or build the chosen view + if chosen_view: + if not getattr(chosen_view, 'model', None) == model: + raise AssertionError("Incorrect model attribute for {}: '{}.{}' is expected".format( + chosen_view.__name__, model.__module__, model.__name__)) + assert hasattr(chosen_view, 'title_field'), "chooser_view must define 'title_field'" + else: + defaults = {'model': model, 'title_field': title_field} + defaults.update(**chosen_view_attrs) + chosen_view = type(str('{}ChosenView'.format(class_name)), (ModelChosenView,), defaults) + + # Build the chooser panel class + chooser_panel_class = type(str('{}ChooserPanel'.format(class_name)), (ModelChooserPanel,), { + 'object_type_name': model._meta.model_name, + 'widget_class': widget_class, + 'model': model, + 'chooser_view': chooser_view, + 'chosen_view': chosen_view, + }) + + # Register with wagtail hooks + chooser_panel_class.register_with_wagtail() + + return chooser_panel_class diff --git a/pool/shard000/Python/0000106_helpers.py b/pool/shard000/Python/0000106_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f1b8c1c1a2b4a8261713aa98b4fdc5b384ea4f --- /dev/null +++ b/pool/shard000/Python/0000106_helpers.py @@ -0,0 +1,34 @@ +counter = 0 +variables = [] + +class Variable: + def __init__(self): + global counter + self._index = counter + counter += 1 + def get_index(self): + return self._index + def to_string(self): + return 'V[ ' + str(self._index) + ']' + +def createVariableInstance(): + v = Variable() + variables.append(v) + return v + +def createVarPos(): + x = createVariableInstance() + y = createVariableInstance() + z = createVariableInstance() + return [x, y, z] + +def equaliseTwoVars(x, y, relations): + fn_str = 'lambda V: ' + x.to_string() + ' - ( ' + y.to_string() + ')' + print (fn_str) + fn = eval(fn_str) + relations.append(fn) + +def equaliseTwoLists(xs, ys, relations): + length = len(xs) + for i in range(0, length): + equaliseTwoVars(xs[i], ys[i], relations) diff --git a/pool/shard000/Python/0000107_band.py b/pool/shard000/Python/0000107_band.py new file mode 100644 index 0000000000000000000000000000000000000000..e78b370c09ee8181939a90031effb13563410b0b --- /dev/null +++ b/pool/shard000/Python/0000107_band.py @@ -0,0 +1,249 @@ +from ctypes import byref, c_double, c_int, c_void_p + +from django.contrib.gis.gdal.base import GDALBase +from django.contrib.gis.gdal.error import GDALException +from django.contrib.gis.gdal.prototypes import raster as capi +from django.contrib.gis.shortcuts import numpy +from django.utils.encoding import force_text + +from .const import GDAL_INTEGER_TYPES, GDAL_PIXEL_TYPES, GDAL_TO_CTYPES + + +class GDALBand(GDALBase): + """ + Wrap a GDAL raster band, needs to be obtained from a GDALRaster object. + """ + def __init__(self, source, index): + self.source = source + self._ptr = capi.get_ds_raster_band(source._ptr, index) + + def _flush(self): + """ + Call the flush method on the Band's parent raster and force a refresh + of the statistics attribute when requested the next time. + """ + self.source._flush() + self._stats_refresh = True + + @property + def description(self): + """ + Return the description string of the band. + """ + return force_text(capi.get_band_description(self._ptr)) + + @property + def width(self): + """ + Width (X axis) in pixels of the band. + """ + return capi.get_band_xsize(self._ptr) + + @property + def height(self): + """ + Height (Y axis) in pixels of the band. + """ + return capi.get_band_ysize(self._ptr) + + @property + def pixel_count(self): + """ + Return the total number of pixels in this band. + """ + return self.width * self.height + + _stats_refresh = False + + def statistics(self, refresh=False, approximate=False): + """ + Compute statistics on the pixel values of this band. + + The return value is a tuple with the following structure: + (minimum, maximum, mean, standard deviation). + + If approximate=True, the statistics may be computed based on overviews + or a subset of image tiles. + + If refresh=True, the statistics will be computed from the data directly, + and the cache will be updated where applicable. + + For empty bands (where all pixel values are nodata), all statistics + values are returned as None. + + For raster formats using Persistent Auxiliary Metadata (PAM) services, + the statistics might be cached in an auxiliary file. + """ + # Prepare array with arguments for capi function + smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double() + stats_args = [ + self._ptr, c_int(approximate), byref(smin), byref(smax), + byref(smean), byref(sstd), c_void_p(), c_void_p(), + ] + + if refresh or self._stats_refresh: + func = capi.compute_band_statistics + else: + # Add additional argument to force computation if there is no + # existing PAM file to take the values from. + force = True + stats_args.insert(2, c_int(force)) + func = capi.get_band_statistics + + # Computation of statistics fails for empty bands. + try: + func(*stats_args) + result = smin.value, smax.value, smean.value, sstd.value + except GDALException: + result = (None, None, None, None) + + self._stats_refresh = False + + return result + + @property + def min(self): + """ + Return the minimum pixel value for this band. + """ + return self.statistics()[0] + + @property + def max(self): + """ + Return the maximum pixel value for this band. + """ + return self.statistics()[1] + + @property + def mean(self): + """ + Return the mean of all pixel values of this band. + """ + return self.statistics()[2] + + @property + def std(self): + """ + Return the standard deviation of all pixel values of this band. + """ + return self.statistics()[3] + + @property + def nodata_value(self): + """ + Return the nodata value for this band, or None if it isn't set. + """ + # Get value and nodata exists flag + nodata_exists = c_int() + value = capi.get_band_nodata_value(self._ptr, nodata_exists) + if not nodata_exists: + value = None + # If the pixeltype is an integer, convert to int + elif self.datatype() in GDAL_INTEGER_TYPES: + value = int(value) + return value + + @nodata_value.setter + def nodata_value(self, value): + """ + Set the nodata value for this band. + """ + if value is None: + if not capi.delete_band_nodata_value: + raise ValueError('GDAL >= 2.1 required to delete nodata values.') + capi.delete_band_nodata_value(self._ptr) + elif not isinstance(value, (int, float)): + raise ValueError('Nodata value must be numeric or None.') + else: + capi.set_band_nodata_value(self._ptr, value) + self._flush() + + def datatype(self, as_string=False): + """ + Return the GDAL Pixel Datatype for this band. + """ + dtype = capi.get_band_datatype(self._ptr) + if as_string: + dtype = GDAL_PIXEL_TYPES[dtype] + return dtype + + def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False): + """ + Read or writes pixel values for this band. Blocks of data can + be accessed by specifying the width, height and offset of the + desired block. The same specification can be used to update + parts of a raster by providing an array of values. + + Allowed input data types are bytes, memoryview, list, tuple, and array. + """ + if not offset: + offset = (0, 0) + + if not size: + size = (self.width - offset[0], self.height - offset[1]) + + if not shape: + shape = size + + if any(x <= 0 for x in size): + raise ValueError('Offset too big for this raster.') + + if size[0] > self.width or size[1] > self.height: + raise ValueError('Size is larger than raster.') + + # Create ctypes type array generator + ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (shape[0] * shape[1]) + + if data is None: + # Set read mode + access_flag = 0 + # Prepare empty ctypes array + data_array = ctypes_array() + else: + # Set write mode + access_flag = 1 + + # Instantiate ctypes array holding the input data + if isinstance(data, (bytes, memoryview)) or (numpy and isinstance(data, numpy.ndarray)): + data_array = ctypes_array.from_buffer_copy(data) + else: + data_array = ctypes_array(*data) + + # Access band + capi.band_io(self._ptr, access_flag, offset[0], offset[1], + size[0], size[1], byref(data_array), shape[0], + shape[1], self.datatype(), 0, 0) + + # Return data as numpy array if possible, otherwise as list + if data is None: + if as_memoryview: + return memoryview(data_array) + elif numpy: + # reshape() needs a reshape parameter with the height first. + return numpy.frombuffer( + data_array, dtype=numpy.dtype(data_array) + ).reshape(tuple(reversed(size))) + else: + return list(data_array) + else: + self._flush() + + +class BandList(list): + def __init__(self, source): + self.source = source + list.__init__(self) + + def __iter__(self): + for idx in range(1, len(self) + 1): + yield GDALBand(self.source, idx) + + def __len__(self): + return capi.get_ds_raster_count(self.source._ptr) + + def __getitem__(self, index): + try: + return GDALBand(self.source, index + 1) + except GDALException: + raise GDALException('Unable to get band index %d' % index) diff --git a/pool/shard000/Python/0000109_test_config.py b/pool/shard000/Python/0000109_test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bb07d1a47efb2ee38f9a0d35641498504c9324e1 --- /dev/null +++ b/pool/shard000/Python/0000109_test_config.py @@ -0,0 +1,95 @@ +""" Tests for config file loading and backup """ +import copy +import json +import os + +import pytest + +from otupdate import buildroot + + +def test_load_ok(otupdate_config): + conf = buildroot.config.load_from_path(otupdate_config) + config_data = json.load(open(otupdate_config)) + assert conf.signature_required == config_data['signature_required'] + assert conf.download_storage_path == config_data['download_storage_path'] + assert conf.update_cert_path == config_data['update_cert_path'] + assert conf.path == otupdate_config + + +@pytest.mark.no_cert_path +def test_load_no_cert(otupdate_config): + conf = buildroot.config.load_from_path(otupdate_config) + assert not conf.signature_required + assert conf.update_cert_path == '/etc/opentrons-robot-signing-key.crt' + + +@pytest.mark.bad_cert_path +def test_load_bad_cert(otupdate_config): + conf = buildroot.config.load_from_path(otupdate_config) + assert not conf.signature_required + assert conf.update_cert_path == '/etc/opentrons-robot-signing-key.crt' + + +def check_defaults(conf, good_cert=True): + assert conf.signature_required == good_cert + assert conf.download_storage_path == '/var/lib/otupdate/downloads' + assert conf.update_cert_path == '/etc/opentrons-robot-signing-key.crt' + + +def test_load_bad_json(tmpdir): + path = os.path.join(tmpdir, 'badconfig') + open(path, 'w').write("this isn't json") + conf = buildroot.config.load_from_path(path) + assert conf.path == path + check_defaults(conf, False) + + assert json.load(open(path)) == {k: v for k, v in conf._asdict().items() + if k != 'path'} + + +def test_load_removes_extra_keys(otupdate_config): + orig = json.load(open(otupdate_config)) + modded = copy.copy(orig) + modded['this-key-is-extra'] = False + modded_path = os.path.join(os.path.dirname(otupdate_config), 'modded') + json.dump(modded, open(modded_path, 'w')) + buildroot.config.load_from_path(modded_path) + reverted = json.load(open(otupdate_config)) + assert reverted == orig + + +def test_load_defaults_missing(otupdate_config): + orig = json.load(open(otupdate_config)) + modded = copy.copy(orig) + del modded['download_storage_path'] + modded_path = os.path.join(os.path.dirname(otupdate_config), 'modded') + json.dump(modded, open(modded_path, 'w')) + conf = buildroot.config.load_from_path(modded_path) + assert conf.download_storage_path == '/var/lib/otupdate/downloads' + reverted = json.load(open(modded_path)) + orig['download_storage_path'] = '/var/lib/otupdate/downloads' + assert orig == reverted + + +def test_load_defaults_wrong_types(otupdate_config): + orig = json.load(open(otupdate_config)) + modded = copy.copy(orig) + modded['download_storage_path'] = 2 + modded_path = os.path.join(os.path.dirname(otupdate_config), 'modded') + json.dump(modded, open(modded_path, 'w')) + conf = buildroot.config.load_from_path(modded_path) + assert conf.download_storage_path == '/var/lib/otupdate/downloads' + reverted = json.load(open(modded_path)) + orig['download_storage_path'] = '/var/lib/otupdate/downloads' + assert orig == reverted + + +def test_load_wrong_path(tmpdir): + bad_path = os.path.join(tmpdir, 'nofile.json') + conf = buildroot.config.load_from_path(bad_path) + assert conf.path == bad_path + loaded = json.load(open(bad_path)) + assert loaded == {k: v for k, v in conf._asdict().items() + if k != 'path'} + check_defaults(conf, False) diff --git a/pool/shard000/Python/0000110_test_digest_authentication.py b/pool/shard000/Python/0000110_test_digest_authentication.py new file mode 100644 index 0000000000000000000000000000000000000000..80d963cfaa1712ac87ed1dcb486a7fcf91128819 --- /dev/null +++ b/pool/shard000/Python/0000110_test_digest_authentication.py @@ -0,0 +1,79 @@ +import os + +from django_digest.test import Client as DigestClient +from main.tests.test_base import MainTestCase +from main.models import UserProfile + + +class TestDigestAuthentication(MainTestCase): + def setUp(self): + super(MainTestCase, self).setUp() + self._create_user_and_login() + self._publish_transportation_form() + + def _authenticated_client( + self, url, username='bob', password='bob', extra={}): + client = DigestClient() + # request with no credentials + req = client.get(url, {}, **extra) + self.assertEqual(req.status_code, 401) + # apply credentials + client.set_authorization(username, password, 'Digest') + req = client.get(url, {}, **extra) + # if 204 authorization successfull, proceed + self.assertEqual(req.status_code, 204) + # submissions should use this authenticated client + return client + + def test_authenticated_submissions(self): + """ + xml_submission_file is the field name for the posted xml file. + """ + s = self.surveys[0] + xml_submission_file_path = os.path.join( + self.this_directory, 'fixtures', + 'transportation', 'instances', s, s + '.xml' + ) + # authenticate first + url = '/%s/submission' % self.user.username + #url = '/submission' + extra = { + 'REQUEST_METHOD': 'HEAD', + } + self._set_require_auth() + client = self._authenticated_client(url, extra=extra) + self.anon = client + self._make_submission(xml_submission_file_path, add_uuid=True) + self.assertEqual(self.response.status_code, 201) + + def _set_require_auth(self, auth=True): + profile, created = \ + UserProfile.objects.get_or_create(user=self.user) + profile.require_auth = auth + profile.save() + + def test_fail_authenticated_submissions_to_wrong_account(self): + username = 'dennis' + prev_user = self.user + # set require_auth b4 we switch user + self._set_require_auth() + self._create_user_and_login(username=username, password=username) + self._set_require_auth() + s = self.surveys[0] + xml_submission_file_path = os.path.join( + self.this_directory, 'fixtures', + 'transportation', 'instances', s, s + '.xml' + ) + url = '/%s/submission' % prev_user.username + extra = { + 'REQUEST_METHOD': 'HEAD', + } + client = self._authenticated_client( + url, username=username, password=username, extra=extra) + self._make_submission(xml_submission_file_path, add_uuid=True) + # Not allowed + self.assertEqual(self.response.status_code, 401) + self.anon = client + self._make_submission(xml_submission_file_path, add_uuid=True) + # Not allowed + self.assertEqual(self.response.status_code, 405) diff --git a/pool/shard000/Python/0000117_subject_result.py b/pool/shard000/Python/0000117_subject_result.py new file mode 100644 index 0000000000000000000000000000000000000000..8e81933a0e2361272c6965f15c3a4af1bfab0e21 --- /dev/null +++ b/pool/shard000/Python/0000117_subject_result.py @@ -0,0 +1,31 @@ +from openerp.osv import osv,fields + +class subject_result_wiz(osv.osv_memory): + + _name= "subject.result.wiz" + _description= "Subject Wise Result" + + _columns={ + 'result_ids': fields.many2many("exam.subject",'subject_result_wiz_rel','result_id',"exam_id","Exam Subjects",select=1), + } + + def result_report(self, cr, uid, ids, context): + data = self.read(cr, uid, ids)[0] + + datas = { + 'ids': context.get('active_ids',[]), + 'form': data, + + 'model':'exam.result', + } + return {'type': 'ir.actions.report.xml', 'report_name': 'add_exam_result', 'datas':datas } + +subject_result_wiz() + + + +# def _get_activeresult(self, cr, uid, context=None): +# list = [] +# if not list: +# list.append(ID) +# return self.pool.get('exam.result').search(cr, uid, [("active","=",True)], context=None) \ No newline at end of file diff --git a/pool/shard000/Python/0000120_app.py b/pool/shard000/Python/0000120_app.py new file mode 100644 index 0000000000000000000000000000000000000000..0bec70728166ada9af81b21a4cedf09ca6f57949 --- /dev/null +++ b/pool/shard000/Python/0000120_app.py @@ -0,0 +1,59 @@ + +import os +import sys +import falcon +from falcon_cors import CORS + +from .user import UserResource, UsersEndpoint +from .validator import Validator +from .utils import error_serializer +from .db import DB +from .cfg import Config + + +# pick the config directory +config_dir = os.environ.get('OWNJSON_CONFIG_DIR', None) +if config_dir is None: + prefix = os.environ.get('XDG_CONFIG_DIR') + if prefix is None: + prefix = os.environ.get('HOME') + config_dir = os.path.join(prefix, '.config/ownjson') + +# load config +config = Config() +ok = config.load(config_dir) +if not ok: + sys.exit(1) + +# set up the validator object +schema_dir = os.path.join(config_dir, 'server_schemas') +server_validator = Validator() +for name in config.config['server_schemas']: + server_validator.add_schema(name, os.path.join(schema_dir, '%s.schema' % (name) )) + + +uri = config.get('db_uri') +db_name = config.get('db_name') +db = DB(uri, db_name) + +# data to send to kwargs for each resource +data = { + 'config': config.config, + 'server_validator': server_validator, + 'db': db +} + +# set up the resources +users = UserResource(**data) +user_endpoint = UsersEndpoint(**data) + +cors = CORS(allow_all_origins=True, allow_all_methods=True, + allow_headers_list=['accept', 'content-type', 'authorization']) + +# set up the wsgi app and add routes +app = falcon.API(middleware=[ + cors.middleware +]) +app.set_error_serializer(error_serializer) +app.add_route('/api/{username}', users) +app.add_route('/api/users', user_endpoint) diff --git a/pool/shard000/Python/0000124_outcomes.py b/pool/shard000/Python/0000124_outcomes.py new file mode 100644 index 0000000000000000000000000000000000000000..756b4098b36a2ec01b234fabee57a47991e4e3ff --- /dev/null +++ b/pool/shard000/Python/0000124_outcomes.py @@ -0,0 +1,232 @@ +"""Exception classes and constants handling test outcomes as well as +functions creating them.""" +import sys +from typing import Any +from typing import Callable +from typing import cast +from typing import Optional +from typing import Type +from typing import TypeVar + +TYPE_CHECKING = False # Avoid circular import through compat. + +if TYPE_CHECKING: + from typing import NoReturn + from typing_extensions import Protocol +else: + # typing.Protocol is only available starting from Python 3.8. It is also + # available from typing_extensions, but we don't want a runtime dependency + # on that. So use a dummy runtime implementation. + from typing import Generic + + Protocol = Generic + + +class OutcomeException(BaseException): + """OutcomeException and its subclass instances indicate and contain info + about test and collection outcomes.""" + + def __init__(self, msg: Optional[str] = None, pytrace: bool = True) -> None: + if msg is not None and not isinstance(msg, str): + error_msg = ( # type: ignore[unreachable] + "{} expected string as 'msg' parameter, got '{}' instead.\n" + "Perhaps you meant to use a mark?" + ) + raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__)) + BaseException.__init__(self, msg) + self.msg = msg + self.pytrace = pytrace + + def __repr__(self) -> str: + if self.msg is not None: + return self.msg + return f"<{self.__class__.__name__} instance>" + + __str__ = __repr__ + + +TEST_OUTCOME = (OutcomeException, Exception) + + +class Skipped(OutcomeException): + # XXX hackish: on 3k we fake to live in the builtins + # in order to have Skipped exception printing shorter/nicer + __module__ = "builtins" + + def __init__( + self, + msg: Optional[str] = None, + pytrace: bool = True, + allow_module_level: bool = False, + *, + _use_item_location: bool = False, + ) -> None: + OutcomeException.__init__(self, msg=msg, pytrace=pytrace) + self.allow_module_level = allow_module_level + # If true, the skip location is reported as the item's location, + # instead of the place that raises the exception/calls skip(). + self._use_item_location = _use_item_location + + +class Failed(OutcomeException): + """Raised from an explicit call to pytest.fail().""" + + __module__ = "builtins" + + +class Exit(Exception): + """Raised for immediate program exits (no tracebacks/summaries).""" + + def __init__( + self, msg: str = "unknown reason", returncode: Optional[int] = None + ) -> None: + self.msg = msg + self.returncode = returncode + super().__init__(msg) + + +# Elaborate hack to work around https://github.com/python/mypy/issues/2087. +# Ideally would just be `exit.Exception = Exit` etc. + +_F = TypeVar("_F", bound=Callable[..., object]) +_ET = TypeVar("_ET", bound=Type[BaseException]) + + +class _WithException(Protocol[_F, _ET]): + Exception: _ET + __call__: _F + + +def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]: + def decorate(func: _F) -> _WithException[_F, _ET]: + func_with_exception = cast(_WithException[_F, _ET], func) + func_with_exception.Exception = exception_type + return func_with_exception + + return decorate + + +# Exposed helper methods. + + +@_with_exception(Exit) +def exit(msg: str, returncode: Optional[int] = None) -> "NoReturn": + """Exit testing process. + + :param str msg: Message to display upon exit. + :param int returncode: Return code to be used when exiting pytest. + """ + __tracebackhide__ = True + raise Exit(msg, returncode) + + +@_with_exception(Skipped) +def skip(msg: str = "", *, allow_module_level: bool = False) -> "NoReturn": + """Skip an executing test with the given message. + + This function should be called only during testing (setup, call or teardown) or + during collection by using the ``allow_module_level`` flag. This function can + be called in doctests as well. + + :param bool allow_module_level: + Allows this function to be called at module level, skipping the rest + of the module. Defaults to False. + + .. note:: + It is better to use the :ref:`pytest.mark.skipif ref` marker when + possible to declare a test to be skipped under certain conditions + like mismatching platforms or dependencies. + Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP + `_) + to skip a doctest statically. + """ + __tracebackhide__ = True + raise Skipped(msg=msg, allow_module_level=allow_module_level) + + +@_with_exception(Failed) +def fail(msg: str = "", pytrace: bool = True) -> "NoReturn": + """Explicitly fail an executing test with the given message. + + :param str msg: + The message to show the user as reason for the failure. + :param bool pytrace: + If False, msg represents the full failure information and no + python traceback will be reported. + """ + __tracebackhide__ = True + raise Failed(msg=msg, pytrace=pytrace) + + +class XFailed(Failed): + """Raised from an explicit call to pytest.xfail().""" + + +@_with_exception(XFailed) +def xfail(reason: str = "") -> "NoReturn": + """Imperatively xfail an executing test or setup function with the given reason. + + This function should be called only during testing (setup, call or teardown). + + .. note:: + It is better to use the :ref:`pytest.mark.xfail ref` marker when + possible to declare a test to be xfailed under certain conditions + like known bugs or missing features. + """ + __tracebackhide__ = True + raise XFailed(reason) + + +def importorskip( + modname: str, minversion: Optional[str] = None, reason: Optional[str] = None +) -> Any: + """Import and return the requested module ``modname``, or skip the + current test if the module cannot be imported. + + :param str modname: + The name of the module to import. + :param str minversion: + If given, the imported module's ``__version__`` attribute must be at + least this minimal version, otherwise the test is still skipped. + :param str reason: + If given, this reason is shown as the message when the module cannot + be imported. + + :returns: + The imported module. This should be assigned to its canonical name. + + Example:: + + docutils = pytest.importorskip("docutils") + """ + import warnings + + __tracebackhide__ = True + compile(modname, "", "eval") # to catch syntaxerrors + + with warnings.catch_warnings(): + # Make sure to ignore ImportWarnings that might happen because + # of existing directories with the same name we're trying to + # import but without a __init__.py file. + warnings.simplefilter("ignore") + try: + __import__(modname) + except ImportError as exc: + if reason is None: + reason = f"could not import {modname!r}: {exc}" + raise Skipped(reason, allow_module_level=True) from None + mod = sys.modules[modname] + if minversion is None: + return mod + verattr = getattr(mod, "__version__", None) + if minversion is not None: + # Imported lazily to improve start-up time. + from packaging.version import Version + + if verattr is None or Version(verattr) < Version(minversion): + raise Skipped( + "module %r has __version__ %r, required is: %r" + % (modname, verattr, minversion), + allow_module_level=True, + ) + return mod diff --git a/pool/shard000/Python/0000126_call.py b/pool/shard000/Python/0000126_call.py new file mode 100644 index 0000000000000000000000000000000000000000..686dcab56f04d9ca031ee28217ade22e6251cc34 --- /dev/null +++ b/pool/shard000/Python/0000126_call.py @@ -0,0 +1,48 @@ +import re + +import twilio.twiml.voice_response + +import vbx +import vbx.config + + +number = re.compile(r'^[\d\+\-\(\) ]+$') + + +class Call(vbx.Event): + def __init__(self, request): + super().__init__(request) + + self.sid = request['CallSid'] + self.status = request['CallStatus'] + self.direction = request['Direction'] + + try: + self.forwarded_from = request['ForwardedFrom'] + except KeyError: + self.forwarded_from = None + + try: + self.caller_name = request['CallerName'] + except KeyError: + self.caller_name = None + + def handle(self, flows): + response = twilio.twiml.voice_response.VoiceResponse() + + if self.to == vbx.config.number: + for flow in flows: + flow.dial(self, response) + + if not flow.completed and flow.next: + response.redirect(flow.next) + break + else: + dial = response.dial(self.to, caller_id=vbx.config.number) + + if number.match(self.to): + dial.number(self.to) + else: + dial.client(self.to) + + return response diff --git a/pool/shard000/Python/0000128_getSize.py b/pool/shard000/Python/0000128_getSize.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9df162519e59bf541dc4be330dfd985a1ccdc2 --- /dev/null +++ b/pool/shard000/Python/0000128_getSize.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# [HARPIA PROJECT] +# +# +# S2i - Intelligent Industrial Systems +# DAS - Automation and Systems Department +# UFSC - Federal University of Santa Catarina +# Copyright: 2006 - 2007 Luis Carlos Dill Junges (lcdjunges@yahoo.com.br), Clovis Peruchi Scotti (scotti@ieee.org), +# Guilherme Augusto Rutzen (rutzen@das.ufsc.br), Mathias Erdtmann (erdtmann@gmail.com) and S2i (www.s2i.das.ufsc.br) +# 2007 - 2009 Clovis Peruchi Scotti (scotti@ieee.org), S2i (www.s2i.das.ufsc.br) +# +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, 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 . +# +# For further information, check the COPYING file distributed with this software. +# +#---------------------------------------------------------------------- + +from harpia.GladeWindow import GladeWindow +from harpia.amara import binderytools as bt +import gtk +from harpia.s2icommonproperties import S2iCommonProperties +#i18n +import os +import gettext +APP='harpia' +DIR=os.environ['HARPIA_DATA_DIR']+'po' +_ = gettext.gettext +gettext.bindtextdomain(APP, DIR) +gettext.textdomain(APP) + +#---------------------------------------------------------------------- + +class Properties( GladeWindow, S2iCommonProperties ): + + #---------------------------------------------------------------------- + + def __init__( self, PropertiesXML, S2iBlockProperties): + + self.m_sDataDir = os.environ['HARPIA_DATA_DIR'] + + filename = self.m_sDataDir+'glade/getSize.glade' + self.m_oPropertiesXML = PropertiesXML + self.m_oS2iBlockProperties = S2iBlockProperties + + widget_list = [ + 'Properties', + 'propBackgroundColor', + 'propBorderColor', + 'propHelpView' + ] + + handlers = [ + 'on_prop_cancel_clicked', + 'on_prop_confirm_clicked', + 'on_propBackColorButton_clicked', + 'on_propBorderColorButton_clicked' + ] + + top_window = 'Properties' + + GladeWindow.__init__(self, filename, top_window, widget_list, handlers) + + self.widgets['Properties'].set_icon_from_file(self.m_sDataDir+"images/harpia_ave.png") + + #load border color + self.m_oBorderColor = self.m_oS2iBlockProperties.GetBorderColor() + + t_nBorderRed = self.m_oBorderColor[0] * 257 + t_nBorderGreen = self.m_oBorderColor[1] * 257 + t_nBorderBlue = self.m_oBorderColor[2] * 257 + + t_oBorderColor = gtk.gdk.Color(red=t_nBorderRed,green=t_nBorderGreen,blue=t_nBorderBlue) + + self.widgets['propBorderColor'].modify_bg(gtk.STATE_NORMAL,t_oBorderColor) + + #load block color + self.m_oBackColor = self.m_oS2iBlockProperties.GetBackColor() + + t_nBackRed = self.m_oBackColor[0] * 257 + t_nBackGreen = self.m_oBackColor[1] * 257 + t_nBackBlue = self.m_oBackColor[2] * 257 + + t_oBackColor = gtk.gdk.Color(red=t_nBackRed,green=t_nBackGreen,blue=t_nBackBlue) + + self.widgets['propBackgroundColor'].modify_bg(gtk.STATE_NORMAL,t_oBackColor) + + #load help text + t_oS2iHelp = bt.bind_file(self.m_sDataDir+"help/getSize"+ _("_en.help")) + + t_oTextBuffer = gtk.TextBuffer() + + t_oTextBuffer.set_text( unicode( str( t_oS2iHelp.help.content) ) ) + + self.widgets['propHelpView'].set_buffer( t_oTextBuffer ) + + #---------------------------------------------------------------------- + + def __del__(self): + pass + + #---------------------------------------------------------------------- + + def on_prop_cancel_clicked( self, *args ): + self.widgets['Properties'].destroy() + + #---------------------------------------------------------------------- + + def on_prop_confirm_clicked( self, *args ): + + #for Property in self.m_oPropertiesXML.properties.block.property: + #if Property.name == "method": + #Active = self.widgets['method'].get_active( ) + #if int(Active) == 0: + #Property.value = unicode("CV_INTER_NN") + #if int(Active) == 1: + #Property.value = unicode("CV_INTER_LINEAR") + #if int(Active) == 2: + #Property.value = unicode("CV_INTER_AREA") + #if int(Active) == 3: + #Property.value = unicode("CV_INTER_CUBIC") + + self.m_oS2iBlockProperties.SetPropertiesXML( self.m_oPropertiesXML ) + + self.m_oS2iBlockProperties.SetBorderColor( self.m_oBorderColor ) + self.m_oS2iBlockProperties.SetBackColor( self.m_oBackColor ) + self.widgets['Properties'].destroy() + + #---------------------------------------------------------------------- + + def on_propBackColorButton_clicked(self,*args): + + t_oColor = self.RunColorSelection() + + if t_oColor <> None: + + self.widgets['propBackgroundColor'].modify_bg(gtk.STATE_NORMAL,t_oColor) + + self.m_oBackColor[0] = t_oColor.red / 257 + + self.m_oBackColor[1] = t_oColor.green / 257 + + self.m_oBackColor[2] = t_oColor.blue / 257 + + #---------------------------------------------------------------------- + + def on_propBorderColorButton_clicked(self,*args): + + t_oColor = self.RunColorSelection() + + if t_oColor <> None: + + self.widgets['propBorderColor'].modify_bg(gtk.STATE_NORMAL,t_oColor) + + self.m_oBorderColor[0] = t_oColor.red / 257 + + self.m_oBorderColor[1] = t_oColor.green / 257 + + self.m_oBorderColor[2] = t_oColor.blue / 257 + + #---------------------------------------------------------------------- + +#propProperties = Properties()() +#propProperties.show( center=0 ) + + diff --git a/pool/shard000/Python/0000131_views.py b/pool/shard000/Python/0000131_views.py new file mode 100644 index 0000000000000000000000000000000000000000..c85c5e982d1e70593b2aebcd4159d21e1b829865 --- /dev/null +++ b/pool/shard000/Python/0000131_views.py @@ -0,0 +1,60 @@ +"""Views handler for ask admin page rendering.""" +import json +from django.core.urlresolvers import reverse + +from django.http import Http404, HttpResponse +from django.template.loader import render_to_string +from django.core.mail.message import EmailMultiAlternatives +from apps.managers.challenge_mgr import challenge_mgr + +from apps.widgets.ask_admin.forms import FeedbackForm + + +def supply(request, page_name): + """Supply view_objects for widget rendering, returns form.""" + _ = request + _ = page_name + form = FeedbackForm(auto_id="help_%s") + form.url = reverse("help_index") + return { + "form": form, + } + + +def send_feedback(request): + """send feedback.""" + if request.method == "POST": + form = FeedbackForm(request.POST) + if form.is_valid(): + html_message = render_to_string("email/ask_admin.html", { + "user": request.user, + "url": form.cleaned_data["url"], + "question": form.cleaned_data["question"], + }) + message = render_to_string("email/ask_admin.txt", { + "user": request.user, + "url": form.cleaned_data["url"], + "question": form.cleaned_data["question"], + }) + + challenge = challenge_mgr.get_challenge() + # Using adapted version from Django source code + subject = u'[%s] %s asked a question' % ( + challenge.name, + request.user.profile.name) + + if challenge.email_enabled or True: + mail = EmailMultiAlternatives(subject, message, challenge.contact_email, + [challenge.contact_email, ], headers={ + "Reply-To": request.user.email}) + + mail.attach_alternative(html_message, 'text/html') + print html_message + mail.send() + + #print "email sent %s" % html_message + if request.is_ajax(): + return HttpResponse(json.dumps({"success": True}), + mimetype="application/json") + + raise Http404 diff --git a/pool/shard000/Python/0000136_videossh.py b/pool/shard000/Python/0000136_videossh.py new file mode 100644 index 0000000000000000000000000000000000000000..4faa6379680a4114af6f0f176080d73e51639139 --- /dev/null +++ b/pool/shard000/Python/0000136_videossh.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# -------------------------------------------------------- +# Conector videossh By Alfa development Group +# -------------------------------------------------------- + +from core import httptools +from core import scrapertools +from platformcode import logger + + +def test_video_exists(page_url): + logger.info("(page_url='%s')" % page_url) + response = httptools.downloadpage(page_url) + if not response.sucess or "Not Found" in response.data or "File was deleted" in response.data or "is no longer available" in response.data: + return False, "[videossh] El fichero no existe o ha sido borrado" + return True, "" + + +def get_video_url(page_url, premium=False, user="", password="", video_password=""): + logger.info("(page_url='%s')" % page_url) + video_urls = [] + data = httptools.downloadpage(page_url).data + patron = 'file:"([^"]+)"' + match = scrapertools.find_multiple_matches(data, patron) + for media_url in match: + media_url += "|Referer=%s" %page_url + title = "mp4 [videossh]" + video_urls.append([title, media_url]) + return video_urls diff --git a/pool/shard000/Python/0000140_cameraremotecontrol.py b/pool/shard000/Python/0000140_cameraremotecontrol.py new file mode 100644 index 0000000000000000000000000000000000000000..fbca16b19144c59b6e44a9cb536b52bc1ef95428 --- /dev/null +++ b/pool/shard000/Python/0000140_cameraremotecontrol.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- + +import asyncio +import gi +gi.require_version("GUPnP", "1.0") +from gi.repository import GUPnP +import urllib.request +import urllib.parse +from xml.etree.ElementTree import XML, XMLParser +from xmlutils import StripNamespace + +from cameraremoteapi import CameraRemoteApi +# from utils import debug_trace + + +class CameraRemoteControl(object): + + def __init__(self, friendly_name, callback): + self.__friendly_name = friendly_name + self.__device_available_callback = callback + + ctx = GUPnP.Context.new(None, None, 0) + # caution : keep cp as an attribute ! + self.cp = GUPnP.ControlPoint.new(ctx, "upnp:rootdevice") + self.cp.set_active(True) + self.cp.connect("device-proxy-available", self.__device_available) + + def __device_available(self, cp, proxy): + proxy_friendly_name = proxy.get_friendly_name() + # print("Found " + proxy_friendly_name) + if proxy_friendly_name.startswith(self.__friendly_name): + service = proxy.get_service("urn:schemas-sony-com:service:ScalarWebAPI:1") + if service is not None: + + # browse the xml location file and search for the camera service + # and set the action list uri + location = proxy.get_location() + xd = urllib.request.urlopen(location) + s = xd.read() + + target = StripNamespace() + parser = XMLParser(target=target) + root = XML(s, parser=parser) + + sl = root.findall("device/X_ScalarWebAPI_DeviceInfo/X_ScalarWebAPI_ServiceList/X_ScalarWebAPI_Service") + for s in sl: + service_type = s.find("X_ScalarWebAPI_ServiceType").text + if service_type == CameraRemoteApi.SERVICE_NAME: + camera_action_list = s.find("X_ScalarWebAPI_ActionList_URL").text + if not camera_action_list.endswith('/'): + camera_action_list += '/' + endpoint_url = urllib.parse.urljoin(camera_action_list, CameraRemoteApi.SERVICE_NAME) + asyncio.ensure_future(self.__device_available_callback(proxy_friendly_name, endpoint_url)) + break diff --git a/pool/shard000/Python/0000146_wishmerchant.py b/pool/shard000/Python/0000146_wishmerchant.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3890c76fafe0697ecbe57b3d86bfa2cee7c2d1 --- /dev/null +++ b/pool/shard000/Python/0000146_wishmerchant.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +import json +from urllib import quote, urlencode + +import re +import scrapy + +from .. import items + + +class WishMerchantSpider(scrapy.Spider): + name = "wishmerchant" + allowed_domains = ["wish.com"] + start_urls = ( + 'http://www.wish.com/', + ) + + merchants = set() + + xsrfpattern = re.compile(r'.*_xsrf=(.*?);') + + def __init__(self, username, password, merchant, ajaxcount=100): + self.username = username + self.password = password + self.ajaxcount = ajaxcount + self.merchant = merchant + + def start_requests(self): + yield scrapy.Request('https://www.wish.com/', callback=self.login) + + def login(self, response): + match = self.xsrfpattern.match(str(response.headers)) + + if match: + xsrf = match.group(1) + yield scrapy.Request( + 'https://www.wish.com/api/email-login?email={}&password={}&_buckets=&_experiments='.format( + quote(self.username), quote(self.password)), + method='POST', + headers={ + 'Accept': 'application/json, text/javascript, */*; q=0.01', + 'Content-Type': ' application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'X-XSRFToken': xsrf + }, meta={'xsrf': xsrf}, + callback=self.request_merchant) + + def request_merchant(self, response): + merchant_name = self.merchant + if merchant_name not in self.merchants: + self.merchants.add(merchant_name) + merchant_url = "https://www.wish.com/merchant/%s" % merchant_name + return scrapy.Request(merchant_url, meta={'xsrf': response.meta['xsrf']}, callback=self.parse_merchant_page) + + def parse_merchant_page(self, response): + xscript = response.xpath('//script') + + next_offset = xscript.re_first("\['next_offset'\] = (.*?);") + merchant_name = xscript.re_first("\['merchant_name'\] = \"(.*?)\";") + urls = xscript.re(r'"external_url": "(.*?)"') + + print 'page:{}'.format(len(urls)) + for url in urls: + item = items.WishItem() + item['url'] = url + # item['merchant'] = merchant_name + yield item + + if len(urls) > 0: + yield self.feed_merchant_ajax(response.meta['xsrf'], merchant_name, next_offset, urls) + + def feed_merchant_ajax(self, xsrf, merchant_name, offset, last_cids, num_results=0): + formdata = { + 'start': str(offset), + 'query': merchant_name, + 'is_commerce': 'true', + 'transform': 'true', + 'count': str(self.ajaxcount), + 'include_buy_link': 'true', + 'num_results': str(num_results), + '_buckets': '', + '_experiments': '', + 'last_cids[]': last_cids + } + + return scrapy.Request('https://www.wish.com/api/merchant', method='POST', body=urlencode(formdata), + headers={ + 'Accept': 'application/json, text/javascript, */*; q=0.01', + 'Content-Type': ' application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'X-XSRFToken': xsrf + }, meta={'xsrf': xsrf}, callback=self.parse_merchant_ajax) + + def parse_merchant_ajax(self, response): + json_data = json.loads(response.body) + data = json_data.get('data', None) + if data is not None: + next_offset = data.get('next_offset') + num_results = data.get('num_results') + merchant_name = data.get('merchant_info')['name'] + + urls = [] + for result in data.get('results'): + url = result.get('external_url') + urls.append(url) + item = items.WishItem() + item['url'] = url + # item['merchant'] = merchant_name + yield item + + if len(urls) > 0: + yield self.feed_merchant_ajax(response.meta['xsrf'], merchant_name, next_offset, urls, num_results) diff --git a/pool/shard000/Python/0000149_sort_exer_template.py b/pool/shard000/Python/0000149_sort_exer_template.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d841d6d837fd277f43c6991778859287c2b298 --- /dev/null +++ b/pool/shard000/Python/0000149_sort_exer_template.py @@ -0,0 +1,101 @@ +__author__ = 'maxiee' +import Sort.utils as utils + +class Base: + data = [] + aux = [] + + def __init__(self, data): + self.data = data + + def sort(self): + pass + + def less(self, i, j): + return self.data[i] < self.data[j] + + def more(self, i, j): + return self.data[i] > self.data[j] + + def exch(self, i, j): + temp = self.data[i] + self.data[i] = self.data[j] + self.data[j] = temp + + def show(self): + print(self.data) + + def is_sorted(self): + for I in range(len(self.data) - 1): + if self.less(I + 1, I): + return False + return True + +#选择排序 +class SelectSort(Base): + def sort(self): + #填写算法 + return self.data + +#插入排序 +class InsertSort(Base): + def sort(self): + #填写算法 + return self.data + +#希尔排序 +class Shell(Base): + def sort(self): + #填写算法 + return self.data + +#归并排序 +class Merge(Base): + def __init__(self, data): + super().__init__(data) + self.aux = list(data) + + def sort(self): + self.sort_sub(0, len(self.data) - 1) + return self.data + + #递归排序 + def sort_sub(self, lo, hi): + #填写算法 + pass + + #归并方法 + def merge(self, lo, mid, hi): + #填写算法 + pass + +#快排 +class Quick(Base): + def sort(self): + self.sort_sub(0, len(self.data) -1) + return self.data + + #递归排序 + def sort_sub(self, lo, hi): + #填写算法 + pass + + #分区 + def partition(self, lo, hi): + #填写算法 + pass + + +def sort_and_test(name, cls, l): + c = cls(list(l)) + c.sort() + print(name, c.is_sorted()) + +if __name__ == "__main__": + length = 1000 + l = utils.gen_string_list(length) + sort_and_test("选择排序", SelectSort, l) + sort_and_test("插入排序", InsertSort, l) + sort_and_test("希尔排序", Shell, l) + sort_and_test("自顶向下归并", Merge, l) + sort_and_test("快速排序", Quick, l) \ No newline at end of file diff --git a/pool/shard000/Python/0000152_views.py b/pool/shard000/Python/0000152_views.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ea2dfc467e4237b927d4a4e477a6863faf9267 --- /dev/null +++ b/pool/shard000/Python/0000152_views.py @@ -0,0 +1,192 @@ +""" +Deployment User Views +""" + +from django.contrib import auth +from django.contrib import messages +from django.contrib.auth.forms import PasswordResetForm +from django.contrib.auth.views import password_reset_confirm, redirect_to_login +from django.core.urlresolvers import reverse, reverse_lazy +from django.http import HttpResponseRedirect +from django.shortcuts import redirect +from django.views.generic.base import TemplateView +from django.views.generic import FormView, UpdateView, CreateView, DeleteView, DetailView +from django_tables2 import SingleTableView + +from fabric_bolt.core.mixins.views import MultipleGroupRequiredMixin +from fabric_bolt.accounts import forms, tables + + +class UserPermissions(TemplateView): + template_name = 'accounts/permissions.html' + + +class Login(TemplateView): + """ + Login view handles generating the login form, login authentication, and redirect after auth + """ + + template_name = 'accounts/login.html' + + def get_context_data(self, **kwargs): + return {'form': forms.LoginForm} + + def get(self, request, *args, **kwargs): + """If the user is authenticated take them to the homepage""" + + if request.user.is_authenticated(): + return HttpResponseRedirect(reverse('index')) + + context = self.get_context_data(**kwargs) + return self.render_to_response(context) + + def post(self, request, *args, **kwargs): + """ + Verify the correct username and password have been set and let them in if so + """ + + email = request.POST.get('email', '') + password = request.POST.get('password', '') + + user = auth.authenticate(email=email, password=password) + + # Log the user in and send them on their merry way + if user is not None and user.is_active: + auth.login(request, user) + goto = request.GET.get('next', reverse('index')) + return HttpResponseRedirect(goto) + + else: + messages.error(request, 'Invalid username or password. Please try again.') + return HttpResponseRedirect(reverse('accounts_user_login')) + + +class Logout(TemplateView): + """ + Logout view calls logout() on the request and redirects to the login screen + """ + + template_name = 'accounts/login.html' + + def get(self, request, *args, **kwargs): + + if not request.user.is_authenticated(): + return HttpResponseRedirect(reverse('accounts_user_login')) + + auth.logout(request) + + return HttpResponseRedirect(reverse('accounts_user_login')) + + +# Admin: List Users +class UserList(MultipleGroupRequiredMixin, SingleTableView): + """ + List of users. Uses UserFilter and UserTable. + """ + group_required = 'Admin' + template_name = 'accounts/user_list.html' + table_class = tables.UserListTable + model = auth.get_user_model() + + +# Admin Change/Edit User (modal) +class UserChange(UpdateView): + """ + Change/Edit User view. Used in a modal window. + """ + model = auth.get_user_model() + success_url = reverse_lazy('accounts_user_list', args=()) + form_class = forms.UserChangeForm + template_name = 'accounts/deployuser_change.html' + + def dispatch(self, request, *args, **kwargs): + # Edit your profile or you're an admin, load the view + if self.request.user.pk == int(kwargs.get('pk')) or self.request.user.user_is_admin(): + return super(UserChange, self).dispatch(request, *args, **kwargs) + + # Redirect to index or login for other users + if request.user.is_authenticated(): + return redirect('index') + else: + return redirect_to_login(request.get_full_path()) + + def get_form_kwargs(self): + kwargs = super(UserChange, self).get_form_kwargs() + kwargs['user_is_admin'] = self.request.user.user_is_admin() + + return kwargs + + +# Admin Add Users (modal) +class UserAdd(MultipleGroupRequiredMixin, CreateView): + """ + Create User view. Used in a modal window. + """ + group_required = 'Admin' + model = auth.get_user_model() + success_url = reverse_lazy('accounts_user_list', args=()) + form_class = forms.UserCreationForm + template_name = 'accounts/deployuser_create.html' + + def get_form_kwargs(self): + kwargs = super(UserAdd, self).get_form_kwargs() + kwargs['user_is_admin'] = self.request.user.user_is_admin() + + return kwargs + + def form_valid(self, form): + # Save form + response = super(UserAdd, self).form_valid(form) + + # Send a password recover email + email_form = PasswordResetForm({'email': form.cleaned_data['email']}) + email_form.is_valid() + email_form.save(email_template_name='accounts/welcome_email.html') + + # send response + return response + + +# Admin User Detail +class UserDetail(DetailView): + model = auth.get_user_model() + + +# Admin Delete User +class UserDelete(MultipleGroupRequiredMixin, DeleteView): + group_required = 'Admin' + model = auth.get_user_model() + success_url = reverse_lazy('accounts_user_list') + + def delete(self, request, *args, **kwargs): + messages.success(self.request, 'User {} Successfully Deleted'.format(self.get_object())) + return super(UserDelete, self).delete(self, request, *args, **kwargs) + + +class PasswordChange(FormView): + + template_name = 'accounts/password_change.html' + + def get_success_url(self): + return reverse('accounts_user_view', args=(self.request.user.id,)) + + def get_form(self, form_class): + return forms.UserPasswordChangeForm(self.request.user, self.request.POST or None) + + def form_valid(self, form): + form.save() + return super(PasswordChange, self).form_valid(form) + + +class PasswordCreate(FormView): + + template_name = 'accounts/password_create.html' + + def get_success_url(self): + return reverse('accounts_user_view', args=(self.request.user.id,)) + + def get_form(self, form_class): + return forms.UserPasswordCreateForm(self.request.user, self.request.POST or None) + + def post(self, request, *args, **kwargs): + return password_reset_confirm(request, **kwargs) diff --git a/pool/shard000/Python/0000153_api.py b/pool/shard000/Python/0000153_api.py new file mode 100644 index 0000000000000000000000000000000000000000..9a883f79fea0c39c3c57926b2dd22528997ca536 --- /dev/null +++ b/pool/shard000/Python/0000153_api.py @@ -0,0 +1,242 @@ + +import os, sys +import time +from ConfigParser import ConfigParser + +import boto +from boto import ec2 +from boto.ec2 import elb +from boto.ec2.connection import EC2Connection +from boto.ec2.elb import HealthCheck + +from fabric.api import env, execute, local +from fabric.tasks import Task + +from fab_deploy import functions + +from utils import get_security_group + + +DEFAULT_AMI = 'ami-5965401c' # ubuntu 12.04 x86_64 +DEFAULT_INSTANCE_TYPE = 'm1.medium' +DEFAULT_REGION = 'us-west-1' + + +def get_ec2_connection(server_type, **kwargs): + """ + Create and return a valid connection to AWS. + + To establish a valid connection, aws_access_key and aws_secret_key have to + be defined in a file specified by env.AWS_CREDENTIAL, with a format similar + to server.ini file. You should define env.AWS_CREDENTIAL in your fabfile. + By default, this function looks into $PROJECT_DIR/deploy/amazon.ini for the + credential information, and this file should has a section named 'amazon-aws' + and containing lines defining aws_access_key and aws_secret_key, like below + + [amazon-aws] + aws_access_key = + aws_secret_key = + """ + + amzn = env.get('AWS_CREDENTIAL', + os.path.join(env.deploy_path, 'amazon.ini')) + if not os.path.exists(amzn): + print ("Cannot find environment variable AMAZON_CREDENTIALS which should" + " point to a file with your aws_access_key and aws_secret_key info" + " inside. You may specify it through your fab env.") + sys.exit(1) + + parser = ConfigParser() + parser.read(amzn) + + aws_access_key = parser.get('amazon-aws', 'aws_access_key') + aws_secret_key = parser.get('amazon-aws', 'aws_secret_key') + + if not aws_access_key or not aws_secret_key: + print "You must specify your amazon aws credentials to your env." + sys.exit(1) + + region = kwargs.get('region', env.get('region')) + if not region: + region = DEFAULT_REGION + + if server_type == 'ec2': + conn = ec2.connect_to_region(region, + aws_access_key_id=aws_access_key, + aws_secret_access_key=aws_secret_key) + return conn + elif server_type == 'elb': + conn = elb.connect_to_region(region, + aws_access_key_id=aws_access_key, + aws_secret_access_key=aws_secret_key) + return conn + + +class CreateKeyPair(Task): + """ + Create an AWS key pair. + + This task should be run before you try to add any type of server, because + task api.add_server will look for the key pair on your local machine. + + AWS requires a key pair to create EC2 instances, and the same key file is + needed to login to the instances. This task creates a key pair, and + save its content in a file located under the same directory as + env.AWS_CREDENTIAL file. The key name and file location will be registered + into the file specified by env.AWS_CREDENTIAL. + + You are responsible to keep the file in a secure place and never lose it. + Make your own decision if you should push the key file to remote repo, or + let git ignore it. + """ + + name = 'create_key' + serial = True + + section = 'amazon-aws' + + def run(self, **kwargs): + conn = get_ec2_connection(server_type='ec2', **kwargs) + sys.stdout.write("Please give a name to the key: ") + + amzn = env.get('AWS_CREDENTIAL', + os.path.join(env.deploy_path, 'amazon.ini')) + key_dir = os.path.dirname(amzn) + while True: + key_name = raw_input() + key_file = os.path.join(key_dir, key_name+'.pem') + key = conn.get_key_pair(key_name) + + if key: + if os.path.exists(key_file): + print ("Looks like key file %s already exists on your " + "machine. I will skip creating, and just use it." + %key_file) + break + else: + print ("Key '%s' already exist on AWS, but I couldn't " + "find it at %s. We need to create a new key, please" + "give a name to the key: " %(key.name, key_file)) + continue + else: + key = conn.create_key_pair(key_name) + key.save(key_dir) + break + + parser = ConfigParser() + parser.read(amzn) + if not parser.has_section(self.section): + parser.add_section(self.section) + parser.set(self.section, 'ec2-key-name', key.name) + parser.set(self.section, 'ec2-key-file', key_file) + fp = open(amzn, 'w') + parser.write(fp) + fp.close() + local('ssh-add %s' %key_file) + + +class New(Task): + """ + Provisions and set up a new amazon AWS EC2 instance + + This task reads in a number of variables defining the properties of EC2 + instance, and create it. Finally, if the instance is created successfully, + this task will output its properties, and set up the instance as certain + type of server by execute another task with the name of setup.***. + + You may provide the following parameters through command line. + * **type**: Required. server types, can be db_server, app_server, + dev_server, or slave_db + * **region**: default is us-west-1 + * **ami_id**: AMI ID + * **static_ip**: Set to true to use. By default this is not used. + """ + + name = 'add_server' + serial = True + + def run(self, **kwargs): + assert not env.hosts + conn = get_ec2_connection(server_type='ec2', **kwargs) + + type = kwargs.get('type') + setup_name = 'setup.%s' % type + + instance_type = DEFAULT_INSTANCE_TYPE + + ami_id = kwargs.get('ami_id') + if not ami_id: + ami_id = DEFAULT_AMI + + task = functions.get_task_instance(setup_name) + if task: + if hasattr(task, 'instance_type'): + instance_type = task.instance_type + if hasattr(task, 'ami'): + ami_id = task.ami + else: + print "I don't know how to add a %s server" % type + sys.exit(1) + + amzn = env.get('AWS_CREDENTIAL', + os.path.join(env.deploy_path, 'amazon.ini')) + parser = ConfigParser() + parser.read(amzn) + key_name = parser.get('amazon-aws', 'ec2-key-name') + key_file = parser.get('amazon-aws', 'ec2-key-file') + + if not key_name: + print "Sorry. You need to create key pair with create_key first." + sys.exit(1) + elif not os.path.exists(key_file): + print ("I find key %s in server.ini file, but the key file is not" + " on its location %s. There is something wrong. Please fix " + "it, or recreate key pair" % (key_name, key_file)) + sys.exit(1) + + image = conn.get_image(ami_id) + security_group = get_security_group(conn, task.config_section) + + name = functions.get_remote_name(None, task.config_section, + name=kwargs.get('name')) + SERVER = { + 'image_id': image.id, + 'instance_type': instance_type, + 'security_groups': [security_group], + 'key_name': key_name,} + + reservation = conn.run_instances(**SERVER) + print reservation + + instance = reservation.instances[0] + while instance.state != 'running': + time.sleep(5) + instance.update() + print "...instance state: %s" % (instance.state) + + conn.create_tags([instance.id], {"Name": name}) + + if not kwargs.get('static_ip', False): + ip = instance.ip_address + else: + elastic_ip = conn.allocate_address() + print "...Elastic IP %s allocated" % elastic_ip + elastic_ip.associate(instance.id) + ip = elastic_ip.public_ip + + print "...EC2 instance is successfully created." + print "...wait 5 seconds for the server to be ready" + print "...while waiting, you may want to note down the following info" + time.sleep(5) + print "..." + print "...Instance using image: %s" % image.name + print "...Added into security group: %s" %security_group.name + print "...Instance ID: %s" % instance.id + print "...Public IP: %s" % ip + + host_string = 'ubuntu@%s' % instance.public_dns_name + execute(setup_name, name=name, hosts=[host_string]) + + +create_key = CreateKeyPair() +add_server = New() diff --git a/pool/shard000/Python/0000154_GetWorksheetPivotTablesInformationByIndex.py b/pool/shard000/Python/0000154_GetWorksheetPivotTablesInformationByIndex.py new file mode 100644 index 0000000000000000000000000000000000000000..cff82d4bae6dfa10cd2d2e761746c3c034c79ff4 --- /dev/null +++ b/pool/shard000/Python/0000154_GetWorksheetPivotTablesInformationByIndex.py @@ -0,0 +1,41 @@ +import asposecellscloud +from asposecellscloud.CellsApi import CellsApi +from asposecellscloud.CellsApi import ApiException + +import asposestoragecloud +from asposestoragecloud.StorageApi import StorageApi + +apiKey = "XXXXX" #sepcify App Key +appSid = "XXXXX" #sepcify App SID +apiServer = "http://api.aspose.com/v1.1" +data_folder = "../../data/" + +#Instantiate Aspose Storage API SDK +storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) +storageApi = StorageApi(storage_apiClient) +#Instantiate Aspose Cells API SDK +api_client = asposecellscloud.ApiClient.ApiClient(apiKey, appSid, True) +cellsApi = CellsApi(api_client); + +#set input file name +filename = "EastNorthCentralFTWorkers.xls" +sheetName = "Tables" +pivottableIndex = 0 + +#upload file to aspose cloud storage +storageApi.PutCreate(Path=filename, file=data_folder + filename) + +try: + #invoke Aspose.Cells Cloud SDK API to get worksheet pivot table information by index + response = cellsApi.GetWorksheetPivotTable(name=filename, sheetName=sheetName, pivottableIndex=pivottableIndex) + + if response.Status == "OK": + pivotTable = response.PivotTable + print "Name :: " + pivotTable.Name + for item in pivotTable.ColumnFields[0].Items: + print "item :: " + item + +except ApiException as ex: + print "ApiException:" + print "Code:" + str(ex.code) + print "Message:" + ex.message diff --git a/pool/shard000/Python/0000157_urlshortener.py b/pool/shard000/Python/0000157_urlshortener.py new file mode 100644 index 0000000000000000000000000000000000000000..3df04ef08e875b434ab4b1899d2860e9598680cb --- /dev/null +++ b/pool/shard000/Python/0000157_urlshortener.py @@ -0,0 +1,122 @@ +#!/usr/bin/python2.4 +# -*- coding: utf-8 -*- +# +# Copyright (C) 2010 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. + +"""Command-line sample for the Google URL Shortener API. + +Simple command-line example for Google URL Shortener API that shortens +a URI then expands it. + +Usage: + $ python urlshortener.py + +You can also get help on all the command-line flags the program understands +by running: + + $ python urlshortener.py --help + +To get detailed log output run: + + $ python urlshortener.py --logging_level=DEBUG +""" + +__author__ = 'jcgregorio@google.com (Joe Gregorio)' + +import gflags +import httplib2 +import logging +import pprint +import sys + +from apiclient.discovery import build +from oauth2client.file import Storage +from oauth2client.client import AccessTokenRefreshError +from oauth2client.client import OAuth2WebServerFlow +from oauth2client.tools import run + +FLAGS = gflags.FLAGS + +# Set up a Flow object to be used if we need to authenticate. This +# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with +# the information it needs to authenticate. Note that it is called +# the Web Server Flow, but it can also handle the flow for native +# applications +# The client_id client_secret are copied from the API Access tab on +# the Google APIs Console . When +# creating credentials for this application be sure to choose an Application +# type of "Installed application". +FLOW = OAuth2WebServerFlow( + client_id='433807057907.apps.googleusercontent.com', + client_secret='jigtZpMApkRxncxikFpR+SFg', + scope='https://www.googleapis.com/auth/urlshortener', + user_agent='urlshortener-cmdline-sample/1.0') + +# The gflags module makes defining command-line options easy for +# applications. Run this program with the '--help' argument to see +# all the flags that it understands. +gflags.DEFINE_enum('logging_level', 'ERROR', + ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], + 'Set the level of logging detail.') + + +def main(argv): + # Let the gflags module process the command-line arguments + try: + argv = FLAGS(argv) + except gflags.FlagsError, e: + print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS) + sys.exit(1) + + # Set the logging according to the command-line flag + logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) + + # If the Credentials don't exist or are invalid run through the native client + # flow. The Storage object will ensure that if successful the good + # Credentials will get written back to a file. + storage = Storage('urlshortener.dat') + credentials = storage.get() + if credentials is None or credentials.invalid: + credentials = run(FLOW, storage) + + # Create an httplib2.Http object to handle our HTTP requests and authorize it + # with our good Credentials. + http = httplib2.Http() + http = credentials.authorize(http) + + service = build("urlshortener", "v1", http=http) + + try: + + url = service.url() + + # Create a shortened URL by inserting the URL into the url collection. + body = {"longUrl": "http://code.google.com/apis/urlshortener/" } + resp = url.insert(body=body).execute() + pprint.pprint(resp) + + short_url = resp['id'] + + # Convert the shortened URL back into a long URL + resp = url.get(shortUrl=short_url).execute() + pprint.pprint(resp) + + + except AccessTokenRefreshError: + print ("The credentials have been revoked or expired, please re-run" + "the application to re-authorize") + +if __name__ == '__main__': + main(sys.argv) diff --git a/pool/shard000/Python/0000159_models.py b/pool/shard000/Python/0000159_models.py new file mode 100644 index 0000000000000000000000000000000000000000..ce145edcd623103d87f0b30d450d8b60fbce44ce --- /dev/null +++ b/pool/shard000/Python/0000159_models.py @@ -0,0 +1,49 @@ +from django.db import models +from django.contrib.auth.models import AbstractBaseUser, BaseUserManager + +# Create your models here. +class MyUserManager(BaseUserManager): + def create_user(self, email, password=None): + if not email: + raise ValueError('Users must have an email address') + user = self.model( + email=self.normalize_email(email), + ) + user.set_password(password) + user.save(using=self._db) + return user + def create_superuser(self, email, password): + user = self.create_user( + email, + password=password, + ) + user.is_admin = True + user.save(using=self._db) + return user + +class MyUser(AbstractBaseUser): + email = models.EmailField(unique=True) + avatar = models.ImageField(blank=True) + kudos_points = models.PositiveIntegerField(default=0) + is_admin = models.BooleanField(default=False) + is_active = models.BooleanField(default=True) + activation_key = models.CharField(max_length=16,editable=False,blank=True) + key_expiration = models.DateTimeField(editable=False,null=True) + objects=MyUserManager() + USERNAME_FIELD = 'email' + def __str__(self): + return self.email + def get_full_name(self): + return self.email + def get_short_name(self): + return self.email + def has_perm(self,perm,obj=None): + return True + def has_module_perms(self,app_label): + return True + @property + def is_staff(self): + return self.is_admin + def set_activation(self,key,expiration): + self.activation_key=key + self.key_expiration=expiration diff --git a/pool/shard000/Python/0000161_success_outline_steps.py b/pool/shard000/Python/0000161_success_outline_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..e3acc0011f2dcf5854fd7f0761567b14b3345a51 --- /dev/null +++ b/pool/shard000/Python/0000161_success_outline_steps.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) <2010-2011> Gabriel Falcão +# +# 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 . + +from lettuce import step + +@step(r'Given I open browser at "http://(.*)"') +def given_i_open_browser_at_http_address(step, address): + pass + +@step(r'And click on "sign[-]up"') +def and_click_on_sign_up(step): + pass + +@step(r'I fill the field "(.*)" with "(.*)"') +def when_i_fill_the_field_x_with_y(step, field, value): + pass + +@step(r'And I click "done"') +def and_i_click_done(step): + pass + +@step(r'I see the title of the page is "(.*)"') +def then_i_see_the_message_message(step, title): + possible_titles = [ + u'John | My Website', + u'Mary | My Website', + u'Foo | My Website', + ] + + assert title in possible_titles, \ + '"%s" should be between the options [%s]' % (title, ", ".join(possible_titles)) diff --git a/pool/shard000/Python/0000162_threading_Lock.py b/pool/shard000/Python/0000162_threading_Lock.py new file mode 100644 index 0000000000000000000000000000000000000000..775a09d06bc95e64bb45f4a05137824cde7598d7 --- /dev/null +++ b/pool/shard000/Python/0000162_threading_Lock.py @@ -0,0 +1,37 @@ +""" +@author: Maneesh D +@email: maneeshd77@gmail.com +@created: 09-Feb-17 + +A very simple example to understand Lock in threads. Locks are useful when a resource should be accessed by +only one thread at a time to prevent deadlock and race conditions. +""" +from threading import Thread, Lock +from time import sleep, ctime, time + +t_lock = Lock() + + +def timer(name, delay, repeat): + print("[INFO] " + name + " started") + t_lock.acquire() # 'with p_lock:' can be used. + print("[INFO] " + name + " has acquired the Lock...") + while repeat > 0: + sleep(delay) + print("[INFO] " + name + ": " + str(ctime(time()))) + repeat -= 1 + print("[INFO] " + name + " is releasing the Lock...") + t_lock.release() + print("[INFO] " + name + " completed") + + +def main(): + my_thread_1 = Thread(target=timer, args=("Timer-1", 1, 5)) + my_thread_2 = Thread(target=timer, args=("Timer-2", 2, 5)) + my_thread_1.start() + my_thread_2.start() + timer("MainTimer", 0.5, 5) + print("[INFO] MainThread Exited") + +if __name__ == '__main__': + main() diff --git a/pool/shard000/Python/0000165_zip.py b/pool/shard000/Python/0000165_zip.py new file mode 100644 index 0000000000000000000000000000000000000000..26181659d1dc2d02e2dbcefb52580396a4f5b92b --- /dev/null +++ b/pool/shard000/Python/0000165_zip.py @@ -0,0 +1,17 @@ +#!/usr/local/bin/python +# -*- coding: utf-8 -*- + +import os +import zipfile + + +class Zip: + ZIP_EXTENSION = 'zip' + + @staticmethod + def zipdir(input_path, output_fullpath): + zipf = zipfile.ZipFile(output_fullpath, 'w', zipfile.ZIP_DEFLATED) + for root, dirs, files in os.walk(input_path): + for file in files: + zipf.write(os.path.join(root, file)) + zipf.close() diff --git a/pool/shard000/Python/0000167_audio.py b/pool/shard000/Python/0000167_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb2075920898b121cd9f3be1d562cd72ee48292 --- /dev/null +++ b/pool/shard000/Python/0000167_audio.py @@ -0,0 +1,32 @@ +import os +import pygame + +from subprocess import call + + +home = os.path.expanduser("~") +fifo = os.path.join(home, '.player-control') + + +class Player(object): + def __init__(self, filepath): + self.filepath = filepath + pygame.init() + + def play(self): + pygame.mixer.init() + pygame.mixer.music.load(self.filepath) + pygame.mixer.music.play() + + def pause(self): + pygame.mixer.pause() + + def unpause(self): + pygame.mixer.unpause() + + def stop(self): + pygame.mixer.quit() + + def __exit__(self): + print("DEBUG: Exit Audio") + pygame.quit() diff --git a/pool/shard000/Python/0000169_test_database_patching.py b/pool/shard000/Python/0000169_test_database_patching.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf51cff04fa4f674b6341b546032f54bdada507 --- /dev/null +++ b/pool/shard000/Python/0000169_test_database_patching.py @@ -0,0 +1,107 @@ +import pytest +import flask +from flask.ext.sqlalchemy import SQLAlchemy + +db = SQLAlchemy() + + +def random_uuid(): + return str(uuid.uuid4()) + + +class Thing(db.Model): + id = db.Column(db.String, primary_key=True, default=random_uuid) + code = db.Column(db.String) + number = db.Column(db.Integer) + name = db.Column(db.String) + + +@pytest.fixture +def db_app(request): + app = flask.Flask('__main__') + db.init_app(app) + ctx = app.app_context() + ctx.push() + db.create_all() + request.addfinalizer(ctx.pop) + return app + + +@pytest.fixture +def patcher(db_app): + from mptracker.patcher import TablePatcher + return TablePatcher(Thing, db.session, key_columns=['code']) + + +@pytest.fixture +def patcher_twin_key(db_app): + from mptracker.patcher import TablePatcher + return TablePatcher(Thing, db.session, key_columns=['code', 'number']) + + +def test_empty_input(patcher): + patcher.update([]) + assert list(Thing.query) == [] + + +def test_insert_new_records(patcher): + records = [{'code': 'an', 'name': "Anne"}, + {'code': 'bo', 'name': "Bob"}] + patcher.update(records) + assert sorted([t.name for t in Thing.query]) == ["Anne", "Bob"] + + +def test_update_existing_records(patcher): + records = [{'code': 'an', 'name': "Anne"}, + {'code': 'bo', 'name': "Bob"}] + patcher.update(records) + records[0]['name'] = "Annette" + patcher.update(records) + assert sorted([t.name for t in Thing.query]) == ["Annette", "Bob"] + + +def test_remove_extra_records(patcher): + records = [{'code': 'an', 'name': "Anne"}, + {'code': 'bo', 'name': "Bob"}] + patcher.update(records) + patcher.update(records[:1], remove=True) + assert sorted([t.name for t in Thing.query]) == ["Anne"] + + +def test_remove_extra_records_honors_filter(db_app): + records = [{'code': 'an', 'number': 1, 'name': "Anne"}, + {'code': 'bo', 'number': 1, 'name': "Bob"}, + {'code': 'cl', 'number': 2, 'name': "Claire"}, + {'code': 'da', 'number': 2, 'name': "Dan"}] + from mptracker.patcher import TablePatcher + filter_patcher = TablePatcher( + Thing, + db.session, + key_columns=['code'], + filter={'number': 1}, + ) + filter_patcher.update(records) + filter_patcher.update(records[:1], remove=True) + assert sorted([t.name for t in Thing.query]) == ["Anne", "Claire", "Dan"] + + +def test_refuse_to_create_records(patcher): + from mptracker.patcher import RowNotFound + records = [{'code': 'an', 'name': "Anne"}] + with pytest.raises(RowNotFound): + patcher.update(records, create=False) + + +def test_twin_natural_key(patcher_twin_key): + records = [{'code': 'an', 'number': 1, 'name': "Anne"}, + {'code': 'bo', 'number': 2, 'name': "Bob"}] + patcher_twin_key.update(records) + records[0]['name'] = "Annette" + patcher_twin_key.update(records) + assert sorted([t.name for t in Thing.query]) == ["Annette", "Bob"] + + +def test_patcher_add_returns_row(patcher): + row1 = patcher.add({'code': 'an', 'name': "Anne"}).row + row2 = patcher.add({'code': 'an', 'name': "Annette"}).row + assert row1 == row2 diff --git a/pool/shard000/Python/0000170_test_morfologik.py b/pool/shard000/Python/0000170_test_morfologik.py new file mode 100644 index 0000000000000000000000000000000000000000..9296c6b97d50459b01241274dafdcada1b1eaaa5 --- /dev/null +++ b/pool/shard000/Python/0000170_test_morfologik.py @@ -0,0 +1,21 @@ +# coding=utf-8 + +import unittest + +from pymorfologik import Morfologik + + +class MorfologikTest(unittest.TestCase): + def test_get_simple_stem(self): + stemms = Morfologik().get_simple_stem(['tańczyłem', 'gra']) + self.assertEquals(2, len(stemms)) + self.assertListEqual(['tańczyć'], stemms['tańczyłem']) + self.assertEquals(['gra', 'grać'], stemms['gra']) + + def test_get_simple_stem_duplicates(self): + stemms = Morfologik().get_simple_stem(['gra', 'gra', 'gra']) + self.assertEquals(1, len(stemms)) + + def test_get_simple_stem_word_does_not_exist(self): + stemms = Morfologik().get_simple_stem(['niematakiegosłowa']) + self.assertEquals(0, len(stemms)) diff --git a/pool/shard000/Python/0000171_qrwindow.py b/pool/shard000/Python/0000171_qrwindow.py new file mode 100644 index 0000000000000000000000000000000000000000..de18a58fcdaf66dfc25e2d56e5f4f066177d4ad5 --- /dev/null +++ b/pool/shard000/Python/0000171_qrwindow.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# +# Electrum - lightweight Bitcoin client +# Copyright (C) 2014 Thomas Voegtlin +# +# 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 . + +import re +import platform +from decimal import Decimal +from urllib import quote + +from PyQt4.QtGui import * +from PyQt4.QtCore import * +import PyQt4.QtCore as QtCore +import PyQt4.QtGui as QtGui + +from scallop_gui.qt.qrcodewidget import QRCodeWidget +from scallop.i18n import _ + +if platform.system() == 'Windows': + MONOSPACE_FONT = 'Lucida Console' +elif platform.system() == 'Darwin': + MONOSPACE_FONT = 'Monaco' +else: + MONOSPACE_FONT = 'monospace' + +column_index = 4 + +class QR_Window(QWidget): + + def __init__(self, win): + QWidget.__init__(self) + self.win = win + self.setWindowTitle('Electrum - '+_('Payment Request')) + self.setMinimumSize(800, 250) + self.address = '' + self.label = '' + self.amount = 0 + self.setFocusPolicy(QtCore.Qt.NoFocus) + + main_box = QHBoxLayout() + + self.qrw = QRCodeWidget() + main_box.addWidget(self.qrw, 1) + + vbox = QVBoxLayout() + main_box.addLayout(vbox) + + self.address_label = QLabel("") + #self.address_label.setFont(QFont(MONOSPACE_FONT)) + vbox.addWidget(self.address_label) + + self.label_label = QLabel("") + vbox.addWidget(self.label_label) + + self.amount_label = QLabel("") + vbox.addWidget(self.amount_label) + + vbox.addStretch(1) + self.setLayout(main_box) + + + def set_content(self, address, amount, message, url): + address_text = "%s" % address if address else "" + self.address_label.setText(address_text) + if amount: + amount = self.win.format_amount(amount) + amount_text = "%s %s " % (amount, self.win.base_unit()) + else: + amount_text = '' + self.amount_label.setText(amount_text) + label_text = "%s" % message if message else "" + self.label_label.setText(label_text) + self.qrw.setData(url) diff --git a/pool/shard000/Python/0000173_pywnserver.py b/pool/shard000/Python/0000173_pywnserver.py new file mode 100644 index 0000000000000000000000000000000000000000..ee5c463bbdfc591d10bf0d409b77832b2be51146 --- /dev/null +++ b/pool/shard000/Python/0000173_pywnserver.py @@ -0,0 +1,70 @@ +#! /usr/bin/env python + +from socket import * +from stdwn import impl +from StringIO import * +import thread +import cPickle + +stayalive = 1 +port = 3334 + +def acceptConnections(arg): + s = socket(AF_INET, SOCK_STREAM) + s.bind(('', port)) + s.listen(1) + print "pwynserver listening on port", port + print " to stop" + while stayalive: + conn = s.accept() + print 'connection opened('+conn[1][0]+':'+`conn[1][1]`+')' + thread.start_new_thread(handleRequests, (conn,)) + s.shutdown(2) + +kstr = impl.getSynsetKeyFromString + +def processCommand(cmd): + if cmd[0] == 'ss': + func = impl.grabSynset + elif cmd[0] == 'key': + func = impl.grabKeys + else: + return None + return func(cmd[1]) + +def handleRequests(arg): + sock = arg[0] + sockfile = sock.makefile('r+') + host = arg[1][0] + port = `arg[1][1]` + while 1: + try: + cmd = cPickle.load(sockfile) + print host+":"+port, cmd[0], cmd[1] + except error: + break + except EOFError: + break + except cPickle.UnpicklingError: + break + if not cmd: + break + cPickle.dump(processCommand(cmd), sockfile) + sockfile.close() + sock.shutdown(2) + print 'connection closed('+host+':'+port+')' + + +def open(): + thread.start_new_thread(acceptConnections, (None,)) + +def close(): + stayalive = 0 + +if __name__ == '__main__': + #default pywnserver port + import sys + port = int(sys.argv[1]) + open() + sys.stdin.readline() + close() diff --git a/pool/shard000/Python/0000177_g2lib.py b/pool/shard000/Python/0000177_g2lib.py new file mode 100644 index 0000000000000000000000000000000000000000..2fbfac93bc56fe8084e74d91a1d15cc406f6258d --- /dev/null +++ b/pool/shard000/Python/0000177_g2lib.py @@ -0,0 +1,81 @@ +## +# Copyright 2009-2018 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# https://github.com/easybuilders/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for building and installing g2lib, implemented as an easyblock + +@author: Stijn De Weirdt (Ghent University) +@author: Dries Verdegem (Ghent University) +@author: Kenneth Hoste (Ghent University) +@author: Pieter De Baets (Ghent University) +@author: Jens Timmerman (Ghent University) +""" + +import os +import shutil + +from easybuild.easyblocks.generic.configuremake import ConfigureMake +from easybuild.tools.build_log import EasyBuildError +from easybuild.tools.modules import get_software_root + + +class EB_g2lib(ConfigureMake): + """Support for building g2clib GRIB2 library.""" + + def configure_step(self): + """No configuration needed""" + pass + + def build_step(self): + """Build by supplying required make options, and running build_step.""" + + jasper = get_software_root('JASPER') + if not jasper: + raise EasyBuildError("JasPer module not loaded?") + + buildopts = 'CC="%s" FC="%s" INCDIR="-I%s/include"' % (os.getenv('CC'), os.getenv('F90'), jasper) + self.cfg.update('buildopts', buildopts) + + super(EB_g2lib, self).build_step() + + def install_step(self): + """Install by copying generated library to install directory.""" + + try: + targetdir = os.path.join(self.installdir, "lib") + os.mkdir(targetdir) + fn = "libg2.a" + shutil.copyfile(os.path.join(self.cfg['start_dir'], fn), os.path.join(targetdir, fn)) + except OSError, err: + raise EasyBuildError("Failed to copy files to install dir: %s", err) + + def sanity_check_step(self): + """Custom sanity check for g2lib.""" + + custom_paths = { + 'files': ["lib/libg2.a"], + 'dirs': [] + } + + super(EB_g2lib, self).sanity_check_step(custom_paths=custom_paths) diff --git a/pool/shard000/Python/0000183_package.py b/pool/shard000/Python/0000183_package.py new file mode 100644 index 0000000000000000000000000000000000000000..2bab0646f3642c510031f53bc730167d00de6818 --- /dev/null +++ b/pool/shard000/Python/0000183_package.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +#coding=utf-8 + +# This script will create a package for AnyStore SDK +import os +import traceback +import shutil, errno +import zipfile + +def zip(src, dst): + zf = zipfile.ZipFile("%s.zip" % (dst), "w") + abs_src = os.path.abspath(src) + for dirname, subdirs, files in os.walk(src): + for filename in files: + absname = os.path.abspath(os.path.join(dirname, filename)) + arcname = absname[len(abs_src) + 1:] + # print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) + zf.write(absname, arcname) + zf.close() + +def copyanything(src, dst): + try: + shutil.copytree(src, dst) + except OSError as exc: # python >2.5 + if exc.errno == errno.ENOTDIR: + shutil.copy(src, dst) + else: raise + +def main(): + from optparse import OptionParser + parser = OptionParser(usage='usage: %prog -v 1.0') + parser.add_option('-v', '--version',dest='version', help="Version number for the SDK") + opts, args = parser.parse_args() + if not opts.version: + parser.error('please specify version with -v') + + if opts.version: + version = opts.version + + + pubDir = '/publish' + binDir = '/publish/bin' + demoDir = '/Demo' + sdkDir = '/SDK' + archiveName = '/AnyStore_SDK' + + print('==> creating publish folder') + currDir = os.getcwd() + publishPath = currDir + pubDir + binPath = currDir + binDir + + docPath = currDir + '/docs/guide.md' + outDocPath = binPath + '/Readme.html' + + print(publishPath) + if os.path.exists(publishPath): + shutil.rmtree(publishPath) + os.makedirs(publishPath) + os.makedirs(binPath) + print + + print('==> generating documentation form markdown') + from grip import export + export(path=docPath, out_filename=outDocPath) + print + + print('==> copy resources to publish folder') + copyanything(currDir + sdkDir, binPath + sdkDir) + copyanything(currDir + demoDir, binPath + demoDir) + print + + print('==> create archive') + zip(binPath, publishPath + archiveName + version) + print + +# ---------- main ------------- +if __name__ == '__main__': + try: + main() + except Exception as e: + traceback.print_exc() + sys.exit(1) \ No newline at end of file diff --git a/pool/shard000/Python/0000195_test_heroku.py b/pool/shard000/Python/0000195_test_heroku.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d0d15fa9783811748302f81abeb14b7ec5c151 --- /dev/null +++ b/pool/shard000/Python/0000195_test_heroku.py @@ -0,0 +1,132 @@ +import pytest +from mock import patch, call, Mock + +from blt.tools import heroku + +# -- Set Fixtures ------------------------------------------------------------- +@pytest.fixture +def heroku_cmds(): + config = { + "heroku": { + "app": "pubweb-staging" + , "git_remote": "heroku-staging" + , "git_branch": "test-branch" + , "addons": { + "papertrail": "choklad" + , "newrelic": "standard" + } + , "config": { + "DEBUG": "False" + , "PRODUCTION": "True" + , "SSL_ENABLED": "False" + } + , "post_deploy": [ + "python djangoproj/manage.py syncdb" + , "python djangoproj/manage.py migrate" + , "python djangoproj/manage.py loaddata dev_data" + ] + , "domains": [ + "app1.pubvest.com" + , "app2.pubvest.com" + ] + , "migrate": [ + "python djangoproj/manage.py migrate" + ] + } + , "blt_envtype": "staging" + } + + return heroku.HerokuCommands(config) + +# -- Setup/Teardown ----------------------------------------------------------- + +# Setup Module-wide mocks +heroku.local = Mock() + +# def setup_function(function): +# """this is called before every test case runs""" +# heroku.cfg = heroku_config() + +def teardown_function(function): + """this is called after every test case runs""" + heroku.local.reset_mock() + +# -- Test Cases! -------------------------------------------------------------- +def test_info(heroku_cmds): + heroku_cmds.info() + heroku.local.assert_called_once_with('heroku apps:info --app pubweb-staging') + +def test_destroy(heroku_cmds): + heroku_cmds.destroy() + heroku.local.assert_called_once_with('heroku apps:destroy pubweb-staging') + +def test_config_no_args(heroku_cmds): + heroku_cmds.config() + heroku.local.assert_called_once_with('heroku config --app pubweb-staging') + +def test_config_set_default(heroku_cmds): + heroku_cmds.config('set') + heroku.local.assert_called_once_with('heroku config:set DEBUG=False SSL_ENABLED=False PRODUCTION=True --app pubweb-staging') + +def test_config_cmd_and_args(heroku_cmds): + heroku_cmds.config('set', 'Darth=Vader Han=Solo') + heroku.local.assert_called_once_with('heroku config:set Darth=Vader Han=Solo --app pubweb-staging') + +def test_addon_no_args(heroku_cmds): + heroku_cmds.addon() + heroku.local.assert_called_once_with('heroku addons --app pubweb-staging') + +def test_addon_add_default(heroku_cmds): + heroku_cmds.addon('add') + calls = [call('heroku addons:add papertrail:choklad --app pubweb-staging') + , call('heroku addons:add newrelic:standard --app pubweb-staging')] + heroku.local.assert_has_calls(calls) + +def test_addon_cmd_and_args(heroku_cmds): + heroku_cmds.addon('add', 'Darth:Vader') + heroku.local.assert_called_once_with('heroku addons:add Darth:Vader --app pubweb-staging') + +def test_push(heroku_cmds): + heroku_cmds.push() + heroku.local.assert_called_once_with('git push heroku-staging test-branch:master') + +def test_push_with_force(heroku_cmds): + heroku_cmds.push('force') + heroku.local.assert_called_once_with('git push heroku-staging test-branch:master --force') + +def test_create(heroku_cmds): + heroku.prompt = Mock(return_value='yes') + heroku_cmds.create() + calls = [call('heroku apps:create pubweb-staging --remote heroku-staging') + , call('heroku config:set DEBUG=False SSL_ENABLED=False PRODUCTION=True --app pubweb-staging') + , call('git push heroku-staging test-branch:master') + , call('heroku addons:add papertrail:choklad --app pubweb-staging') + , call('heroku addons:add newrelic:standard --app pubweb-staging') + , call('heroku domains:add app1.pubvest.com --app pubweb-staging') + , call('heroku domains:add app2.pubvest.com --app pubweb-staging') + , call('heroku run "python djangoproj/manage.py syncdb" --app pubweb-staging') + , call('heroku run "python djangoproj/manage.py migrate" --app pubweb-staging')] + + heroku.local.assert_has_calls(calls) + +def test_run(heroku_cmds): + heroku_cmds.run('python manage.py runserver') + heroku.local.assert_called_once_with('heroku run "python manage.py runserver" --app pubweb-staging') + +def test_domain_no_args(heroku_cmds): + heroku_cmds.domain() + heroku.local.assert_called_once_with('heroku domains --app pubweb-staging') + +def test_domain_add_default(heroku_cmds): + heroku_cmds.domain('add') + calls = [call('heroku domains:add app1.pubvest.com --app pubweb-staging') + , call('heroku domains:add app2.pubvest.com --app pubweb-staging')] + heroku.local.assert_has_calls(calls) + +def test_domain_cmd_and_args(heroku_cmds): + heroku_cmds.domain('add', 'app3.pubvest.com') + heroku.local.assert_called_once_with('heroku domains:add app3.pubvest.com --app pubweb-staging') + +def test_migrate(heroku_cmds): + heroku_cmds.migrate() + heroku.local.assert_called_once_with('heroku run "python djangoproj/manage.py migrate" --app pubweb-staging') diff --git a/pool/shard000/Python/0000199_spaghetti.py b/pool/shard000/Python/0000199_spaghetti.py new file mode 100644 index 0000000000000000000000000000000000000000..361dc9155ac389cebf236eccfce1cf9ba1daf2f8 --- /dev/null +++ b/pool/shard000/Python/0000199_spaghetti.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import +from __future__ import print_function +from __future__ import with_statement + +import warnings + + +class FSM(object): + """ + Pass callables for matcher and handler to add_handler to create + transitions between states. A "matcher" is a predicate, and if a + transition handles something, it returns the next state. + + If you want something to track global state, put it in your data + instance passed to process so that transitions and states can + access it. + + Example: + idle = State("IDLE") + stuff = State("STUFF") + + def is_capital(letter): + return letter in string.uppercase + + def is_small(letter): + return letter in string.lowercase + + def do_something_with_capitals(letter): + print("Got capital:", letter) + return stuff + + idle.add_transition( + Transition(stuff, is_capital, self.do_something_with_capitals) + ) + stuff.add_transition( + Transition(idle, is_lower, None) + ) + """ + + states = [] + state = None + + def __init__(self, states): + """first state is the initial state""" + if len(states) > 0: + self.state = states[0] + self.states = states + + def process(self, data): + if self.state is None: + raise RuntimeError("There is no initial state.") + next_state = self.state.process(data) + if next_state: + self.state = next_state + else: + warnings.warn("No next state", RuntimeWarning) + + def add_state(self, state): + # first added state is initial state + if len(self.states) == 0: + self.state = state + self.states.append(state) + + def dotty(self): + r = 'digraph fsm {\n\n' + for s in self.states: + r = r + s.dotty() + r = r + '\n}\n' + return r + + +class State(object): + def __init__(self, name): + self.name = name + self.transitions = [] + + def process(self, data): + for t in self.transitions: + r = t.process(data) + if r is not None: + return r + return None + + def add_transition(self, t): + self.transitions.append(t) + t.start_state = self + + def add_transitions(self, transitions): + for t in transitions: + self.add_transition(t) + + def __str__(self): + r = '%s ' % t.next_state.name) + r = r + ']>' + return r + + def dotty(self): + r = '%s;\n' % self.name + r = r + 'edge [fontsize=8]\n' + r = r + 'rankdir=TB;\nnodesep=2;\n' + for t in self.transitions: + r = r + '%s -> %s [label="%s\\n%s"]\n' % (self.name, + t.next_state.name, + t.matcher.__name__, + t.handler.__name__) + return r + + +class Transition(object): + def __init__(self, next_state, matcher, handler): + self.matcher = matcher + self.handler = handler + self.start_state = None + self.next_state = next_state + if self.next_state is None: + raise RuntimeError("next_state must be valid") + + def match(self, data): + """ + used by process; calls handler if matcher returns true for + data by default. may override instead of providing a matcher + methdo to ctor. + """ + if self.matcher is not None: + return self.matcher(data) + return True + + def handle(self, data): + """ + return next state. May override in a subclass to change + behavior or pass a handler method to ctor + """ + if self.handler: + state = self.handler(data) + if state is None: + return self.next_state + return state + return self.next_state + + def process(self, data): + """return next state, or None if not handled.""" + if self.match(data): + return self.handle(data) + return None + + def __str__(self): + if self.start_state: + return "%s>" % (self.start_state.name, + self.next_state.name) + return "%s>" % (self.next_state.name,) diff --git a/pool/shard000/Python/0000201_checks.py b/pool/shard000/Python/0000201_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..38c6e4e243ee45c617075e2e78202a3a21fe1c96 --- /dev/null +++ b/pool/shard000/Python/0000201_checks.py @@ -0,0 +1,118 @@ +from importlib import import_module + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured + +from django.contrib.auth import get_user_model + +from ping.defaults import PING_DEFAULT_CHECKS, PING_CELERY_TIMEOUT + + +AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") + + +def checks(request): + """ + Iterates through a tuple of systems checks, + then returns a key name for the check and the value + for that check. + """ + response_dict = {} + + # Taken straight from Django + # If there is a better way, I don't know it + for path in getattr(settings, 'PING_CHECKS', PING_DEFAULT_CHECKS): + i = path.rfind('.') + module, attr = path[:i], path[i+1:] + try: + mod = import_module(module) + except ImportError as e: + raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) + try: + func = getattr(mod, attr) + except AttributeError: + raise ImproperlyConfigured('Module "%s" does not define a "%s" callable' % (module, attr)) + + key, value = func(request) + response_dict[key] = value + + return response_dict + + +# DEFAULT SYSTEM CHECKS + +# Database +def check_database_sessions(request): + from django.contrib.sessions.models import Session + try: + Session.objects.all()[0] + return 'db_sessions', True + except: + return 'db_sessions', False + + +def check_database_sites(request): + from django.contrib.sites.models import Site + try: + Site.objects.all()[0] + return 'db_site', True + except: + return 'db_site', False + + +# Caching +CACHE_KEY = 'django-ping-test' +CACHE_VALUE = 'abc123' + + +def check_cache_set(request): + from django.core.cache import cache + try: + cache.set(CACHE_KEY, CACHE_VALUE, 30) + return 'cache_set', True + except: + return 'cache_set', False + + +def check_cache_get(request): + from django.core.cache import cache + try: + data = cache.get(CACHE_KEY) + if data == CACHE_VALUE: + return 'cache_get', True + else: + return 'cache_get', False + except: + return 'cache_get', False + + +# User +def check_user_exists(request): + try: + username = getattr(settings, 'PING_KNOWN_USER_EXISTS', request.GET.get('username')) + get_user_model().objects.get(username=username) + return 'user_exists', True + except: + return 'user_exists', False + + +# Celery +def check_celery(request): + from datetime import datetime, timedelta + from time import sleep, time + from ping.tasks import sample_task + + now = time() + datetimenow = datetime.now() + expires = datetimenow + timedelta(seconds=getattr(settings, 'PING_CELERY_TIMEOUT', PING_CELERY_TIMEOUT)) + + try: + task = sample_task.apply_async(expires=expires) + while expires > datetime.now(): + if task.ready() and task.result is True: + finished = str(time() - now) + return 'celery', {'success': True, 'time': finished } + sleep(0.25) + return 'celery', {'success': False} + except Exception: + return 'celery', {'success': False}