+ this.utils.matcherHint('.not.toBeSameTimeAs') +
+ '\n\n' +
+ `Expected time to not be (using moment.isSame):\n` +
+ ` ${this.utils.printExpected(expected)}\n` +
+ `Received:\n` +
+ ` ${this.utils.printReceived(received)}`
+ : () => {
+ const diffString = diff(expected, received, {
+ expand: this.expand,
+ });
+ return (
+ this.utils.matcherHint('.toBeSameTimeAs') +
+ '\n\n' +
+ `Expected time to be (using moment.isSame):\n` +
+ ` ${this.utils.printExpected(expected)}\n` +
+ `Received:\n` +
+ ` ${this.utils.printReceived(received)}` +
+ (diffString ? `\n\nDifference:\n\n${diffString}` : '')
+ );
+ };
+
+ return { actual: received, message, pass };
+ },
+});
diff --git a/pool/shard006/JavaScript/0041703_PlaylistItemRow.js b/pool/shard006/JavaScript/0041703_PlaylistItemRow.js
new file mode 100644
index 0000000000000000000000000000000000000000..c9bbbc6db90356d10a28f45daba41f826cf8a840
--- /dev/null
+++ b/pool/shard006/JavaScript/0041703_PlaylistItemRow.js
@@ -0,0 +1,87 @@
+import cx from 'clsx';
+import React from 'react';
+import PropTypes from 'prop-types';
+import MediaDuration from '../../MediaList/MediaDuration';
+import MediaLoadingIndicator from '../../MediaList/MediaLoadingIndicator';
+import MediaRowBase from '../../MediaList/MediaRowBase';
+import MediaSourceIcon from '../../MediaList/MediaSourceIcon';
+import MediaThumbnail from '../../MediaList/MediaThumbnail';
+import PlaylistItemActions from './PlaylistItemActions';
+
+const {
+ useCallback,
+ useState,
+} = React;
+
+function PlaylistItemRow({
+ className,
+ style,
+ containerRef,
+ index,
+ media,
+ onClick,
+}) {
+ const loadingClass = media.loading ? 'is-loading' : '';
+ const [showActions, setShowActions] = useState(false);
+
+ // We need `onMouseOver` instead of `onMouseEnter` because we may enter
+ // a playlist item row because the one above it was deleted; in that case,
+ // `onMouseEnter` does not trigger, but `onMouseOver` does
+ const handleMouseOver = useCallback(() => {
+ setShowActions(true);
+ }, []);
+
+ const handleMouseLeave = useCallback(() => {
+ setShowActions(false);
+ }, []);
+
+ return (
+
+ {media.loading ? (
+
+ ) : (
+
+ )}
+
+
+ {media.artist}
+
+
+ {media.title}
+
+
+
+
+
+
+
+
+ {showActions ? (
+
+ ) : null}
+
+ );
+}
+
+PlaylistItemRow.propTypes = {
+ className: PropTypes.string,
+ style: PropTypes.object, // from react-window
+ index: PropTypes.number.isRequired,
+ containerRef: PropTypes.any,
+ media: PropTypes.object.isRequired,
+ onClick: PropTypes.func.isRequired,
+};
+
+export default PlaylistItemRow;
diff --git a/pool/shard006/JavaScript/0041704_widget.js b/pool/shard006/JavaScript/0041704_widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..a7833d11a6cfd658b3c8cf0c2e896f03364613c2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041704_widget.js
@@ -0,0 +1,70 @@
+var args = arguments[0] || {},
+ stars = [],
+ rating = 0,
+ max = 5;
+
+// public method to set the rating
+var setRating = function(newRating) {
+ // save newRating to the instance's rating property
+ if(newRating > max) {
+ newRating = max;
+ }
+ rating = newRating;
+
+ // use a loop to set the stars[i].image property
+ // using the half-image for fractional values
+ for (var i = 0, l = stars.length; i < l; i++) {
+ if (i >= rating) {
+ stars[i].image = WPATH('star_off.png');
+ }
+ else if (rating > i && rating < i+1) {
+ stars[i].image = WPATH('star_half.png');
+ }
+ else {
+ stars[i].image = WPATH('star.png');
+ }
+ }
+};
+exports.setRating = setRating;
+
+// public method to get current rating
+exports.getRating = function() {
+ return rating;
+};
+
+// private method
+var createStars = function(num, cb) {
+ for (var i = 0; i < num; i++) {
+ // define the image view
+ var star = Alloy.createWidget('starrating', 'star').getView();
+
+ if (!args.editable){
+ // use a closure (self-calling function) to add
+ // a click-event listener that calls setRating
+ // passing the value of i+1
+ (function() {
+ var index = i;
+ star.addEventListener('click', function() {
+ setRating(index+1);
+ cb(index+1);
+ });
+ })();
+ }
+ // add the star image to the stars array
+ stars.push(star);
+ // add the star image to the instance view
+ $.starrating.add(star);
+ }
+};
+
+exports.init = function (callback) {
+ var max = args.max || 5,
+ initialRating = args.initialRating || 0,
+ cb = callback || function(){};
+ createStars(max, cb);
+ setRating(initialRating);
+ // can't apply view properties from the calling context when you use this widget
+ // without coding them in to this controller, alloy limitation as of this writing
+ _.extend($.starrating, args);
+
+};
diff --git a/pool/shard006/JavaScript/0041706_format.jam.js b/pool/shard006/JavaScript/0041706_format.jam.js
new file mode 100644
index 0000000000000000000000000000000000000000..598d16e8a5dd3c90b32e9b8fd47df297e4955141
--- /dev/null
+++ b/pool/shard006/JavaScript/0041706_format.jam.js
@@ -0,0 +1,48 @@
+/**
+ * Generator of date-formatters.
+ * Date-formatter is a function that returns string representation of a date.
+ *
+ * 0 params: hash-table of all patterns
+ * 1 param: return date-formatter by pattern
+ * 2 params: assign date-formatter for pattern
+ *
+ * Mnemonics:
+ *
+ * * single letter for numbers: M - month number, D - day of month.
+ * * uppercase letters for dates, lowercase for times: M - month number , m - minutes number
+ * * repeated letters for define register count: YYYY - full year, YY - shot year, MM - padded month number
+ * * words, same letter case: Month - localized capitalized month name
+ * * shortcuts: WD - short day of week, Mon - short month name.
+ * * special identifiers: iso8601, stamp.
+ *
+ * Complex patterns splits by words and then substitute by date-formatters for short patterns
+ * For localize output override $jin.l10n( scope, text )
+ *
+ * Typical usage:
+ * var formatTime = $jin.time1.format( 'Weekday, YYYY-MM-DD hh:mm' )
+ * formatTime( $jin.time1.moment() )
+ *
+ * @name $jin.time1.format
+ * @method format
+ * @member $jin.time
+ * @param {string} [pattern]
+ * @param {function( $jin.date )} [formatter]
+ * @static
+ */
+$jin.property.hash({ '$jin.time1.format': { pull: function( pattern ) {
+
+ var lexems = $jin.time1.format()
+ var patterns = Object.keys( lexems )
+ patterns.sort()
+ patterns.reverse()
+
+ var funcs = []
+
+ var lexer = RegExp( '(.*?)(' + patterns.join( '|' ) + '|$)', 'g' )
+ pattern.replace( lexer, function( str, text, token ){
+ if( text ) funcs.push( function(){ return text } )
+ if( token ) funcs.push( lexems[ token ] )
+ })
+
+ return $jin.concater( funcs )
+}}})
diff --git a/pool/shard006/JavaScript/0041708_server.js b/pool/shard006/JavaScript/0041708_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..2ab1448116385e5550cd40dc2ba978b2192cd7ec
--- /dev/null
+++ b/pool/shard006/JavaScript/0041708_server.js
@@ -0,0 +1,69 @@
+var express = require('express'),
+ app = express(),
+ swig = require('swig'),
+ cookieParser = require('cookie-parser'),
+ i18n = require('i18n-2'),
+ bodyParser = require('body-parser');
+ PORT = process.env.PORT || 6060;
+ isProduction = true;
+
+/* Getting the current enviroment */
+if(process.env.NODE_ENV === 'development') {
+ isProduction = false;
+ console.log('App running on Development enviroment...');
+}
+
+/* View Engine Setup */
+app.engine('html', swig.renderFile);
+app.set('view engine', 'html');
+
+if(!isProduction) {
+ app.set('view cache', false);
+ swig.setDefaults({ cache: false });
+}
+
+/* for parsing application/x-www-form-urlencoded */
+app.use(bodyParser.urlencoded({ extended: true }));
+
+/* Set static files path */
+app.use(express.static(__dirname + '/app/public/'));
+
+/* Set views path */
+app.set('views', __dirname + '/app/views/');
+
+
+/* Setup Middlewares */
+app.use(cookieParser('un gran secreto'));
+
+ //setup i18n
+i18n.expressBind(app, {
+ locales: ['es','en'],
+ defaultLocale: 'es',
+ cookiename: 'locale'
+});
+app.use(function(req, res, next){
+ req.i18n.setLocaleFromCookie();
+ next();
+});
+
+/* Routes */
+app.get('/', function(req, res){
+ res.render('layout', {
+ isProduction: isProduction,
+ headerTitle: req.i18n.__('headerTitle'),
+ headerQuote: req.i18n.__('headerQuote'),
+ headerText: req.i18n.__('headerText')
+ });
+});
+
+// Request via contact form
+app.post('/', function(req, res){
+ console.log(req.body);
+ res.send(JSON.stringify({ok:"ok"}));
+});
+
+app.listen(PORT, function() {
+ console.log('app running on port: %d', PORT);
+});
+
+
diff --git a/pool/shard006/JavaScript/0041711_xml-test.js b/pool/shard006/JavaScript/0041711_xml-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..2e3e745dd2cdafe4383bea472653a7a81ba9965d
--- /dev/null
+++ b/pool/shard006/JavaScript/0041711_xml-test.js
@@ -0,0 +1,47 @@
+require("../env");
+
+var vows = require("vows"),
+ assert = require("assert");
+
+var suite = vows.describe("d3.xml");
+
+suite.addBatch({
+ "xml": {
+ topic: function() {
+ var cb = this.callback;
+ d3.xml("test/data/sample.xml", function(error, xml) {
+ cb(null, xml);
+ });
+ },
+ "invokes the callback with the loaded xml": function(xml) {
+ assert.deepEqual(xml, {_xml: "\n\n \n \n"});
+ },
+ "does not override the mime type by default": function(xml) {
+ assert.isUndefined(XMLHttpRequest._last._info.mimeType);
+ },
+ "": {
+ topic: function() {
+ var cb = this.callback;
+ d3.xml("test/data/sample.txt", "application/xml+sample", function(error, xml) {
+ cb(null, xml);
+ });
+ },
+ "observes the optional mime type": function(xml) {
+ assert.equal(XMLHttpRequest._last._info.mimeType, "application/xml+sample");
+ }
+ },
+ " ": {
+ topic: function() {
+ var cb = this.callback;
+ d3.xml("//does/not/exist.xml", function(error, xml) {
+ cb(null, xml);
+ });
+ },
+ "invokes the callback with undefined when an error occurs": function(xml) {
+ assert.isUndefined(xml);
+ }
+ }
+ }
+});
+
+suite.export(module);
diff --git a/pool/shard006/JavaScript/0041712_customer.js b/pool/shard006/JavaScript/0041712_customer.js
new file mode 100644
index 0000000000000000000000000000000000000000..0d7e1bdb33fd16cb6f64df0fe0b380ecb2ececbc
--- /dev/null
+++ b/pool/shard006/JavaScript/0041712_customer.js
@@ -0,0 +1,51 @@
+var doc = {
+ toggleActive: function (obj) {
+ if ($(obj).next().length == 0) {
+ $(".menu").find("a").removeClass("active");
+ $(obj).addClass("active").attr("href", obj.href.split('?')[0] + "?_=" + new Date().getTime()).attr("target", "mainFrame");
+ } else {
+ if ($(obj).next("ul").is(":hidden")) { $(obj).parents("ul").find("li ul").not(":hidden").toggle(200).prev("a").find("i").toggleClass("arrow-down arrow-right"); }
+ $(obj).next("ul").toggle(200).prev("a").find("i").toggleClass("arrow-down arrow-right");
+ }
+ },
+ resizeStyle: function () {
+ $(".main-content,iframe[name='mainFrame']").width($(window).width() - $(".menu").width()).height("100%");
+ var textareaHeight = $(window).height() - ($(".form-horizontal").height() - $("textarea[name='response']").height() + 70);
+ if ($("textarea[name='response']").height() < textareaHeight) { $("textarea[name='response']").height(textareaHeight); }
+ },
+ submitForm: function (obj) {
+ var data = this.serializeJson($(obj));
+ $.ajax({
+ type: data.method, dataType: "json",
+ beforeSend: function () { $(obj).find('input[type="submit"]').button("loading"); },
+ complete: function () { $(obj).find('input[type="submit"]').button("reset"); },
+ url: "/Api/Dev/Debug?Url=" + encodeURI(data.action) + "&Method=" + data.method + "&Platform=" + data.Platform + "&Parma=" + encodeURI(data.parameter.replace(/&/g, "|")),
+ success: function (response) { $("input[name='response']").val(response.Response); doc.formatJson(response.Response); $("input[name='sign']").val(response.Sign); },
+ error: function () { modal.alert({ content: "请求出错了 !", cancel: "确定", type: "danger" }); }
+ }); return false;
+ },
+ formatJson: function (json) {
+ if ($("input[name='response']").length > 0) {
+ (new JsonFormater({ dom: ".response", isCollapsible: $(".console").prop("checked") })).doFormat(json);
+ $(".console").change(function () { (new JsonFormater({ dom: ".response", isCollapsible: $(".console").prop("checked") })).doFormat($("input[name='response']").val()); });
+ }
+ },
+ serializeJson: function (obj) {
+ var serializeObj = {}; var array = obj.serializeArray();
+ $(array).each(function () {
+ if (serializeObj[this.name]) {
+ if ($.isArray(serializeObj[this.name])) {
+ serializeObj[this.name].push(this.value);
+ } else { serializeObj[this.name] = [serializeObj[this.name], this.value]; }
+ } else { serializeObj[this.name] = this.value; }
+ }); return serializeObj;
+ },
+ init: function () {
+ window.onresize = this.resizeStyle; $(window).resize();
+ $(".menu").find("li ul").prev("a").css("padding-left", "0").prepend(' ');
+ $(".menu").find("a").bind("click", function () { doc.toggleActive(this); });
+ $(".form-horizontal").bind("submit", function () { return doc.submitForm(this); });
+ if ($("input[name='response']")) { this.formatJson($("input[name='response']").val()); }
+ }
+};
+$(function () { doc.init(); });
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041716_feed.js b/pool/shard006/JavaScript/0041716_feed.js
new file mode 100644
index 0000000000000000000000000000000000000000..0d4a2b286f2449089d1761e62628272a5e129047
--- /dev/null
+++ b/pool/shard006/JavaScript/0041716_feed.js
@@ -0,0 +1,20 @@
+import NavigationBar from './navigation-bar';
+import HolidayList from './holiday-list';
+
+export const Feed = (props) => {
+ // todo: derive these from dataset
+ const minimumDate = '2017-07-14';
+ const maximumDate = '2018-07-12';
+
+
+ let pathDate = new Date();
+ if (props.year && props.month && props.day) {
+ pathDate = new Date(props.year, props.month - 1, props.day);
+ }
+ return (
+
+
+
+
+ );
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041718_StyleButton.js b/pool/shard006/JavaScript/0041718_StyleButton.js
new file mode 100644
index 0000000000000000000000000000000000000000..dc0431f3f52e3966c23bb722cfb185a9dc1189b2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041718_StyleButton.js
@@ -0,0 +1,18 @@
+const React = require('react');
+
+module.exports = (props) => {
+ const onToggle = function(e) {
+ e.preventDefault();
+ props.onToggle(props.style || e);
+ }
+
+ const label = (props.icon) ?
+ ( ) :
+ (props.label);
+
+ return (
+
+ {label}
+
+ );
+};
diff --git a/pool/shard006/JavaScript/0041719_primeng-tabmenu.js b/pool/shard006/JavaScript/0041719_primeng-tabmenu.js
new file mode 100644
index 0000000000000000000000000000000000000000..aeafbc7b61fa2637a326832bfa37af04ef42233e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041719_primeng-tabmenu.js
@@ -0,0 +1,115 @@
+import { Component, ChangeDetectionStrategy, ViewEncapsulation, Input, ViewChild, ContentChildren, NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { RippleModule } from 'primeng/ripple';
+import { PrimeTemplate, SharedModule } from 'primeng/api';
+import { RouterModule } from '@angular/router';
+import { DomHandler } from 'primeng/dom';
+
+class TabMenu {
+ ngAfterContentInit() {
+ this.templates.forEach((item) => {
+ switch (item.getType()) {
+ case 'item':
+ this.itemTemplate = item.template;
+ break;
+ default:
+ this.itemTemplate = item.template;
+ break;
+ }
+ });
+ }
+ ngAfterViewInit() {
+ this.updateInkBar();
+ }
+ ngAfterViewChecked() {
+ if (this.tabChanged) {
+ this.updateInkBar();
+ this.tabChanged = false;
+ }
+ }
+ itemClick(event, item) {
+ if (item.disabled) {
+ event.preventDefault();
+ return;
+ }
+ if (item.command) {
+ item.command({
+ originalEvent: event,
+ item: item
+ });
+ }
+ this.activeItem = item;
+ this.tabChanged = true;
+ }
+ updateInkBar() {
+ let tabHeader = DomHandler.findSingle(this.navbar.nativeElement, 'li.p-highlight');
+ if (tabHeader) {
+ this.inkbar.nativeElement.style.width = DomHandler.getWidth(tabHeader) + 'px';
+ this.inkbar.nativeElement.style.left = DomHandler.getOffset(tabHeader).left - DomHandler.getOffset(this.navbar.nativeElement).left + 'px';
+ }
+ }
+}
+TabMenu.decorators = [
+ { type: Component, args: [{
+ selector: 'p-tabMenu',
+ template: `
+
+
+
+ `,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ encapsulation: ViewEncapsulation.None,
+ styles: [".p-tabmenu-nav{display:flex;flex-wrap:wrap;list-style-type:none;margin:0;padding:0}.p-tabmenu-nav a{-ms-user-select:none;-webkit-user-select:none;align-items:center;cursor:pointer;display:flex;overflow:hidden;position:relative;text-decoration:none;user-select:none}.p-tabmenu-nav a:focus{z-index:1}.p-tabmenu-nav .p-menuitem-text{line-height:1}.p-tabmenu-ink-bar{display:none;z-index:1}"]
+ },] }
+];
+TabMenu.propDecorators = {
+ model: [{ type: Input }],
+ activeItem: [{ type: Input }],
+ popup: [{ type: Input }],
+ style: [{ type: Input }],
+ styleClass: [{ type: Input }],
+ navbar: [{ type: ViewChild, args: ['navbar',] }],
+ inkbar: [{ type: ViewChild, args: ['inkbar',] }],
+ templates: [{ type: ContentChildren, args: [PrimeTemplate,] }]
+};
+class TabMenuModule {
+}
+TabMenuModule.decorators = [
+ { type: NgModule, args: [{
+ imports: [CommonModule, RouterModule, SharedModule, RippleModule],
+ exports: [TabMenu, RouterModule, SharedModule],
+ declarations: [TabMenu]
+ },] }
+];
+
+/**
+ * Generated bundle index. Do not edit.
+ */
+
+export { TabMenu, TabMenuModule };
+//# sourceMappingURL=primeng-tabmenu.js.map
diff --git a/pool/shard006/JavaScript/0041720_mapAccum.js b/pool/shard006/JavaScript/0041720_mapAccum.js
new file mode 100644
index 0000000000000000000000000000000000000000..f4134d379f4b38913fb6cf7050f2a2beb45f6a02
--- /dev/null
+++ b/pool/shard006/JavaScript/0041720_mapAccum.js
@@ -0,0 +1,49 @@
+var _curry3 = require('./internal/_curry3');
+
+
+/**
+ * The mapAccum function behaves like a combination of map and reduce; it
+ * applies a function to each element of a list, passing an accumulating
+ * parameter from left to right, and returning a final value of this
+ * accumulator together with the new list.
+ *
+ * The iterator function receives two arguments, *acc* and *value*, and should
+ * return a tuple *[acc, value]*.
+ *
+ * @func
+ * @memberOf R
+ * @since v0.10.0
+ * @category List
+ * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
+ * @param {Function} fn The function to be called on every element of the input `list`.
+ * @param {*} acc The accumulator value.
+ * @param {Array} list The list to iterate over.
+ * @return {*} The final, accumulated value.
+ * @see R.addIndex, R.mapAccumRight
+ * @example
+ *
+ * var digits = ['1', '2', '3', '4'];
+ * var appender = (a, b) => [a + b, a + b];
+ *
+ * R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
+ * @symb R.mapAccum(f, a, [b, c, d]) = [
+ * f(f(f(a, b)[0], c)[0], d)[0],
+ * [
+ * f(a, b)[1],
+ * f(f(a, b)[0], c)[1],
+ * f(f(f(a, b)[0], c)[0], d)[1]
+ * ]
+ * ]
+ */
+module.exports = _curry3(function mapAccum(fn, acc, list) {
+ var idx = 0;
+ var len = list.length;
+ var result = [];
+ var tuple = [acc];
+ while (idx < len) {
+ tuple = fn(tuple[0], list[idx]);
+ result[idx] = tuple[1];
+ idx += 1;
+ }
+ return [tuple[0], result];
+});
diff --git a/pool/shard006/JavaScript/0041724_global.js b/pool/shard006/JavaScript/0041724_global.js
new file mode 100644
index 0000000000000000000000000000000000000000..f8e94c3fbf40a0f33fd60e4045cf79d03fabb663
--- /dev/null
+++ b/pool/shard006/JavaScript/0041724_global.js
@@ -0,0 +1,134 @@
+/* global ConversationPanel: true */
+/* eslint no-unused-vars: "off" */
+
+// Other JS files required to be loaded first: apis.js, conversation.js
+(function() {
+ // Initialize all modules
+ ConversationPanel.init();
+})();
+
+// nasty globals for state
+var tripRetrieved = false;
+var alternatesRetrieved = false;
+var problemState = {};
+
+// this function handles responses from the Watson conversation service
+// and optionally uses intents and e
+function handleResponseMessage(incomingMsg) {
+ var response = incomingMsg;
+ for (var i = 0; i < response.intents.length; i++) {
+ var intent = response.intents[i];
+ var handled = false;
+ switch (intent.intent) {
+ case "when":
+ if (intent.confidence > 0.5) {
+ response = handleWhen(response);
+ handled = true;
+ } else {
+ // not enough confidence to guess "when"..ask for more
+ response.output.text = "Can you rephrase what you are looking for?";
+ }
+ break;
+ case "alternate":
+ if (intent.confidence > 0.5) {
+ response = handleAlternate(response);
+ handled = true;
+ break;
+ } else {
+ // not enough confidence to guess "when"..ask for more
+ response.output.text = "Can you rephrase what you are looking for?";
+ }
+ break;
+ case "problem":
+ if (intent.confidence > 0.5) {
+ response = handleProblem(intent, response);
+ handled = true;
+ break;
+ } else {
+ // not enough confidence to guess "when"..ask for more
+ response.output.text = "Can you rephrase what you are looking for?";
+ }
+ break;
+ }
+ if (handled) {
+ break;
+ }
+ }
+ return response;
+}
+
+function handleWhen(response) {
+ if (tripRetrieved === true) {
+ $('#flight-alternates').css("display", "none");
+ $('#flight-results').css("display", "block");
+ } else {
+ parseTripsForFlights(false, false);
+ tripRetrieved = true;
+ }
+ response.output.text = "I've loaded your next trip details for you.";
+ return response;
+}
+
+function handleAlternate(response) {
+ if (!tripRetrieved) {
+ parseTripsForFlights(false, true);
+ tripRetrieved = true;
+ }
+ $('#flight-results').css("display", "none");
+ if (alternatesRetrieved) {
+ $('#flight-alternates').css("display", "block");
+ } else {
+ $('#flight-alternates').trigger('instantiate');
+ alternatesRetrieved = true;
+ }
+ response.output.text = "I've loaded alternate flights between your origin and destination for you.";
+ return response;
+}
+
+function handleProblem(intent, response) {
+ // first check if the conversation service has a response (to clarify information):
+ if (response.output.text.length > 0) {
+ problemState = response;
+ return response;
+ }
+ var airport = "";
+ if (response.entities.length > 0) {
+ if (response.entities[0].entity === "Airport") {
+ // user has responded with an airport:
+ airport = response.entities[0].value; // this will be the official entity name
+ }
+ }
+ if (airport !== "") {
+ var childDiv = $("#flight-alternates").children("div");
+ response.output.text = "Let me see if I can help you get from " + airport + " to your destination via an alternate flight.";
+ // BIG FIXME: Due to time constraints, for our DockerCon demo with the
+ // conversation service, we hardcoded Austin and the date to show a
+ // lookup specific to a story we were telling about Lin's canceled flight
+ // FIX: actually parse the known trip JSON to find where the traveler is
+ // going and use the date of "now" or that original flight date/time to
+ // do the alternate search.
+ outputAlternateFlights(childDiv[0], airportCode(airport), "AUS", "2017-04-18T13:00:00-05:00", 12, 15);
+ } else {
+ response.output.text = "I see you are having flight problems.";
+ }
+ return response;
+}
+
+function airportCode(cityEntity) {
+ switch (cityEntity) {
+ case "Dallas":
+ return "DFW";
+ case "Austin":
+ return "AUS";
+ case "Chicago":
+ return "ORD";
+ case "Raleigh":
+ return "RDU";
+ case "Charlotte":
+ return "CLT";
+ case "Charlottesville":
+ return "CHO";
+ default:
+ return "Unknown";
+ }
+}
diff --git a/pool/shard006/JavaScript/0041726_lvl99-plugin.js b/pool/shard006/JavaScript/0041726_lvl99-plugin.js
new file mode 100644
index 0000000000000000000000000000000000000000..348bb46f4489fd82ef26eb0bbd3f79ea87f84f6f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041726_lvl99-plugin.js
@@ -0,0 +1,160 @@
+/*
+* LVL99 Plugin JS
+*/
+
+var lvl99 = lvl99 || {};
+
+lvl99.enableDebug = true;
+lvl99.activeWidgets = 0;
+lvl99.widgetCount = 0;
+lvl99.widgets = {};
+
+// Toggle
+lvl99.widgetCount++;
+lvl99.widgets.toggle = {
+ active: false,
+ requires: [ 'jQuery' ],
+ init: function () {
+ jQuery(document).on('click', '.lvl99-toggle', function (event) {
+ var $elem = jQuery(this);
+ if ( $elem.is('.lvl99-toggle-hidden') ) {
+ $elem.css({
+ overflow: 'visible',
+ height: 'auto'
+ }).removeClass('lvl99-toggle-hidden');
+ } else {
+ $elem.css({
+ overflow: 'hidden',
+ height: '1em'
+ }).addClass('lvl99-toggle-hidden');
+ }
+ });
+ }
+};
+
+// Sortable fields
+lvl99.widgetCount++;
+lvl99.widgets.sortable = {
+ active: false,
+ requires: [ 'jQuery', 'jQuery.fn.sortable' ],
+ init: function () {
+ // Events
+ jQuery(document).trigger('lvl99-plugin-sortable');
+ }
+}
+
+// File uploads
+lvl99.widgetCount++;
+lvl99.widgets.fileUploaders = {
+ active: false,
+ requires: [ 'jQuery' ],
+ init: function () {
+ jQuery(document).ready(function() {
+ jQuery(document).on( 'click', '.upload_file_button', function (event) {
+ event.preventDefault();
+
+ jQuery.data( document.body, 'upload_file_element', jQuery(this).parents('.lvl99-plugin-option') );
+
+ window.send_to_editor = function (html) {
+ var imgurl = jQuery(html).find('img').eq(0).attr('src').replace(wp_homeurl, '/');
+ var $option = jQuery.data( document.body, 'upload_file_element' );
+
+ if ( $option != undefined && $option != '' ) {
+ $option.find('input').val(imgurl);
+ $option.find('img').attr('src', imgurl).show();
+ $option.find('.remove_file_button').show();
+ }
+
+ tb_remove();
+ };
+
+ tb_show('', 'media-upload.php?type=image&TB_iframe=true');
+ return false;
+ });
+
+ jQuery(document).on( 'click', '.remove_file_button', function (event) {
+ event.preventDefault();
+
+ var $option = jQuery(this).parents('.lvl99-plugin-option');
+ $option.find('input').val('');
+ $option.find('img').attr('src', '').hide();
+ jQuery(this).hide();
+ });
+
+ jQuery(document).trigger('lvl99-plugin-file-uploader');
+ });
+ }
+}
+
+// See: http://stackoverflow.com/a/6491621/1421162
+Object.byString = function(o, s) {
+ s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
+ s = s.replace(/^\./, ''); // strip a leading dot
+ var a = s.split('.');
+ for (var i = 0, n = a.length; i < n; ++i) {
+ var k = a[i];
+ if (k in o) {
+ o = o[k];
+ } else {
+ return;
+ }
+ }
+ return o;
+}
+
+// Initialise the widgets
+function __initLvl99Widgets( counter ) {
+ if ( counter < 0 ) {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( 'Maximum widget checks performed. Aborting...' );
+ return;
+ }
+
+ // Check if widgets have all their required dependencies before initialising
+ for( i in lvl99.widgets ) {
+ var widget = lvl99.widgets[i];
+ widget.checked = widget.checked + 1;
+ var requiresPassed = 0;
+
+ // If exceeded 10 checks, abort this widget
+ if ( widget.checked > 10 || widget.active ) continue;
+
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( 'Checking '+widget.requires.length+' dependencies for ' + i );
+
+ // Check requires are present
+ for ( x in widget.requires ) {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( ' --> Requires ' + widget.requires[x] );
+
+ if ( typeof Object.byString( window, widget.requires[x]) != 'undefined' ) {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( ' ✓ Detected '+(parseInt(x, 10)+1)+'/'+widget.requires.length+': ' + widget.requires[x] );
+ requiresPassed++;
+ } else {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( ' x Not found...' );
+ }
+ }
+
+ // If all requires passed, initialise widget JS
+ if ( requiresPassed === widget.requires.length ) {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( '✓ Detected all required for widget ' + i );
+ if ( typeof widget.init == 'function' ) {
+ widget.init();
+ widget.active = true;
+ lvl99.activeWidgets++;
+ }
+ } else {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( 'x Missing dependencies for widget ' + i );
+ }
+ }
+
+ // All widgets have initialised
+ if ( lvl99.activeWidgets === lvl99.widgetCount ) {
+ if ( lvl99.enableDebug && window.console ) if ( console.log ) console.log( 'All widgets successfully initialised!' );
+
+ // Retry initialising
+ } else {
+ setTimeout( function () {
+ __initLvl99Widgets(counter - 1);
+ }, 1000 );
+ }
+}
+
+if ( lvl99.widgetCount > 0 ) __initLvl99Widgets( 10 );
diff --git a/pool/shard006/JavaScript/0041732_activity.js b/pool/shard006/JavaScript/0041732_activity.js
new file mode 100644
index 0000000000000000000000000000000000000000..6716dc973fe2f5b1afd9ad6cac3e3ce0cd00cd9c
--- /dev/null
+++ b/pool/shard006/JavaScript/0041732_activity.js
@@ -0,0 +1,375 @@
+/*
+ * 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.
+ */
+
+/*global opensocial */
+
+/**
+ * @class
+ * Representation of an activity.
+ *
+ * Activities are rendered with a title and an optional activity body.
+ *
+ * You may set the title and body directly as strings when calling
+ * opensocial.createActivity.
+ *
+ * However, it is usually beneficial to create activities using
+ * Activity Templates for the title and body. Activity Templates support:
+ *
+ * Internationalization
+ * Replacement variables in the message
+ * Activity Summaries, which are message variations used to summarize
+ * repeated activities that share something in common.
+ *
+ *
+ * Activity Templates are defined as messages in the gadget specification.
+ * To define messages, you create and reference message bundle XML files for
+ * each locale you support.
+ *
+ * Example module spec in gadget XML:
+ *
+ * <ModulePrefs title="ListenToThis">
+ * <Locale messages="http://www.listentostuff.com/messages.xml"/>
+ * <Locale lang="de" messages="http://www.listentostuff.com/messages-DE.xml"/>
+ * </ModulePrefs>
+ *
+ *
+ *
+ * Example message bundle:
+ *
+ * <messagebundle>
+ * <msg name="LISTEN_TO_THIS_SONG">
+ * ${Subject.DisplayName} told ${Owner.DisplayName} to
+ * listen to a song!
+ * </msg>
+ * </messagebundle>
+ *
+ *
+ *
+ * You can set custom key/value string pairs when posting an activity.
+ * These values will be used for variable substitution in the templates.
+ * Example JS call:
+ *
+ * var owner = ...;
+ * var viewer = ...;
+ * var activity = opensocial.newActivity('LISTEN_TO_THIS_SONG',
+ * {Song: 'Do That There - (Young Einstein hoo-hoo mix)',
+ * Artist: 'Lyrics Born', Subject: viewer, Owner: owner})
+ *
+ *
+ *
+ * Associated message:
+ *
+ * <msg name="LISTEN_TO_THIS_SONG">
+ * ${Subject.DisplayName} told ${Owner.DisplayName} to listen
+ * to ${Song} by ${Artist}
+ * </msg>
+ *
+ *
+ *
+ * People can also be set as values in key/value pairs when posting
+ * an activity. You can then reference the following fields on a person:
+ *
+ * ${Person.DisplayName} The person's name
+ * ${Person.Id} The user ID of the person
+ * ${Person.ProfileUrl} The profile URL of the person
+ * ${Person} This will show the display name, but containers may optionally
+ * provide special formatting, such as showing the name as a link
+ *
+ *
+ * Users will have many activities in their activity streams, and containers
+ * will not show every activity that is visible to a user. To help display
+ * large numbers of activities, containers will summarize a list of activities
+ * from a given source to a single entry.
+ *
+ * You can provide Activity Summaries to customize the text shown when
+ * multiple activities are summarized. If no customization is provided, a
+ * container may ignore your activities altogether or provide default text
+ * such as "Bob changed his status message + 20 other events like this."
+ *
+ * Activity Summaries will always summarize around a specific key in a
+ * key/value pair. This is so that the summary can say something concrete
+ * (this is clearer in the example below).
+ * Other variables will have synthetic "Count" variables created with
+ * the total number of items summarized.
+ * Message ID of the summary is the message ID of the main template + ":" +
+ * the data key
+ *
+ *
+ * Example summaries:
+ *
+ * <messagebundle>
+ * <msg name="LISTEN_TO_THIS_SONG:Artist">
+ * ${Subject.Count} of your friends have suggested listening to songs
+ * by ${Artist}!
+ * </msg>
+ * <msg name="LISTEN_TO_THIS_SONG:Song">
+ * ${Subject.Count} of your friends have suggested listening to ${Song}
+ * !</msg>
+ * <msg name="LISTEN_TO_THIS_SONG:Subject">
+ * ${Subject.DisplayName} has recommended ${Song.Count} songs to you.
+ * </msg>
+ * </messagebundle>
+ *
+ *
+ * Activity Templates may only have the following HTML tags: <b>,
+ * <i>, <a>, <span>. The container also has the option
+ * to strip out these tags when rendering the activity.
+ *
+ *
+ * See also:
+ * opensocial.newActivity() ,
+ *
+ * opensocial.requestCreateActivity()
+ *
+ * @name opensocial.Activity
+ */
+
+
+/**
+ * Base interface for all activity objects.
+ *
+ * Private, see opensocial.createActivity() for usage.
+ *
+ * @param {Object.} params Parameters defining the activity.
+ * @private
+ * @constructor
+ */
+opensocial.Activity = function(params) {
+ this.fields_ = params;
+};
+
+
+/**
+ * @static
+ * @class
+ * All of the fields that activities can have.
+ *
+ * It is only required to set one of TITLE_ID or TITLE. In addition, if you
+ * are using any variables in your title or title template,
+ * you must set TEMPLATE_PARAMS.
+ *
+ * Other possible fields to set are: URL, MEDIA_ITEMS, BODY_ID, BODY,
+ * EXTERNAL_ID, PRIORITY, STREAM_TITLE, STREAM_URL, STREAM_SOURCE_URL,
+ * and STREAM_FAVICON_URL.
+ *
+ * Containers are only required to use TITLE_ID or TITLE, they may ignore
+ * additional parameters.
+ *
+ *
+ * See also:
+ * opensocial.Activity.getField()
+ *
+ *
+ * @name opensocial.Activity.Field
+ * @enum {string}
+ */
+opensocial.Activity.Field = {
+ /**
+ * A string specifying the title template message ID in the gadget
+ * spec.
+ *
+ * The title is the primary text of an activity.
+ *
+ * Titles may only have the following HTML tags: <b> <i>,
+ * <a>, <span>.
+ * The container may ignore this formatting when rendering the activity.
+ *
+ * @member opensocial.Activity.Field
+ */
+ TITLE_ID : 'titleId',
+
+ /**
+ * A string specifying the primary text of an activity.
+ *
+ * Titles may only have the following HTML tags: <b> <i>,
+ * <a>, <span>.
+ * The container may ignore this formatting when rendering the activity.
+ *
+ * @member opensocial.Activity.Field
+ */
+ TITLE : 'title',
+
+ /**
+ * A map of custom keys to values associated with this activity.
+ * These will be used for evaluation in templates.
+ *
+ * The data has type Map<String, Object>. The
+ * object may be either a String or an opensocial.Person.
+ *
+ * When passing in a person with key PersonKey, can use the following
+ * replacement variables in the template:
+ *
+ * PersonKey.DisplayName - Display name for the person
+ * PersonKey.ProfileUrl. URL of the person's profile
+ * PersonKey.Id - The ID of the person
+ * PersonKey - Container may replace with DisplayName, but may also
+ * optionally link to the user.
+ *
+ *
+ * @member opensocial.Activity.Field
+ */
+ TEMPLATE_PARAMS : 'templateParams',
+
+ /**
+ * A string specifying the
+ * URL that represents this activity.
+ * @member opensocial.Activity.Field
+ */
+ URL : 'url',
+
+ /**
+ * Any photos, videos, or images that should be associated
+ * with the activity. Higher priority ones are higher in the list.
+ * The data has type Array<
+ * MediaItem >.
+ * @member opensocial.Activity.Field
+ */
+ MEDIA_ITEMS : 'mediaItems',
+
+ /**
+ * A string specifying the body template message ID in the gadget spec.
+ *
+ * The body is an optional expanded version of an activity.
+ *
+ * Bodies may only have the following HTML tags: <b> <i>,
+ * <a>, <span>.
+ * The container may ignore this formatting when rendering the activity.
+ *
+ * @member opensocial.Activity.Field
+ */
+ BODY_ID : 'bodyId',
+
+ /**
+ * A string specifying an optional expanded version of an activity.
+ *
+ * Bodies may only have the following HTML tags: <b> <i>,
+ * <a>, <span>.
+ * The container may ignore this formatting when rendering the activity.
+ *
+ * @member opensocial.Activity.Field
+ */
+ BODY : 'body',
+
+ /**
+ * An optional string ID generated by the posting application.
+ * @member opensocial.Activity.Field
+ */
+ EXTERNAL_ID : 'externalId',
+
+ /**
+ * A string specifing the title of the stream.
+ * @member opensocial.Activity.Field
+ */
+ STREAM_TITLE : 'streamTitle',
+
+ /**
+ * A string specifying the stream's URL.
+ * @member opensocial.Activity.Field
+ */
+ STREAM_URL : 'streamUrl',
+
+ /**
+ * A string specifying the stream's source URL.
+ * @member opensocial.Activity.Field
+ */
+ STREAM_SOURCE_URL : 'streamSourceUrl',
+
+ /**
+ * A string specifying the URL for the stream's favicon.
+ * @member opensocial.Activity.Field
+ */
+ STREAM_FAVICON_URL : 'streamFaviconUrl',
+
+ /**
+ * A number between 0 and 1 representing the relative priority of
+ * this activity in relation to other activities from the same source
+ * @member opensocial.Activity.Field
+ */
+ PRIORITY : 'priority',
+
+ /**
+ * A string ID that is permanently associated with this activity.
+ * This value can not be set.
+ * @member opensocial.Activity.Field
+ */
+ ID : 'id',
+
+ /**
+ * The string ID of the user who this activity is for.
+ * This value can not be set.
+ * @member opensocial.Activity.Field
+ */
+ USER_ID : 'userId',
+
+ /**
+ * A string specifying the application that this activity is associated with.
+ * This value can not be set.
+ * @member opensocial.Activity.Field
+ */
+ APP_ID : 'appId',
+
+ /**
+ * A string specifying the time at which this activity took place
+ * in milliseconds since the epoch.
+ * This value can not be set.
+ * @member opensocial.Activity.Field
+ */
+ POSTED_TIME : 'postedTime'
+};
+
+
+/**
+ * Gets an ID that can be permanently associated with this activity.
+ *
+ * @return {string} The ID
+ * @member opensocial.Activity
+ */
+opensocial.Activity.prototype.getId = function() {
+ return this.getField(opensocial.Activity.Field.ID);
+};
+
+
+/**
+ * Gets the activity data that's associated with the specified key.
+ *
+ * @param {string} key The key to get data for;
+ * see the Field class
+ * for possible values
+ * @param {Object.=}
+ * opt_params Additional
+ * params
+ * to pass to the request.
+ * @return {string} The data
+ * @member opensocial.Activity
+ */
+opensocial.Activity.prototype.getField = function(key, opt_params) {
+ return opensocial.Container.getField(this.fields_, key, opt_params);
+};
+
+
+/**
+ * Sets data for this activity associated with the given key.
+ *
+ * @param {string} key The key to set data for
+ * @param {string} data The data to set
+ */
+opensocial.Activity.prototype.setField = function(key, data) {
+ return (this.fields_[key] = data);
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041736_edit.js b/pool/shard006/JavaScript/0041736_edit.js
new file mode 100644
index 0000000000000000000000000000000000000000..608773619b1566628b7ca6a075e62f9cfdeb59af
--- /dev/null
+++ b/pool/shard006/JavaScript/0041736_edit.js
@@ -0,0 +1,36 @@
+'use strict';
+
+app.controller('AdminEditCtrl', ['$scope', 'business', '$location', function ($scope, Business, $location) {
+ if (!Business.user.getIsAdmin()) {
+ $location.path('/');
+ }
+ $scope.$on('$LOGOUT', function() {
+ $location.path('/');
+ })
+
+ $scope.goTo = function(path) {
+ $location.search({});
+ $location.path(path);
+ }
+
+ $scope.searchTypes = [
+ {name:'Title and Comments', value:'default'},
+ {name:'Person Tag', value:'person'},
+ {name:'Place Tag', value:'place'},
+ {name:'Collection Tag', value:'collection'},
+ ];
+ $scope.fileSearchType = $scope.searchTypes[0];
+
+ $scope.individual;
+ $scope.file;
+
+ $scope.deleteInd = function(ind){
+ var cont = confirm("Delete this individual?\n"+ind.typeahead+"\nIndividual ID: "+ind.id);
+ if (cont) {
+ Business.individual.deleteInd(ind.id).then(function(result){
+ console.log('result', result);
+ });
+ }
+ }
+
+}]);
diff --git a/pool/shard006/JavaScript/0041738_IDE.js b/pool/shard006/JavaScript/0041738_IDE.js
new file mode 100644
index 0000000000000000000000000000000000000000..21453837414a65f6a2894ace8025b18c4fd8f7b4
--- /dev/null
+++ b/pool/shard006/JavaScript/0041738_IDE.js
@@ -0,0 +1,29 @@
+import { connect } from 'react-redux'
+import IDE from '../components/IDE'
+import { writeCode, editMode, editTheme } from '../actions/editor'
+import { submit } from '../actions/submit'
+import { logout } from '../actions/user'
+
+const mapStateToProps = state => ({
+ code: state.editor.code,
+ alreadyEdit: state.editor.alreadyEdit,
+ mode: state.editor.mode,
+ theme: state.editor.theme,
+ user: state.user,
+ output: state.game.output,
+ challenges: state.game.challenges || [],
+ challenge: state.game.challenge,
+ pending: state.game.pending,
+ results: state.game.results,
+ score: state.game.score
+})
+
+const mapDispatchToProps = (dispatch) => ({
+ writeCode: code => dispatch(writeCode(code)),
+ editMode: mode => dispatch(editMode(mode)),
+ editTheme: theme => dispatch(editTheme(theme)),
+ logout: () => dispatch(logout()),
+ submit: (challengeId, code, lang, userId, simulation) => dispatch(submit(challengeId, code, lang, userId, simulation))
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(IDE)
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041742_language-name.js b/pool/shard006/JavaScript/0041742_language-name.js
new file mode 100644
index 0000000000000000000000000000000000000000..b754328bacb91e5748c710a6275c1d328382f20b
--- /dev/null
+++ b/pool/shard006/JavaScript/0041742_language-name.js
@@ -0,0 +1,26 @@
+/**
+ * Copyright (c) 2017-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// Turn off ESLint for this file because it's sent down to users as-is.
+/* eslint-disable */
+window.addEventListener('load', function() {
+ function language(label) {
+ const div = document.createElement('div');
+ div.classList.add('languageBadge');
+ div.innerHTML = label;
+ return div;
+ }
+
+ function addLanguage(codeBlockSelector, language) {
+ document.querySelectorAll(codeBlockSelector).forEach(function(code) {
+ code.parentNode.appendChild(language.cloneNode(true));
+ });
+ }
+
+ addLanguage('.hljs.language-coq', language('Coq'));
+ addLanguage('.hljs.language-ocaml', language('OCaml'));
+});
diff --git a/pool/shard006/JavaScript/0041743_routes.js b/pool/shard006/JavaScript/0041743_routes.js
new file mode 100644
index 0000000000000000000000000000000000000000..aebf0dbe1b9167d5c05bc21b7063cd9a8b0ee9f9
--- /dev/null
+++ b/pool/shard006/JavaScript/0041743_routes.js
@@ -0,0 +1,13 @@
+module.exports = (function(App,Express,Package){
+
+ var Route = App.Route;
+ var names = {
+ SiteHome : '/'
+ };
+
+ Route.set(names);
+ Express.use(Route.use);
+ //Express.use(Cart);
+ Express.use('/',App.Auth.middleware.applyCSRF,require('./routes/index')(App,Route,Package));
+
+});
diff --git a/pool/shard006/JavaScript/0041744_selector.js b/pool/shard006/JavaScript/0041744_selector.js
new file mode 100644
index 0000000000000000000000000000000000000000..c9cfa704f0ab6e51a8d01e7050af20f30eccb11b
--- /dev/null
+++ b/pool/shard006/JavaScript/0041744_selector.js
@@ -0,0 +1,63 @@
+var $ = function(expr, context) {
+ return new $.init(expr, context);
+};
+$.init = function(expr,context) {
+ if(expr.nodeName && !context) this[0] = expr;
+ else {
+ try { var el = (context||document)['querySelectorAll'](expr); }
+ catch(err){ var el = expr; }
+ [].push.apply(this,[].slice.call(el));
+ }
+};
+$.init.prototype = {
+ each: function(el) {
+ for (var l=0;l1) return 1 < this.length ? this.each(function(o){o.style[prop] = val;}) : el.style[prop] = val,"";
+ else return el.style[prop]==''?(
+ el.currentStyle && !lt?
+ el.currentStyle[prop]:(lt?
+ Math.round(el.getBoundingClientRect()[prop]):
+ document.defaultView.getComputedStyle(el, null).getPropertyValue(prop)
+ )
+ ):el.style[prop];
+ }
+ },
+ on: function(evt, fn) {
+ for (var l = this.length; l--;) {
+ var el = this[l];
+ el.addEventListener ? el.addEventListener(evt, fn, !1) : el.attachEvent("on" + evt, function() {
+ return fn.call(el, window.event);
+ });
+ }
+ },
+ append: function(param) {
+ var el = document.createElement(param.element||'div');
+ param.hasOwnProperty('element') && delete param.element;
+ el.innerHTML = param.hasOwnProperty('text')?param.text:null;
+ this[0].appendChild(el);
+ for(var i in param) el.setAttribute(i,param[i]);
+ },
+ remove: function() {
+ this[0].parentNode.removeChild(this[0]);
+ },
+ attr: function(key,val) {
+ var el = this[0];
+ return val ? (el.setAttribute(key, val), '') : el.getAttribute(key);
+ },
+ val: function(dat){
+ var el = this[0];
+ return arguments.length ? (el.value = dat, '') : el.value;
+ },
+ text: function(dat){
+ var el = this[0];
+ return arguments.length ? (el.innerHTML = dat, '') : el.innerHTML;
+ }
+};
diff --git a/pool/shard006/JavaScript/0041746_gulpfile.js b/pool/shard006/JavaScript/0041746_gulpfile.js
new file mode 100644
index 0000000000000000000000000000000000000000..4303882adb14e57f0db980f5888387e68cf057a8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041746_gulpfile.js
@@ -0,0 +1,12 @@
+var gulp = require('gulp');
+var uglify = require('gulp-uglify');
+var concat = require('gulp-concat');
+
+gulp.task('uglify', function() {
+ gulp.src('lib/scramble.js')
+ .pipe(uglify())
+ .pipe(concat('scramble.min.js'))
+ .pipe(gulp.dest('.'));
+});
+
+gulp.task('default', ['uglify']);
diff --git a/pool/shard006/JavaScript/0041751_AffinityPlayersOptions.js b/pool/shard006/JavaScript/0041751_AffinityPlayersOptions.js
new file mode 100644
index 0000000000000000000000000000000000000000..222c323878f5df1f80f62a4c469b5b738653930f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041751_AffinityPlayersOptions.js
@@ -0,0 +1,48 @@
+import React from 'react';
+
+import PropTypes from 'prop-types';
+
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+
+import AutosizedRatedPlayersDataList from 'builder/players/containers/AutosizedRatedPlayersDataList';
+
+import { selectRatedPlayers as selectPlayers } from 'players/selectors';
+import { selectCanLoadRatedPlayer as selectCanLoad } from 'players/selectors/request';
+import { selectSmallScreen } from 'views/selectors';
+
+import AddIcon from 'grommet/components/icons/base/AddCircle';
+
+import { moveNextPage } from 'players/actions/ratedPlayers';
+import { addTeamPlayer } from 'builder/players/actions';
+
+const AffinityPlayersOptions = (props) =>
+ props.nextPage() : null} buttonAction={props.buttonAction} buttonIcon={ } />;
+
+AffinityPlayersOptions.propTypes = {
+ canLoad: PropTypes.bool.isRequired,
+ nextPage: PropTypes.func.isRequired,
+ smallView: PropTypes.bool.isRequired,
+ buttonAction: PropTypes.func.isRequired,
+ source: PropTypes.array.isRequired
+};
+
+const mapStateToProps = (state) => {
+ return {
+ source: selectPlayers(state),
+ canLoad: selectCanLoad(state),
+ smallView: selectSmallScreen(state)
+ };
+};
+
+const mapDispatchToProps = (dispatch) => {
+ return {
+ nextPage: bindActionCreators(moveNextPage, dispatch),
+ buttonAction: bindActionCreators(addTeamPlayer, dispatch)
+ };
+};
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(AffinityPlayersOptions);
diff --git a/pool/shard006/JavaScript/0041754_angular-translate-interpolation-messageformat.js b/pool/shard006/JavaScript/0041754_angular-translate-interpolation-messageformat.js
new file mode 100644
index 0000000000000000000000000000000000000000..0ae61cd3762c6c18ddf874c2438c3180417fffcf
--- /dev/null
+++ b/pool/shard006/JavaScript/0041754_angular-translate-interpolation-messageformat.js
@@ -0,0 +1,157 @@
+/*!
+ * angular-translate - v2.9.2 - 2016-02-21
+ *
+ * Copyright (c) 2016 The angular-translate team, Pascal Precht; Licensed MIT
+ */
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module unless amdModuleId is set
+ define(["messageformat"], function (a0) {
+ return (factory(a0));
+ });
+ } else if (typeof exports === 'object') {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like environments that support module.exports,
+ // like Node.
+ module.exports = factory(require("messageformat"));
+ } else {
+ factory(MessageFormat);
+ }
+}(this, function (MessageFormat) {
+
+angular.module('pascalprecht.translate')
+
+/**
+ * @ngdoc property
+ * @name pascalprecht.translate.TRANSLATE_MF_INTERPOLATION_CACHE
+ * @requires TRANSLATE_MF_INTERPOLATION_CACHE
+ *
+ * @description
+ * Uses MessageFormat.js to interpolate strings against some values.
+ */
+.constant('TRANSLATE_MF_INTERPOLATION_CACHE', '$translateMessageFormatInterpolation')
+
+/**
+ * @ngdoc object
+ * @name pascalprecht.translate.$translateMessageFormatInterpolation
+ * @requires pascalprecht.translate.TRANSLATE_MF_INTERPOLATION_CACHE
+ *
+ * @description
+ * Uses MessageFormat.js to interpolate strings against some values.
+ *
+ * Be aware to configure a proper sanitization strategy.
+ *
+ * See also:
+ * * {@link pascalprecht.translate.$translateSanitization}
+ * * {@link https://github.com/SlexAxton/messageformat.js}
+ *
+ * @return {object} $translateMessageFormatInterpolation Interpolator service
+ */
+.factory('$translateMessageFormatInterpolation', $translateMessageFormatInterpolation);
+
+function $translateMessageFormatInterpolation($translateSanitization, $cacheFactory, TRANSLATE_MF_INTERPOLATION_CACHE) {
+
+ 'use strict';
+
+ var $translateInterpolator = {},
+ $cache = $cacheFactory.get(TRANSLATE_MF_INTERPOLATION_CACHE),
+ // instantiate with default locale (which is 'en')
+ $mf = new MessageFormat('en'),
+ $identifier = 'messageformat';
+
+ if (!$cache) {
+ // create cache if it doesn't exist already
+ $cache = $cacheFactory(TRANSLATE_MF_INTERPOLATION_CACHE);
+ }
+
+ $cache.put('en', $mf);
+
+ /**
+ * @ngdoc function
+ * @name pascalprecht.translate.$translateMessageFormatInterpolation#setLocale
+ * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation
+ *
+ * @description
+ * Sets current locale (this is currently not use in this interpolation).
+ *
+ * @param {string} locale Language key or locale.
+ */
+ $translateInterpolator.setLocale = function (locale) {
+ $mf = $cache.get(locale);
+ if (!$mf) {
+ $mf = new MessageFormat(locale);
+ $cache.put(locale, $mf);
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name pascalprecht.translate.$translateMessageFormatInterpolation#getInterpolationIdentifier
+ * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation
+ *
+ * @description
+ * Returns an identifier for this interpolation service.
+ *
+ * @returns {string} $identifier
+ */
+ $translateInterpolator.getInterpolationIdentifier = function () {
+ return $identifier;
+ };
+
+ /**
+ * @deprecated will be removed in 3.0
+ * @see {@link pascalprecht.translate.$translateSanitization}
+ */
+ $translateInterpolator.useSanitizeValueStrategy = function (value) {
+ $translateSanitization.useStrategy(value);
+ return this;
+ };
+
+ /**
+ * @ngdoc function
+ * @name pascalprecht.translate.$translateMessageFormatInterpolation#interpolate
+ * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation
+ *
+ * @description
+ * Interpolates given string against given interpolate params using MessageFormat.js.
+ *
+ * @returns {string} interpolated string.
+ */
+ $translateInterpolator.interpolate = function (string, interpolationParams) {
+ interpolationParams = interpolationParams || {};
+ interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params');
+
+ var interpolatedText = $cache.get(string + angular.toJson(interpolationParams));
+
+ // if given string wasn't interpolated yet, we do so now and never have to do it again
+ if (!interpolatedText) {
+
+ // Ensure explicit type if possible
+ // MessageFormat checks the actual type (i.e. for amount based conditions)
+ for (var key in interpolationParams) {
+ if (interpolationParams.hasOwnProperty(key)) {
+ // ensure number
+ var number = parseInt(interpolationParams[key], 10);
+ if (angular.isNumber(number) && ('' + number) === interpolationParams[key]) {
+ interpolationParams[key] = number;
+ }
+ }
+ }
+
+ interpolatedText = $mf.compile(string)(interpolationParams);
+ interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text');
+
+ $cache.put(string + angular.toJson(interpolationParams), interpolatedText);
+ }
+
+ return interpolatedText;
+ };
+
+ return $translateInterpolator;
+}
+$translateMessageFormatInterpolation.$inject = ['$translateSanitization', '$cacheFactory', 'TRANSLATE_MF_INTERPOLATION_CACHE'];
+
+$translateMessageFormatInterpolation.displayName = '$translateMessageFormatInterpolation';
+return 'pascalprecht.translate';
+
+}));
diff --git a/pool/shard006/JavaScript/0041755_sass.js b/pool/shard006/JavaScript/0041755_sass.js
new file mode 100644
index 0000000000000000000000000000000000000000..968a73eff84f073739280fd7c8d90002d5711997
--- /dev/null
+++ b/pool/shard006/JavaScript/0041755_sass.js
@@ -0,0 +1,203 @@
+/*! sass.js - v0.10.12 (e6281ce) - built 2018-11-14
+ providing libsass 3.5.5 (39e30874)
+ via emscripten 1.38.18 (7a0e274)
+ */
+
+(function (root, factory) {
+ 'use strict';
+ if (typeof define === 'function' && define.amd) {
+ define([], factory);
+ } else if (typeof exports === 'object') {
+ module.exports = factory();
+ } else {
+ root.Sass = factory();
+ }
+}(this, function () {/*global document*/
+// identify the path sass.js is located at in case we're loaded by a simple
+//
+// this path can be used to identify the location of
+// * sass.worker.js from sass.js
+// * libsass.js.mem from sass.sync.js
+// see https://github.com/medialize/sass.js/pull/32#issuecomment-103142214
+// see https://github.com/medialize/sass.js/issues/33
+var SASSJS_RELATIVE_PATH = (function() {
+ 'use strict';
+
+ // in Node things are rather simple
+ const hasDir = typeof __dirname !== 'undefined';
+ if (hasDir) {
+ return __dirname;
+ }
+
+ // we can only run this test in the browser,
+ // so make sure we actually have a DOM to work with.
+ if (typeof document === 'undefined' || !document.getElementsByTagName) {
+ return null;
+ }
+
+ // http://www.2ality.com/2014/05/current-script.html
+ var currentScript = document.currentScript || (function() {
+ var scripts = document.getElementsByTagName('script');
+ return scripts[scripts.length - 1];
+ })();
+
+ var path = currentScript && currentScript.src;
+ if (!path) {
+ return null;
+ }
+
+ // [worker] make sure we're not running in some concatenated thing
+ if (path.slice(-8) === '/sass.js') {
+ return path.slice(0, -8);
+ }
+
+ // [sync] make sure we're not running in some concatenated thing
+ if (path.slice(-13) === '/sass.sync.js') {
+ return path.slice(0, -13);
+ }
+
+ return null;
+})() || '.';
+
+/*global Worker, SASSJS_RELATIVE_PATH*/
+'use strict';
+
+var noop = function(){};
+var slice = [].slice;
+// defined upon first Sass.initialize() call
+var globalWorkerUrl;
+
+function Sass(workerUrl) {
+ if (!workerUrl && !globalWorkerUrl) {
+ /*jshint laxbreak:true */
+ throw new Error(
+ 'Sass needs to be initialized with the URL of sass.worker.js - '
+ + 'either via Sass.setWorkerUrl(url) or by new Sass(url)'
+ );
+ /*jshint laxbreak:false */
+ }
+
+ if (!globalWorkerUrl) {
+ globalWorkerUrl = workerUrl;
+ }
+
+ // bind all functions
+ // we're doing this because we used to have a single hard-wired instance that allowed
+ // [].map(Sass.removeFile) and we need to maintain that for now (at least until 1.0.0)
+ for (var key in this) {
+ if (typeof this[key] === 'function') {
+ this[key] = this[key].bind(this);
+ }
+ }
+
+ this._callbacks = {};
+ this._worker = new Worker(workerUrl || globalWorkerUrl);
+ this._worker.addEventListener('message', this._handleWorkerMessage, false);
+}
+
+// allow setting the workerUrl before the first Sass instance is initialized,
+// where registering the global workerUrl would've happened automatically
+Sass.setWorkerUrl = function(workerUrl) {
+ globalWorkerUrl = workerUrl;
+};
+
+Sass.style = {
+ nested: 0,
+ expanded: 1,
+ compact: 2,
+ compressed: 3
+};
+
+Sass.comments = {
+ 'none': 0,
+ 'default': 1
+};
+
+Sass.prototype = {
+ style: Sass.style,
+ comments: Sass.comments,
+
+ destroy: function() {
+ this._worker && this._worker.terminate();
+ this._worker = null;
+ this._callbacks = {};
+ this._importer = null;
+ },
+
+ _handleWorkerMessage: function(event) {
+ if (event.data.command) {
+ this[event.data.command](event.data.args);
+ }
+
+ this._callbacks[event.data.id] && this._callbacks[event.data.id](event.data.result);
+ delete this._callbacks[event.data.id];
+ },
+
+ _dispatch: function(options, callback) {
+ if (!this._worker) {
+ throw new Error('Sass worker has been terminated');
+ }
+
+ options.id = 'cb' + Date.now() + Math.random();
+ this._callbacks[options.id] = callback;
+ this._worker.postMessage(options);
+ },
+
+ _importerInit: function(args) {
+ // importer API done callback pushing results
+ // back to the worker
+ var done = function done(result) {
+ this._worker.postMessage({
+ command: '_importerFinish',
+ args: [result]
+ });
+ }.bind(this);
+
+ try {
+ this._importer(args[0], done);
+ } catch(e) {
+ done({ error: e.message });
+ throw e;
+ }
+ },
+
+ importer: function(importerCallback, callback) {
+ if (typeof importerCallback !== 'function' && importerCallback !== null) {
+ throw new Error('importer callback must either be a function or null');
+ }
+
+ // callback is executed in the main EventLoop
+ this._importer = importerCallback;
+ // tell worker to activate importer callback
+ this._worker.postMessage({
+ command: 'importer',
+ args: [Boolean(importerCallback)]
+ });
+
+ callback && callback();
+ },
+};
+
+var commands = 'writeFile readFile listFiles removeFile clearFiles lazyFiles preloadFiles options compile compileFile';
+commands.split(' ').forEach(function(command) {
+ Sass.prototype[command] = function() {
+ var callback = slice.call(arguments, -1)[0];
+ var args = slice.call(arguments, 0, -1);
+ if (typeof callback !== 'function') {
+ args.push(callback);
+ callback = noop;
+ }
+
+ this._dispatch({
+ command: command,
+ args: args
+ }, callback);
+ };
+});
+
+// automatically set the workerUrl in case we're loaded by a simple
+//
+// see https://github.com/medialize/sass.js/pull/32#issuecomment-103142214
+Sass.setWorkerUrl(SASSJS_RELATIVE_PATH + '/sass.worker.js');
+return Sass;
+}));
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041764_bool.js b/pool/shard006/JavaScript/0041764_bool.js
new file mode 100644
index 0000000000000000000000000000000000000000..6bb1aa4da0890c8f53caa38b996ca0c0994f087e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041764_bool.js
@@ -0,0 +1,32 @@
+Fox.define('Views.Fields.Bool', 'Views.Fields.Base', function (Dep) {
+
+ return Dep.extend({
+
+ type: 'bool',
+
+ listTemplate: 'fields.bool.detail',
+
+ detailTemplate: 'fields.bool.detail',
+
+ editTemplate: 'fields.bool.edit',
+
+ searchTemplate: 'fields.bool.search',
+
+ validations: [],
+
+ fetch: function () {
+ var value = this.$element.get(0).checked;
+ var data = {};
+ data[this.name] = value;
+ return data;
+ },
+
+ fetchSearch: function () {
+ var data = {
+ type: this.$element.get(0).checked ? 'isTrue' : 'isFalse',
+ };
+ return data;
+ },
+ });
+});
+
diff --git a/pool/shard006/JavaScript/0041766_validate.js b/pool/shard006/JavaScript/0041766_validate.js
new file mode 100644
index 0000000000000000000000000000000000000000..70661d38de79edc05eb724fb3d9f77ba2cfa05d6
--- /dev/null
+++ b/pool/shard006/JavaScript/0041766_validate.js
@@ -0,0 +1,160 @@
+var should = require('should')
+ , tsa = require('../');
+
+describe('Custom Validations', function(){
+ var mustBeUpper = function(value, cb){
+ if(value === value.toUpperCase()){
+ cb();
+ }else{
+ cb('not uppercase');
+ }
+ };
+ var guard = tsa({
+ foo: tsa.property({ validate: mustBeUpper })
+ });
+
+ it('succeeds properly', function(done){
+ //arrange
+ var input = {
+ foo: 'BAR'
+ };
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.not.exist(err);
+ should.exist(result);
+ result.foo.should.equal('BAR');
+
+ done();
+ });
+ });
+
+ it('fails properly', function(done){
+ //arrange
+ var input = {
+ foo: 'bar'
+ };
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.exist(err);
+ err[0].error.should.equal('not uppercase');
+ should.not.exist(result);
+
+ done();
+ });
+ });
+
+ it('works with nested guards - negative', function(done){
+ //arrange
+ var v = function(json, cb){
+ if(json.bar === 'blah')
+ cb('can\'t equal blah');
+ else
+ cb();
+ };
+ var innerGuard = tsa({
+ bar: tsa.required()
+ });
+ var guard = tsa({
+ foo: innerGuard({ validate: v })
+ });
+ var input = {foo: {bar: 'blah'}};
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.exist(err);
+ err.length.should.equal(1);
+ should.not.exist(result);
+
+ done();
+ });
+ });
+
+ it('works with nested guards - positive', function(done){
+ //arrange
+ var v = function(json, cb){
+ if(json.bar === 'blah')
+ cb('can\'t equal blah');
+ else
+ cb();
+ };
+ var innerGuard = tsa({
+ bar: tsa.required()
+ });
+ var guard = tsa({
+ foo: innerGuard({ validate: v })
+ });
+ var input = {foo: {bar: 'blah2'}};
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.not.exist(err);
+ should.exist(result);
+
+ done();
+ });
+ });
+
+ it('can supply key name for error', function(done){
+ //arrange
+ var passwordsMustMatch = function(json, cb){
+ if(json.password1 === json.password2)
+ cb();
+ else
+ cb({ key: 'password2', error: 'Passwords must match.' });
+ };
+ var guard = tsa({
+ password1: tsa.required()
+ , password2: tsa.required()
+ }, { validate: passwordsMustMatch });
+ var input = {
+ password1: 'foo'
+ , password2: 'bar'
+ };
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.exist(err);
+ err.should.be.an.instanceof(Array);
+ err.length.should.equal(1);
+ err[0].key.should.equal('password2');
+ err[0].error.should.equal('Passwords must match.');
+ should.not.exist(result);
+
+ done();
+ });
+ });
+
+ it('can return multiple errors', function(done){
+ //arrange
+ var v = function(json, cb){
+ cb(['error1', 'error2']);
+ };
+ var guard = tsa({
+ foo: tsa.validate(v)
+ });
+ var input = {foo: 'blah'};
+
+ //act
+ guard().frisk(input, function(err, result){
+ //assert
+ should.exist(err);
+ err.should.be.an.instanceof(Array);
+ err.length.should.equal(1);
+ err[0].key.should.equal('foo');
+ err[0].error.should.be.an.instanceof(Array);
+ err[0].error.length.should.equal(2);
+ err[0].error[0].should.equal('error1');
+ err[0].error[1].should.equal('error2');
+ should.not.exist(result);
+
+ done();
+ });
+ });
+});
diff --git a/pool/shard006/JavaScript/0041767_displayDocumentsAndUpload.js b/pool/shard006/JavaScript/0041767_displayDocumentsAndUpload.js
new file mode 100644
index 0000000000000000000000000000000000000000..97c0f2ef256a2c9afe214f5ef2d67742f5a6258a
--- /dev/null
+++ b/pool/shard006/JavaScript/0041767_displayDocumentsAndUpload.js
@@ -0,0 +1,228 @@
+import React, {Component} from 'react';
+import {Field, reduxForm} from 'redux-form';
+import { getLinkDocsWithLinkIdAction, getLinkDocsWithRFPAndIOIAction, uploadDocumentRequest, getLinksWithCompanyIdAction, deleteLinkDocumentAction, downloadLinkDocumentAction } from '../actions/index';
+import { Link } from "react-router-dom";
+import validator from 'validator';
+import lsUtils from '../utils/ls_utils';
+import cUtils from '../utils/common_utils';
+import constants from '../utils/constants';
+import Header from './header';
+import { connect } from "react-redux";
+import { bindActionCreators } from 'redux';
+import FileReaderInput from 'react-file-reader-input';
+import * as actionCreators from '../actions/index';
+import formatCurrency from 'format-currency';
+import dateFormat from 'dateformat';
+import moment from 'moment';
+import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
+
+
+class DisplayDocumentsAndUpload extends Component{
+ constructor(props){
+ super(props);
+ this.state = {
+ user : null,
+ company : null,
+ displayLinkId : null
+ };
+ }
+
+ componentWillMount() {
+ let that = this;
+ let user = lsUtils.getValue(constants.KEY_USER_OBJECT);
+ let company = lsUtils.getValue(constants.KEY_COMPANY_OBJECT);
+ this.setState({
+ user : user,
+ company : company
+ });
+ }
+
+ handleFileUpload(type, inputFiles) {
+ inputFiles.persist();
+ var files = inputFiles.currentTarget.files;
+ if(files && files.length > 0){
+ let that = this;
+ let file = files[0];
+ this.props.uploadDocumentRequest({
+ file,
+ type : type,
+ ioiId : this.props.link.ioiId,
+ rfpId : this.props.link.rfpId,
+ linkId : this.props.link.linkId,
+ uploadedCompanyId : this.state.user.companyId
+ }).then((data)=>{
+ that.props.getLinkDocsWithLinkIdAction(that.props.link.linkId);
+ that.myFileInput=null;
+ });
+ }
+ }
+
+ downloadDocument(fileName){
+ this.props.downloadLinkDocumentAction(fileName)
+ .then((data) => {
+ window.open(data.payload.data.data);
+ });
+ }
+
+ deleteDocument(linkDocId, fileName){
+ let that = this;
+ this.props.deleteLinkDocumentAction(linkDocId, fileName)
+ .then((data) => {
+ for(let i=0;i
+
+
+
+
+
+ );
+ }
+ }
+
+ renderDocumentItem(type){
+ var that = this;
+ if(this.props.linkDocList && this.props.linkDocList.length > 0){
+ let list = this.props.linkDocList.filter(linkDoc => linkDoc.type === type);
+ if(list && list.length > 0){
+ return list.map(function(item){
+ return(
+ {item.originalFileName}
+ {item.companyName}
+ {dateFormat(moment(item.timestamp), 'longDate')}
+
+
+
+
+ {that.addDeleteIcon(item)}
+
+ );
+ });
+ } else {
+ return(
+ No document uploaded
+ );
+ }
+ }
+ }
+
+ renderRFPAndDocuments(type){
+ let that=this;
+ let inputTagStyle= {
+ 'display':'inline'
+ };
+
+ return();
+ }
+
+ renderTabs(){
+ return(
+
+
+
+ Non-Disclosure Agreement(NDA)
+
+
+ Transaction Overview
+
+
+ Company
+
+
+ Financial
+
+
+ Legal
+
+
+ Operations
+
+
+
+ {this.renderRFPAndDocuments('TXN_NDA')}
+
+
+ {this.renderRFPAndDocuments('TXN_OVERVIEW')}
+
+
+ {this.renderRFPAndDocuments('COMPANY')}
+
+
+ {this.renderRFPAndDocuments('FINANCIAL')}
+
+
+ {this.renderRFPAndDocuments('LEGAL')}
+
+
+ {this.renderRFPAndDocuments('OPERATIONS')}
+
+
+ );
+ }
+
+ render(){
+ return(
+ {this.renderTabs()}
+
);
+ }
+
+}
+
+function mapStateToProps(state) {
+ let rObject={};
+
+ if(state.link.linkDocList){
+ rObject.linkDocList = state.link.linkDocList;
+ }
+
+ return rObject;
+}
+
+function mapDispatchToProps(dispatch) {
+ return bindActionCreators({
+ uploadDocumentRequest : uploadDocumentRequest,
+ getLinksWithCompanyIdAction : getLinksWithCompanyIdAction,
+ deleteLinkDocumentAction : deleteLinkDocumentAction,
+ downloadLinkDocumentAction : downloadLinkDocumentAction,
+ getLinkDocsWithRFPAndIOIAction : getLinkDocsWithRFPAndIOIAction,
+ getLinkDocsWithLinkIdAction : getLinkDocsWithLinkIdAction
+ }, dispatch);
+}
+
+
+export default connect(mapStateToProps, mapDispatchToProps)(DisplayDocumentsAndUpload);
diff --git a/pool/shard006/JavaScript/0041773_file_upload.js b/pool/shard006/JavaScript/0041773_file_upload.js
new file mode 100644
index 0000000000000000000000000000000000000000..01bfae26ef80a1d28d2840eff080317d782b964a
--- /dev/null
+++ b/pool/shard006/JavaScript/0041773_file_upload.js
@@ -0,0 +1,52 @@
+$(function() {
+ $('.directUpload').find("input:file").each(function(i, elem) {
+ var fileInput = $(elem);
+ var form = $(fileInput.parents('form:first'));
+ var submitButton = form.find('input[type="submit"]');
+ var progressBar = $("
");
+ var barContainer = $("
").append(progressBar);
+ fileInput.after(barContainer);
+ fileInput.fileupload({
+ fileInput: fileInput,
+ url: form.data('url'),
+ type: 'POST',
+ autoUpload: true,
+ formData: form.data('form-data'),
+ paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
+ dataType: 'XML', // S3 returns XML if success_action_status is set to 201
+ replaceFileInput: false,
+ progressall: function (e, data) {
+ var progress = parseInt(data.loaded / data.total * 100, 10);
+ progressBar.css('width', progress + '%');
+ },
+ start: function (e) {
+ submitButton.prop('disabled', true);
+
+ progressBar.
+ css('background', 'green').
+ css('display', 'block').
+ css('width', '0%').
+ text("Loading...");
+ },
+ done: function(e, data) {
+ submitButton.prop('disabled', false);
+ progressBar.text("Uploading done");
+
+ // extract key and generate URL from response
+ var key = $(data.jqXHR.responseXML).find("Key").text();
+ var url = 'https://' + form.data('host') + '/' + key;
+
+ // create hidden field
+ var input = $(" ", { type:'hidden', name: fileInput.attr('name'), value: url });
+ form.append(input);
+ },
+ fail: function(e, data) {
+ submitButton.prop('disabled', false);
+
+ progressBar.
+ css("background", "red").
+ text("Failed");
+ }
+ });
+ });
+});
diff --git a/pool/shard006/JavaScript/0041775_progress_bar.js b/pool/shard006/JavaScript/0041775_progress_bar.js
new file mode 100644
index 0000000000000000000000000000000000000000..951eb47899c1954815e6e3ba67070cb336d64e0e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041775_progress_bar.js
@@ -0,0 +1,16 @@
+var get = Ember.get, fmt = Ember.String.fmt;
+
+Bootstrap.ProgressBar = Ember.View.extend({
+ classNames: ['progress'],
+ classNameBindings: ['isStriped:progress-striped', 'isAnimated:active'],
+ template: Ember.Handlebars.compile('
'),
+ isAnimated: false,
+ isStriped: false,
+ progress: 0,
+
+ style: Ember.computed(function() {
+ var progress = get(this, 'progress');
+
+ return fmt('width:%@%;', [progress]);
+ }).property('progress').cacheable()
+});
diff --git a/pool/shard006/JavaScript/0041776_common.js b/pool/shard006/JavaScript/0041776_common.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf65cf617f56572ae66e93a141989728e0031a14
--- /dev/null
+++ b/pool/shard006/JavaScript/0041776_common.js
@@ -0,0 +1,77 @@
+/**
+ *
+ * build by rwson @ 2015-01-10
+ *
+ * 完成微信端的一些自适应屏幕功能(css3中的缩放特性)
+ *
+ */
+
+$(function () {
+
+ var phoneWidth = parseInt(window.screen.width),
+ phoneScale = phoneWidth / 640,
+ ua = navigator.userAgent;
+ if (/Android/.test(ua)) {
+ if (/Android (\d+\.\d+)/.test(ua)) {
+ var version = parseFloat(RegExp.$1);
+ $("head").append(' ');
+ } else {
+ $("head").append(' ');
+ }
+ } else {
+ $("head").append(' ');
+ }
+
+ var w = $(window).width();
+ var h = $(window).height();
+
+ var scale = w / 640;
+
+ var tw = Math.ceil(w / scale);
+ var th = Math.ceil(h / scale);
+
+ $(".zoomer").css({
+ "-webkit-transform-origin": "0 0",
+ "-moz-transform-origin": "0 0",
+ "-ms-transform-origin": "0 0",
+ "-o-transform-origin": "0 0",
+ "transform-origin": "0 0"
+ });
+ $(".zoomer").css({
+ "-webkit-transform": "scale(" + scale + "," + scale + ")",
+ "-moz-transform": "scale(" + scale + "," + scale + ")",
+ "-ms-transform": "scale(" + scale + "," + scale + ")",
+ "-o-transform": "scale(" + scale + "," + scale + ")",
+ "transform": "scale(" + scale + "," + scale + ")"
+ });
+
+ $("html").css({"width": w});
+ $("body").css({"width": w});
+ $(".zoomer").css({"width": tw});
+
+ if($("div.full-screen").length > 0){
+ $("html").css({"height": h});
+ $("body").css({"height": h});
+ $(".zoomer").css({"height": th});
+ $(".wrap").css({"height": th});
+ }
+ /*
+ * 在页面上制定了全屏时,再应用高度值
+ * */
+
+ var imgs = [
+ "img/common/loading.gif",
+ "img/common/pop_close.png",
+ "http://c.hiphotos.baidu.com/image/pic/item/a71ea8d3fd1f4134c5f15073271f95cad0c85efc.jpg",
+ "http://f.hiphotos.baidu.com/image/pic/item/aab219ebc4b74543a95f4ed0c41c178a82b9011464.jpg",
+ "http://c.hiphotos.baidu.com/image/pic/item/730e0cf3d7ca7bcbc0ac8422bc096b63f724a8ec.jpg",
+ "http://g.hiphotos.baidu.com/image/pic/item/9a504fc2d562853553a9290e93ef76c6a7ef6350.jpg"
+ ];
+
+ preloadImage(imgs, function () {
+ });
+
+ $("body").tap(function(){
+ alert("fuck");
+ });
+});
diff --git a/pool/shard006/JavaScript/0041780_weather-process.js b/pool/shard006/JavaScript/0041780_weather-process.js
new file mode 100644
index 0000000000000000000000000000000000000000..5f9fc2db1497fd1c6d158208b98188735816cba7
--- /dev/null
+++ b/pool/shard006/JavaScript/0041780_weather-process.js
@@ -0,0 +1,69 @@
+// # A Simple Process for Checking the Weather
+//
+var requirejs = require('requirejs')
+define(['restify', 'restify-q', 'pvm-q', 'q'], function(restify, rq, pvm, Q) {
+
+ // Definition of a process starts by creating an empty ProcessDefinition.
+ var weather = new pvm.ProcessDefinition()
+
+ // The initial task uses the [OpenWeatherMap API](http://openweathermap.org/API)
+ // to get the temperature at a specified location on Earth. The query runs
+ // asynchronously with the help of [Restify](https://github.com/mcavage/node-restify)
+ // and [Q](https://github.com/kriskowal/q).
+ weather.task('start', function() {
+ console.log(
+ '[' + this.city + '] Fetching weather info from openweathermap.org...')
+
+ // We start of by setting up a client for querying the OpenWeatherMap API.
+ var client = restify.createJsonClient({
+ url: 'http://api.openweathermap.org/'
+ })
+
+ // We then make the request for the weather data at the specified city. We
+ // expect that the user defines this city when starting the process.
+ //
+ // Note that we return the promise of this 'calculation' as a return value
+ // for this task. We must do this for the PVM to be able to capture this
+ // promise and react to its completion as needed. If we don't do this then
+ // the PVM will immediately move on to the transition phase, even if the
+ // task itself was not yet completed.
+ return rq.get(client, '/data/2.5/weather?units=metric&q=' + this.city)
+ // When we get the answer we store the temperature in the process state,
+ // making it available for the transitioning logic.
+ .then(function(R) {
+ this.temperature = R.obj.main.temp
+ console.log(
+ '[' + this.city + '] Currently a temperature of ' + this.temperature
+ + ' degrees Celcius.')
+ }.bind(this))
+ // Whatever happens, we should always close the connection at the end.
+ // Otherwise the program may hang.
+ .fin(function() { client.close() })
+ })
+ // The transitioning itself is pretty basic. Depending on the reported
+ // temperature we transition to one of three different outcomes.
+ .transition(function() {
+ if (this.temperature < 0) return 'freezing'
+ else if (this.temperature > 25) return 'hot'
+ else return 'moderate'
+ })
+
+ // This is the outcome for when it's freezing.
+ weather.task('freezing', function() {
+ console.log('[' + this.city + '] Don\'t forget your scarf !')
+ })
+
+ // This is what to do when the weather is hot.
+ weather.task('hot', function() {
+ console.log('[' + this.city + '] Don\'t forget your sunblock !')
+ })
+
+ // Otherwise there's some generic good advice to follow.
+ weather.task('moderate', function() {
+ console.log('[' + this.city + '] Don\'t forget your pants !')
+ })
+
+ // Finally, we return the completed process definition as the result of this
+ // module.
+ return weather
+})
diff --git a/pool/shard006/JavaScript/0041783_background_importer_item_view.js b/pool/shard006/JavaScript/0041783_background_importer_item_view.js
new file mode 100644
index 0000000000000000000000000000000000000000..d371501b0ed8fbb4e08915cd8126ee5d1009eb98
--- /dev/null
+++ b/pool/shard006/JavaScript/0041783_background_importer_item_view.js
@@ -0,0 +1,126 @@
+var cdb = require('cartodb.js');
+var UploadConfig = require('../../new_common/upload_config');
+var ErrorDetailsDialog = require('../../new_dashboard/dialogs/error_details_view');
+var SuccessDetailsDialog = require('../../new_dashboard/dialogs/success_details_view');
+
+/**
+ * Import item within background importer
+ *
+ */
+
+module.exports = cdb.core.View.extend({
+
+ className: 'ImportItem',
+ tagName: 'li',
+
+ events: {
+ 'click .js-abort': '_removeItem',
+ 'click .js-show_error': '_showImportError',
+ 'click .js-show_stats': '_showImportStats',
+ 'click .js-close': '_removeItem'
+ },
+
+ initialize: function() {
+ this.router = this.options.router;
+ this.user = this.options.user;
+ this.template = cdb.templates.getTemplate('new_dashboard/views/background_importer/background_importer_item_view');
+ this._initBinds();
+ },
+
+ render: function() {
+ var upload = this.model.get('upload');
+ var imp = this.model.get('import');
+
+ var d = {
+ name: '',
+ state: this.model.get('state'),
+ progress: '',
+ service: '',
+ step: this.model.get('step'),
+ url: '',
+ failed: this.model.hasFailed(),
+ completed: this.model.hasCompleted(),
+ tables_created_count: imp.tables_created_count
+ };
+
+ // URL
+ if (d.state === "complete") {
+ var vis = this.model.importedVis();
+ if (vis) {
+ d.url = encodeURI(vis.viewUrl(this.user).edit());
+ }
+ }
+
+ // Name
+ if (upload.type) {
+ if (upload.type === "file") {
+ if (upload.value.length > 1) {
+ d.name = upload.value.length + ' files';
+ } else {
+ d.name = upload.value.name;
+ }
+ }
+ if (upload.type === "url" || upload.type === "remote") {
+ d.name = upload.value;
+ }
+ if (upload.type === "service") {
+ d.name = upload.value && upload.value.filename || '';
+ }
+ if (upload.service_name === "twitter_search") {
+ d.name = 'Twitter import';
+ }
+ } else {
+ d.name = imp.item_queue_id || 'import';
+ }
+
+ // Service
+ var serviceName = this.model.get('upload').service_name;
+ if (serviceName && serviceName !== 'twitter_search') {
+ d.service = serviceName;
+ }
+
+ // Progress
+ if (this.model.get('step') === 'upload') {
+ d.progress = this.model.get('upload').progress;
+ } else {
+ d.progress = (UploadConfig.uploadStates.indexOf(d.state)/UploadConfig.uploadStates.length) * 100;
+ }
+
+ this.$el.html(this.template(d));
+
+ return this;
+ },
+
+ _initBinds: function() {
+ this.model.bind('change:state', this._onStateChange, this);
+ this.model.bind('change', this.render, this);
+ this.model.bind('remove', this.clean, this);
+ },
+
+ _onStateChange: function() {
+ if (this.model.get('state') === "complete") {
+ this.trigger('completed', this);
+ }
+ },
+
+ _removeItem: function() {
+ this.trigger('remove', this.model, this);
+ this.model.pause();
+ this.clean();
+ },
+
+ _showImportStats: function() {
+ (new SuccessDetailsDialog({
+ clean_on_hide: true,
+ model: this.model
+ })).appendToBody();
+ },
+
+ _showImportError: function() {
+ (new ErrorDetailsDialog({
+ clean_on_hide: true,
+ model: this.model
+ })).appendToBody();
+ }
+
+});
diff --git a/pool/shard006/JavaScript/0041790_controls.js b/pool/shard006/JavaScript/0041790_controls.js
new file mode 100644
index 0000000000000000000000000000000000000000..c660e4df907716f10d6d0c9f72f62f94dc1924fa
--- /dev/null
+++ b/pool/shard006/JavaScript/0041790_controls.js
@@ -0,0 +1,162 @@
+import { glMatrix, vec3 } from './dependencies/gl-matrix.js';
+import Input from './input.js';
+import Console from './console.js';
+import Camera from './camera.js';
+import Settings from './settings.js';
+import State from './state.js';
+import UI from './ui.js';
+import Update from './update.js';
+import Translations from './translations.js';
+import Utils from './utils.js';
+import Resources from './resources.js';
+import Weapons from './weapons.js';
+
+const music = Resources.get('sounds/music.sfx');
+
+UI.register('MAIN_MENU', {
+ header: Translations.get('MAIN_MENU'),
+ controls: [
+ {
+ text: Translations.get('CONTINUE_GAME'),
+ callback: () => {
+ Utils.dispatchCustomEvent('changestate', {
+ state: 'GAME'
+ });
+ music.play();
+ }
+ },
+ {
+ text: Translations.get('VERSION_CHECK'),
+ callback: () => {
+ Update.force();
+ }
+ }
+ ]
+});
+
+document.addEventListener(
+ 'pointerlockchange',
+ () => {
+ if (document.pointerLockElement === null) {
+ if (State !== 'MENU') {
+ Utils.dispatchCustomEvent('changestate', {
+ state: 'MENU',
+ menu: 'MAIN_MENU'
+ });
+ music.pause();
+ }
+ }
+ },
+ false
+);
+
+document.addEventListener('pointerlockerror', () => {
+ // Workarround for Chrome where it would throw an error in some weird case.
+ Utils.dispatchCustomEvent('changestate', {
+ state: 'GAME'
+ });
+});
+
+window.addEventListener(
+ 'focus',
+ () => {
+ if (State !== 'MENU') {
+ Utils.dispatchCustomEvent('changestate', {
+ state: 'MENU',
+ menu: 'MAIN_MENU'
+ });
+ }
+ },
+ false
+);
+
+// console
+Input.addKeyDownEvent(192, () => {
+ Console.toggle();
+});
+Input.addKeyDownEvent(13, () => {
+ Console.executeCmd();
+});
+
+// mouse buttons input
+window.addEventListener('click', (e) => {
+ if (e.button > 0) return;
+ if ((e.target.tagName.toUpperCase() !== 'BODY') && !Utils.isMobile()) return;
+ if ((e.target.id !== 'look') && Utils.isMobile()) return;
+ Weapons.shootGrenade();
+});
+
+window.addEventListener('wheel', (e) => {
+ if (State !== 'GAME') return;
+ if (e.deltaY < 0) {
+ Weapons.selectNext();
+ } else if (e.deltaY > 0) {
+ Weapons.selectPrevious();
+ }
+});
+
+// mouse movement and keyboard input
+const Controls = {
+ update(frametime) {
+ if (Console.visible() || State === 'MENU') return;
+ const ft = frametime / 1000;
+
+ // look
+ const mpos = Input.cursorMovement();
+ Camera.rotation[0] -= (mpos.x / 33.0) * Settings.lookSensitivity;
+ Camera.rotation[1] += (mpos.y / 33.0) * Settings.lookSensitivity;
+ if (Camera.rotation[1] > 89) {
+ Camera.rotation[1] = 89;
+ }
+ if (Camera.rotation[1] < -89) {
+ Camera.rotation[1] = -89;
+ }
+ if (Camera.rotation[0] < 0) {
+ Camera.rotation[0] = 360;
+ }
+ if (Camera.rotation[0] > 360) {
+ Camera.rotation[0] = 0;
+ }
+ Camera.direction[0] = 0;
+ Camera.direction[1] = 0;
+ Camera.direction[2] = 1;
+ vec3.rotateX(Camera.direction, Camera.direction, [0, 0, 0], glMatrix.toRadian(Camera.rotation[1]));
+ vec3.rotateY(Camera.direction, Camera.direction, [0, 0, 0], glMatrix.toRadian(Camera.rotation[0]));
+ vec3.normalize(Camera.direction, Camera.direction);
+
+ // movement
+ let move = 0;
+ let strafe = 0;
+
+ Weapons.setIsMoving(false);
+ if (Input.isDown(Settings.forward)) {
+ move += 1;
+ Weapons.setIsMoving(true);
+ }
+ if (Input.isDown(Settings.backwards)) {
+ move -= 1;
+ Weapons.setIsMoving(true);
+ }
+ if (Input.isDown(Settings.left)) {
+ strafe -= 1;
+ Weapons.setIsMoving(true);
+ }
+ if (Input.isDown(Settings.right)) {
+ strafe += 1;
+ Weapons.setIsMoving(true);
+ }
+
+ // calculate new position and view direction
+ const v = vec3.clone(Camera.direction);
+ v[1] = 0;
+ vec3.rotateY(v, v, [0, 0, 0], glMatrix.toRadian(-90));
+ vec3.normalize(v, v);
+ move *= ft * Settings.moveSpeed;
+ strafe *= ft * Settings.moveSpeed;
+ Camera.position[0] = Camera.position[0] + Camera.direction[0] * move + v[0] * strafe;
+ Camera.position[1] = Camera.position[1] + Camera.direction[1] * move + v[1] * strafe;
+ Camera.position[2] = Camera.position[2] + Camera.direction[2] * move + v[2] * strafe;
+ }
+};
+
+export { Controls as default };
diff --git a/pool/shard006/JavaScript/0041792_index.js b/pool/shard006/JavaScript/0041792_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..f72c04858712d0108b0d87b1f522059f92c7f791
--- /dev/null
+++ b/pool/shard006/JavaScript/0041792_index.js
@@ -0,0 +1,112 @@
+
+import React, { Component } from 'react';
+import { connect } from 'react-redux';
+import { actions } from 'react-native-navigation-redux-helpers';
+import { Dimensions, BackAndroid } from 'react-native'
+import { Container, Header, Title, Content, Text, Button, Icon, Item, Input, Left,Thumbnail, Right, Body, Footer } from 'native-base';
+import Classified from '../classified'
+import ListZone from '../listZone'
+import { openDrawer } from '../../actions/drawer';
+import styles from './styles';
+import { Grid, Row, Col } from 'react-native-easy-grid';
+import { fetchAdvertisingZone, resetState, resetStateBack } from '../../actions/list';
+
+
+const {
+ reset,
+ popRoute,
+} = actions;
+
+
+class BlankPage extends Component {
+
+ static propTypes = {
+ name: React.PropTypes.string,
+ index: React.PropTypes.number,
+ list: React.PropTypes.arrayOf(React.PropTypes.object),
+ openDrawer: React.PropTypes.func,
+ popRoute: React.PropTypes.func,
+ reset: React.PropTypes.func,
+ navigation: React.PropTypes.shape({
+ key: React.PropTypes.string,
+ }),
+ }
+ componentWillMount(){
+
+
+ this.props.fetchAdvertisingZone()
+
+ }
+
+ popRoute() {
+ this.props.popRoute(this.props.navigation.key);
+ this.props.resetState()
+
+ }
+ componentWillUnmount(){
+
+ this.props.resetStateBack()
+
+ }
+
+
+
+ render() {
+
+ const { props: { name, index, list } } = this;
+ const { width, height } = Dimensions.get('window')
+ return (
+
+
+
+
+ this.popRoute()}>
+
+
+
+
+ {this.props.list[index].category_name}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+ }
+}
+
+function bindAction(dispatch) {
+ return {
+ openDrawer: () => dispatch(openDrawer()),
+ popRoute: key => dispatch(popRoute(key)),
+ reset: key => dispatch(reset([{ key: 'home' }], key, 0)),
+ fetchAdvertisingZone: index => dispatch(fetchAdvertisingZone(index)),
+ resetState: () => dispatch(resetState()),
+ resetStateBack: () => dispatch(resetStateBack()),
+
+ };
+}
+
+const mapStateToProps = state => ({
+ navigation: state.cardNavigation,
+ name: state.user.name,
+ index: state.list.selectedIndex,
+ list: state.list.list,
+ advertising: state.list.advertisingZone,
+});
+
+
+export default connect(mapStateToProps, bindAction)(BlankPage);
diff --git a/pool/shard006/JavaScript/0041793_master-track-script.js b/pool/shard006/JavaScript/0041793_master-track-script.js
new file mode 100644
index 0000000000000000000000000000000000000000..1aca49e4873d9f16d2b28b21d730aca1a50c3ff2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041793_master-track-script.js
@@ -0,0 +1,43 @@
+var CodeMirror = require('./lib/codemirror');
+require('./simple.js');
+var parsers = require('../../interpreter/parsers');
+
+var parsers = [].concat(parsers.setter).concat(parsers.master);
+
+var trackRegex = [];
+
+trackRegex.push({regex: /$^/, token: 'annotation', push:'start'});
+trackRegex.push({regex: /$^/, token: 'substitution', push:'start'});
+
+var parserRegex = parsers.map(p => {
+ var parser = new p();
+ if (!parser.test || parser.dynamic) return null;
+ return {
+ regex: parser.test,
+ token: parser.type.toLowerCase(),// + parser.sub ? ' sub' : '',
+ push: 'start'
+ };
+}).filter(p => p !== null);
+
+trackRegex = trackRegex.concat(parserRegex);
+
+trackRegex.push({regex: /\(|\)/, token: 'bracket',push:'start'});
+trackRegex.push({regex: /\{|\}/, token: 'brace',push:'start'});
+trackRegex.push({regex: /( ?)\*( ?)[\d]+/, token: 'loop',push:'start'});
+
+CodeMirror.defineSimpleMode('master-track-script', {
+ start: trackRegex,
+ // The multi-line comment state.
+ comment: [
+ {regex: /.*?\*\//, token: "comment", next: "start"},
+ {regex: /.*/, token: "comment"}
+ ],
+ // The meta property contains global information about the mode. It
+ // can contain properties like lineComment, which are supported by
+ // all modes, and also directives like dontIndentStates, which are
+ // specific to simple modes.
+ meta: {
+ dontIndentStates: ["comment"],
+ lineComment: "rem"
+ }
+});
diff --git a/pool/shard006/JavaScript/0041796_get-npm-exec-opts.js b/pool/shard006/JavaScript/0041796_get-npm-exec-opts.js
new file mode 100644
index 0000000000000000000000000000000000000000..569482bb163cbce0b6c18760b0f23debd430ff24
--- /dev/null
+++ b/pool/shard006/JavaScript/0041796_get-npm-exec-opts.js
@@ -0,0 +1,21 @@
+"use strict";
+
+const log = require("npmlog");
+
+module.exports = getExecOpts;
+
+function getExecOpts(pkg, registry) {
+ // execa automatically extends process.env
+ const env = {};
+
+ if (registry) {
+ env.npm_config_registry = registry;
+ }
+
+ log.silly("getExecOpts", pkg.location, registry);
+ return {
+ cwd: pkg.location,
+ env,
+ pkg,
+ };
+}
diff --git a/pool/shard006/JavaScript/0041797_wysiwyg.init.js b/pool/shard006/JavaScript/0041797_wysiwyg.init.js
new file mode 100644
index 0000000000000000000000000000000000000000..3a09a0f3e04493ccff832098054bc15e39b9dc5f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041797_wysiwyg.init.js
@@ -0,0 +1,21 @@
+
+jQuery.support = jQuery.support || {}; // D6- only.
+
+Nochommons.wysiwyg = Nochommons.wysiwyg || { 'instances': {} };
+
+Nochommons.wysiwyg.editor = Nochommons.wysiwyg.editor || { 'init': {}, 'attach': {}, 'detach': {}, 'instance': {} };
+
+Nochommons.wysiwyg.plugins = Nochommons.wysiwyg.plugins || {};
+
+(function ($) {
+ // Determine support for queryCommandEnabled().
+ // An exception should be thrown for non-existing commands.
+ // Safari and Chrome (WebKit based) return -1 instead.
+ try {
+ document.queryCommandEnabled('__wysiwygTestCommand');
+ $.support.queryCommandEnabled = false;
+ }
+ catch (error) {
+ $.support.queryCommandEnabled = true;
+ }
+})(jQuery);
diff --git a/pool/shard006/JavaScript/0041798_webpack.dev.conf.js b/pool/shard006/JavaScript/0041798_webpack.dev.conf.js
new file mode 100644
index 0000000000000000000000000000000000000000..101503a018a79154f4a1079c7f70d2482be86bf8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041798_webpack.dev.conf.js
@@ -0,0 +1,37 @@
+'use strict'
+
+let utils = require('./utils');
+let webpack = require('webpack');
+let config = require('../config');
+let merge = require('webpack-merge');
+let baseWebpackConfig = require('./webpack.base.conf');
+let HtmlWebpackPlugin = require('html-webpack-plugin');
+let FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
+
+// add hot-reload related code to entry chunks
+Object.keys(baseWebpackConfig.entry).forEach(function (name) {
+ baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
+})
+
+module.exports = merge(baseWebpackConfig, {
+ module: {
+ rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
+ },
+ // cheap-module-eval-source-map is faster for development
+ devtool: '#cheap-module-eval-source-map',
+ plugins: [
+ new webpack.DefinePlugin({
+ 'process.env': config.dev.env
+ }),
+ // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
+ new webpack.HotModuleReplacementPlugin(),
+ new webpack.NoEmitOnErrorsPlugin(),
+ // https://github.com/ampedandwired/html-webpack-plugin
+ new HtmlWebpackPlugin({
+ filename: 'index.html',
+ template: 'index.html',
+ inject: true
+ }),
+ new FriendlyErrorsPlugin()
+ ]
+});
diff --git a/pool/shard006/JavaScript/0041800_adsense.directive.js b/pool/shard006/JavaScript/0041800_adsense.directive.js
new file mode 100644
index 0000000000000000000000000000000000000000..3ca5311efcb8d4038190375d6110ed15c163dbb0
--- /dev/null
+++ b/pool/shard006/JavaScript/0041800_adsense.directive.js
@@ -0,0 +1,42 @@
+(function () {
+
+ 'use strict';
+
+ var ngAdSense = angular.module('trialsReportApp');
+ ngAdSense.constant('SCRIPT_URL', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
+
+ ngAdSense.service('AdsenseTracker', [function () {
+ this.isLoaded = false;
+ }]);
+
+ ngAdSense.controller('AdsenseController', ["SCRIPT_URL", "AdsenseTracker", "$timeout", "$scope", function (SCRIPT_URL, AdsenseTracker, $timeout, $scope) {
+
+ if (!$scope.playerAd) {
+ var s = document.createElement('script');
+ s.src = SCRIPT_URL;
+ document.body.appendChild(s);
+ AdsenseTracker.isLoaded = true;
+ }
+ $timeout(function () {
+ try {
+ (window.adsbygoogle = window.adsbygoogle || []).push({});
+ } catch (ex) {
+ }
+ }, 750);
+ }]);
+
+ ngAdSense.directive('adsense', function () {
+ return {
+ restrict: 'E',
+ replace: true,
+ scope: {
+ adClient: '@',
+ adSlot: '@',
+ inlineStyle: '@',
+ playerAd: '@'
+ },
+ template: '
',
+ controller: 'AdsenseController'
+ };
+ });
+}());
diff --git a/pool/shard006/JavaScript/0041801_index.js b/pool/shard006/JavaScript/0041801_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..c090a95a4fe089fbf501d5fbb36b1403c63e8962
--- /dev/null
+++ b/pool/shard006/JavaScript/0041801_index.js
@@ -0,0 +1,107 @@
+'use strict';
+var util = require('util');
+var path = require('path');
+var yeoman = require('yeoman-generator');
+
+
+var WpwidgetGenerator = module.exports = function WpwidgetGenerator(args, options, config) {
+ yeoman.generators.Base.apply(this, arguments);
+
+ this.on('end', function () {
+ this.installDependencies({ skipInstall: options['skip-install'] });
+ });
+
+ this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
+};
+
+util.inherits(WpwidgetGenerator, yeoman.generators.Base);
+
+WpwidgetGenerator.prototype.askFor = function askFor() {
+ var cb = this.async();
+
+ // have Yeoman greet the user.
+ console.log(this.yeoman);
+
+ var prompts = [{
+ name: 'widgetName',
+ message: 'What do you want to call your WP-Widget\n(use spaces if necesary, avoid using \'_\' or \'-\' characters, eg. My Widget) \n?'
+ }, {
+ name: 'domainPrefix',
+ message: 'What is your domain prefix (eg. myapp)\n?'
+ }, {
+ name: 'widgetDescription',
+ message: 'What is the description of your widget\n?'
+ }, {
+ type: 'list',
+ name: 'jsFramework',
+ message: 'Which JS js setup do you have\n?',
+ choices: [{
+ name: "plain js",
+ value: 'plain'
+ },{
+ name: "jQuery",
+ value: 'jquery'
+ },{
+ name: "AngularJS",
+ value: 'angularjs'
+ },{
+ name: "Module",
+ value: 'module'
+ },{
+ name: "let me handle it",
+ value: 'none'
+ }
+ ]
+ }];
+
+ this.prompt(prompts, function (props) {
+ this.widgetName = this._sanitize( props.widgetName );
+ this.domainPrefix = this._sanitize( props.domainPrefix );
+ this.widgetDescription = this._sanitize( props.widgetDescription );
+ this.jsFramework = props.jsFramework;
+ console.log("this.jsFramework", this.jsFramework);
+
+ cb();
+ }.bind(this));
+};
+
+WpwidgetGenerator.prototype.app = function app() {
+ this.dashedWidgetName = this.widgetName.replace( /\s/g, '-').toLowerCase();
+ this.underscoredWidgetName = this.widgetName.replace( /\s/g, '_');
+ this.TitleCaseWidgetName = this.widgetName.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
+ this.classWidgetName = this.TitleCaseWidgetName.replace( /\s/g, '_');
+
+
+ this.mkdir(this.dashedWidgetName);
+ this.mkdir(this.dashedWidgetName + '/css');
+ this.mkdir(this.dashedWidgetName + '/js');
+ this.mkdir(this.dashedWidgetName + '/lang');
+ this.mkdir(this.dashedWidgetName + '/views');
+
+ this.template('_plugin.php', this.dashedWidgetName + '/' + this.dashedWidgetName + '-widget.php');
+
+ this.template('css/' + '_admin.css', this.dashedWidgetName + '/css/admin.css');
+ this.template('css/' + '_widget.css', this.dashedWidgetName + '/css/widget.css');
+
+ this.template('views/' + '_admin.php', this.dashedWidgetName + '/views/admin.php');
+ this.template('views/' + '_widget.php', this.dashedWidgetName + '/views/widget.php');
+
+ this.template('js/' + '_admin.js', this.dashedWidgetName + '/js/admin.js');
+ this.template('js/' + '_widget.js', this.dashedWidgetName + '/js/widget.js');
+
+ this.copy('lang/_plugin.po', this.dashedWidgetName + '/lang/plugin.po');
+ this.copy('README.txt', this.dashedWidgetName + '/README.txt');
+
+ this.template('_package.json', 'package.json');
+ this.template('_bower.json', 'bower.json');
+};
+
+WpwidgetGenerator.prototype.projectfiles = function projectfiles() {
+ this.copy('editorconfig', '.editorconfig');
+ this.copy('jshintrc', '.jshintrc');
+};
+
+
+WpwidgetGenerator.prototype._sanitize = function sanitize(str) {
+ return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041802_difference.js b/pool/shard006/JavaScript/0041802_difference.js
new file mode 100644
index 0000000000000000000000000000000000000000..4275c4b2e83c6808d2bbc6e7b2dc0c6285d531e3
--- /dev/null
+++ b/pool/shard006/JavaScript/0041802_difference.js
@@ -0,0 +1,27 @@
+/* global jsts, self */
+
+/**
+ *
+ * Hand the script two geojson objects and return the geometry that is the difference of the two
+ */
+importScripts('../js/libs/javascript.util.js', '../js/libs/jsts.js');
+
+var wkts = null;
+var buffers = [];
+reader = new jsts.io.GeoJSONReader();
+writer = new jsts.io.GeoJSONWriter();
+
+onmessage = function (evt) {
+ var geometry1 = reader.read(evt.data.queue[0]).geometry;
+ var geometry2 = reader.read(evt.data.queue[1]).geometry;
+
+ //do they touch?
+ var result = geometry1.difference(geometry2);
+ var output = [];
+ //result.forEach(function (geom) {
+ // var f = {type: "Feature", properties: {}, geometry: writer.write(geom)};
+ // output.features.push(f);
+ // });
+ output = writer.write(result);
+ self.postMessage(JSON.stringify(output));
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041805_HomeControllerSpec.js b/pool/shard006/JavaScript/0041805_HomeControllerSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..649f3cd639d1a8a815d1ce310623f0c2c16b964a
--- /dev/null
+++ b/pool/shard006/JavaScript/0041805_HomeControllerSpec.js
@@ -0,0 +1,72 @@
+'use strict';
+
+describe('Controller: public/HomeController', function() {
+ var $rootScope, $scope;
+ var $controller, service;
+ var websiteDeferred, blogDeferred, authorDeferred;
+
+ var mockWebsite = {
+ $get: function(rel) {}
+ };
+
+ var mockBlogPost = {
+ title: 'Test Blog',
+ content: 'This is first paragraph.
Other parts...',
+ $get: function(rel) {}
+ };
+
+ var mockAuthor = {
+ displayName: 'author'
+ };
+
+ beforeEach(module('jiwhizWeb'));
+
+ beforeEach(inject(function(_$rootScope_, _$controller_, _$q_, _$timeout_, _WebsiteService_){
+ $rootScope = _$rootScope_;
+ $scope = $rootScope.$new();
+ $controller = _$controller_;
+ service = _WebsiteService_;
+
+ websiteDeferred = _$q_.defer();
+ websiteDeferred.resolve(mockWebsite);
+ spyOn(service, 'load').and.returnValue(websiteDeferred.promise);
+
+ blogDeferred = _$q_.defer();
+ spyOn(mockWebsite, '$get').and.returnValue(blogDeferred.promise);
+
+ authorDeferred = _$q_.defer();
+ spyOn(mockBlogPost, '$get').and.returnValue(authorDeferred.promise);
+
+ $controller('HomeController',
+ {
+ '$rootScope' : $rootScope,
+ '$scope': $scope,
+ '$timeout': _$timeout_,
+ 'WebsiteService': service
+ });
+ }));
+
+ it('should have correct UI setup, such as active home menu, show slider, hide title.', function() {
+ expect($rootScope.activeMenu.home == 'active');
+ expect($rootScope.showTitle == false);
+ });
+
+ it('should not have blog if latest blog returned is null.', function() {
+ blogDeferred.resolve(null);
+ $rootScope.$apply();
+ expect($scope.hasBlog).toBe(false);
+ expect($scope.blog).toBeUndefined();
+ });
+
+ it('should have blog if latest blog returned.', function() {
+ blogDeferred.resolve(mockBlogPost);
+ authorDeferred.resolve(mockAuthor);
+ $rootScope.$apply();
+ expect($scope.hasBlog).toBe(true);
+ expect($scope.blog).not.toBeNull();
+ expect($scope.blog.title).toEqual('Test Blog');
+ });
+
+
+
+});
diff --git a/pool/shard006/JavaScript/0041806_pokemail.js b/pool/shard006/JavaScript/0041806_pokemail.js
new file mode 100644
index 0000000000000000000000000000000000000000..fb3ae51e721143deac1d7297b23066c66db52478
--- /dev/null
+++ b/pool/shard006/JavaScript/0041806_pokemail.js
@@ -0,0 +1,71 @@
+import checkSyntax from './checks/syntax'
+import checkDisposable from './checks/disposable'
+import checkReachability from './checks/reachability'
+import packageData from '../package.json'
+
+/**
+ * Verifies the given email address against a set of predefined checks.
+ *
+ * @param {String} str - The email address to verify
+ * @param {Function} callback - An error-first callback
+ * @returns undefined
+ */
+function verify(str, callback) {
+ if (!callback) {
+ throw new Error('Error-first callback is required')
+ }
+
+ const makeResult = props => (
+ Object.assign({
+ result: '',
+ reason: '',
+ disposable: false,
+ email: str,
+ success: true,
+ }, props)
+ )
+
+ const reject = err => callback(err, makeResult({ result: 'unknown', reason: err.message, success: false }))
+
+ if (!checkSyntax(str)) {
+ callback(null, makeResult({
+ result: 'undeliverable',
+ reason: 'invalid_email',
+ }))
+ return
+ }
+
+ // eslint-disable-next-line consistent-return
+ checkDisposable(str, (errDisposable, isDisposable) => {
+ if (errDisposable) {
+ reject(errDisposable)
+ return
+ }
+
+ if (isDisposable) {
+ callback(null, makeResult({
+ result: 'risky',
+ reason: 'low_quality',
+ disposable: true,
+ }))
+ return
+ }
+
+ checkReachability(str, (errHostname, reachable) => {
+ if (errHostname) {
+ reject(errHostname)
+ return
+ }
+
+ callback(null, makeResult({
+ result: reachable ? 'deliverable' : 'undeliverable',
+ reason: reachable ? 'low_deliverability' : 'invalid_domain',
+ disposable: false, // TODO
+ }))
+ })
+ })
+}
+
+// Use what Node currently supports
+// See https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0
+module.exports = { verify, version: packageData.version }
diff --git a/pool/shard006/JavaScript/0041809_sharedCalendarParser.js b/pool/shard006/JavaScript/0041809_sharedCalendarParser.js
new file mode 100644
index 0000000000000000000000000000000000000000..851062ad6c9f69ef8155afabbd3f79e005e2bff8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041809_sharedCalendarParser.js
@@ -0,0 +1,138 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: GPL 3.0
+ *
+ * The contents of this file are subject to the General Public License
+ * 3.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.gnu.org/licenses/gpl.html
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * -- Exchange 2007/2010 Calendar and Tasks Provider.
+ * -- For Thunderbird with the Lightning add-on.
+ *
+ * Borrowed from the enigMail project.
+ *
+ * Author: Michel Verbraak (info@1st-setup.nl)
+ * Website: http://www.1st-setup.nl/wordpress/?page_id=133
+ * email: exchangecalendar@extensions.1st-setup.nl
+ *
+ *
+ * ***** BEGIN LICENSE BLOCK *****/
+
+var Cc = Components.classes;
+var Ci = Components.interfaces;
+var Cu = Components.utils;
+
+
+Cu.import("resource://exchangecommon/ecFunctions.js");
+Cu.import("chrome://exchangecommon/content/msgHdrUtils.js");
+Cu.import("resource:///modules/gloda/utils.js");
+
+if (!exchWebService) var exchWebService = {};
+
+exchWebService.hdrView = {
+
+ theHeaders: null,
+
+ msgHdrViewLoad: function _msgHdrViewLoad(event) {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: this.msgHdrViewLoad");
+
+ var listener = {
+ onBeforeShowHeaderPane: function _listener_onBeforeShowHeaderPane() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: _listener_onBeforeShowHeaderPane");
+ },
+
+ onStartHeaders: function _listener_onStartHeaders() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: _listener_onStartHeaders");
+
+ exchWebService.hdrView.statusBarHide();
+ },
+
+ onEndHeaders: function _listener_onEndHeaders() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: _listener_onEndHeaders");
+ exchWebService.hdrView.statusBarHide();
+
+ msgHdrGetHeaders(gFolderDisplay.selectedMessage, function (aHeaders) {
+
+ if ((exchWebService.check4Lightning) && (exchWebService.check4Lightning.lightningIsInstalled != 2)) {
+ return;
+ }
+
+ exchWebService.hdrView.theHeaders = null;
+
+ if ((aHeaders.has("x-sharing-remote-uid"))
+ && (aHeaders.has("x-sharing-local-type"))
+ && (aHeaders.has("x-sharing-remote-name"))) {
+ if (aHeaders.get("x-sharing-local-type") == "IPF.Appointment") {
+ exchWebService.commonFunctions.LOG("This message has a x-sharing-remote-uid header; its value is " + aHeaders.get("x-sharing-remote-uid"));
+ document.getElementById("exchWebServiceSharedCalendarLabel").value = GlodaUtils.deMime(aHeaders.get("x-sharing-remote-name"));
+ exchWebService.hdrView.theHeaders = aHeaders;
+ exchWebService.hdrView.statusBarShow();
+ }
+ }
+ else {
+ exchWebService.commonFunctions.LOG("NO x-sharing-remote-uid header");
+ }
+ });
+ },
+
+ };
+
+ gMessageListeners.push(listener);
+
+ // Next part is to hide the bar when the user changes to another folder and
+ // a new message is not selected. Otherwise it will stay visible.
+ listener.tbHideMessageHeaderPane = HideMessageHeaderPane;
+ HideMessageHeaderPane = function exchWebServiceHideMessageHeaderPane() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: exchWebServiceHideMessageHeaderPane");
+ try {
+ exchWebService.hdrView.statusBarHide();
+ }
+ catch (ex) {};
+ listener.tbHideMessageHeaderPane.apply(null, arguments);
+ };
+
+ },
+
+ hdrViewUnload: function _hdrViewUnload() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: this.hdrViewUnLoad");
+ this.statusBarHide();
+ },
+
+ statusBarHide: function _statusBarHide() {
+ var exchWebServiceSharedCalendarBox = document.getElementById("exchWebServiceSharedCalendarBox");
+ try {
+ exchWebServiceSharedCalendarBox.setAttribute("collapsed", "true")
+ //Enigmail.msg.setAttachmentReveal(null);
+ }
+ catch (ex) {}
+ },
+
+ statusBarShow: function _statusBarShow() {
+ var exchWebServiceSharedCalendarBox = document.getElementById("exchWebServiceSharedCalendarBox");
+ try {
+ exchWebServiceSharedCalendarBox.removeAttribute("collapsed");
+ }
+ catch (ex) {
+ exchWebService.commonFunctions.LOG("ERROR:" + ex);
+ }
+ },
+
+
+ doAddSharedCalendar: function _doAddSharedCalendar() {
+ exchWebService.commonFunctions.LOG("exchWebService.sharedCalendarParser.js: this.doAddSharedCalendar");
+ if (this.theHeaders) {
+ exchWebService.commonFunctions.LOG(" uid:" + this.theHeaders.get("x-sharing-remote-uid"));
+ exchWebService.commonFunctions.LOG(" name:" + GlodaUtils.deMime(this.theHeaders.get("x-sharing-remote-name")));
+
+ }
+ },
+}
+
+// Currently turned of because not yet ready for version 1.7.13
+//addEventListener('messagepane-loaded', exchWebService.hdrView.msgHdrViewLoad, true);
+//addEventListener('messagepane-unloaded', exchWebService.hdrView.hdrViewUnload, true);
diff --git a/pool/shard006/JavaScript/0041812_init.js b/pool/shard006/JavaScript/0041812_init.js
new file mode 100644
index 0000000000000000000000000000000000000000..059513aad565101a926d73c261248014f775fcca
--- /dev/null
+++ b/pool/shard006/JavaScript/0041812_init.js
@@ -0,0 +1,149 @@
+/* Global initialization script */
+var z = {};
+
+$(document).ready(function(){
+ // Initialize install buttons.
+ $('.install').installButton();
+ $(window).trigger('buttons_loaded');
+
+ // Initialize any tabbed interfaces. See: tabs.js
+ if ($.fn.tabify) {
+ $('.tab-wrapper').tabify();
+ }
+
+ // Initialize email links
+ $('span.emaillink').each(function() {
+ $(this).find('.i').remove();
+ var em = $(this).text().split('').reverse().join('');
+ $(this).prev('a').attr('href', 'mailto:' + em).addClass('email');
+ });
+
+ // fake placeholders if we need to.
+ if (!('placeholder' in document.createElement('input'))) {
+ $('input[placeholder]').placeholder();
+ }
+
+ if (z.readonly) {
+ $('form[method=post]')
+ .before(gettext('This feature is temporarily disabled while we perform website maintenance. Please check back a little later.'))
+ .find('input, button, select').prop('disabled', true).addClass('disabled');
+ }
+});
+
+z.inlineSVG = (function() {
+ var e = document.createElement('div');
+ e.innerHTML = ' ';
+ return !!(window.SVGSVGElement && e.firstChild instanceof window.SVGSVGElement);
+})();
+if (!z.inlineSVG) {
+ $("body").addClass("noInlineSVG");
+}
+
+/* prevent-default function wrapper */
+function _pd(func) {
+ return function(e) {
+ e.preventDefault();
+ func.apply(this, arguments);
+ };
+}
+
+
+/* Fake the placeholder attribute since Firefox 3.6 doesn't support it. */
+jQuery.fn.placeholder = function(new_value) {
+
+ if (new_value) {
+ this.attr('placeholder', new_value);
+ }
+
+ /* Bail early if we have built-in placeholder support. */
+ if ('placeholder' in document.createElement('input')) {
+ return this;
+ }
+
+ if (new_value && this.hasClass('placeholder')) {
+ this.val('').blur();
+ }
+
+ return this.focus(function() {
+ var $this = $(this),
+ text = $this.attr('placeholder');
+
+ if ($this.val() == text) {
+ $this.val('').removeClass('placeholder');
+ }
+ }).blur(function() {
+ var $this = $(this),
+ text = $this.attr('placeholder');
+
+ if ($this.val() === '') {
+ $this.val(text).addClass('placeholder');
+ }
+ }).each(function(){
+ /* Remove the placeholder text before submitting the form. */
+ var self = $(this);
+ self.closest('form').submit(function() {
+ if (self.hasClass('placeholder')) {
+ self.val('');
+ }
+ });
+ }).blur();
+};
+
+
+jQuery.fn.hasattr = function(name) {
+ return this.attr(name) !== undefined;
+};
+
+
+var escape_ = function(s){
+ if (s === undefined) {
+ return;
+ }
+ return s.replace(/&/g, '&').replace(/>/g, '>').replace(/ -1);
+ }
+ var betaVer = document.body.getAttribute('data-min-beta-version');
+ z.fxBeta = (VersionCompare.compareVersions(z.browserVersion, betaVer) > -1);
+ if (z.fxBeta) {
+ $(document.body).addClass('fxbeta');
+ }
+} else {
+ z.fxBeta = false;
+}
+
+if (z.badBrowser) {
+ $(".get-fx-message").show();
+}
+
+z.apps = $(document.body).hasClass('apps');
diff --git a/pool/shard006/JavaScript/0041813_touch-volume.js b/pool/shard006/JavaScript/0041813_touch-volume.js
new file mode 100644
index 0000000000000000000000000000000000000000..1be9a886b0f9b895353a949a1caffa08cd28fe03
--- /dev/null
+++ b/pool/shard006/JavaScript/0041813_touch-volume.js
@@ -0,0 +1,147 @@
+function TouchVolumeSlider(containerObj, callback) {
+ var state = {
+ cursorX: 0,
+ originalX: 0,
+ maxX: 0,
+ currentX: 0,
+ slider: null,
+ tooltip: null,
+ volume: 0,
+ disableUpdate: false,
+ numberOfTouches: 0,
+ disableTimer: null
+ };
+
+ function setVolume(volume) {
+ // calculate a pixel offset based on percentage
+ if (state.volume == volume) return;
+ setScrubberPosition(volume);
+ if (typeof callback == "function")
+ callback(volume);
+ }
+
+ function setScrubberPosition(volume) {
+ var offset = Math.round(state.maxX * volume * 0.01);
+ state.currentX = offset;
+ //state.slider.style.marginLeft = offset + 'px';
+ state.slider.style.transform = 'translateX(' + offset + 'px)';
+ // For chrome 35 or less
+ state.slider.style.webkitTransform = 'translateX(' + offset + 'px)';
+ state.tooltip.textContent = volume;
+ // calculate tooltip offset
+ var adjustedOffset = offset + (state.slider.clientWidth - state.tooltip.clientWidth) * 0.5;
+ state.tooltip.style.transform = 'translateX(' + adjustedOffset + 'px)';
+ // For chrome 35 or less
+ state.tooltip.style.webkitTransform = 'translateX(' + adjustedOffset + 'px)';
+ state.volume = volume;
+ }
+
+ function handleVolumeWheel(e) {
+ var newVolume;
+ if(e.deltaY > 0) {
+ // volume down
+ newVolume = state.volume - 2;
+ } else {
+ // volume up
+ newVolume = state.volume + 2;
+ }
+ if (newVolume < 0) newVolume = 0;
+ if (newVolume > 100) newVolume = 100;
+
+ setVolume( newVolume );
+ clearTimeout(state.disableTimer);
+ state.disableUpdate = true;
+ state.disableTimer = setTimeout(function () {state.disableUpdate = false}, 800);
+
+ //socket.emit('group-volume', {uuid: Sonos.currentState.selectedZone, volume: newVolume});
+ //newVolume = Sonos.currentZoneCoordinator().groupState.volume = newVolume;
+
+
+ }
+
+ function handleClick(e) {
+ // Be able to cancel this from a callback if necessary
+ if (typeof clickCallback == "function" && clickCallback(this) == false) return;
+
+ if (e.target.tagName == "IMG") return;
+
+ var newVolume;
+ if(e.layerX < state.currentX) {
+ // volume down
+ newVolume = state.volume - 2;
+ } else {
+ // volume up
+ newVolume = state.volume + 2;
+ }
+
+ if (newVolume < 0) newVolume = 0;
+ if (newVolume > 100) newVolume = 100;
+
+ setVolume(newVolume);
+ clearTimeout(state.disableTimer);
+ state.disableUpdate = true;
+ state.disableTimer = setTimeout(function () {state.disableUpdate = false}, 800);
+ }
+
+ function onDrag(multi) {
+ var e = multi.touches[0];
+ var deltaX = (e.clientX - state.cursorX) * 0.25;
+ var nextX = state.originalX + deltaX;
+
+ if ( nextX > state.maxX ) nextX = state.maxX;
+ else if ( nextX < 1) nextX = 1;
+
+ // calculate percentage
+ var volume = Math.floor(nextX / state.maxX * 100);
+ setVolume(volume);
+ multi.preventDefault();
+ }
+
+
+ var sliderWidth = containerObj.clientWidth;
+ state.maxX = sliderWidth - 21;
+ state.slider = containerObj.querySelector('.scrubber');
+ state.tooltip = containerObj.querySelector('.tooltip');
+
+ containerObj.addEventListener('touchstart', function (multi) {
+ state.numberOfTouches++;
+ var e = multi.touches[0];
+ state.cursorX = e.clientX;
+ state.originalX = state.currentX;
+ clearTimeout(state.disableTimer);
+ state.disableUpdate = true;
+ state.tooltip.classList.remove("hide");
+ document.addEventListener('touchmove', onDrag);
+ //multi.preventDefault();
+ });
+
+ document.addEventListener('touchend', function () {
+ state.numberOfTouches--;
+ if (state.numberOfTouches > 0) return;
+ state.tooltip.classList.add("hide");
+ document.removeEventListener('touchmove', onDrag);
+ state.disableTimer = setTimeout(function () { state.disableUpdate = false }, 800);
+ });
+
+ // Since Chrome 31 wheel event is also supported
+ //containerObj.addEventListener("wheel", handleVolumeWheel);
+
+ // For click-to-adjust
+ //containerObj.addEventListener("click", handleClick);
+
+
+
+ // Add some functions to go
+ this.setVolume = function (volume) {
+ if (state.disableUpdate) return;
+
+ // To make a successful adjust of the tooltip, we need to show it temporarily.
+ state.tooltip.classList.remove("hide");
+ setScrubberPosition(volume);
+ state.tooltip.classList.add("hide");
+
+
+ }
+
+ return this;
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041814_index.js b/pool/shard006/JavaScript/0041814_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..4b986e375b4fc01c31864588d9a100071d70987c
--- /dev/null
+++ b/pool/shard006/JavaScript/0041814_index.js
@@ -0,0 +1,68 @@
+var fs = require('fs')
+var path = require('path')
+var mktemp = require('mktemp')
+var rimraf = require('rimraf')
+var underscoreString = require('underscore.string')
+
+exports.makeOrRemake = makeOrRemake
+function makeOrRemake(obj, prop) {
+ if (obj[prop] != null) {
+ remove(obj, prop)
+ }
+ return obj[prop] = makeTmpDir(obj.constructor && obj.constructor.name || '', prop)
+}
+
+exports.makeOrReuse = makeOrReuse
+function makeOrReuse(obj, prop) {
+ if (obj[prop] != null) {
+ return obj[prop]
+ }
+ return obj[prop] = makeTmpDir(obj.constructor && obj.constructor.name || '', prop)
+}
+
+exports.remove = remove
+function remove(obj, prop) {
+ if (obj[prop] != null) {
+ rimraf.sync(obj[prop])
+ }
+ obj[prop] = null
+}
+
+
+function makeTmpDir(name, prop) {
+ if (baseDir == null) {
+ findBaseDir()
+ }
+ var tmpDirName = prettyTmpDirName(name, prop)
+ return mktemp.createDirSync(path.join(baseDir, tmpDirName))
+}
+
+var baseDir
+
+function findBaseDir () {
+ try {
+ if (fs.statSync('tmp').isDirectory()) {
+ baseDir = fs.realpathSync('tmp')
+ }
+ } catch (err) {
+ if (err.code !== 'ENOENT') throw err
+ // We could try other directories, but for now we just create ./tmp if
+ // it doesn't exist
+ fs.mkdirSync('tmp')
+ baseDir = fs.realpathSync('tmp')
+ }
+}
+
+function cleanString (s) {
+ return underscoreString.underscored(s || '')
+ .replace(/[^a-z_]/g, '')
+ .replace(/^_+/, '')
+}
+
+function prettyTmpDirName (name, prop) {
+ var cleanObjectName = cleanString(name)
+ if (cleanObjectName === 'object') cleanObjectName = ''
+ if (cleanObjectName) cleanObjectName += '-'
+ var cleanPropertyName = cleanString(prop)
+ return cleanObjectName + cleanPropertyName + '-XXXXXXXX.tmp'
+}
diff --git a/pool/shard006/JavaScript/0041815_require-shim.js b/pool/shard006/JavaScript/0041815_require-shim.js
new file mode 100644
index 0000000000000000000000000000000000000000..11768492901487c13c2d3c6f4012f2dd00eab047
--- /dev/null
+++ b/pool/shard006/JavaScript/0041815_require-shim.js
@@ -0,0 +1,58 @@
+(function (global, globals, entries) {
+ var originalRequire = typeof require === 'function' && require;
+ var modules = {};
+
+ function loadModule(entry) {
+ var m = { exports: {} };
+ entry.body(localRequire.bind(global, entry.refs), m, m.exports);
+ return (modules[entry.path] = m.exports);
+ }
+
+ function findEntry(path) {
+ for (var i = 0, ln = entries.length; i < ln; i++) {
+ if (path === entries[i].path) {
+ return entries[i];
+ }
+ }
+
+ return null;
+ }
+
+ function localRequire(refs, path) {
+ if (globals && path in globals) {
+ return global[globals[path]];
+ }
+
+ if (path[path.length - 1] === '/') {
+ path += 'index';
+ }
+
+ if (refs && path in refs) {
+ path = refs[path];
+ }
+
+ if (path in modules) {
+ return modules[path];
+ }
+
+ var entry = findEntry(path);
+ if (entry) {
+ return loadModule(entry);
+ }
+
+ if (originalRequire) {
+ return originalRequire(path, true)
+ }
+
+ throw Error('Unable to find module: ' + path);
+ }
+
+ // load all modules
+ entries.forEach(function (entry) {
+ if (!(entry.path in modules)) {
+ loadModule(entry);
+ }
+ });
+
+ return localRequire.bind(global, {});
+})
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041817_index.js b/pool/shard006/JavaScript/0041817_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..bb1ba5601c6b8f6d01c0876ac751d280ea9cb24f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041817_index.js
@@ -0,0 +1,26 @@
+let Discordie = require('discordie');
+let fs = require('fs');
+let _ = require('underscore');
+
+let rb = require('./core/RazzBot');
+let config = require('./config');
+
+let Events = Discordie.Events;
+let client = new Discordie();
+let RazzBot = new rb();
+
+client.connect({
+ token: config.local.discordToken
+});
+
+client.Dispatcher.on(Events.GATEWAY_READY, e => {
+ console.log('Connected as: ' + client.User.username);
+});
+
+client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
+ RazzBot.checkMessageForCommand(e.message, (moduleName, message, isSubcommand) => {
+ if (moduleName) {
+ RazzBot.runModule(moduleName, message, isSubcommand);
+ }
+ });
+});
diff --git a/pool/shard006/JavaScript/0041819_s3_setup.test.js b/pool/shard006/JavaScript/0041819_s3_setup.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..ead945d143e999fb92aeac5c60e53efa2e1207c4
--- /dev/null
+++ b/pool/shard006/JavaScript/0041819_s3_setup.test.js
@@ -0,0 +1,22 @@
+"use strict";
+
+var s3_setup = require('../lib/util/s3_setup.js');
+var assert = require('assert');
+
+describe('s3_setup', function() {
+ it('should propertly detect s3 bucket and prefix', function() {
+ var url = "https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com";
+ var result = {};
+ s3_setup.detect(url, result);
+ assert.equal(result.prefix,'');
+ assert.equal(result.bucket,'node-pre-gyp-tests');
+ });
+
+ it('should propertly detect s3 bucket and prefix with dots', function() {
+ var url = "https://bucket.with.dots.s3.amazonaws.com/prefix";
+ var result = {};
+ s3_setup.detect(url, result);
+ assert.equal(result.prefix,'prefix');
+ assert.equal(result.bucket,'bucket.with.dots');
+ });
+});
diff --git a/pool/shard006/JavaScript/0041821_html-build.js b/pool/shard006/JavaScript/0041821_html-build.js
new file mode 100644
index 0000000000000000000000000000000000000000..cee7ce7b433b80fc3f94ad894cdeb326bd58439e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041821_html-build.js
@@ -0,0 +1,32 @@
+'use strict';
+
+// VENDOR LIBS
+const browserSync = require('browser-sync');
+const gulpif = require('gulp-if');
+const handlebars = require('gulp-compile-handlebars');
+
+module.exports = function (id, application) {
+ let applicationScripts = application.scripts;
+ let applicationStyles = application.styles;
+ let assetsFolder = config.assets;
+ let destination = application.destination;
+ let source = application.source;
+ let htmlSource = application.html.source;
+ let htmlDestination = path.join(config.destination, destination);
+ let scriptsDestinationFolder = applicationScripts.destination;
+ let stylesDestinationFolder = applicationStyles.destination;
+ let scriptsRename = applicationScripts.rename;
+ let stylesRename = applicationStyles.rename;
+ let vendors = config.vendors;
+
+ source = path.join(source, htmlSource);
+
+ return gulp.src(source)
+ .pipe(handlebars({
+ vendorsPath: path.join('/', vendors.destination, vendors.rename),
+ scriptsPath: path.join('/', destination, scriptsDestinationFolder, scriptsRename),
+ stylesPath: path.join('/', destination, assetsFolder, stylesDestinationFolder, stylesRename)
+ }))
+ .pipe(gulp.dest(htmlDestination))
+ .pipe(gulpif(!env.isProductionBuild(), browserSync.reload({stream: true})));
+};
diff --git a/pool/shard006/JavaScript/0041823_tmpl.js b/pool/shard006/JavaScript/0041823_tmpl.js
new file mode 100644
index 0000000000000000000000000000000000000000..3c2b765fd505058ce2211ffc67f86591a0cf4ff9
--- /dev/null
+++ b/pool/shard006/JavaScript/0041823_tmpl.js
@@ -0,0 +1,52 @@
+describe("template engine", function () {
+
+ var tmpl = require("../../../lib/tmpl");
+
+ it("can replace locals", function () {
+ var result,
+ data = {
+ locals : {
+ name : "Nukul"
+ }
+ },
+ source = "{{name}} wrote this";
+ result = tmpl.render(source, data);
+ expect(result).toEqual("Nukul wrote this");
+ });
+
+ it("can replace locals and escape locals", function () {
+ var result,
+ data = {
+ locals : {
+ name : "Nukul {
+ var srgb_color = 0.0042;
+ var expected_value = 0.0042 / 255.0 / 12.92;
+ var actual_value = colorspace.sRGB_to_linear(srgb_color);
+ assert.equal(actual_value, expected_value);
+
+ srgb_color = 255.0;
+ expected_value = 1;
+ actual_value = colorspace.sRGB_to_linear(srgb_color);
+ assert.equal(actual_value, expected_value);
+});
+
+run_test('rgb_luminance', () => {
+ var channel = [1, 1, 1];
+ var expected_value = 1;
+ var actual_value = colorspace.rgb_luminance(channel);
+ assert.equal(actual_value, expected_value);
+});
+
+run_test('luminance_to_lightness', () => {
+ var luminance = 0;
+ var expected_value = 116 * 4 / 29 - 16;
+ var actual_value = colorspace.luminance_to_lightness(luminance);
+ assert.equal(actual_value, expected_value);
+
+ luminance = 1;
+ expected_value = 100;
+ actual_value = colorspace.luminance_to_lightness(luminance);
+ assert.equal(actual_value, expected_value);
+});
+
+run_test('getDecimalColor', () => {
+ var hex_color = '#1f293b';
+ var expected_value = {
+ r: 31,
+ g: 41,
+ b: 59,
+ };
+ var actual_value = colorspace.getDecimalColor(hex_color);
+ assert.deepEqual(actual_value, expected_value);
+});
+
+run_test('getLighterColor', () => {
+ var rgb_color = {
+ r: 31,
+ g: 41,
+ b: 59,
+ };
+ var lightness = 0;
+ var expected_value = rgb_color;
+ var actual_value = colorspace.getLighterColor(rgb_color, lightness);
+ assert.deepEqual(actual_value, expected_value);
+});
+
+run_test('getHexColor', () => {
+ var rgb_color = {
+ r: 31,
+ g: 41,
+ b: 59,
+ };
+ var expected_value = '#1f293b';
+ var actual_value = colorspace.getHexColor(rgb_color);
+ assert.equal(actual_value, expected_value);
+});
diff --git a/pool/shard006/JavaScript/0041834_ReactComponentAdapter.js b/pool/shard006/JavaScript/0041834_ReactComponentAdapter.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a8fc88c41a8548caafbcd4cd47877ec2b5971bc
--- /dev/null
+++ b/pool/shard006/JavaScript/0041834_ReactComponentAdapter.js
@@ -0,0 +1,121 @@
+'use strict';
+
+import Component from '../base/Component';
+import Element from '../base/Element';
+import ComponentAdapter from '../base/ComponentAdapter';
+import DOMBuilder from '../base/DOMBuilder';
+import PropsReader from '../base/PropsReader';
+
+const {Objects, Seq, Reader} = mojo;
+
+export default class ReactAdapter extends ComponentAdapter {
+ isMountable(obj) {console.log(45555, obj)
+ return obj && typeof obj === 'object' && React.isValidElement(obj);
+ }
+
+ mount(obj, domElement) {
+ var ret;
+
+ if (!this.isMountable(obj) || !domElement || typeof domElement.appendChild !== 'function') {
+ ret = false;
+ } else {
+ React.render(obj, domElement);
+
+ domElement.__unmountComponent = () => {
+ React.unmountComponentAtNode(domElement);
+ delete domElement.__unmount;
+ }
+
+ ret = true;
+ }
+
+ return ret;
+ }
+
+ convertElement(element) {
+ var ret;
+
+ const
+ tag = element.getTag(),
+ props = element.getProps(),
+ reactChildren = Seq.from(element.getChildren()).map(child => child instanceof Element ? this.convertElement(child) : child), // TODO
+ reactProps = Objects.shallowCopy(props instanceof Reader ? props.__data : props); // TODO
+
+ reactProps.children = reactChildren.toArray();
+
+ if (typeof tag === 'string') {
+ ret = React.createElement(tag, reactProps);
+ } else if (tag.prototype instanceof Component) {
+ ret = React.createElement(this.convertComponentClass(tag), reactProps);
+ } else {
+ throw "This should never happen: " + tag;
+ }
+
+ return ret;
+ }
+
+ convertComponentClass(componentClass) {
+ if (!componentClass || !(componentClass.prototype instanceof Component)) {
+ throw new TypeError('[ReactComponentAdaptor.convertComponentClass] '
+ + "First argument 'componentClass' is not really a component class");
+ }
+
+ const
+ typeName = componentClass.getTypeName(),
+ stateTransitions = componentClass.getStateTransitions(),
+ initialState = componentClass.getInitialState(),
+ defaultProps = componentClass.getDefaultProps();
+
+ const ret = function(...args) {
+ ReactComponent.call(this, ...args);
+ this.state = {data: this.__originalComponentClass.getInitialState()};
+ }
+
+ ret.prototype = new ReactComponent();
+ ret.defaultProps = componentClass.getDefaultProps();
+ ret.prototype.__originalComponentClass = componentClass;
+ ret.prototype.__componentAdapter = this;
+ ret.__originalComponentClass = componentClass;
+ ret.displayName = typeName.replace(/^(.*?)([A-Za-z0-9-_\.]+)$/, '$2');
+ return ret;
+ }
+}
+
+class ReactComponent extends React.Component {
+ constructor() {
+ super();
+ this.__cleanupCallback = null;
+ }
+
+ render() {
+ const
+ componentClass = this.__originalComponentClass,
+ stateTransitions = componentClass.getStateTransitions(),
+ view = componentClass.getView(),
+ children = this.props.children,
+ stateController = this.__componentAdapter.createStateController(
+ componentClass,
+ () => this.state.data,
+ state => this.setState({data: state}));
+
+ return this.__componentAdapter.convertElement(view.renderView(DOMBuilder.getDefault(), stateController)(PropsReader.from(this.props), children));
+ }
+
+ componentDidMount() {
+ const view = this.__originalComponentClass.getView();
+
+ this.__cleanupCallback = view.initView(React.findDOMNode(this));
+ }
+
+ componentWillUnmount() {
+ if (typeof this.__cleanupCallback === 'function') {
+ this.__cleanupCallback();
+ this.__cleanupCallback = null;
+ }
+ }
+
+ shouldComponentUpdate(nextProps, nextState) {
+ const componentClass = this.__originalComponentClass;
+ return componentClass.shouldComponentUpdate(this.props, nextProps, this.state.data, nextState.data);
+ }
+}
diff --git a/pool/shard006/JavaScript/0041835_UsersStore.js b/pool/shard006/JavaScript/0041835_UsersStore.js
new file mode 100644
index 0000000000000000000000000000000000000000..c42375ed0cf7b47ba0498c9e876c330591dc8fdf
--- /dev/null
+++ b/pool/shard006/JavaScript/0041835_UsersStore.js
@@ -0,0 +1,86 @@
+import PluginSDK from "PluginSDK";
+
+import {
+ REQUEST_USERS_SUCCESS,
+ REQUEST_USERS_ERROR,
+ SERVER_ACTION
+} from "../constants/ActionTypes";
+import AppDispatcher from "../events/AppDispatcher";
+import { USERS_CHANGE, USERS_REQUEST_ERROR } from "../constants/EventTypes";
+import GetSetBaseStore from "./GetSetBaseStore";
+import UsersActions from "../events/UsersActions";
+import UsersList from "../structs/UsersList";
+
+class UsersStore extends GetSetBaseStore {
+ constructor() {
+ super(...arguments);
+
+ this.getSet_data = {
+ users: []
+ };
+
+ PluginSDK.addStoreConfig({
+ store: this,
+ storeID: this.storeID,
+ events: {
+ success: USERS_CHANGE,
+ error: USERS_REQUEST_ERROR
+ },
+ unmountWhen() {
+ return true;
+ },
+ listenAlways: true
+ });
+
+ this.dispatcherIndex = AppDispatcher.register(payload => {
+ if (payload.source !== SERVER_ACTION) {
+ return false;
+ }
+
+ var action = payload.action;
+ switch (action.type) {
+ case REQUEST_USERS_SUCCESS:
+ this.processUsers(action.data);
+ break;
+ case REQUEST_USERS_ERROR:
+ this.processUsersError(action.data);
+ break;
+ }
+ });
+ }
+
+ fetchUsers() {
+ return UsersActions.fetch(...arguments);
+ }
+
+ getUsers() {
+ return new UsersList({ items: this.getUsersRaw() });
+ }
+
+ getUsersRaw() {
+ return this.get("users");
+ }
+
+ addChangeListener(eventName, callback) {
+ this.on(eventName, callback);
+ }
+
+ removeChangeListener(eventName, callback) {
+ this.removeListener(eventName, callback);
+ }
+
+ processUsers(users) {
+ this.set({ users });
+ this.emit(USERS_CHANGE);
+ }
+
+ processUsersError(error) {
+ this.emit(USERS_REQUEST_ERROR, error);
+ }
+
+ get storeID() {
+ return "users";
+ }
+}
+
+module.exports = new UsersStore();
diff --git a/pool/shard006/JavaScript/0041836_MessageListBinding.qunit.js b/pool/shard006/JavaScript/0041836_MessageListBinding.qunit.js
new file mode 100644
index 0000000000000000000000000000000000000000..8eed98279e2fedc9aa16f9f31c72c80c6b7b0209
--- /dev/null
+++ b/pool/shard006/JavaScript/0041836_MessageListBinding.qunit.js
@@ -0,0 +1,107 @@
+/*global QUnit */
+sap.ui.define(["sap/ui/model/json/JSONModel", "sap/ui/core/message/Message"], function(JSONModel, Message) {
+ "use strict";
+
+ QUnit.module("sap/ui/model/message/MessageListBinding", {
+ afterEach: function() {
+ sap.ui.getCore().getMessageManager().removeAllMessages();
+ },
+ beforeEach: function() {
+ sap.ui.getCore().getMessageManager().removeAllMessages();
+ }
+ });
+
+ var oModel = new JSONModel();
+ var createMessage = function(sText, sTarget, sType) {
+ return new Message({
+ target: sTarget || '/form/firstname',
+ message: sText || "test message",
+ processor: oModel,
+ type: sType || "Error"
+ });
+ };
+
+
+ QUnit.test("test MessageListBinding", function(assert) {
+ var oMessageManager = sap.ui.getCore().getMessageManager();
+ var oModel = oMessageManager.getMessageModel();
+ oMessageManager.addMessages(createMessage("mine", "rel1"));
+ oMessageManager.addMessages(createMessage("two", "rel2"));
+ oMessageManager.addMessages(createMessage("three", "rel3"));
+ oMessageManager.addMessages(createMessage("for", "rel4"));
+ oMessageManager.addMessages(createMessage("fiv", "rel5"));
+ var oMessageListBinding = oModel.bindList("/");
+ var aContexts = oMessageListBinding.getContexts(1, 3);
+ assert.ok(aContexts);
+ assert.equal(aContexts.length, 3);
+
+ });
+
+
+ QUnit.test("test MessageListBinding extended change detection", function(assert) {
+ var done = assert.async();
+ var oMessageManager = sap.ui.getCore().getMessageManager();
+ oMessageManager.addMessages(createMessage("mine", "rel1"));
+ oMessageManager.addMessages(createMessage("two", "rel2"));
+ oMessageManager.addMessages(createMessage("three", "rel3"));
+ oMessageManager.addMessages(createMessage("for", "rel4"));
+ oMessageManager.addMessages(createMessage("for2", "rel4"));
+ oMessageManager.addMessages(createMessage("for3", "rel4"));
+ oMessageManager.addMessages(createMessage("for13", "rel4"));
+ oMessageManager.addMessages(createMessage("for23", "rel4"));
+
+ var oModel = oMessageManager.getMessageModel();
+ var listBinding = oModel.bindList("/");
+ listBinding.enableExtendedChangeDetection();
+
+
+ var contexts = listBinding.getContexts(0, 5);
+ assert.notOk(contexts.diff, "Delta information is initially not available");
+ var currentContexts = listBinding.getCurrentContexts();
+
+ assert.equal(contexts.length, 5, "contexts should contain 5 items");
+ assert.equal(currentContexts.length, 8, "Current contexts should contain 8 items");
+ currentContexts.forEach(function(context, i) {
+ assert.equal(context.getPath(), "/" + i, "ListBinding context");
+ });
+
+ oModel.getData()[3].setMessage("message12");
+ oModel.getData()[5].setMessage("messa121");
+ oModel.getData()[1].setDate(new Date());
+ oMessageManager.addMessages(createMessage("for323", "rel4"));
+
+ var fnContextLengthChangedHandler = function(){
+ listBinding.detachChange(fnContextLengthChangedHandler);
+ currentContexts = listBinding.getCurrentContexts();
+ assert.equal(currentContexts.length, 9, "Current contexts should contain 9 items.");
+ currentContexts.forEach(function(context, i) {
+ assert.equal(context.getPath(), "/" + i, "ListBinding context");
+ });
+ contexts = listBinding.getContexts(0, 5);
+ assert.equal(contexts.diff.length, 14, "Delta information is available");
+
+ oModel.getData()[3].setMessage("newContent");
+ var fnMessageDataChangedHandler = function(){
+ listBinding.detachChange(fnMessageDataChangedHandler);
+ oModel.getData()[3].setMessage("message12");
+ var fnNoChangeHandler = function(){
+ assert.ok(false, "Should not be called, since nothing changed.");
+ };
+ listBinding.attachChange(fnNoChangeHandler);
+ listBinding.checkUpdate();
+ setTimeout(function(){
+ listBinding.detachChange(fnNoChangeHandler);
+ done();
+ }, 0);
+ };
+ listBinding.attachChange(fnMessageDataChangedHandler);
+ listBinding.checkUpdate();
+
+ };
+
+ listBinding.attachChange(fnContextLengthChangedHandler);
+ listBinding.checkUpdate();
+
+
+ });
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041844_retrospectivas.server.routes.js b/pool/shard006/JavaScript/0041844_retrospectivas.server.routes.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a35dedbf1383ab0279881ecd1075a7e7d8c5958
--- /dev/null
+++ b/pool/shard006/JavaScript/0041844_retrospectivas.server.routes.js
@@ -0,0 +1,19 @@
+'use strict';
+
+module.exports = function(app) {
+ var users = require('../../app/controllers/users.server.controller');
+ var retrospectivas = require('../../app/controllers/retrospectivas.server.controller');
+
+ // Retrospectivas Routes
+ app.route('/retrospectivas')
+ .get(retrospectivas.list)
+ .post(users.requiresLogin, retrospectivas.create);
+
+ app.route('/retrospectivas/:retrospectivaId')
+ .get(retrospectivas.read)
+ .put(users.requiresLogin, retrospectivas.hasAuthorization, retrospectivas.update)
+ .delete(users.requiresLogin, retrospectivas.hasAuthorization, retrospectivas.delete);
+
+ // Finish by binding the Retrospectiva middleware
+ app.param('retrospectivaId', retrospectivas.retrospectivaByID);
+};
diff --git a/pool/shard006/JavaScript/0041848_screener.js b/pool/shard006/JavaScript/0041848_screener.js
new file mode 100644
index 0000000000000000000000000000000000000000..1c892aa5cb8f3388150c6d6f0303a8b904c9fde7
--- /dev/null
+++ b/pool/shard006/JavaScript/0041848_screener.js
@@ -0,0 +1,23 @@
+var React = require('react');
+var PropTypes = require('prop-types');
+var extend = require('lodash/extend');
+
+function Screener(p) {
+ return React.createElement('div', null, p.children);
+}
+
+Screener.propTypes = {
+ children: PropTypes.any,
+ steps: PropTypes.array,
+ isScreenerComponent: PropTypes.bool
+};
+
+Screener.defaultProps = {
+ isScreenerComponent: true
+};
+
+exports.default = Screener;
+exports.Steps = require('screener-runner/src/steps');
+exports.Keys = require('screener-runner/src/keys');
+
+module.exports = extend(exports.default, exports);
diff --git a/pool/shard006/JavaScript/0041849_showStacks.js b/pool/shard006/JavaScript/0041849_showStacks.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf0821525af4c60cc417e2cdb04a0cd286be22c3
--- /dev/null
+++ b/pool/shard006/JavaScript/0041849_showStacks.js
@@ -0,0 +1,44 @@
+/**
+ * Copyright 2015, Xianfeng Yuan.
+ * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
+ */
+import debugLib from 'debug';
+import config from '../configs/config';
+import StackStore from '../stores/StackStore';
+
+const debug = debugLib('StackAction');
+
+export default function (context, route, done) {
+ let routeConfig = route.config || {};
+ let pageTitle = routeConfig.pageTitle || (routeConfig.pageTitlePrefix + ' | ' + config.appTitle);
+ let service = routeConfig.service;
+
+ debug(service);
+
+ let stackFromCache = context.getStore(StackStore).get(service);
+
+ if (stackFromCache) {
+ context.dispatch('RECEIVE_STACK_SUCCESS', stackFromCache);
+ context.dispatch('UPDATE_PAGE_TITLE', {
+ pageTitle: pageTitle
+ });
+ return done();
+ }
+
+ // Load from service
+ context.service.read('stacks', {service: service}, {}, function (err, data) {
+ if (err) {
+ return done(err);
+ }
+
+ if (!data) {
+ return done('data error');
+ }
+
+ context.dispatch('RECEIVE_STACK_SUCCESS', data);
+ context.dispatch('UPDATE_PAGE_TITLE', {
+ pageTitle: pageTitle
+ });
+ done();
+ });
+}
diff --git a/pool/shard006/JavaScript/0041851_fixed_element.js b/pool/shard006/JavaScript/0041851_fixed_element.js
new file mode 100644
index 0000000000000000000000000000000000000000..1efa8bce6de29e1ab90936eb5598d4e99914edbf
--- /dev/null
+++ b/pool/shard006/JavaScript/0041851_fixed_element.js
@@ -0,0 +1,31 @@
+var _ = require('lodash');
+var $ = require('jquery');
+
+var app = require('ui/modules').get('apps/timelion', []);
+app.directive('fixedElementRoot', function ($timeout) {
+ return {
+ restrict: 'A',
+ link: function ($scope, $elem, attrs) {
+ var fixedAt;
+ $(window).bind('scroll', function () {
+ var fixed = $('[fixed-element]', $elem);
+ var body = $('[fixed-element-body]', $elem);
+ var top = fixed.offset().top;
+
+ if ($(window).scrollTop() > top) {
+ // This is a gross hack, but its better than it was. I guess
+ fixedAt = $(window).scrollTop();
+ fixed.addClass(fixed.attr('fixed-element'));
+ body.addClass(fixed.attr('fixed-element-body'));
+ body.css({top: fixed.height()});
+ }
+
+ if ($(window).scrollTop() < fixedAt) {
+ fixed.removeClass(fixed.attr('fixed-element'));
+ body.removeClass(fixed.attr('fixed-element-body'));
+ body.removeAttr('style');
+ }
+ });
+ }
+ };
+});
diff --git a/pool/shard006/JavaScript/0041854_Animation.js b/pool/shard006/JavaScript/0041854_Animation.js
new file mode 100644
index 0000000000000000000000000000000000000000..2a004aa3d80694a28b8b3be7cc8f4257bc92fbb4
--- /dev/null
+++ b/pool/shard006/JavaScript/0041854_Animation.js
@@ -0,0 +1,63 @@
+(function () {
+ var Animation = YYC.Class({
+ Init: function (config) {
+ this._frames = YYC.Tool.array.clone(config);
+ this._init();
+ },
+ Private: {
+ // Animation 包含的Frame, 类型:数组
+ _frames: null,
+ // 包含的Frame数目
+ _frameCount: -1,
+ // 所使用的图片id(在ImgCache中存放的Key), 字符串类型.
+ _img: null,
+ _currentFrame: null,
+ _currentFrameIndex: -1,
+ _currentFramePlayed: -1,
+
+ _init: function () {
+ this._frameCount = this._frames.length;
+
+ this.setCurrentFrame(0);
+ }
+ },
+ Public: {
+ setCurrentFrame: function (index) {
+ this._currentFrameIndex = index;
+ this._currentFrame = this._frames[index];
+ this._currentFramePlayed = 0;
+ },
+ // 更新Animation状态. deltaTime表示时间的变化量.
+ update: function (deltaTime) {
+ //如果没有duration属性(表示只有一帧),则返回
+ if (this._currentFrame.duration === undefined) {
+ return;
+ }
+
+ //判断当前Frame是否已经播放完成,
+ if (this._currentFramePlayed >= this._currentFrame.duration) {
+ //播放下一帧
+
+ if (this._currentFrameIndex >= this._frameCount - 1) {
+ //当前是最后一帧,则播放第0帧
+ this._currentFrameIndex = 0;
+ } else {
+ //播放下一帧
+ this._currentFrameIndex++;
+ }
+ //设置当前帧信息
+ this.setCurrentFrame(this._currentFrameIndex);
+
+ } else {
+ //增加当前帧的已播放时间.
+ this._currentFramePlayed += deltaTime;
+ }
+ },
+ getCurrentFrame: function () {
+ return this._currentFrame;
+ }
+ }
+ });
+
+ window.Animation = Animation;
+}());
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041855_default.js b/pool/shard006/JavaScript/0041855_default.js
new file mode 100644
index 0000000000000000000000000000000000000000..df24e9027ba92f23c146cc590cdef8109b79543d
--- /dev/null
+++ b/pool/shard006/JavaScript/0041855_default.js
@@ -0,0 +1,102 @@
+ngDefine('camunda.common.pages', function(module) {
+
+ var ResponseErrorHandler = function(Notifications, Authentication, $location) {
+
+ this.handlerFn = function(event, responseError) {
+ var status = responseError.status,
+ data = responseError.data;
+
+ Notifications.clear({ type: "error" });
+
+ switch (status) {
+ case 500:
+ if (data && data.message) {
+ Notifications.addError({ status: "Error", message: data.message, exceptionType: data.exceptionType });
+ } else {
+ Notifications.addError({ status: "Error", message: "A problem occurred: Try to refresh the view or login and out of the application. If the problem persists, contact your administrator." });
+ }
+ break;
+
+ case 0:
+ Notifications.addError({ status: "Request Timeout", message: "Your request timed out. Try refreshing the page." });
+ break;
+
+ case 401:
+ Authentication.clear();
+ $location.path("/login");
+ break;
+
+ case 403:
+ if(!!data.type && data.type=="AuthorizationException") {
+ Notifications.addError({ status: "Error", message : "You are unauthorized to "
+ + data.permissionName.toLowerCase()+" "
+ + data.resourceName.toLowerCase()
+ + (!!data.resourceId ? " " + data.resourceId : "s")
+ + "." });
+ break;
+ }
+
+ default:
+ Notifications.addError({ status: "Error", message : "A problem occurred: Try to refresh the view or login and out of the application. If the problem persists, contact your administrator." });
+ }
+ };
+ };
+
+ var DefaultController = [ '$scope', '$rootScope', 'Notifications', 'Authentication', '$location', function($scope, $rootScope, Notifications, Authentication, $location) {
+ $rootScope.$on("responseError", new ResponseErrorHandler(Notifications, Authentication, $location).handlerFn);
+
+ }];
+
+ var ProcessEngineSelectionController = [
+ '$scope', '$http', '$location', '$window', 'Uri', 'Notifications',
+ function($scope, $http, $location, $window, Uri, Notifications) {
+
+ var current = Uri.appUri(':engine');
+ var enginesByName = {};
+
+ $http.get(Uri.appUri('engine://engine/')).then(function(response) {
+ $scope.engines = response.data;
+
+ angular.forEach($scope.engines , function(engine) {
+ enginesByName[engine.name] = engine;
+ });
+
+ $scope.currentEngine = enginesByName[current];
+
+ if (!$scope.currentEngine) {
+ Notifications.addError({ status: 'Not found', message: 'The process engine you are trying to access does not exist' });
+ $location.path('/')
+ }
+ });
+
+ $scope.$watch('currentEngine', function(engine) {
+ if (engine && current !== engine.name) {
+ $window.location.href = Uri.appUri("app://../" + engine.name + "/");
+ }
+ });
+ }];
+
+ var NavigationController = [ '$scope', '$location', function($scope, $location) {
+
+ $scope.activeClass = function(link) {
+ var path = $location.absUrl();
+ return path.indexOf(link) != -1 ? "active" : "";
+ };
+ }];
+
+ var AuthenticationController = [
+ '$scope', 'Notifications', 'Authentication', '$location',
+ function($scope, Notifications, Authentication, $location) {
+
+ $scope.logout = function() {
+ Authentication.logout();
+ $location.path("/");
+ }
+ }];
+
+ module
+ .controller('DefaultController', DefaultController)
+ .controller('ProcessEngineSelectionController', ProcessEngineSelectionController)
+ .controller('AuthenticationController', AuthenticationController)
+ .controller('NavigationController', NavigationController);
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041857_users.js b/pool/shard006/JavaScript/0041857_users.js
new file mode 100644
index 0000000000000000000000000000000000000000..30db1c2d65c8ae3e74d4be9f9f97a40ded3d59f2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041857_users.js
@@ -0,0 +1,169 @@
+let request = require('supertest');
+
+let { db, pgp } = require('../database');
+
+function cleandb() {
+
+ if (process.env.NODE_ENV === 'test') {
+
+ db.none('DELETE FROM users');
+ db.none('ALTER SEQUENCE users_id_seq RESTART WITH 1');
+
+ }
+
+}
+
+describe('Testing users methods', function () {
+
+ let server;
+ let token, user_id;
+
+ before(cleandb);
+
+ beforeEach('Clean server', function () {
+ delete require.cache[require.resolve('./appTest')];
+ server = require('./appTest');
+ });
+
+ afterEach(function (done) {
+ server.close(done);
+ });
+
+ after(() => {
+ cleandb();
+ pgp.end();
+ });
+
+ it('Register a new user', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'login': 'userTest',
+ 'email': 'user@test.org',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(201, done);
+ });
+
+ it('Register a new user no email', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'login': 'userTest1',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(400, done);
+ });
+
+ it('Register a new user no login', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'email': 'user@test.org',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(400, done);
+ });
+
+ it('Register a new user short password', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'login': 'userTest2',
+ 'email': 'user2@test.org',
+ 'password': 'foo'
+ })
+ .set('Accept', 'application/json')
+ .expect(400, done);
+ });
+
+ it('Register a new user duplicated login', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'login': 'userTest',
+ 'email': 'user2@test.org',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(400, done);
+ });
+
+ it('Register a new user duplicated email', (done) => {
+ request(server)
+ .post('/register')
+ .send({
+ 'login': 'user1Test',
+ 'email': 'user@test.org',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(400, done);
+ });
+
+ it('Login with good informations', (done) => {
+ request(server)
+ .post('/login')
+ .send({
+ 'login': 'userTest',
+ 'password': 'fooBar'
+ })
+ .set('Accept', 'application/json')
+ .expect(200, (err, res) => {
+ if (res && res.body && res.body.token) {
+ token = res.body.token;
+ user_id = res.body.user_id;
+ }
+ done();
+ });
+ });
+
+ it('Login with bad informations', (done) => {
+ request(server)
+ .post('/login')
+ .send({
+ 'login': 'userTest',
+ 'password': 'fooBartol'
+ })
+ .set('Accept', 'application/json')
+ .expect(401, done);
+ });
+
+ it('Update user good informations', (done) => {
+ request(server)
+ .put('/users/' + user_id)
+ .set('Authorization', 'Bearer ' + token)
+ .send({
+ 'login': 'userTest2',
+ })
+ .expect(200, done);
+ });
+
+ it('Update user bad login', (done) => {
+ request(server)
+ .put('/users/' + user_id)
+ .set('Authorization', 'Bearer ' + token)
+ .send({
+ 'login': 'user',
+ })
+ .expect(400, done);
+ });
+
+ it('Delete a user not authorized', (done) => {
+ request(server)
+ .delete('/users/' + (user_id + 1))
+ .set('Authorization', 'Bearer ' + token)
+ .expect(403, done);
+ });
+
+ it('Delete a user', (done) => {
+ request(server)
+ .delete('/users/' + user_id)
+ .set('Authorization', 'Bearer ' + token)
+ .expect(200, done);
+ });
+
+});
diff --git a/pool/shard006/JavaScript/0041859_clean.js b/pool/shard006/JavaScript/0041859_clean.js
new file mode 100644
index 0000000000000000000000000000000000000000..479b4f5a2d4cd85686aa6a5aa478721edd1a2cc2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041859_clean.js
@@ -0,0 +1,16 @@
+/*eslint-env node*/
+var gulp = require('gulp');
+var rimraf = require('rimraf');
+
+// Cleans the build directory
+gulp.task('clean', function(cb) {
+ rimraf('./build', cb);
+});
+
+gulp.task('clean:templates', function(cb){
+ rimraf('./build/assets/js/templates.js', cb);
+});
+
+gulp.task('clean:package', function(cb){
+ rimraf('./tmp/lucidworks-view', cb);
+});
diff --git a/pool/shard006/JavaScript/0041860_timing-trace-saver-test.js b/pool/shard006/JavaScript/0041860_timing-trace-saver-test.js
new file mode 100644
index 0000000000000000000000000000000000000000..cceaa448660656b317c66b816732edcfd24a3b5f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041860_timing-trace-saver-test.js
@@ -0,0 +1,58 @@
+/**
+ * @license Copyright 2018 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.
+ */
+'use strict';
+
+/* eslint-env jest */
+
+/* eslint-disable no-console */
+
+const {generateTraceEvents, createTraceString} = require('../../lib/timing-trace-saver.js');
+
+const mockEntries = [{
+ startTime: 650,
+ name: 'lh:init:config',
+ duration: 210,
+ entryType: 'measure',
+},
+{
+ startTime: 870,
+ name: 'lh:runner:run',
+ duration: 120,
+ entryType: 'measure',
+},
+{
+ startTime: 990,
+ name: 'lh:runner:auditing',
+ duration: 750,
+ entryType: 'measure',
+},
+{
+ startTime: 1010,
+ name: 'lh:audit:is-on-https',
+ duration: 10,
+ entryType: 'measure',
+},
+];
+
+describe('generateTraceEvents', () => {
+ it('generates a pair of trace events', () => {
+ const events = generateTraceEvents([mockEntries[0]]);
+ expect(events.slice(0, 2)).toMatchSnapshot();
+ });
+});
+
+describe('createTraceString', () => {
+ it('creates a real trace', () => {
+ const jsonStr = createTraceString({
+ timing: {
+ entries: mockEntries,
+ },
+ });
+ const traceJson = JSON.parse(jsonStr);
+ const eventsWithoutMetadata = traceJson.traceEvents.filter(e => e.cat !== '__metadata');
+ expect(eventsWithoutMetadata).toMatchSnapshot();
+ });
+});
diff --git a/pool/shard006/JavaScript/0041863_commit-version.js b/pool/shard006/JavaScript/0041863_commit-version.js
new file mode 100644
index 0000000000000000000000000000000000000000..c83ab12a8a61e85b21015dc05b952126b1bcf24e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041863_commit-version.js
@@ -0,0 +1,108 @@
+'use strict';
+
+const simpleGit = require('simple-git')();
+const RSVP = require('rsvp');
+const exec = require('child_process').execSync;
+const EOL = require('os').EOL;
+
+const addFiles = RSVP.denodeify(simpleGit.add.bind(simpleGit));
+const commit = RSVP.denodeify(simpleGit.commit.bind(simpleGit));
+const addTag = RSVP.denodeify(simpleGit.addAnnotatedTag.bind(simpleGit));
+const push = RSVP.denodeify(simpleGit.push.bind(simpleGit));
+
+/*
+ Uses a `versioner` to read the current version and write new versions to files.
+
+ @class Task.CommitVersion
+ @params {Object} options `{ branch, remote, formatter, log }`
+ @public
+*/
+class CommitVersion {
+ constructor(options) {
+ this.branch = options.branch;
+ this.remote = options.remote;
+ this.formatter = options.formatter;
+ this.log = options.log;
+ }
+
+ /**
+ @method stageFiles
+ @param {Array} files
+ @public
+ */
+ stageFiles(files) {
+ return addFiles(files);
+ }
+
+ /**
+ @method commitVersion
+ @param {String|Number} version
+ @returns {Promise}
+ @public
+ */
+ commitVersion(version, message) {
+ const formattedVersion = this.formatter(version);
+ const remote = this._remote();
+ const branch = this._branch();
+
+ message = this._formatMessage(message, { version, formattedVersion });
+
+ this.log(`Begin committing "${message}" to ${remote} ${branch}`, {
+ verbose: true
+ });
+
+ return commit(message)
+ .then(() => push(remote, branch))
+ .then(() => {
+ this.log(`Done committing "${message}" to ${remote} ${branch}`);
+ });
+ }
+
+ /**
+ @method tagVersion
+ @param {String|Number} version
+ @returns {Promise}
+ @public
+ */
+ tagVersion(version, annotation) {
+ const formattedVersion = this.formatter(version);
+
+ annotation = this._formatMessage(annotation, { version, formattedVersion });
+
+ this.log(`Begin tagging w/ message "${annotation}"`, { verbose: true });
+
+ return addTag(formattedVersion, annotation)
+ .then(() => push(this._remote(), formattedVersion))
+ .then(() => {
+ this.log(`Done tagging "${formattedVersion}"`);
+
+ return formattedVersion;
+ });
+ }
+
+ _formatMessage(message, options = {}) {
+ return (message || '')
+ .replace('%V', options.version)
+ .replace('%FV', options.formattedVersion);
+ }
+
+ /**
+ @method _remote
+ @private
+ */
+ _remote() {
+ return this.remote;
+ }
+
+ /**
+ @method _branch
+ @private
+ */
+ _branch() {
+ return this.branch ||
+ exec('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' })
+ .replace(EOL, '');
+ }
+}
+
+module.exports = CommitVersion;
diff --git a/pool/shard006/JavaScript/0041868_cli.js b/pool/shard006/JavaScript/0041868_cli.js
new file mode 100644
index 0000000000000000000000000000000000000000..27aeefad7bb20ab7ec4194635eb56219bac5da46
--- /dev/null
+++ b/pool/shard006/JavaScript/0041868_cli.js
@@ -0,0 +1,66 @@
+var Builder, console, exists, fs, get_config_path, get_options_parser, path;
+
+path = require("path");
+
+fs = require("fs");
+
+console = require("./console");
+
+Builder = require("./").Builder;
+
+exists = function(filepath) {
+ var stats;
+ console.log("Trying to find " + filepath);
+ if (!fs.existsSync(filepath)) {
+ return;
+ }
+ stats = fs.statSync(filepath);
+ if (!stats.isFile()) {
+ return;
+ }
+ return filepath;
+};
+
+get_config_path = function(arg) {
+ var cwd, _ref, _ref1, _ref2;
+ cwd = process.cwd();
+ return (_ref = (_ref1 = (_ref2 = exists(path.resolve(cwd, arg))) != null ? _ref2 : exists(path.resolve(cwd, arg, "spa.json"))) != null ? _ref1 : exists(path.resolve(cwd, arg, "spa.yaml"))) != null ? _ref : exists(path.resolve(cwd, arg, "spa.yml"));
+};
+
+get_options_parser = function() {
+ return require("nomnom").script('spa').options({
+ config: {
+ abbr: 'c',
+ type: 'string',
+ metavar: 'FILE',
+ help: 'Path to build config file',
+ "default": '.'
+ },
+ silent: {
+ abbr: 's',
+ flag: true,
+ "default": false,
+ help: 'Suppress all console output.'
+ }
+ });
+};
+
+exports.run = function() {
+ var argv, builder, error, options_parser;
+ options_parser = get_options_parser();
+ argv = options_parser.parse(process.argv);
+ console.setEnabled(!argv.silent);
+ path = get_config_path(argv.config);
+ if (path == null) {
+ console.log("Can't locate config file");
+ return;
+ }
+ console.log("Reading config from " + path);
+ builder = Builder.from_config(path);
+ try {
+ return builder.build();
+ } catch (_error) {
+ error = _error;
+ return console.error(error.toString());
+ }
+};
diff --git a/pool/shard006/JavaScript/0041869_output.js b/pool/shard006/JavaScript/0041869_output.js
new file mode 100644
index 0000000000000000000000000000000000000000..33e00ec8dd14d29c44987401b974f5b4c6f11e38
--- /dev/null
+++ b/pool/shard006/JavaScript/0041869_output.js
@@ -0,0 +1,33 @@
+import React from 'react';
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+
+const Output = props => {
+ // Display first 50 results from output
+ const finalOutput = props.output.slice(0,50).map(
+ (line, i) => i < 50 ? {line}
: null
+ );
+
+ //Show shortened output only if there are elements to show
+ return (
+
+ {
+ props.output.length > 0 ?
+
{finalOutput} :
+ null
+ }
+
+ );
+}
+
+const mapStateToProps = state => ({
+ output: state.reducer.output
+})
+
+const mapDispatchToProps = dispatch => bindActionCreators({
+}, dispatch)
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(Output)
diff --git a/pool/shard006/JavaScript/0041870_create_test.js b/pool/shard006/JavaScript/0041870_create_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..41d0b952d3017a6028b28cd5e73db28c1201b2f0
--- /dev/null
+++ b/pool/shard006/JavaScript/0041870_create_test.js
@@ -0,0 +1,29 @@
+/**
+ * Created by yurik on 07.08.16.
+ */
+function createTest() {
+ var name = "business_c_token";
+ var token=getCookie(name);
+ // alert(token);
+ var json = '{"token":"'+ token +'", "body":"'+ document.getElementById("c_test_name").value +'"}';
+ var xhr = new XMLHttpRequest();
+ xhr.open('POST',"http://127.0.0.1:5000/api/v1.0/create/test" , false);
+ xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
+ // send the collected data as JSON
+ xhr.send(JSON.stringify(json));
+}
+
+function getCookie(cname) {
+ var name = cname + "=";
+ var ca = document.cookie.split(';');
+ for(var i = 0; i 0) {
+ //Util.warn(Util.getMessage("warning.title"), Util.getMessage("document.missing.external.resources", this.missedFilePaths.join("\n\t● ")), Util.getMessage("button.cancel.close"));
+ alert(Util.getMessage("document.missing.external.resources", this.missedFilePaths.join("\n\t● ")));
+ this.missedFilePaths = [];
+ }
+ if (this.badImageDataFound) {
+ //Util.error(Util.getMessage("error.title"), Util.getMessage("error.bad.image.data.was.found.in.the.document"), Util.getMessage("button.cancel.close"));
+ alert(Util.getMessage("error.bad.image.data.was.found.in.the.document"));
+ this.badImageDataFound = false;
+ }
+ }
+}
+
+XMLDocumentPersister.hooks.push(relativeHRefHook);
diff --git a/pool/shard006/JavaScript/0041879_updateValidators.js b/pool/shard006/JavaScript/0041879_updateValidators.js
new file mode 100644
index 0000000000000000000000000000000000000000..31161ea19df1728794a5dfacd6138e30c7715642
--- /dev/null
+++ b/pool/shard006/JavaScript/0041879_updateValidators.js
@@ -0,0 +1,101 @@
+/*!
+ * Module dependencies.
+ */
+
+var Mixed = require('../schema/mixed');
+var ValidationError = require('../error/validation');
+var async = require('async');
+var flatten = require('./common').flatten;
+var modifiedPaths = require('./common').modifiedPaths;
+
+/**
+ * Applies validators and defaults to update and findOneAndUpdate operations,
+ * specifically passing a null doc as `this` to validators and defaults
+ *
+ * @param {Query} query
+ * @param {Schema} schema
+ * @param {Object} castedDoc
+ * @param {Object} options
+ * @method runValidatorsOnUpdate
+ * @api private
+ */
+
+module.exports = function(query, schema, castedDoc, options) {
+ var keys = Object.keys(castedDoc || {});
+ var updatedKeys = {};
+ var updatedValues = {};
+ var numKeys = keys.length;
+ var hasDollarUpdate = false;
+ var modified = {};
+
+ for (var i = 0; i < numKeys; ++i) {
+ if (keys[i].charAt(0) === '$') {
+ modifiedPaths(castedDoc[keys[i]], '', modified);
+ var flat = flatten(castedDoc[keys[i]]);
+ var paths = Object.keys(flat);
+ var numPaths = paths.length;
+ for (var j = 0; j < numPaths; ++j) {
+ var updatedPath = paths[j].replace('.$.', '.0.');
+ updatedPath = updatedPath.replace(/\.\$$/, '.0');
+ if (keys[i] === '$set' || keys[i] === '$setOnInsert') {
+ updatedValues[updatedPath] = flat[paths[j]];
+ } else if (keys[i] === '$unset') {
+ updatedValues[updatedPath] = undefined;
+ }
+ updatedKeys[updatedPath] = true;
+ }
+ hasDollarUpdate = true;
+ }
+ }
+
+ if (!hasDollarUpdate) {
+ modifiedPaths(castedDoc, '', modified);
+ updatedValues = flatten(castedDoc);
+ updatedKeys = Object.keys(updatedValues);
+ }
+
+ var updates = Object.keys(updatedValues);
+ var numUpdates = updates.length;
+ var validatorsToExecute = [];
+ var validationErrors = [];
+ function iter(i) {
+ var schemaPath = schema._getSchema(updates[i]);
+ if (schemaPath) {
+ // gh-4305: `_getSchema()` will report all sub-fields of a 'Mixed' path
+ // as 'Mixed', so avoid double validating them.
+ if (schemaPath instanceof Mixed && schemaPath.$fullPath !== updates[i]) {
+ return;
+ }
+
+ validatorsToExecute.push(function(callback) {
+ schemaPath.doValidate(
+ updatedValues[updates[i]],
+ function(err) {
+ if (err) {
+ err.path = updates[i];
+ validationErrors.push(err);
+ }
+ callback(null);
+ },
+ options && options.context === 'query' ? query : null,
+ {updateValidator: true});
+ });
+ }
+ }
+ for (i = 0; i < numUpdates; ++i) {
+ iter(i);
+ }
+
+ return function(callback) {
+ async.parallel(validatorsToExecute, function() {
+ if (validationErrors.length) {
+ var err = new ValidationError(null);
+ for (var i = 0; i < validationErrors.length; ++i) {
+ err.errors[validationErrors[i].path] = validationErrors[i];
+ }
+ return callback(err);
+ }
+ callback(null);
+ });
+ };
+};
diff --git a/pool/shard006/JavaScript/0041882_calculator.js b/pool/shard006/JavaScript/0041882_calculator.js
new file mode 100644
index 0000000000000000000000000000000000000000..4bd2225dbadc69c97d8cfb66f09fc79929013b79
--- /dev/null
+++ b/pool/shard006/JavaScript/0041882_calculator.js
@@ -0,0 +1,95 @@
+const ERROR_TYPES = {
+ INVALID_PARAM: 'Invalid parameters',
+ INFINITY: 'Résultat trop grand pour être affiché',
+ DIVISION_BY_ZERO: 'Division par zéro',
+ MODULO_BY_ZERO: 'Modulo par zéro'
+}
+
+function filterFloat(value) {
+ if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value)) {
+ return Number(value);
+ }
+ return NaN;
+}
+
+class Calculator {
+ add(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = a + b;
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+
+ sub(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = a - b;
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+
+ div(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ if (b === 0) {
+ return ERROR_TYPES.DIVISION_BY_ZERO;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = a / b;
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+
+ mult(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = a * b;
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+
+ mod(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ if (b === 0) {
+ return ERROR_TYPES.MODULO_BY_ZERO;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = a % b;
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+
+ pow(op1, op2) {
+ if (isNaN(filterFloat(op1)) || isNaN(filterFloat(op2))) {
+ return ERROR_TYPES.INVALID_PARAM;
+ }
+ const a = parseFloat(op1);
+ const b = parseFloat(op2);
+ const res = Math.pow(a, b);
+
+ return isFinite(res) ? res : ERROR_TYPES.INFINITY;
+ }
+}
+
+const singleton = new Calculator();
+
+export {
+ ERROR_TYPES,
+ singleton as calculator,
+ Calculator
+}
diff --git a/pool/shard006/JavaScript/0041892_utils.js b/pool/shard006/JavaScript/0041892_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..059ab7fe9269da151e1bc8063a4e3fccfb677521
--- /dev/null
+++ b/pool/shard006/JavaScript/0041892_utils.js
@@ -0,0 +1,34 @@
+
+function showClock(div)
+{
+ var today=new Date();
+ var h=today.getHours();
+ var m=today.getMinutes();
+ // add a zero in front of numbers<10
+ if (m<10){
+ m="0"+m
+ }
+ div.innerHTML=h+":"+m;
+ t=setTimeout(function(){
+ showClock(div)
+ },30000);
+}
+
+
+function checkSubmit(){
+ var fr=document.forms[0]
+ if (fr.uname.value=="") {
+ alert ("El nombre no puede quedar en blanco")
+ return false
+ }
+ if (fr.surname.value==""){
+ alert ("El apellido no puede quedar en blanco")
+ return false
+ }
+ return true
+}
+
+
+
+
+
diff --git a/pool/shard006/JavaScript/0041895_AnaglyphEffect.js b/pool/shard006/JavaScript/0041895_AnaglyphEffect.js
new file mode 100644
index 0000000000000000000000000000000000000000..e61fd19035e2279f8724e9a614289c4e6dee09b2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041895_AnaglyphEffect.js
@@ -0,0 +1,168 @@
+import {
+ LinearFilter,
+ Matrix3,
+ Mesh,
+ NearestFilter,
+ OrthographicCamera,
+ PlaneGeometry,
+ RGBAFormat,
+ Scene,
+ ShaderMaterial,
+ StereoCamera,
+ WebGLRenderTarget
+} from 'three';
+
+class AnaglyphEffect {
+
+ constructor( renderer, width = 512, height = 512 ) {
+
+ // Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4
+
+ this.colorMatrixLeft = new Matrix3().fromArray( [
+ 0.456100, - 0.0400822, - 0.0152161,
+ 0.500484, - 0.0378246, - 0.0205971,
+ 0.176381, - 0.0157589, - 0.00546856
+ ] );
+
+ this.colorMatrixRight = new Matrix3().fromArray( [
+ - 0.0434706, 0.378476, - 0.0721527,
+ - 0.0879388, 0.73364, - 0.112961,
+ - 0.00155529, - 0.0184503, 1.2264
+ ] );
+
+ const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
+
+ const _scene = new Scene();
+
+ const _stereo = new StereoCamera();
+
+ const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat };
+
+ const _renderTargetL = new WebGLRenderTarget( width, height, _params );
+ const _renderTargetR = new WebGLRenderTarget( width, height, _params );
+
+ const _material = new ShaderMaterial( {
+
+ uniforms: {
+
+ 'mapLeft': { value: _renderTargetL.texture },
+ 'mapRight': { value: _renderTargetR.texture },
+
+ 'colorMatrixLeft': { value: this.colorMatrixLeft },
+ 'colorMatrixRight': { value: this.colorMatrixRight }
+
+ },
+
+ vertexShader: [
+
+ 'varying vec2 vUv;',
+
+ 'void main() {',
+
+ ' vUv = vec2( uv.x, uv.y );',
+ ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
+
+ '}'
+
+ ].join( '\n' ),
+
+ fragmentShader: [
+
+ 'uniform sampler2D mapLeft;',
+ 'uniform sampler2D mapRight;',
+ 'varying vec2 vUv;',
+
+ 'uniform mat3 colorMatrixLeft;',
+ 'uniform mat3 colorMatrixRight;',
+
+ // These functions implement sRGB linearization and gamma correction
+
+ 'float lin( float c ) {',
+ ' return c <= 0.04045 ? c * 0.0773993808 :',
+ ' pow( c * 0.9478672986 + 0.0521327014, 2.4 );',
+ '}',
+
+ 'vec4 lin( vec4 c ) {',
+ ' return vec4( lin( c.r ), lin( c.g ), lin( c.b ), c.a );',
+ '}',
+
+ 'float dev( float c ) {',
+ ' return c <= 0.0031308 ? c * 12.92',
+ ' : pow( c, 0.41666 ) * 1.055 - 0.055;',
+ '}',
+
+
+ 'void main() {',
+
+ ' vec2 uv = vUv;',
+
+ ' vec4 colorL = lin( texture2D( mapLeft, uv ) );',
+ ' vec4 colorR = lin( texture2D( mapRight, uv ) );',
+
+ ' vec3 color = clamp(',
+ ' colorMatrixLeft * colorL.rgb +',
+ ' colorMatrixRight * colorR.rgb, 0., 1. );',
+
+ ' gl_FragColor = vec4(',
+ ' dev( color.r ), dev( color.g ), dev( color.b ),',
+ ' max( colorL.a, colorR.a ) );',
+
+ '}'
+
+ ].join( '\n' )
+
+ } );
+
+ const _mesh = new Mesh( new PlaneGeometry( 2, 2 ), _material );
+ _scene.add( _mesh );
+
+ this.setSize = function ( width, height ) {
+
+ renderer.setSize( width, height );
+
+ const pixelRatio = renderer.getPixelRatio();
+
+ _renderTargetL.setSize( width * pixelRatio, height * pixelRatio );
+ _renderTargetR.setSize( width * pixelRatio, height * pixelRatio );
+
+ };
+
+ this.render = function ( scene, camera ) {
+
+ const currentRenderTarget = renderer.getRenderTarget();
+
+ scene.updateMatrixWorld();
+
+ if ( camera.parent === null ) camera.updateMatrixWorld();
+
+ _stereo.update( camera );
+
+ renderer.setRenderTarget( _renderTargetL );
+ renderer.clear();
+ renderer.render( scene, _stereo.cameraL );
+
+ renderer.setRenderTarget( _renderTargetR );
+ renderer.clear();
+ renderer.render( scene, _stereo.cameraR );
+
+ renderer.setRenderTarget( null );
+ renderer.render( _scene, _camera );
+
+ renderer.setRenderTarget( currentRenderTarget );
+
+ };
+
+ this.dispose = function () {
+
+ if ( _renderTargetL ) _renderTargetL.dispose();
+ if ( _renderTargetR ) _renderTargetR.dispose();
+ if ( _mesh ) _mesh.geometry.dispose();
+ if ( _material ) _material.dispose();
+
+ };
+
+ }
+
+}
+
+export { AnaglyphEffect };
diff --git a/pool/shard006/JavaScript/0041898_index.js b/pool/shard006/JavaScript/0041898_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..2098ce09872e1a8eb2b9ab33316e389ee48c9157
--- /dev/null
+++ b/pool/shard006/JavaScript/0041898_index.js
@@ -0,0 +1,45 @@
+import { Component } from "react";
+import template from "./template.jsx";
+import merge from "lodash/merge";
+
+export default class Auth extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ oauth_token: null,
+ pin: null
+ };
+ props.token.subscribe(this.onTokenFetch.bind(this));
+ }
+
+ onTokenFetch(oauth_token) {
+ this.setState({
+ oauth_token
+ });
+ }
+
+ openTwitter() {
+ var url = "https://api.twitter.com/oauth/authorize?oauth_token=";
+ url += encodeURIComponent(this.state.oauth_token);
+ window.shell.openExternal(url);
+ }
+
+ changePIN(evt, pin) {
+ this.setState({
+ oauth_token: this.state.oauth_token,
+ pin
+ });
+ }
+
+ submitPIN() {
+ this.props.onSubmit(this.state.oauth_token, this.state.pin);
+ }
+
+ render() {
+ if (this.state.oauth_token) {
+ return template.apply(this);
+ } else {
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041899_grouperTeacher.js b/pool/shard006/JavaScript/0041899_grouperTeacher.js
new file mode 100644
index 0000000000000000000000000000000000000000..feb56c8e58d0fd1622f6981d791db97fddc6da1f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041899_grouperTeacher.js
@@ -0,0 +1,287 @@
+var PLUGIN_NAME = 'GROUPER';
+
+jq(document).ready(function() {
+//jq(document).on('AppReady', function(e) {
+ if (true) {
+ //listener for messages from server to plugin
+ jq(document).on('ServerToPlugin' + PLUGIN_NAME, function(event, param) {
+ var messageReceived = param.detail;
+
+ switch (messageReceived.pluginMessageType)
+ {
+ //set all custom message type here
+ case 'StudentJoin':
+ break;
+ case 'StudentChosen':
+ break;
+ case 'GetStudentsResponse':
+ break;
+ case 'StudentGrouping':
+ processStudentGrouping(messageReceived.data);
+ break;
+ case 'StudentPingGroup':
+ processStudentPingGroupForTeacher(messageReceived.data);
+ break;
+ case 'StudentUpdateStatus':
+ processStudentUpdateStatus(messageReceived.data);
+ break;
+ }
+ });
+
+
+ jq("#manageClass").click(function() {
+ clickManageGrouping();
+ });
+ //end teacher
+
+// document.pluginToServer(PLUGIN_NAME, 'TeacherOpen', {});
+ }
+});
+
+function processStudentUpdateStatus(data) {
+ var studentID = data.studentID;
+ var active = data.active;
+ if (active) {
+ jq("#student" + studentID).css("background-color", "");
+ } else {
+ jq("#student" + studentID).css("background-color", "gray");
+ }
+}
+
+function processGetStudentsResponse(data) {
+ var studentsData = data.studentsData;
+ var html = "";
+ _.each(studentsData, function(student) {
+ html = html + "" + student.studentName + " ";
+ });
+ html = html + " ";
+
+ jq("#groupAll").html(html);
+ jq("#number-of-students").html(_.size(studentsData));
+}
+
+function processStudentPingStudent(data) {
+ var sourceStudent = data.studentName;
+
+ var msg = document.Messenger().post({
+ message: "Invitation from " + sourceStudent,
+ actions: {
+ retry: {
+ label: 'Accept',
+ phrase: 'Retrying TIME',
+ auto: true,
+ delay: 10,
+ action: function() {
+ parent.pluginToServer(PLUGIN_NAME, 'StudentPingStudent', {studentID: data.studentID});
+ }
+ },
+ cancel: {
+ label: 'Decline',
+ action: function() {
+ return msg.cancel();
+ }
+ }
+ }
+ });
+}
+
+
+
+function processStudentPingGroup(data) {
+ console.log("Student Ping");
+ var groupNumber = data.groupNumber;
+ var originalColor;// = jq('#SURFACE').css('background');
+ switch (groupNumber) {
+ case 0:
+ originalColor = 'skyblue';
+ break;
+ case 1:
+ originalColor = 'LightGoldenRodYellow';
+ break;
+ case 2:
+ originalColor = 'lightgreen';
+ break;
+ case 3:
+ originalColor = 'pink';
+ break;
+ }
+
+ jq('#SURFACE').css('background', '#FF0000');
+ setTimeout(function() {
+ jq('#SURFACE').css('background', originalColor);
+ }, 200);
+}
+
+function processStudentPingGroupForTeacher(data) {
+ var groupNumber = data.groupNumber;
+
+// var originalColor = jq('#group' + (groupNumber + 1)).css('background');
+ switch (groupNumber) {
+ case 0:
+ originalColor = 'skyblue';
+ break;
+ case 1:
+ originalColor = 'LightGoldenRodYellow';
+ break;
+ case 2:
+ originalColor = 'lightgreen';
+ break;
+ case 3:
+ originalColor = 'pink';
+ break;
+ }
+
+ jq('#group' + (groupNumber + 1)).css('background', '#FF0000');
+ setTimeout(function() {
+ jq('#group' + (groupNumber + 1)).css('background', originalColor);
+ }, 200);
+}
+
+function processStudentGrouping(data) {
+ jq("#divName").html("" + document.student.name + " ");
+
+ var groups = data.groups;
+ var numberOfGroups = data.numberOfGroups;
+ var groupType = data.groupType;
+ if (!document.students)
+ document.students = {};
+
+// var previousGroup = parent.document.student.groupNumber;
+// parent.document.student.groupNumber = assignedGroup;
+ document.students.grouping = groups;
+ document.students.numberOfGroups = numberOfGroups;
+ document.students.groupType = groupType;
+
+ updateGroupMenu();
+
+// if (previousGroup != assignedGroup)
+// if(data.isNew)
+// {
+// parent.Messenger().post({
+// message: 'Group: ' + (assignedGroup + 1),
+// id: 'Group',
+// type: 'success',
+// hideAfter: 5,
+// showCloseButton: true
+// });
+// }
+
+}
+
+
+function updateGroupMenu() {
+// if (parent.document.student.groupNumber)
+ var dataAll = '';
+ var numberOfStudents = 0;
+// console.log(document.students.numberOfGroups);
+ _.each(document.students.grouping, function(group, i) {
+ if (group.length === 0)
+ return;
+
+ var dataGroup;
+ if (document.students.numberOfGroups && document.students.numberOfGroups > 1) {
+ dataGroup = ' ';
+ } else {
+ dataGroup = '';
+ }
+ dataGroup += '';
+ dataAll += dataGroup;
+ });
+
+
+ var element = jq("#regionGroupList");
+ element.html(dataAll);
+
+ if (document.studentsScoreData) {
+ _.each(document.studentsScoreData, function(studentScoreData) {
+ var strScore = getRepString(studentScoreData.studentScore);
+ jq("#score" + studentScoreData.studentID).html(strScore);
+ });
+ }
+
+
+ jq("#number-of-students").html(numberOfStudents);
+
+ var options = {
+ valueNames: ['name', 'scoreValue']
+ };
+
+ if (numberOfStudents > 0) {
+ var list = new List('divList', options);
+ list.sort('scoreValue', {order: "desc"});
+ }
+}
+
+function clickStudentList(studentID) {
+ var studentName = getStudentName(studentID);
+ var message = {
+ type: 'UrlUpdate',
+ title: studentName,
+ resourceURL: '../../plugins/wallStudent/wallStudent.html?studentID='
+ + studentID + '&studentName=' + studentName};
+
+ jq(document).trigger('DialogUrl', {detail: message});
+}
+
+function clickGroupList(groupNumber) {
+// var studentName = getStudentName(studentID);
+ var message = {
+ type: 'UrlUpdate',
+ title: 'Group ' + (groupNumber + 1),
+ resourceURL: '../../plugins/wallGroup/wallGroup.html?groupNumber=' + groupNumber};
+
+ jq(document).trigger('DialogUrl', {detail: message});
+}
+
+function getStudentName(studentID) {
+
+ var students = _.flatten(document.students.grouping);
+
+ var studentName;
+ _.each(students, function(student) {
+ if (student.studentID === studentID) {
+ studentName = student.studentName;
+ }
+ });
+
+ return studentName;
+}
+
+function clickManageGrouping() {
+// var studentName = getStudentName(studentID);
+ var message = {
+ type: 'UrlUpdate',
+ title: 'Manage',
+ resourceURL: '../../plugins/grouper/grouperManage.html'};
+
+ jq(document).trigger('DialogUrl', {detail: message});
+}
+
+function getRepString(rep) {
+ rep = rep + ''; // coerce to string
+ if (rep < 1000) {
+ return rep; // return the same number
+ }
+ if (rep < 10000) { // place a comma between
+ return rep.charAt(0) + ',' + rep.substring(1);
+ }
+ // divide and format
+ return (rep / 1000).toFixed(rep % 1000 != 0) + 'k';
+}
+
+String.prototype.trunc = String.prototype.trunc ||
+ function(n) {
+ return this.length > n ? this.substr(0, n - 1) + '…' : this;
+ };
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041903_model.js b/pool/shard006/JavaScript/0041903_model.js
new file mode 100644
index 0000000000000000000000000000000000000000..3b15475e219a7a8330a92e5cd75d44ccd95c4f0f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041903_model.js
@@ -0,0 +1,56 @@
+var People = {
+ total:people
+};
+
+var Time = {
+ total:0
+};
+
+var Salary = {
+ total:salary
+};
+
+var Meeting = {
+ cost:cost,
+ update:function(){
+ // Look at this!
+ this.cost = ((People.total * Salary.total)/3600000) * Time.total.getTime();
+ costLabel.text = currency+this.cost.toFixed(2)
+ }
+};
+
+var timer, now, then;
+
+var Stopwatch = {
+ start:function(){
+ then = new Date();
+ timer = setInterval(function(){
+ Stopwatch.updateDisplay();
+ }, 1000);
+ },
+ stop:function(){
+ clearInterval(timer);
+ },
+ reset:function(){
+ then = new Date();
+ now = then;
+ Stopwatch.updateDisplay();
+ Meeting.update();
+ },
+ updateDisplay:function(){
+ now = new Date();
+ Time.total = new Date(Math.abs(now.getTime() - then.getTime()));
+ var seconds = Time.total.getSeconds();
+ var minutes = Time.total.getMinutes();
+ var hours = Time.total.getHours();
+ Meeting.update();
+ minutesLabel.text = [this.doubleDigits(hours), this.doubleDigits(minutes), this.doubleDigits(seconds)].join(':');
+ },
+ doubleDigits:function(n){
+ if(n.toString().length == 1){
+ return '0'+n;
+ } else{
+ return n;
+ }
+ }
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041907_type-serializers.js b/pool/shard006/JavaScript/0041907_type-serializers.js
new file mode 100644
index 0000000000000000000000000000000000000000..304888fbc2d62692a743b95326f51ca65ec36357
--- /dev/null
+++ b/pool/shard006/JavaScript/0041907_type-serializers.js
@@ -0,0 +1,295 @@
+/*
+ * 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.
+ */
+
+/**
+ * @author Jorge Bay Gondra
+ */
+'use strict';
+
+const t = require('../../process/traversal');
+const Bytecode = require('../../process/bytecode');
+const g = require('../graph');
+const utils = require('../../utils');
+
+const valueKey = '@value';
+const typeKey = '@type';
+
+/**
+ * @abstract
+ */
+class TypeSerializer {
+ serialize() {
+ throw new Error('serialize() method not implemented for ' + this.constructor.name);
+ }
+
+ deserialize() {
+ throw new Error('deserialize() method not implemented for ' + this.constructor.name);
+ }
+
+ canBeUsedFor() {
+ throw new Error('canBeUsedFor() method not implemented for ' + this.constructor.name);
+ }
+}
+
+class NumberSerializer extends TypeSerializer {
+ serialize(item) {
+ return item;
+ }
+
+ deserialize(obj) {
+ return parseFloat(obj[valueKey]);
+ }
+
+ canBeUsedFor(value) {
+ return (typeof value === 'number');
+ }
+}
+
+class LongSerializer extends TypeSerializer {
+ serialize(item) {
+ return {
+ [typeKey]: 'g:Int64',
+ [valueKey]: item.value
+ };
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof utils.Long);
+ }
+}
+
+class BytecodeSerializer extends TypeSerializer {
+ serialize(item) {
+ let bytecode = item;
+ if (item instanceof t.Traversal) {
+ bytecode = item.getBytecode();
+ }
+ const result = {};
+ result[typeKey] = 'g:Bytecode';
+ const resultValue = result[valueKey] = {};
+ const sources = this._serializeInstructions(bytecode.sourceInstructions);
+ if (sources) {
+ resultValue['source'] = sources;
+ }
+ const steps = this._serializeInstructions(bytecode.stepInstructions);
+ if (steps) {
+ resultValue['step'] = steps;
+ }
+ return result;
+ }
+
+ _serializeInstructions(instructions) {
+ if (instructions.length === 0) {
+ return null;
+ }
+ const result = new Array(instructions.length);
+ result[0] = instructions[0];
+ for (let i = 0; i < instructions.length; i++) {
+ result[i] = this.writer.adaptObject(instructions[i]);
+ }
+ return result;
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof Bytecode) || (value instanceof t.Traversal);
+ }
+}
+
+class PSerializer extends TypeSerializer {
+ /** @param {P} item */
+ serialize(item) {
+ const result = {};
+ result[typeKey] = 'g:P';
+ const resultValue = result[valueKey] = {
+ 'predicate': item.operator
+ };
+ if (item.other === undefined || item.other === null) {
+ resultValue['value'] = this.writer.adaptObject(item.value);
+ }
+ else {
+ resultValue['value'] = [ this.writer.adaptObject(item.value), this.writer.adaptObject(item.other) ];
+ }
+ return result;
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof t.P);
+ }
+}
+
+class LambdaSerializer extends TypeSerializer {
+ /** @param {Function} item */
+ serialize(item) {
+ return {
+ [typeKey]: 'g:Lambda',
+ [valueKey]: {
+ 'arguments': item.length,
+ 'language': 'gremlin-javascript',
+ 'script': item.toString()
+ }
+ };
+ }
+
+ canBeUsedFor(value) {
+ return (typeof value === 'function');
+ }
+}
+
+class EnumSerializer extends TypeSerializer {
+ /** @param {EnumValue} item */
+ serialize(item) {
+ return {
+ [typeKey]: 'g:' + item.typeName,
+ [valueKey]: item.elementName
+ };
+ }
+
+ canBeUsedFor(value) {
+ return value && value.typeName && value instanceof t.EnumValue;
+ }
+}
+
+class TraverserSerializer extends TypeSerializer {
+ /** @param {Traverser} item */
+ serialize(item) {
+ return {
+ [typeKey]: 'g:Traverser',
+ [valueKey]: {
+ 'value': this.writer.adaptObject(item.object),
+ 'bulk': this.writer.adaptObject(item.bulk)
+ }
+ };
+ }
+
+ deserialize(obj) {
+ const value = obj[valueKey];
+ return new t.Traverser(this.reader.read(value['value']), this.reader.read(value['bulk']));
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof t.Traverser);
+ }
+}
+
+class VertexSerializer extends TypeSerializer {
+ deserialize(obj) {
+ const value = obj[valueKey];
+ return new g.Vertex(this.reader.read(value['id']), value['label'], this.reader.read(value['properties']));
+ }
+
+ /** @param {Vertex} item */
+ serialize(item) {
+ return {
+ [typeKey]: 'g:Vertex',
+ [valueKey]: {
+ 'id': this.writer.adaptObject(item.id),
+ 'label': item.label
+ }
+ };
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof g.Vertex);
+ }
+}
+
+class VertexPropertySerializer extends TypeSerializer {
+ deserialize(obj) {
+ const value = obj[valueKey];
+ return new g.VertexProperty(
+ this.reader.read(value['id']),
+ value['label'],
+ this.reader.read(value['value']),
+ this.reader.read(value['properties'])
+ );
+ }
+}
+
+class PropertySerializer extends TypeSerializer {
+ deserialize(obj) {
+ const value = obj[valueKey];
+ return new g.Property(
+ value['key'],
+ this.reader.read(value['value']));
+ }
+}
+
+class EdgeSerializer extends TypeSerializer {
+ deserialize(obj) {
+ const value = obj[valueKey];
+ return new g.Edge(
+ this.reader.read(value['id']),
+ this.reader.read(value['outV']),
+ value['label'],
+ this.reader.read(value['inV']),
+ this.reader.read(value['properties'])
+ );
+ }
+
+ /** @param {Edge} item */
+ serialize(item) {
+ return {
+ [typeKey]: 'g:Edge',
+ [valueKey]: {
+ 'id': this.writer.adaptObject(item.id),
+ 'label': item.label,
+ 'outV': this.writer.adaptObject(item.outV.id),
+ 'outVLabel': item.outV.label,
+ 'inV': this.writer.adaptObject(item.inV.id),
+ 'inVLabel': item.inV.label
+ }
+ };
+ }
+
+ canBeUsedFor(value) {
+ return (value instanceof g.Edge);
+ }
+}
+
+class PathSerializer extends TypeSerializer {
+ deserialize(obj) {
+ const value = obj[valueKey];
+ const objects = value['objects'].map(o => this.reader.read(o));
+ return new g.Path(this.reader.read(value['labels']), objects);
+ }
+}
+
+class TSerializer extends TypeSerializer {
+ deserialize(obj) {
+ return t.t[obj[valueKey]];
+ }
+}
+
+module.exports = {
+ BytecodeSerializer,
+ EdgeSerializer,
+ EnumSerializer,
+ LambdaSerializer,
+ LongSerializer,
+ NumberSerializer,
+ PathSerializer,
+ PropertySerializer,
+ PSerializer,
+ TSerializer,
+ TraverserSerializer,
+ typeKey,
+ valueKey,
+ VertexPropertySerializer,
+ VertexSerializer
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041914_tokenz.unit.test.js b/pool/shard006/JavaScript/0041914_tokenz.unit.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..23b8a5e0fe34569762c6cd7904cdf5db0489c352
--- /dev/null
+++ b/pool/shard006/JavaScript/0041914_tokenz.unit.test.js
@@ -0,0 +1,111 @@
+var should = require('chai').should();
+
+var lconfig = require('lconfig');
+
+lconfig.authSecrets.crypt = 'abc';
+lconfig.authSecrets.sign = '123';
+
+lconfig.minConnections = 1;
+lconfig.maxConnections = 1;
+
+var dalFake = require('dal-fake');
+var dal = require('dal');
+
+dalFake.reset();
+
+var PROFILES = [
+ { profile: '123@facebook' },
+ { profile: '123@twitter' }
+];
+
+dalFake.addFake('SELECT true', []);
+dalFake.addFake('SELECT app, secret, apikeys, notes FROM Apps WHERE app = ? ' +
+ 'LIMIT 1', [{}]);
+dalFake.addFake('SELECT profile FROM Accounts WHERE account = ?', PROFILES);
+
+dal.setBackend('fake');
+
+var tokenz = require('tokenz');
+
+var GOOD_ACCESS_TOKEN = 'JrY54j9w8SToWDYFDPDykSZrsR4.EKO8Xl-m96c3fbe6b28d2401' +
+ '22e5858622d1afc7096bebdb0133ee03d334a3fa7d4bb6804a76c76a26fa5697852b8dd07a' +
+ 'a32fa65766f6a7d27746a5456fe357b8fa3017';
+
+before(tokenz.init);
+
+describe('tokenz', function () {
+ describe('#init', function () {
+ it('should set tokenz.serializer', function () {
+ should.exist(tokenz.serializer);
+ });
+ });
+
+ describe('#createAccessToken', function () {
+ it('should create a valid access token', function (done) {
+ tokenz.createAccessToken('test-account', 'test-app', {},
+ function (err, token) {
+ if (err) {
+ return done(err);
+ }
+
+ should.exist(token);
+
+ should.exist(token.account);
+ should.exist(token.access_token);
+
+ token.access_token.should.be.a('string');
+ token.access_token.length.should.be.below(255);
+
+ var parsed = tokenz.parseAccessToken(token.access_token);
+
+ parsed.account.should.equal('test-account');
+ parsed.app.should.equal('test-app');
+
+ isNaN(parsed.at).should.equal(false);
+
+ done();
+ });
+ });
+ });
+
+ describe('#parseAccessToken', function () {
+ it('should parse a valid access token', function () {
+ var parsed = tokenz.parseAccessToken(GOOD_ACCESS_TOKEN);
+
+ parsed.account.should.equal('test-account');
+ parsed.app.should.equal('test-app');
+
+ should.exist(parsed.at);
+ });
+ });
+
+ describe('#login', function () {
+ it('should return data with a good access token', function (done) {
+ var res = {
+ json: function (json) {
+ throw json;
+ }
+ };
+
+ var req = {
+ param: function (parameter) {
+ var data = {
+ access_token: GOOD_ACCESS_TOKEN
+ };
+
+ return data[parameter];
+ }
+ };
+
+ tokenz.login(req, res, function () {
+ var token = req._authsome;
+
+ token.profiles.should.equal(PROFILES);
+ token.account.should.equal('test-account');
+ token.app.should.equal('test-app');
+
+ done();
+ });
+ });
+ });
+});
diff --git a/pool/shard006/JavaScript/0041917_config.js b/pool/shard006/JavaScript/0041917_config.js
new file mode 100644
index 0000000000000000000000000000000000000000..cd34008c045f501a33c48bb7c964b8fe807e53b8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041917_config.js
@@ -0,0 +1,17 @@
+export default {
+ snapshot(target) {
+ const div = target.querySelector('div');
+
+ return {
+ div,
+ p: div.querySelector('p')
+ };
+ },
+
+ test(assert, target, snapshot) {
+ const div = target.querySelector('div');
+
+ assert.equal(div, snapshot.div);
+ assert.equal(div.querySelector('p'), snapshot.p);
+ }
+};
diff --git a/pool/shard006/JavaScript/0041927_widget_songDetails.js b/pool/shard006/JavaScript/0041927_widget_songDetails.js
new file mode 100644
index 0000000000000000000000000000000000000000..e4b042f0df2a4d6eed7881811b7abeda5e04541f
--- /dev/null
+++ b/pool/shard006/JavaScript/0041927_widget_songDetails.js
@@ -0,0 +1,173 @@
+Mojo.Widget.SongDetails = Class.create({
+ setup: function setup(){
+ this._build();
+ this.controller.exposeMethods(["hide", "show", "incrementRating", "decrementRating", "refresh"]);
+ },
+ _build : function _build() {
+ Element.insert(this.controller.element, "
");
+ this.songDetailsTrackInfoDiv = this.controller.get("song-details-track-info");
+ this.songDetailsTrackStatsDiv = this.controller.get("song-details-track-stats");
+ this.controller.listen(this.songDetailsTrackStatsDiv, Mojo.Event.tap, this.ratingTapHandler = this.songDetailsTap.bind(this));
+ this.controller.listen(this.songDetailsTrackInfoDiv, Mojo.Event.tap, this.popupHandler = this.popupTap.bind(this));
+
+ this.controller.listen(this.controller.element, Mojo.Event.flick, this.flickHandler = this.flick.bind(this));
+ //this.controller.instantiateChildWidgets(this.controller.element);
+ },
+ handleModelChanged : function() {
+
+ },
+ cleanup: function() {
+ this.controller.stopListening(this.songDetailsTrackStatsDiv, Mojo.Event.tap, this.ratingTapHandler);
+ },
+ renderContent: function(){
+ koto.justType.getSongData(this.array[this.index]._id, function(result){
+ //console.log("results " + Object.toJSON(result));
+ renderedContent = Mojo.View.render({
+ object: result,
+ formatters: {
+ "rating": function(value, model){
+ var stars = "";
+ for(var i = 1; i <= model.rating; i++){
+ stars += ("
");
+ }
+ for(var k = model.rating+1; k <= 5; k++){
+ stars +=("
");
+ }
+ return stars;
+ },
+ "playCount": function(value, model){
+ if (model.playCount && model.playCount > 0){
+ return $L("Played ") + ((model.playCount === 1)?model.playCount + $L(" Time"):model.playCount + $L(" Times"));
+ } else {
+ return $L("Played 0 Times");
+ }
+ },
+ "lastPlayed": function(value, model){
+ if (model.lastPlayed && model.lastPlayed !== "n/a"){
+ var d = new Date();
+ d.setTime(model.lastPlayed);
+ return $L("Last Played ") + koto.utilities.formatDate(d);
+ }
+ },
+ },
+ template: "widgets/widget_songDetails-data"
+ });
+ this.songDetailsTrackStatsDiv.innerHTML = renderedContent;
+ }.bind(this));
+
+ db8.getObjsById([this.array[this.index]._id], function(results){
+ results[0].albumArt = koto.albumArt.get(results[0], true);//small
+
+ renderedContent = Mojo.View.render({
+ object: results[0],
+ formatters: {
+ "tracks": function(value, model){
+ var trackNum = parseInt(this.index, 10) + 1;
+ return $L("Track") + " " + trackNum + " " + $L("of") + " " + this.array.length;
+ //return "Track " + model.track.position + " of " + model.track.total;
+
+ }.bind(this),
+ },
+ template: "widgets/widget_songDetails-songInfo"
+ });
+ this.songDetailsTrackInfoDiv.innerHTML = renderedContent;
+ }.bind(this));
+
+ },
+ songDetailsTap: function(event){
+ if (event.target.id === "clear_rating"){
+ koto.justType.setRating(this.array[this.index]._id, 0, function(){
+ this.renderContent();
+ }.bind(this));
+ } else {
+ var rating = parseInt(event.target.id, 10);
+ if (!isNaN(rating)){
+ koto.justType.setRating(this.array[this.index]._id, rating, function(){
+ this.renderContent();
+ }.bind(this));
+ }
+ }
+ },
+ popupTap: function(event){
+ if (event.target.id === "popup"){
+ db8.getObjsById([this.array[this.index]._id], function(results){
+ event.item = results[0];
+ event.index = this.index;
+ event.originalEvent = {target: event.target};
+ event.fromSongDetails = true;
+ this.controller.scene.assistant.listTap(event);
+ }.bind(this));
+ }
+ },
+ flick: function(event){
+ if (event.velocity.x > 600 && (Math.abs(event.velocity.x) > Math.abs(event.velocity.y))){
+ if (this.array[this.index-1]){
+ this.index -= 1;
+ } else {
+ this.index = this.array.length-1;
+ }
+ this.renderContent();
+ }
+ else if (event.velocity.x < -600 && (Math.abs(event.velocity.x) > Math.abs(event.velocity.y))){
+ if (this.array[this.index+1]){
+ this.index += 1;
+ } else {
+ this.index = 0;
+ }
+ this.renderContent();
+ } else if (event.velocity.y < -1000 && (Math.abs(event.velocity.y) > Math.abs(event.velocity.x))){
+ this.controller.scene.assistant.extraDiv.mojo.hide();
+
+ }
+
+ },
+ //Mojo Methods
+ show: function(array, index){
+ this.array = array;
+ this.index = index;
+
+ this.songDetailsTrackStatsDiv.innerHTML = "";
+ this.songDetailsTrackInfoDiv.innerHTML = "";
+ this.renderContent();
+ this.controller.element.show();
+ },
+ hide: function(){
+ //hide div
+ this.controller.element.hide();
+ var currentScene = this.controller.scene.assistant;
+ if (currentScene.controller.sceneName === "view" && currentScene.objType === "playlist" && currentScene.titleObj && currentScene.titleObj.type !== "custom"){
+ currentScene.refreshList();
+ }
+ },
+ incrementRating: function(){
+ koto.justType.getSongData(this.array[this.index]._id, function(result){
+ var rating = result.rating || 0;
+ if (rating < 5){
+ rating += 1;
+ koto.justType.setRating(this.array[this.index]._id, rating, function(){
+ this.renderContent();
+ }.bind(this));
+ }
+ }.bind(this));
+
+ },
+ decrementRating: function(){
+ koto.justType.getSongData(this.array[this.index]._id, function(result){
+ var rating = result.rating || 0;
+ if (rating > 0){
+ rating -= 1;
+ koto.justType.setRating(this.array[this.index]._id, rating, function(){
+ this.renderContent();
+ }.bind(this));
+ }
+ }.bind(this));
+ },
+ refresh: function(arg){
+ if (arg && arg.playedNext){
+ this.index = koto.nowPlaying.currentInfo.index + 1;
+ } else if (arg && arg.playedLast){
+ this.index = koto.nowPlaying.currentInfo.songs.length-1;
+ }
+ this.renderContent();
+ }
+});
diff --git a/pool/shard006/JavaScript/0041929_js-framework-poc-angular.js b/pool/shard006/JavaScript/0041929_js-framework-poc-angular.js
new file mode 100644
index 0000000000000000000000000000000000000000..6bc86f3f58a7bf8a79818a1aacce51d549126601
--- /dev/null
+++ b/pool/shard006/JavaScript/0041929_js-framework-poc-angular.js
@@ -0,0 +1,71 @@
+define([
+ 'angular'
+], function (angular) {
+ 'use strict';
+ var angularApp = angular.module('jsframeworkspocangularApp', [])
+ .controller('jsframeworkspocangularController', ['$scope', function ($scope) {
+ var student1 = {id: 'id1', firstName: 'Student', lastInitial: 'A'};
+ var student2 = {id: 'id2', firstName: 'Student', lastInitial: 'B'};
+ var student3 = {id: 'id3', firstName: 'Student', lastInitial: 'C'};
+
+ var allStudents = [student1, student2, student3];
+
+ $scope.allStudents = allStudents;
+ $scope.currentStudent = student1;
+
+ $scope.availableStandards = ["1.NBT.4", "1.NBT.5", "1.NBT.6"];
+ $scope.currentStandard = "1.NBT.4";
+
+ $scope.resources = {};
+ $scope.resources["1.NBT.4"] = ["1nbt4 - 1", "1nbt4 - 2", "1nbt4 - 3", "1nbt4 - 4"];
+ $scope.resources["1.NBT.5"] = ["1nbt5 - 1", "1nbt5 - 2"];
+ $scope.resources["1.NBT.6"] = ["1nbt6 - 1", "1nbt6 - 2", "1nbt6 - 3"];
+ }]).directive('studentList', function () {
+ return {
+ restrict: 'A',
+ scope: {
+ currentStudent: '=',
+ listOfStudents: '='
+ },
+ templateUrl: 'partials/studentListWidget.html',
+ controller: function ($scope) {
+ $scope.changeStudent = function (newStudent) {
+ $scope.currentStudent = newStudent;
+ console.log(newStudent);
+ };
+ },
+ };
+ }).directive('reportGraph', function () {
+ return {
+ restrict: 'A',
+ scope: {
+ currentStudent: '='
+ },
+ templateUrl: 'partials/reportGraphWidget.html'
+ };
+ }).directive('standards', function () {
+ return {
+ restrict: 'A',
+ scope: {
+ currentStandard: '=',
+ availableStandards: '='
+ },
+ templateUrl: 'partials/standardsWidget.html',
+ controller: function ($scope) {
+ $scope.changeStandard = function (newStandard) {
+ $scope.currentStandard = newStandard;
+ console.log(newStandard);
+ };
+ },
+ };
+ }).directive('resources', function () {
+ return {
+ restrict: 'A',
+ scope: {
+ assets: '=listOfResources'
+ },
+ templateUrl: 'partials/differentiationResourcesWidget.html'
+ };
+ });
+ return angularApp;
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041930_usercenter.test.js b/pool/shard006/JavaScript/0041930_usercenter.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..d783a120bff426b9c4854e379f3f32e4e068fb21
--- /dev/null
+++ b/pool/shard006/JavaScript/0041930_usercenter.test.js
@@ -0,0 +1,70 @@
+var assert = require('chai').assert;
+var expect = require('chai').expect;
+var should = require('chai').should();
+
+var UserCenter = require('../index.js').UserCenter;
+
+var mobile = '13800138000';
+var password = '10086';
+
+/**
+ * 测试 lib/usercenter.js 文件
+ * @Author https://github.com/modood
+ * @DateTime 2016-03-22T15:02:02+0800
+ */
+describe('TEST file lib/usercenter.js', function () {
+ describe('TEST function get_token', function () {
+ it('成功,获取token', function (done) {
+ var uc = new UserCenter(mobile, password);
+ uc.get_token(function (err, token) {
+ should.not.exist(err);
+ should.exist(token);
+ token.should.be.an('String');
+ done();
+ })
+ });
+ it('失败,密码错误', function (done) {
+ var uc = new UserCenter(mobile, password + '1');
+ uc.get_token(function (err, token) {
+ should.exist(err);
+ should.not.exist(token);
+ err.code.should.be.equal(122009);
+ done();
+ })
+ });
+ })
+
+ describe('TEST function get_user_info', function () {
+ it('成功,获取用户信息', function (done) {
+ var uc = new UserCenter(mobile, password);
+ uc.get_token(function (err, token) {
+ should.not.exist(err);
+ uc.get_user_info(token, function (err, user_info) {
+ should.not.exist(err);
+ should.exist(user_info);
+ user_info.should.be.an('Object');
+ user_info.mobile.should.be.equal(mobile);
+ done();
+ })
+ })
+ });
+ it('失败,token信息错误', function (done) {
+ var uc = new UserCenter();
+
+ uc.get_user_info('this is not a token', function (err, user_info) {
+ should.exist(err);
+ err.msg.should.be.equal('token信息错误')
+ done();
+ })
+ });
+ it('失败,没有提供token', function (done) {
+ var uc = new UserCenter();
+
+ uc.get_user_info(undefined, function (err, user_info) {
+ should.exist(err);
+ err.msg.should.be.equal('没有提供token')
+ done();
+ })
+ });
+ })
+})
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041932_extension.js b/pool/shard006/JavaScript/0041932_extension.js
new file mode 100644
index 0000000000000000000000000000000000000000..fbf580d797eba9e9fa3871dc16571480159b5e00
--- /dev/null
+++ b/pool/shard006/JavaScript/0041932_extension.js
@@ -0,0 +1,33 @@
+/* global requirejs */
+
+import { Geonotebook } from 'geonotebook';
+
+if (window.require) {
+ window.require.config({
+ map: {
+ '*': {
+ geonotebook: 'nbextensions/geonotebook/index'
+ }
+ }
+ });
+}
+
+function load_ipython_extension () {
+ return new Promise(function (resolve) {
+ requirejs([
+ 'base/js/namespace',
+ 'base/js/events'
+ ], function (Jupyter, events) {
+ if (Jupyter.kernelselector.current_selection === 'geonotebook2' ||
+ Jupyter.kernelselector.current_selection === 'geonotebook3') {
+ Jupyter.geonotebook = new Geonotebook(Jupyter, events);
+ }
+ console.log('loaded geonotebook');
+ resolve();
+ });
+ });
+}
+
+module.exports = {
+ load_ipython_extension
+};
diff --git a/pool/shard006/JavaScript/0041934_index.js b/pool/shard006/JavaScript/0041934_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..d71c7ef839e053d947298cd24f30568795df2cea
--- /dev/null
+++ b/pool/shard006/JavaScript/0041934_index.js
@@ -0,0 +1,12 @@
+const functions = require('firebase-functions');
+
+exports.ProcessInfo = functions.https.onRequest((req, res) => {
+ res.json(200, {
+ version: process.version,
+ arch: process.arch,
+ platform: process.platform,
+ versions: process.versions,
+ features: process.features,
+ release: process.release
+ });
+})
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041935_webpack.js b/pool/shard006/JavaScript/0041935_webpack.js
new file mode 100644
index 0000000000000000000000000000000000000000..b97acb4fa2d9651006a0a799e0dc3c532a84eeab
--- /dev/null
+++ b/pool/shard006/JavaScript/0041935_webpack.js
@@ -0,0 +1,24 @@
+const path = require('path');
+const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
+const webpack = require('webpack');
+const webpackMerge = require('webpack-merge');
+const appConfig = require('./webpack/config_app');
+const commonConfig = require('./webpack/config_common');
+const PATHS = require('./webpack/paths');
+const getPlugins = require('./webpack/plugins');
+
+module.exports = function (grunt) {
+ const section = [webpackMerge.smart(commonConfig(grunt), appConfig(grunt))];
+
+ const watch_config = {
+ watch: true,
+ optimization: {
+ minimize: false,
+ },
+ };
+
+ return {
+ section,
+ watch: section.map(conf => webpackMerge(conf, watch_config)),
+ };
+};
diff --git a/pool/shard006/JavaScript/0041938_decrementQuantity.js b/pool/shard006/JavaScript/0041938_decrementQuantity.js
new file mode 100644
index 0000000000000000000000000000000000000000..3c13daddad46f6faf5cfc7831b853a927b809cca
--- /dev/null
+++ b/pool/shard006/JavaScript/0041938_decrementQuantity.js
@@ -0,0 +1,50 @@
+'use strict';
+
+const removeItem = require('./removeItem');
+
+module.exports = function(handler, table) {
+
+ const slots = handler.event.request.intent.slots
+ var baseQuantity = 1;
+ var removedQuantity = 1;
+
+ if (slots.Item && slots.Item.value) {
+ table
+ .find({ hash: handler.event.session.user.userId,
+ range: slots.Item.value
+ })
+ .then(function(resp) {
+ if (resp == undefined) {
+ handler.emit(':tell', handler.t('QUANTITY_ZERO', slots.Item.value.toLowerCase()));
+ } else {
+ if (resp.quantity != undefined) {
+ baseQuantity = resp.quantity;
+ }
+ if (slots.Quantity && slots.Quantity.value) {
+ removedQuantity = slots.Quantity.value;
+ }
+ else if (slots.Quantity.value == 0) {
+ removedQuantity = 0;
+ }
+ var finalQuantity = eval(baseQuantity) - eval(removedQuantity);
+ if (finalQuantity <= 0) {
+ removeItem(handler, table);
+ } else {
+ table
+ .update({hash: handler.event.session.user.userId, range: slots.Item.value.toLowerCase()}, { quantity: finalQuantity })
+ .then(function(resp) {
+ handler.emit('Affirmative');
+ })
+ .catch(function(err) {
+ console.log(err);
+ handler.emit('Error');
+ });
+ }
+ }
+ })
+
+ } else {
+ console.log("error with itemName slot");
+ handler.emit('Error')
+ }
+}
diff --git a/pool/shard006/JavaScript/0041939_artifacts.js b/pool/shard006/JavaScript/0041939_artifacts.js
new file mode 100644
index 0000000000000000000000000000000000000000..0fbc261aeadabedc730e01b4456744e139bed271
--- /dev/null
+++ b/pool/shard006/JavaScript/0041939_artifacts.js
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2015 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.
+ */
+define(['mithril', 'lodash', 'string-plus', './model_mixins'], function (m, _, s, Mixins) {
+
+ var Artifacts = function (data) {
+ Mixins.HasMany.call(this, {factory: Artifacts.Artifact.create, as: 'Artifact', collection: data});
+ };
+
+ Artifacts.Artifact = function (data) {
+ this.constructor.modelType = 'artifact';
+ Mixins.HasUUID.call(this);
+
+ this.parent = Mixins.GetterSetter();
+
+ this.type = m.prop(s.defaultToIfBlank(data.type, 'build'));
+ this.source = m.prop(s.defaultToIfBlank(data.source, ''));
+ this.destination = m.prop(s.defaultToIfBlank(data.destination, ''));
+
+ this.isBlank = function () {
+ return s.isBlank(this.source()) && s.isBlank(this.destination());
+ };
+
+ this.validate = function () {
+ var errors = new Mixins.Errors();
+
+ if (s.isBlank(this.source()) && !s.isBlank(this.destination())) {
+ errors.add('source', Mixins.ErrorMessages.mustBePresent('source'));
+ }
+
+ if (!s.isBlank(this.source()) && s.isBlank(this.destination())) {
+ errors.add('destination', Mixins.ErrorMessages.mustBePresent('destination'));
+ }
+
+ return errors;
+ };
+
+ };
+
+ Artifacts.Artifact.create = function (data) {
+ return new Artifacts.Artifact(data);
+ };
+
+ Mixins.fromJSONCollection({
+ parentType: Artifacts,
+ childType: Artifacts.Artifact,
+ via: 'addArtifact'
+ });
+
+ Artifacts.Artifact.fromJSON = function (data) {
+ return new Artifacts.Artifact(_.pick(data, ['type', 'source', 'destination']));
+ };
+
+ return Artifacts;
+});
diff --git a/pool/shard006/JavaScript/0041940_recurrence.js b/pool/shard006/JavaScript/0041940_recurrence.js
new file mode 100644
index 0000000000000000000000000000000000000000..631ea267f6582f976184bad98ac75ea22600ffa8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041940_recurrence.js
@@ -0,0 +1,207 @@
+/**
+ Copyright 2012-2015 Nick Korbel
+
+ This file is part of Booked Scheduler.
+
+ Booked Scheduler 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.
+
+ Booked Scheduler 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 Booked Scheduler. If not, see .
+ */
+//Recurrence
+function Recurrence(recurOptions, recurElements, prefix) {
+ prefix = prefix || '';
+ var e = {
+ repeatOptions:$('#' + prefix + 'repeatOptions'),
+ repeatDiv:$('#' + prefix + 'repeatDiv'),
+ repeatInterval:$('#' + prefix + 'repeatInterval'),
+ repeatTermination:$('#' + prefix + 'formattedEndRepeat'),
+ repeatTerminationTextbox:$('#' + prefix + 'EndRepeat'),
+ beginDate: $('#' + prefix + 'formattedBeginDate'),
+ endDate: $('#' + prefix + 'formattedEndDate'),
+ beginTime: $('#' + prefix + 'BeginPeriod'),
+ endTime: $('#' + prefix + 'EndPeriod')
+ };
+
+ var options = recurOptions;
+
+ var elements = $.extend(e, recurElements);
+
+ var repeatToggled = false;
+ var terminationDateSetManually = false;
+
+ //Initializes
+ this.init = function () {
+ InitializeDateElements();
+ InitializeRepeatElements();
+ InitializeRepeatOptions();
+ };
+
+ //Change repetition options
+ var ChangeRepeatOptions = function () {
+ var repeatDropDown = elements.repeatOptions;
+ if (repeatDropDown.val() != 'none') {
+ $('#' + prefix + 'repeatUntilDiv').show();
+ }
+ else {
+ $('div[id!=' + prefix + 'repeatOptions]', elements.repeatDiv).hide();
+ $('.reserved').show();
+ }
+
+ if (repeatDropDown.val() == 'daily') {
+ $('.weeks', elements.repeatDiv).hide();
+ $('.months', elements.repeatDiv).hide();
+ $('.years', elements.repeatDiv).hide();
+
+ $('.days', elements.repeatDiv).show();
+ $('.reserved').hide();
+ }
+
+ if (repeatDropDown.val() == 'weekly') {
+ $('.days', elements.repeatDiv).hide();
+ $('.months', elements.repeatDiv).hide();
+ $('.years', elements.repeatDiv).hide();
+
+ $('.weeks', elements.repeatDiv).show();
+ $('.reserved').hide();
+ }
+
+ if (repeatDropDown.val() == 'monthly') {
+ $('.days', elements.repeatDiv).hide();
+ $('.weeks', elements.repeatDiv).hide();
+ $('.years', elements.repeatDiv).hide();
+
+ $('.months', elements.repeatDiv).show();
+ $('.reserved').hide();
+ }
+
+ if (repeatDropDown.val() == 'yearly') {
+ $('.days', elements.repeatDiv).hide();
+ $('.weeks', elements.repeatDiv).hide();
+ $('.months', elements.repeatDiv).hide();
+
+ $('.years', elements.repeatDiv).show();
+ $('.reserved').hide();
+ }
+ };
+
+ //Initialize date elements
+ function InitializeDateElements() {
+ elements.beginDate.change(function () {
+ ToggleRepeatOptions();
+ });
+
+ elements.endDate.change(function () {
+ ToggleRepeatOptions();
+ });
+
+ elements.beginTime.change(function () {
+ ToggleRepeatOptions();
+ });
+
+ elements.endTime.change(function () {
+ ToggleRepeatOptions();
+ });
+ }
+
+ //Initialize repeat elements
+ function InitializeRepeatElements() {
+ elements.repeatOptions.change(function () {
+ ChangeRepeatOptions();
+ AdjustTerminationDate();
+ });
+
+ elements.repeatInterval.change(function () {
+ AdjustTerminationDate();
+ });
+
+ elements.beginDate.change(function () {
+ AdjustTerminationDate();
+ });
+
+ elements.repeatTermination.change(function () {
+ terminationDateSetManually = true;
+ });
+ }
+
+ //Initialize repeat options
+ function InitializeRepeatOptions() {
+ if (options.repeatType) {
+ elements.repeatOptions.val(options.repeatType);
+ elements.repeatInterval.val(options.repeatInterval);
+ for (var i = 0; i < options.repeatWeekdays.length; i++) {
+ var id = '#' + prefix + 'repeatDay' + options.repeatWeekdays[i];
+ $(id).attr('checked', true);
+ }
+
+ $("#" + prefix + "repeatOnMonthlyDiv :radio[value='" + options.repeatMonthlyType + "']").attr('checked', true);
+
+ ChangeRepeatOptions();
+ }
+ }
+
+ //Toggle repeat options
+ var ToggleRepeatOptions = function () {
+ var SetValue = function (value, disabled) {
+ elements.repeatOptions.val(value);
+ elements.repeatOptions.trigger('change');
+ if (disabled) {
+ $('select, input', elements.repeatDiv).attr("disabled", 'disabled');
+ }
+ else {
+ $('select, input', elements.repeatDiv).removeAttr("disabled");
+ }
+ };
+
+ if (dateHelper.MoreThanOneDayBetweenBeginAndEnd(elements.beginDate, elements.beginTime, elements.endDate, elements.endTime)) {
+ elements.repeatOptions.data["current"] = elements.repeatOptions.val();
+ repeatToggled = true;
+ SetValue('none', true);
+ }
+ else {
+ if (repeatToggled) {
+ SetValue(elements.repeatOptions.data["current"], false);
+ repeatToggled = false;
+ }
+ }
+ };
+
+ //Adjust date
+ var AdjustTerminationDate = function () {
+ if (terminationDateSetManually) {
+ return;
+ }
+
+ var newEndDate = new Date(elements.beginDate.val());
+ var interval = parseInt(elements.repeatInterval.val());
+ var currentEnd = new Date(elements.repeatTermination.val());
+
+ var repeatOption = elements.repeatOptions.val();
+
+ if (repeatOption == 'daily') {
+ newEndDate.setDate(newEndDate.getDate() + interval);
+ }
+ else if (repeatOption == 'weekly') {
+ newEndDate.setDate(newEndDate.getDate() + (7 * interval));
+ }
+ else if (repeatOption == 'monthly') {
+ newEndDate.setMonth(newEndDate.getMonth() + interval);
+ }
+ else if (repeatOption = 'yearly') {
+ newEndDate.setFullYear(newEndDate.getFullYear() + interval);
+ }
+ else {
+ newEndDate = currentEnd;
+ }
+
+ elements.repeatTerminationTextbox.datepicker("setDate", newEndDate);
+ };
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041947_CreateUser.js b/pool/shard006/JavaScript/0041947_CreateUser.js
new file mode 100644
index 0000000000000000000000000000000000000000..1f152e9694e41aa50730bc2e383e0fb844bc1be3
--- /dev/null
+++ b/pool/shard006/JavaScript/0041947_CreateUser.js
@@ -0,0 +1,113 @@
+import Button from 'react-bootstrap/lib/Button'
+import Col from 'react-bootstrap/lib/Col'
+import React from 'react'
+import Row from 'react-bootstrap/lib/Row'
+import TextField from 'components/TextField'
+import { reduxForm } from 'redux-form'
+import { alphanumericOnly } from 'utils/helpers'
+
+export class CreateUser extends React.Component {
+ render () {
+ const { submitting } = this.props
+ return (
+
+
+
+ Create user
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Create user
+
+
+
+
+
+
+
+ )
+ }
+}
+
+CreateUser.propTypes = {
+ change: React.PropTypes.func,
+ cssName: React.PropTypes.string,
+ submitting: React.PropTypes.bool
+}
+
+CreateUser.defaultProps = {
+ // cssName: 'associated-costs'
+}
+
+const CreateUserReduxForm = reduxForm({
+ form: 'userManagement'
+})(CreateUser)
+
+export default CreateUserReduxForm
diff --git a/pool/shard006/JavaScript/0041951_index.js b/pool/shard006/JavaScript/0041951_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..87f30ae347d1a8c426f406a01af45f0ae559fc14
--- /dev/null
+++ b/pool/shard006/JavaScript/0041951_index.js
@@ -0,0 +1,84 @@
+import React, { Component } from "react";
+import ReactGA from "react-ga";
+import Head from "next/head";
+import Headroom from "react-headroom";
+import slugToTitle from "slug-to-title";
+
+import Nav from "./Nav";
+
+// import "../offline";
+
+const parsePathName = pathname => {
+ if (!pathname) return false;
+ const segments = pathname.split("/");
+ return slugToTitle(segments.pop());
+};
+
+class Layout extends Component {
+ render() {
+ const {
+ children,
+ title,
+ description,
+ url = {},
+ } = this.props;
+ return (
+
+
+
{title || parsePathName(url.pathname) || "Drew & Jen"}
+
+
+
+
+
+
+
+
+
+
+
+
+ {children}
+
+
+
+ Drew and Jen | May 13, 2017
+
+
+
+ );
+ }
+}
+
+Layout.propTypes = {
+ children: React.PropTypes.any,
+ title: React.PropTypes.string,
+ description: React.PropTypes.string,
+ url: React.PropTypes.object,
+};
+
+export default Layout;
diff --git a/pool/shard006/JavaScript/0041952_SessionsExpiredDialog.js b/pool/shard006/JavaScript/0041952_SessionsExpiredDialog.js
new file mode 100644
index 0000000000000000000000000000000000000000..463a3d74f79081016eefc0bed2b3fe8fd046bdb2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041952_SessionsExpiredDialog.js
@@ -0,0 +1,47 @@
+import React from 'react';
+import { withStyles } from '@material-ui/core/styles';
+import Dialog from '@material-ui/core/Dialog';
+import MuiDialogTitle from '@material-ui/core/DialogTitle';
+import MuiDialogContent from '@material-ui/core/DialogContent';
+import MuiDialogActions from '@material-ui/core/DialogActions';
+import Button from '../../components/Buttons';
+
+const styles = () => ({
+ root: {
+ margin: 0,
+ padding: 0,
+ textAlign: 'left'
+ }
+});
+
+const DialogTitle = withStyles(styles)(props => {
+ const { children, classes } = props;
+ return (
+
+ {children}
+
+ );
+});
+
+const DialogContent = withStyles(theme => ({
+ root: {
+ padding: theme.spacing(2),
+ textAlign: 'left'
+ }
+}))(MuiDialogContent);
+
+const SessionsExpiredDialog = ({ onClose, open, i18n }) => (
+
+ {i18n.phrase_session_expired}
+
+ {i18n.text_installation_session_expired}
+
+
+
+ {i18n.word_restart}
+
+
+
+);
+
+export default SessionsExpiredDialog;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041954_users.test.js b/pool/shard006/JavaScript/0041954_users.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..b4eadba14d58d5527d438da1567cf89cd33d3a15
--- /dev/null
+++ b/pool/shard006/JavaScript/0041954_users.test.js
@@ -0,0 +1,127 @@
+const expect = require('chai').expect;
+const supertest = require('supertest');
+const api = supertest('http://localhost');
+const config = require('./config');
+const faker = require('faker');
+
+
+describe('Users', function () {
+ let token = "";
+ let userObject = {
+ username: faker.internet.userName(),
+ group_id: "2",
+ hashedpassword: "klendi",
+ email: faker.internet.email(),
+ telephone: faker.phone.phoneNumber(),
+ isavaible: true,
+ third_party_api_token: "",
+ address: faker.address.streetAddress(),
+ city: faker.address.city(),
+ country: faker.address.country()
+ };
+
+ let usr = {};
+
+ before(function (done) {
+ config.generateToken(tk => {
+ token = tk;
+ done();
+ });
+ });
+
+ it('should create new user', function (done) {
+ api.post('/api/users')
+ .set('Authorization', token)
+ .set('Content-Type', "application/json")
+ .expect('Content-Type', /json/)
+ .send(userObject)
+ .expect(200)
+ .end(function (err, res) {
+ expect(res.body).to.have.property("company_id");
+ expect(res.body.company_id).to.not.equal(null);
+
+ expect(res.body).to.have.property("address");
+ expect(res.body.address).to.equal(userObject.address);
+
+ expect(res.body).to.have.property("country");
+ expect(res.body.country).to.equal(userObject.country);
+
+ expect(res.body).to.have.property("city");
+ expect(res.body.city).to.equal(userObject.city);
+
+ expect(res.body).to.have.property("jwtoken");
+ expect(res.body.jwtoken).to.not.equal(null);
+
+ expect(res.body).to.have.property("username");
+ expect(res.body.username).to.equal(userObject.username);
+
+ expect(res.body).to.have.property("hashedpassword");
+ expect(res.body.hashedpassword).to.not.equal(null);
+
+ expect(res.body).to.have.property("email");
+ expect(res.body.email).to.equal(userObject.email);
+
+ expect(res.body).to.have.property("telephone");
+ expect(res.body.telephone).to.equal(userObject.telephone);
+
+ expect(res.body).to.have.property("salt");
+ expect(res.body.salt).to.not.equal(null);
+
+ expect(res.body).to.have.property("third_party_api_token");
+ expect(res.body.third_party_api_token).to.not.equal(null);
+ usr = res.body;
+ done();
+ });
+ });
+
+ it('should return a 200 response and get users list', function (done) {
+ api.get('/api/users')
+ .set('Authorization', token)
+ .expect('Content-Type', /json/)
+ .expect(200)
+ .end(function (err, res) {
+ expect(res.body).to.be.an('array');
+ done();
+ });
+ });
+
+
+ it('should fetch user', function (done) {
+ api.get('/api/users/' + usr.id)
+ .expect('Content-Type', /json/)
+ .set('Authorization', token)
+ .expect(200)
+ .end(function (err, res) {
+ expect(res.body).to.have.property("username");
+ expect(res.body.name).to.equal(usr.name);
+
+ expect(res.body).to.have.property("email");
+ expect(res.body.email).to.equal(usr.email);
+
+ expect(res.body).to.have.property("telephone");
+ expect(res.body.telephone).to.equal(usr.telephone);
+
+ expect(res.body).to.have.property("group");
+ expect(res.body.role).to.not.equal(null);
+
+ expect(res.body).to.have.property("company_id");
+ expect(res.body.company_id).to.not.equal(null);
+
+ expect(res.body).to.have.property("hashedpassword");
+ expect(res.body.hashedpassword).to.not.equal(null);
+
+ expect(res.body).to.have.property("salt");
+ expect(res.body.salt).to.not.equal(null);
+
+ expect(res.body).to.have.property("country");
+ expect(res.body.country).to.equal(usr.country);
+
+ expect(res.body).to.have.property("city");
+ expect(res.body.city).to.equal(usr.city);
+
+ done();
+ });
+ });
+
+
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041956_BoxGraphics.js b/pool/shard006/JavaScript/0041956_BoxGraphics.js
new file mode 100644
index 0000000000000000000000000000000000000000..981782d7d6fa399e1927297b0dc0fc23263a590e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041956_BoxGraphics.js
@@ -0,0 +1,202 @@
+import defaultValue from "../Core/defaultValue.js";
+import defined from "../Core/defined.js";
+import DeveloperError from "../Core/DeveloperError.js";
+import Event from "../Core/Event.js";
+import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
+import createPropertyDescriptor from "./createPropertyDescriptor.js";
+
+/**
+ * Describes a box. The center position and orientation are determined by the containing {@link Entity}.
+ *
+ * @alias BoxGraphics
+ * @constructor
+ *
+ * @param {Object} [options] Object with the following properties:
+ * @param {Property} [options.show=true] A boolean Property specifying the visibility of the box.
+ * @param {Property} [options.dimensions] A {@link Cartesian3} Property specifying the length, width, and height of the box.
+ * @param {Property} [options.heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
+ * @param {Property} [options.fill=true] A boolean Property specifying whether the box is filled with the provided material.
+ * @param {MaterialProperty} [options.material=Color.WHITE] A Property specifying the material used to fill the box.
+ * @param {Property} [options.outline=false] A boolean Property specifying whether the box is outlined.
+ * @param {Property} [options.outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
+ * @param {Property} [options.outlineWidth=1.0] A numeric Property specifying the width of the outline.
+ * @param {Property} [options.shadows=ShadowMode.DISABLED] An enum Property specifying whether the box casts or receives shadows from light sources.
+ * @param {Property} [options.distanceDisplayCondition] A Property specifying at what distance from the camera that this box will be displayed.
+ *
+ * @demo {@link https://sandcastle.cesium.com/index.html?src=Box.html|Cesium Sandcastle Box Demo}
+ */
+function BoxGraphics(options) {
+ this._definitionChanged = new Event();
+ this._show = undefined;
+ this._showSubscription = undefined;
+ this._dimensions = undefined;
+ this._dimensionsSubscription = undefined;
+ this._heightReference = undefined;
+ this._heightReferenceSubscription = undefined;
+ this._fill = undefined;
+ this._fillSubscription = undefined;
+ this._material = undefined;
+ this._materialSubscription = undefined;
+ this._outline = undefined;
+ this._outlineSubscription = undefined;
+ this._outlineColor = undefined;
+ this._outlineColorSubscription = undefined;
+ this._outlineWidth = undefined;
+ this._outlineWidthSubscription = undefined;
+ this._shadows = undefined;
+ this._shadowsSubscription = undefined;
+ this._distanceDisplayCondition = undefined;
+ this._distanceDisplayConditionSubscription = undefined;
+
+ this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
+}
+
+Object.defineProperties(BoxGraphics.prototype, {
+ /**
+ * Gets the event that is raised whenever a property or sub-property is changed or modified.
+ * @memberof BoxGraphics.prototype
+ * @type {Event}
+ * @readonly
+ */
+ definitionChanged: {
+ get: function () {
+ return this._definitionChanged;
+ },
+ },
+
+ /**
+ * Gets or sets the boolean Property specifying the visibility of the box.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default true
+ */
+ show: createPropertyDescriptor("show"),
+
+ /**
+ * Gets or sets {@link Cartesian3} Property property specifying the length, width, and height of the box.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ */
+ dimensions: createPropertyDescriptor("dimensions"),
+
+ /**
+ * Gets or sets the Property specifying the {@link HeightReference}.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default HeightReference.NONE
+ */
+ heightReference: createPropertyDescriptor("heightReference"),
+
+ /**
+ * Gets or sets the boolean Property specifying whether the box is filled with the provided material.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default true
+ */
+ fill: createPropertyDescriptor("fill"),
+
+ /**
+ * Gets or sets the material used to fill the box.
+ * @memberof BoxGraphics.prototype
+ * @type {MaterialProperty}
+ * @default Color.WHITE
+ */
+ material: createMaterialPropertyDescriptor("material"),
+
+ /**
+ * Gets or sets the Property specifying whether the box is outlined.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default false
+ */
+ outline: createPropertyDescriptor("outline"),
+
+ /**
+ * Gets or sets the Property specifying the {@link Color} of the outline.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default Color.BLACK
+ */
+ outlineColor: createPropertyDescriptor("outlineColor"),
+
+ /**
+ * Gets or sets the numeric Property specifying the width of the outline.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default 1.0
+ */
+ outlineWidth: createPropertyDescriptor("outlineWidth"),
+
+ /**
+ * Get or sets the enum Property specifying whether the box
+ * casts or receives shadows from light sources.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ * @default ShadowMode.DISABLED
+ */
+ shadows: createPropertyDescriptor("shadows"),
+
+ /**
+ * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this box will be displayed.
+ * @memberof BoxGraphics.prototype
+ * @type {Property}
+ */
+ distanceDisplayCondition: createPropertyDescriptor(
+ "distanceDisplayCondition"
+ ),
+});
+
+/**
+ * Duplicates this instance.
+ *
+ * @param {BoxGraphics} [result] The object onto which to store the result.
+ * @returns {BoxGraphics} The modified result parameter or a new instance if one was not provided.
+ */
+BoxGraphics.prototype.clone = function (result) {
+ if (!defined(result)) {
+ return new BoxGraphics(this);
+ }
+ result.show = this.show;
+ result.dimensions = this.dimensions;
+ result.heightReference = this.heightReference;
+ result.fill = this.fill;
+ result.material = this.material;
+ result.outline = this.outline;
+ result.outlineColor = this.outlineColor;
+ result.outlineWidth = this.outlineWidth;
+ result.shadows = this.shadows;
+ result.distanceDisplayCondition = this.distanceDisplayCondition;
+ return result;
+};
+
+/**
+ * Assigns each unassigned property on this object to the value
+ * of the same property on the provided source object.
+ *
+ * @param {BoxGraphics} source The object to be merged into this object.
+ */
+BoxGraphics.prototype.merge = function (source) {
+ //>>includeStart('debug', pragmas.debug);
+ if (!defined(source)) {
+ throw new DeveloperError("source is required.");
+ }
+ //>>includeEnd('debug');
+
+ this.show = defaultValue(this.show, source.show);
+ this.dimensions = defaultValue(this.dimensions, source.dimensions);
+ this.heightReference = defaultValue(
+ this.heightReference,
+ source.heightReference
+ );
+ this.fill = defaultValue(this.fill, source.fill);
+ this.material = defaultValue(this.material, source.material);
+ this.outline = defaultValue(this.outline, source.outline);
+ this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
+ this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
+ this.shadows = defaultValue(this.shadows, source.shadows);
+ this.distanceDisplayCondition = defaultValue(
+ this.distanceDisplayCondition,
+ source.distanceDisplayCondition
+ );
+};
+export default BoxGraphics;
diff --git a/pool/shard006/JavaScript/0041958_tile.js b/pool/shard006/JavaScript/0041958_tile.js
new file mode 100644
index 0000000000000000000000000000000000000000..8b7d57fd1597f65087a8132f1f60d0fb2be2ad4d
--- /dev/null
+++ b/pool/shard006/JavaScript/0041958_tile.js
@@ -0,0 +1,86 @@
+function tile(id){
+ this.id = id;
+ this.frontColor = '#fcfcfc';
+ this.backColor = '#fff';
+ this.startAt = 1000;
+ this.flipped = false;
+ this.backContentImage = null;
+ this.flipCompleteCallbacks = null;
+
+ this.setBackContentImage = function(image){
+ this.backContentImage = image;
+ }
+
+ this.setFrontColor = function(color){
+ this.frontColor = color;
+ }
+
+ this.setStartAt = function(timer){
+ this.startAt = timer;
+ }
+
+ this.setFlipMethod = function(flipMethod){
+ this.flipMethod = flipMethod;
+ }
+
+ this.markSelected = function(){
+ this.removeSelection();
+ $('#'+this.id).addClass('markSelected');
+ //$('#'+this.id).css({'width':"96px", 'height':"96px"});
+ }
+
+ this.removeSelection = function(){
+ $('.tile').removeClass('markSelected');
+ //$('.tile').css({'width':"100px", 'height':"100px"});
+ }
+
+ this.getHtml = function(){
+ var tileId = parseInt(this.id.substr('tile'.length))+1;
+ return '' + '
';
+ }
+
+ this.getFlipped = function(){
+ return this.flipped;
+ }
+
+ this.getStartAt = function(){
+ return this.startAt;
+ }
+
+ this.getBackContent = function() {
+ return ' ';
+ };
+
+ this.getBackContentImage = function(){
+ return this.backContentImage;
+ }
+
+ this.onComplete = function(){
+ if(this.flipCompleteCallbacks !== null){
+ this.flipCompleteCallbacks();
+ this.flipCompleteCallbacks = null;
+ }
+ }
+
+ this.flip = function(){
+ $('#'+this.id).flip({
+ direction: this.flipMethod,
+ color: this.backColor,
+ content: this.getBackContent(),
+ onEnd: this.onComplete()
+ });
+
+ this.flipped = true;
+ }
+
+ this.revertFlip = function(){
+ $('#'+ this.id+ " img").hide();
+ $("#"+ this.id).revertFlip();
+
+ this.flipped = false;
+ }
+
+ this.addFlipCompleteCallback = function(callBack){
+ this.flipCompleteCallbacks = callBack;
+ }
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041961_loadingstrategy.js b/pool/shard006/JavaScript/0041961_loadingstrategy.js
new file mode 100644
index 0000000000000000000000000000000000000000..e27301e89507d8002fc41eeefa03c0d61e51c6d3
--- /dev/null
+++ b/pool/shard006/JavaScript/0041961_loadingstrategy.js
@@ -0,0 +1,74 @@
+/**
+ * @module ol/loadingstrategy
+ */
+
+import {fromUserExtent, fromUserResolution, toUserExtent} from './proj.js';
+
+/**
+ * Strategy function for loading all features with a single request.
+ * @param {import("./extent.js").Extent} extent Extent.
+ * @param {number} resolution Resolution.
+ * @return {Array} Extents.
+ * @api
+ */
+export function all(extent, resolution) {
+ return [[-Infinity, -Infinity, Infinity, Infinity]];
+}
+
+/**
+ * Strategy function for loading features based on the view's extent and
+ * resolution.
+ * @param {import("./extent.js").Extent} extent Extent.
+ * @param {number} resolution Resolution.
+ * @return {Array} Extents.
+ * @api
+ */
+export function bbox(extent, resolution) {
+ return [extent];
+}
+
+/**
+ * Creates a strategy function for loading features based on a tile grid.
+ * @param {import("./tilegrid/TileGrid.js").default} tileGrid Tile grid.
+ * @return {function(import("./extent.js").Extent, number, import("./proj.js").Projection): Array} Loading strategy.
+ * @api
+ */
+export function tile(tileGrid) {
+ return (
+ /**
+ * @param {import("./extent.js").Extent} extent Extent.
+ * @param {number} resolution Resolution.
+ * @param {import("./proj.js").Projection} projection Projection.
+ * @return {Array} Extents.
+ */
+ function (extent, resolution, projection) {
+ const z = tileGrid.getZForResolution(
+ fromUserResolution(resolution, projection)
+ );
+ const tileRange = tileGrid.getTileRangeForExtentAndZ(
+ fromUserExtent(extent, projection),
+ z
+ );
+ /** @type {Array} */
+ const extents = [];
+ /** @type {import("./tilecoord.js").TileCoord} */
+ const tileCoord = [z, 0, 0];
+ for (
+ tileCoord[1] = tileRange.minX;
+ tileCoord[1] <= tileRange.maxX;
+ ++tileCoord[1]
+ ) {
+ for (
+ tileCoord[2] = tileRange.minY;
+ tileCoord[2] <= tileRange.maxY;
+ ++tileCoord[2]
+ ) {
+ extents.push(
+ toUserExtent(tileGrid.getTileCoordExtent(tileCoord), projection)
+ );
+ }
+ }
+ return extents;
+ }
+ );
+}
diff --git a/pool/shard006/JavaScript/0041962_Target.js b/pool/shard006/JavaScript/0041962_Target.js
new file mode 100644
index 0000000000000000000000000000000000000000..26a03955181ec71b482e0957a9d1aa4fd561ee51
--- /dev/null
+++ b/pool/shard006/JavaScript/0041962_Target.js
@@ -0,0 +1,188 @@
+/**
+ * @module ol/events/Target
+ */
+import Disposable from '../Disposable.js';
+import Event from './Event.js';
+import {VOID} from '../functions.js';
+import {clear} from '../obj.js';
+
+/**
+ * @typedef {EventTarget|Target} EventTargetLike
+ */
+
+/**
+ * @classdesc
+ * A simplified implementation of the W3C DOM Level 2 EventTarget interface.
+ * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget.
+ *
+ * There are two important simplifications compared to the specification:
+ *
+ * 1. The handling of `useCapture` in `addEventListener` and
+ * `removeEventListener`. There is no real capture model.
+ * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`.
+ * There is no event target hierarchy. When a listener calls
+ * `stopPropagation` or `preventDefault` on an event object, it means that no
+ * more listeners after this one will be called. Same as when the listener
+ * returns false.
+ */
+class Target extends Disposable {
+ /**
+ * @param {*} [opt_target] Default event target for dispatched events.
+ */
+ constructor(opt_target) {
+ super();
+
+ /**
+ * @private
+ * @type {*}
+ */
+ this.eventTarget_ = opt_target;
+
+ /**
+ * @private
+ * @type {Object}
+ */
+ this.pendingRemovals_ = null;
+
+ /**
+ * @private
+ * @type {Object}
+ */
+ this.dispatching_ = null;
+
+ /**
+ * @private
+ * @type {Object>}
+ */
+ this.listeners_ = null;
+ }
+
+ /**
+ * @param {string} type Type.
+ * @param {import("../events.js").Listener} listener Listener.
+ */
+ addEventListener(type, listener) {
+ if (!type || !listener) {
+ return;
+ }
+ const listeners = this.listeners_ || (this.listeners_ = {});
+ const listenersForType = listeners[type] || (listeners[type] = []);
+ if (listenersForType.indexOf(listener) === -1) {
+ listenersForType.push(listener);
+ }
+ }
+
+ /**
+ * Dispatches an event and calls all listeners listening for events
+ * of this type. The event parameter can either be a string or an
+ * Object with a `type` property.
+ *
+ * @param {import("./Event.js").default|string} event Event object.
+ * @return {boolean|undefined} `false` if anyone called preventDefault on the
+ * event object or if any of the listeners returned false.
+ * @api
+ */
+ dispatchEvent(event) {
+ const isString = typeof event === 'string';
+ const type = isString ? event : event.type;
+ const listeners = this.listeners_ && this.listeners_[type];
+ if (!listeners) {
+ return;
+ }
+
+ const evt = isString ? new Event(event) : /** @type {Event} */ (event);
+ if (!evt.target) {
+ evt.target = this.eventTarget_ || this;
+ }
+ const dispatching = this.dispatching_ || (this.dispatching_ = {});
+ const pendingRemovals =
+ this.pendingRemovals_ || (this.pendingRemovals_ = {});
+ if (!(type in dispatching)) {
+ dispatching[type] = 0;
+ pendingRemovals[type] = 0;
+ }
+ ++dispatching[type];
+ let propagate;
+ for (let i = 0, ii = listeners.length; i < ii; ++i) {
+ if ('handleEvent' in listeners[i]) {
+ propagate = /** @type {import("../events.js").ListenerObject} */ (
+ listeners[i]
+ ).handleEvent(evt);
+ } else {
+ propagate = /** @type {import("../events.js").ListenerFunction} */ (
+ listeners[i]
+ ).call(this, evt);
+ }
+ if (propagate === false || evt.propagationStopped) {
+ propagate = false;
+ break;
+ }
+ }
+ if (--dispatching[type] === 0) {
+ let pr = pendingRemovals[type];
+ delete pendingRemovals[type];
+ while (pr--) {
+ this.removeEventListener(type, VOID);
+ }
+ delete dispatching[type];
+ }
+ return propagate;
+ }
+
+ /**
+ * Clean up.
+ */
+ disposeInternal() {
+ this.listeners_ && clear(this.listeners_);
+ }
+
+ /**
+ * Get the listeners for a specified event type. Listeners are returned in the
+ * order that they will be called in.
+ *
+ * @param {string} type Type.
+ * @return {Array|undefined} Listeners.
+ */
+ getListeners(type) {
+ return (this.listeners_ && this.listeners_[type]) || undefined;
+ }
+
+ /**
+ * @param {string} [opt_type] Type. If not provided,
+ * `true` will be returned if this event target has any listeners.
+ * @return {boolean} Has listeners.
+ */
+ hasListener(opt_type) {
+ if (!this.listeners_) {
+ return false;
+ }
+ return opt_type
+ ? opt_type in this.listeners_
+ : Object.keys(this.listeners_).length > 0;
+ }
+
+ /**
+ * @param {string} type Type.
+ * @param {import("../events.js").Listener} listener Listener.
+ */
+ removeEventListener(type, listener) {
+ const listeners = this.listeners_ && this.listeners_[type];
+ if (listeners) {
+ const index = listeners.indexOf(listener);
+ if (index !== -1) {
+ if (this.pendingRemovals_ && type in this.pendingRemovals_) {
+ // make listener a no-op, and remove later in #dispatchEvent()
+ listeners[index] = VOID;
+ ++this.pendingRemovals_[type];
+ } else {
+ listeners.splice(index, 1);
+ if (listeners.length === 0) {
+ delete this.listeners_[type];
+ }
+ }
+ }
+ }
+ }
+}
+
+export default Target;
diff --git a/pool/shard006/JavaScript/0041963_parabola.js b/pool/shard006/JavaScript/0041963_parabola.js
new file mode 100644
index 0000000000000000000000000000000000000000..60d65f8f165cf0e3a9f9e203cdd8bc9995f426c5
--- /dev/null
+++ b/pool/shard006/JavaScript/0041963_parabola.js
@@ -0,0 +1,212 @@
+/*!
+ * by zhangxinxu(.com) 2012-12-27
+ * you can visit http://www.zhangxinxu.com/wordpress/?p=3855 to get more infomation
+ * under MIT license
+*/
+var funParabola = function(element, target, options) {
+ /*
+ * 网页模拟现实需要一个比例尺
+ * 如果按照1像素就是1米来算,显然不合适,因为页面动不动就几百像素
+ * 页面上,我们放两个物体,200~800像素之间,我们可以映射为现实世界的2米到8米,也就是100:1
+ * 不过,本方法没有对此有所体现,因此不必在意
+ */
+
+ var defaults = {
+ speed: 166.67, // 每帧移动的像素大小,每帧(对于大部分显示屏)大约16~17毫秒
+ curvature: 0.001, // 实际指焦点到准线的距离,你可以抽象成曲率,这里模拟扔物体的抛物线,因此是开口向下的
+ progress: function() {},
+ complete: function() {}
+ };
+
+ var params = {}; options = options || {};
+
+ for (var key in defaults) {
+ params[key] = options[key] || defaults[key];
+ }
+
+ var exports = {
+ mark: function() { return this; },
+ position: function() { return this; },
+ move: function() { return this; },
+ init: function() { return this; }
+ };
+
+ /* 确定移动的方式
+ * IE6-IE8 是margin位移
+ * IE9+使用transform
+ */
+ var moveStyle = "margin", testDiv = document.createElement("div");
+ if ("oninput" in testDiv) {
+ ["", "ms", "webkit"].forEach(function(prefix) {
+ var transform = prefix + (prefix? "T": "t") + "ransform";
+ if (transform in testDiv.style) {
+ moveStyle = transform;
+ }
+ });
+ }
+
+ // 根据两点坐标以及曲率确定运动曲线函数(也就是确定a, b的值)
+ /* 公式: y = a*x*x + b*x + c;
+ */
+ var a = params.curvature, b = 0, c = 0;
+
+ // 是否执行运动的标志量
+ var flagMove = true;
+
+ if (element && target && element.nodeType == 1 && target.nodeType == 1) {
+ var rectElement = {}, rectTarget = {};
+
+ // 移动元素的中心点位置,目标元素的中心点位置
+ var centerElement = {}, centerTarget = {};
+
+ // 目标元素的坐标位置
+ var coordElement = {}, coordTarget = {};
+
+ // 标注当前元素的坐标
+ exports.mark = function() {
+ if (flagMove == false) return this;
+ if (typeof coordElement.x == "undefined") this.position();
+ element.setAttribute("data-center", [coordElement.x, coordElement.y].join());
+ target.setAttribute("data-center", [coordTarget.x, coordTarget.y].join());
+ return this;
+ }
+
+ exports.position = function() {
+ if (flagMove == false) return this;
+
+ var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft,
+ scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
+
+ // 初始位置
+ if (moveStyle == "margin") {
+ element.style.marginLeft = element.style.marginTop = "0px";
+ } else {
+ element.style[moveStyle] = "translate(0, 0)";
+ }
+
+ // 四边缘的坐标
+ rectElement = element.getBoundingClientRect();
+ rectTarget = target.getBoundingClientRect();
+
+ // 移动元素的中心点坐标
+ centerElement = {
+ x: rectElement.left + (rectElement.right - rectElement.left) / 2 + scrollLeft,
+ y: rectElement.top + (rectElement.bottom - rectElement.top) / 2 + scrollTop
+ };
+
+ // 目标元素的中心点位置
+ centerTarget = {
+ x: rectTarget.left + (rectTarget.right - rectTarget.left) / 2 + scrollLeft,
+ y: rectTarget.top + (rectTarget.bottom - rectTarget.top) / 2 + scrollTop
+ };
+
+ // 转换成相对坐标位置
+ coordElement = {
+ x: 0,
+ y: 0
+ };
+ coordTarget = {
+ x: -1 * (centerElement.x - centerTarget.x),
+ y: -1 * (centerElement.y - centerTarget.y)
+ };
+
+ /*
+ * 因为经过(0, 0), 因此c = 0
+ * 于是:
+ * y = a * x*x + b*x;
+ * y1 = a * x1*x1 + b*x1;
+ * y2 = a * x2*x2 + b*x2;
+ * 利用第二个坐标:
+ * b = (y2+ a*x2*x2) / x2
+ */
+ // 于是
+ b = (coordTarget.y - a * coordTarget.x * coordTarget.x) / coordTarget.x;
+
+ return this;
+ };
+
+ // 按照这个曲线运动
+ exports.move = function() {
+ // 如果曲线运动还没有结束,不再执行新的运动
+ if (flagMove == false) return this;
+
+ var startx = 0, rate = coordTarget.x > 0? 1: -1;
+
+ var step = function() {
+ // 切线 y'=2ax+b
+ var tangent = 2 * a * startx + b; // = y / x
+ // y*y + x*x = speed
+ // (tangent * x)^2 + x*x = speed
+ // x = Math.sqr(speed / (tangent * tangent + 1));
+ startx = startx + rate * Math.sqrt(params.speed / (tangent * tangent + 1));
+
+ // 防止过界
+ if ((rate == 1 && startx > coordTarget.x) || (rate == -1 && startx < coordTarget.x)) {
+ startx = coordTarget.x;
+ }
+ var x = startx, y = a * x * x + b * x;
+
+ // 标记当前位置,这里有测试使用的嫌疑,实际使用可以将这一行注释
+ element.setAttribute("data-center", [Math.round(x), Math.round(y)].join());
+
+ // x, y目前是坐标,需要转换成定位的像素值
+ if (moveStyle == "margin") {
+ element.style.marginLeft = x + "px";
+ element.style.marginTop = y + "px";
+ } else {
+ element.style[moveStyle] = "translate("+ [x + "px", y + "px"].join() +")";
+ }
+
+ if (startx !== coordTarget.x) {
+ params.progress(x, y);
+ window.requestAnimationFrame(step);
+ } else {
+ // 运动结束,回调执行
+ params.complete();
+ flagMove = true;
+ }
+ };
+ window.requestAnimationFrame(step);
+ flagMove = false;
+
+ return this;
+ };
+
+ // 初始化方法
+ exports.init = function() {
+ this.position().mark().move();
+ };
+ }
+
+ return exports;
+};
+
+/*! requestAnimationFrame.js
+ * by zhangxinxu 2013-09-30
+*/
+(function() {
+ var lastTime = 0;
+ var vendors = ['webkit', 'moz'];
+ for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
+ window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
+ window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // name has changed in Webkit
+ window[vendors[x] + 'CancelRequestAnimationFrame'];
+ }
+
+ if (!window.requestAnimationFrame) {
+ window.requestAnimationFrame = function(callback, element) {
+ var currTime = new Date().getTime();
+ var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
+ var id = window.setTimeout(function() {
+ callback(currTime + timeToCall);
+ }, timeToCall);
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+ }
+ if (!window.cancelAnimationFrame) {
+ window.cancelAnimationFrame = function(id) {
+ clearTimeout(id);
+ };
+ }
+}());
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041964_number-round.filter.js b/pool/shard006/JavaScript/0041964_number-round.filter.js
new file mode 100644
index 0000000000000000000000000000000000000000..797194180bf6cd8aa3ee70447c13974d9fb668dd
--- /dev/null
+++ b/pool/shard006/JavaScript/0041964_number-round.filter.js
@@ -0,0 +1,39 @@
+/**
+ * Number Round Filter
+ * @namespace Filters
+ */
+(function() { // IIFE structure
+ 'use strict'; // Strict mode
+
+ angular
+ .module('app.core')
+ .filter('numberRound', numberRound);
+
+ numberRound.$inject = ['$locale', 'numberFilter'];
+
+ /**
+ * @namespace numberRound
+ * @desc Filter for rounding a number
+ * @memberof Filters
+ */
+ function numberRound($locale, numberFilter) {
+ var formats = $locale.NUMBER_FORMATS;
+
+ return function(input, fractionSize) {
+ // Get formatted value
+ var formattedValue = numberFilter(input, fractionSize);
+
+ // Get the decimalSepPosition
+ var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP);
+
+ // If no decimal just return
+ if (decimalIdx === -1) { return formattedValue; }
+
+ // Build rounded number
+ var whole = formattedValue.substring(0, decimalIdx);
+ var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString();
+
+ return whole + decimal.substring(1);
+ }
+ }
+})();
diff --git a/pool/shard006/JavaScript/0041970_series.js b/pool/shard006/JavaScript/0041970_series.js
new file mode 100644
index 0000000000000000000000000000000000000000..a08358f316edc6e16e1c232f203e03abf78a2dee
--- /dev/null
+++ b/pool/shard006/JavaScript/0041970_series.js
@@ -0,0 +1,114 @@
+define([
+ 'underscore',
+ 'backbone',
+ 'data/episodes',
+ 'data/schedule'
+], function(_, Backbone, EpisodesFactory, ScheduleFactory) {
+ var status = {
+ IN_PROGRESS: '0',
+ FINISHED: '1',
+ CLOSED: '2'
+ },
+ viewed = {
+ YES: '1',
+ NO: '0'
+ },
+ statusMap = ['снимается', 'закончен', 'закрыт'],
+ privateProps = {};
+
+ return Backbone.Model.extend({
+ idAttribute: 'sid',
+
+ status: status,
+ viewed: viewed,
+
+ defaults: {
+ sid: null,
+ title: '',
+ title_ru: '',
+ description: '',
+ year: '1970',
+ imdb_rating: '0.0',
+ imdb_votes: 0,
+ tvdb_id: '',
+ imdb_id: '',
+ status: status.CLOSED,
+ viewed: viewed.NO,
+ unwatched: 0
+ },
+
+ initialize: function() {
+ privateProps[this.cid] = {
+ reviews: null,
+ schedule: ScheduleFactory(this.id),
+ episodes: EpisodesFactory(this.id),
+ recomendations: null
+ }
+ },
+
+ parse: function(data) {
+ data.sid = parseInt(data.sid, 10);
+ data.unwatched || (data.unwatched = 0);
+ return data;
+ },
+
+ getInfo: function() {
+ return {
+ info: {
+ status: statusMap[this.get('status')],
+ year: this.get('year')
+ }
+ }
+ },
+
+ getEpisodes: function() {
+ return {
+ episodes: privateProps[this.cid].episodes.toJSON()
+ };
+ },
+
+ getSchedule: function() {
+ return {
+ schedule: privateProps[this.cid].schedule.toJSON()
+ };
+ },
+
+ getSeasons: function() {
+ var seasons = [];
+
+ _.each(privateProps[this.cid].episodes.toJSON(), function(episode) {
+ var index = +episode.season - 1;
+
+ if (!seasons[index]) {
+ seasons[index] = {
+ id: episode.season_id,
+ season: episode.season,
+ tags: {
+ hd: false,
+ sd: false,
+ subs: false
+ },
+ unwatched: 0
+ };
+ }
+
+ switch (episode.quality.toLowerCase()) {
+ case 'sd':
+ seasons[index].tags.sd = true;
+ break;
+ case '720p':
+ seasons[index].tags.hd = true;
+ break;
+ }
+
+ if (episode.watched == 0) {
+ seasons[index].unwatched++;
+ }
+ });
+
+ return {
+ seasons: seasons
+ };
+ }
+ });
+});
diff --git a/pool/shard006/JavaScript/0041972_index.js b/pool/shard006/JavaScript/0041972_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..066a7f146efcc9282a867706e0348a0b39031867
--- /dev/null
+++ b/pool/shard006/JavaScript/0041972_index.js
@@ -0,0 +1,15 @@
+var config = require('../../config');
+var mongojs = require('mongojs');
+var db = mongojs(config.DATABASE_URL, ['schools']);
+var schools = db.schools;
+
+exports.getNames = function(callback) {
+ schools.find({}, {name: 1, _id: 1}, function(err, results) {
+ if (err) throw err;
+ schools = {};
+ results.forEach(function(school) {
+ schools[school._id] = school.name;
+ });
+ return callback(schools);
+ });
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041979_index.js b/pool/shard006/JavaScript/0041979_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..45f485bfe1226d2c4d7803c27bef7f6438b79698
--- /dev/null
+++ b/pool/shard006/JavaScript/0041979_index.js
@@ -0,0 +1,74 @@
+/**
+ *
+ * @projectName nools
+ * @github https://github.com/C2FO/nools
+ * @includeDoc [Examples] ../docs-md/examples.md
+ * @includeDoc [Change Log] ../history.md
+ * @header [../readme.md]
+ */
+
+"use strict";
+var extd = require("./extended"),
+ fs = require("fs"),
+ path = require("path"),
+ compile = require("./compile"),
+ FlowContainer = require("./flowContainer");
+
+function isNoolsFile(file) {
+ return (/\.nools$/).test(file);
+}
+
+function parse(source) {
+ var ret;
+ if (isNoolsFile(source)) {
+ ret = compile.parse(fs.readFileSync(source, "utf8"), source);
+ } else {
+ ret = compile.parse(source);
+ }
+ return ret;
+}
+
+exports.Flow = FlowContainer;
+
+exports.getFlow = FlowContainer.getFlow;
+exports.hasFlow = FlowContainer.hasFlow;
+
+exports.deleteFlow = function (name) {
+ FlowContainer.deleteFlow(name);
+ return this;
+};
+
+exports.deleteFlows = function () {
+ FlowContainer.deleteFlows();
+ return this;
+};
+
+exports.flow = FlowContainer.create;
+
+exports.compile = function (file, options, cb) {
+ if (extd.isFunction(options)) {
+ cb = options;
+ options = {};
+ } else {
+ options = options || {};
+ }
+ if (extd.isString(file)) {
+ options.name = options.name || (isNoolsFile(file) ? path.basename(file, path.extname(file)) : null);
+ file = parse(file);
+ }
+ if (!options.name) {
+ throw new Error("Name required when compiling nools source");
+ }
+ return compile.compile(file, options, cb, FlowContainer);
+};
+
+exports.transpile = function (file, options) {
+ options = options || {};
+ if (extd.isString(file)) {
+ options.name = options.name || (isNoolsFile(file) ? path.basename(file, path.extname(file)) : null);
+ file = parse(file);
+ }
+ return compile.transpile(file, options);
+};
+
+exports.parse = parse;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041981_UnsavedDialog__test.js b/pool/shard006/JavaScript/0041981_UnsavedDialog__test.js
new file mode 100644
index 0000000000000000000000000000000000000000..c907638cb9f853995ada0956ae268e38e7e0218e
--- /dev/null
+++ b/pool/shard006/JavaScript/0041981_UnsavedDialog__test.js
@@ -0,0 +1,41 @@
+/**
+ * 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.
+ */
+
+describe('UnsavedDialog Service', function () {
+ var UnsavedDialog, $modal;
+
+ beforeEach(module('ambariAdminConsole', function($provide){
+ }));
+
+ beforeEach(inject(function (_UnsavedDialog_, _$modal_) {
+ UnsavedDialog = _UnsavedDialog_;
+ $modal = _$modal_;
+
+ spyOn($modal, 'open').and.returnValue({
+ result: {
+ then: function() {
+ }
+ }
+ });
+ }));
+
+ it('should open modal window', function () {
+ UnsavedDialog();
+ expect($modal.open).toHaveBeenCalled();
+ });
+});
diff --git a/pool/shard006/JavaScript/0041984_test.js b/pool/shard006/JavaScript/0041984_test.js
new file mode 100644
index 0000000000000000000000000000000000000000..4cc3b8f088a13b254ab0969e99f7a128fe3505e0
--- /dev/null
+++ b/pool/shard006/JavaScript/0041984_test.js
@@ -0,0 +1,26 @@
+"use strict";
+
+var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
+
+var assert = _interopRequire(require("assert"));
+
+var animate = _interopRequire(require("./"));
+
+var p = document.createElement("p");
+
+p.innerHTML = "HELLO";
+
+document.body.appendChild(p);
+
+animate(function () {
+ return [{ opacity: "0.5", transform: "scale(0.5)" }, { opacity: "1.0", transform: "scale(1)" }];
+}, function () {
+ return { direction: "alternate", duration: 500, iterations: Infinity };
+}, p);
+
+
+it("fd-animate", function () {
+ p.pause();
+ assert.equal(p.playState, "paused");
+ assert.equal(p.currentTime > 1, true);
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0041985_test-utils.js b/pool/shard006/JavaScript/0041985_test-utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..1e023d6200cbee3e6d8244406c8169301ddf9d13
--- /dev/null
+++ b/pool/shard006/JavaScript/0041985_test-utils.js
@@ -0,0 +1,34 @@
+'use strict';
+
+var path = require('path');
+var fs = require('fs');
+
+var copyRecursiveSync = function (src, dest) {
+ if (!fs.existsSync(src)) { return; }
+ if (fs.lstatSync(src).isDirectory()) {
+ if (!fs.existsSync(dest)) { fs.mkdirSync(dest); }
+ fs.readdirSync(src).forEach(function(childItemName) {
+ copyRecursiveSync(path.join(src, childItemName),
+ path.join(dest, childItemName));
+ });
+ } else {
+ fs.writeFileSync(dest, fs.readFileSync(src));
+ }
+};
+
+var deleteRecursiveSync = function(src) {
+ if (!fs.existsSync(src)) { return; }
+ if (fs.lstatSync(src).isDirectory()) {
+ fs.readdirSync(src).forEach(function(childItemName) {
+ deleteRecursiveSync(path.join(src, childItemName))
+ });
+ fs.rmdirSync(src);
+ } else {
+ fs.unlinkSync(src);
+ }
+};
+
+module.exports = {
+ copyRecursiveSync : copyRecursiveSync,
+ deleteRecursiveSync : deleteRecursiveSync
+}
diff --git a/pool/shard006/JavaScript/0041986_VideoTexture.js b/pool/shard006/JavaScript/0041986_VideoTexture.js
new file mode 100644
index 0000000000000000000000000000000000000000..e628b1c60815ce712bdf44ba82456e396476e0e5
--- /dev/null
+++ b/pool/shard006/JavaScript/0041986_VideoTexture.js
@@ -0,0 +1,30 @@
+/**
+ * @author mrdoob / http://mrdoob.com/
+ */
+
+THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
+
+ THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
+
+ this.generateMipmaps = false;
+
+ var scope = this;
+
+ function update() {
+
+ requestAnimationFrame( update );
+
+ if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
+
+ scope.needsUpdate = true;
+
+ }
+
+ }
+
+ update();
+
+};
+
+THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
+THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
diff --git a/pool/shard006/JavaScript/0041990_index.js b/pool/shard006/JavaScript/0041990_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..8ba85a8651bd645a3fc2d59a1097a399a8ee16e2
--- /dev/null
+++ b/pool/shard006/JavaScript/0041990_index.js
@@ -0,0 +1,50 @@
+'use strict'
+
+QUnit.module('Extend plugin', {
+ setup: function () {
+ jss.use(jssExtend)
+ },
+ teardown: function () {
+ jss.plugins.registry = []
+ }
+})
+
+test('simple extend', function () {
+ var a = {float: 'left'}
+ var ss = jss.createStyleSheet({
+ a: a,
+ b: {
+ extend: a,
+ width: '1px'
+ }
+ }, {named: false})
+ ok(ss.rules.a instanceof jss.Rule)
+ ok(ss.rules.b instanceof jss.Rule)
+ equal(ss.toString(), 'a {\n float: left;\n}\nb {\n float: left;\n width: 1px;\n}')
+})
+
+test('multi extend', function () {
+ var a = {float: 'left'}
+ var b = {position: 'absolute'}
+ var ss = jss.createStyleSheet({
+ c: {
+ extend: [a, b],
+ width: '1px'
+ }
+ }, {named: false})
+ ok(ss.rules.c instanceof jss.Rule)
+ equal(ss.toString(), 'c {\n float: left;\n position: absolute;\n width: 1px;\n}')
+})
+
+test('nested extend', function () {
+ var c = {float: 'left'}
+ var b = {extend: c, display: 'none'}
+ var ss = jss.createStyleSheet({
+ a: {
+ extend: b,
+ width: '1px'
+ }
+ }, {named: false})
+ ok(ss.rules.a instanceof jss.Rule)
+ equal(ss.toString(), 'a {\n float: left;\n display: none;\n width: 1px;\n}')
+})
diff --git a/pool/shard006/JavaScript/0041995_layout_defaults.js b/pool/shard006/JavaScript/0041995_layout_defaults.js
new file mode 100644
index 0000000000000000000000000000000000000000..6c7fb220dc6a373577086f2b040c617d3ec96847
--- /dev/null
+++ b/pool/shard006/JavaScript/0041995_layout_defaults.js
@@ -0,0 +1,231 @@
+/**
+* Copyright 2012-2019, Plotly, Inc.
+* 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.
+*/
+
+'use strict';
+
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+var Template = require('../../plot_api/plot_template');
+
+var handleSubplotDefaults = require('../subplot_defaults');
+var getSubplotData = require('../get_data').getSubplotData;
+
+var handleTickValueDefaults = require('../cartesian/tick_value_defaults');
+var handleTickMarkDefaults = require('../cartesian/tick_mark_defaults');
+var handleTickLabelDefaults = require('../cartesian/tick_label_defaults');
+var handleCategoryOrderDefaults = require('../cartesian/category_order_defaults');
+var handleLineGridDefaults = require('../cartesian/line_grid_defaults');
+var autoType = require('../cartesian/axis_autotype');
+
+var layoutAttributes = require('./layout_attributes');
+var setConvert = require('./set_convert');
+var constants = require('./constants');
+var axisNames = constants.axisNames;
+
+function handleDefaults(contIn, contOut, coerce, opts) {
+ var bgColor = coerce('bgcolor');
+ opts.bgColor = Color.combine(bgColor, opts.paper_bgcolor);
+
+ var sector = coerce('sector');
+ coerce('hole');
+
+ // could optimize, subplotData is not always needed!
+ var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
+ var layoutOut = opts.layoutOut;
+ var axName;
+
+ function coerceAxis(attr, dflt) {
+ return coerce(axName + '.' + attr, dflt);
+ }
+
+ for(var i = 0; i < axisNames.length; i++) {
+ axName = axisNames[i];
+
+ if(!Lib.isPlainObject(contIn[axName])) {
+ contIn[axName] = {};
+ }
+
+ var axIn = contIn[axName];
+ var axOut = Template.newContainer(contOut, axName);
+ axOut._id = axOut._name = axName;
+ axOut._attr = opts.id + '.' + axName;
+ axOut._traceIndices = subplotData.map(function(t) { return t._expandedIndex; });
+
+ var dataAttr = constants.axisName2dataArray[axName];
+ var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr);
+
+ handleCategoryOrderDefaults(axIn, axOut, coerceAxis, {
+ axData: subplotData,
+ dataAttr: dataAttr
+ });
+
+ var visible = coerceAxis('visible');
+ setConvert(axOut, contOut, layoutOut);
+
+ coerceAxis('uirevision', contOut.uirevision);
+
+ var dfltColor;
+ var dfltFontColor;
+
+ if(visible) {
+ dfltColor = coerceAxis('color');
+ dfltFontColor = (dfltColor === axIn.color) ? dfltColor : opts.font.color;
+ }
+
+ // We don't want to make downstream code call ax.setScale,
+ // as both radial and angular axes don't have a set domain.
+ // Furthermore, angular axes don't have a set range.
+ //
+ // Mocked domains and ranges are set by the polar subplot instances,
+ // but Axes.findExtremes uses the sign of _m to determine which padding value
+ // to use.
+ //
+ // By setting, _m to 1 here, we make Axes.findExtremes think that
+ // range[1] > range[0], and vice-versa for `autorange: 'reversed'` below.
+ axOut._m = 1;
+
+ switch(axName) {
+ case 'radialaxis':
+ var autoRange = coerceAxis('autorange', !axOut.isValidRange(axIn.range));
+ axIn.autorange = autoRange;
+ if(autoRange && (axType === 'linear' || axType === '-')) coerceAxis('rangemode');
+ if(autoRange === 'reversed') axOut._m = -1;
+
+ coerceAxis('range');
+ axOut.cleanRange('range', {dfltRange: [0, 1]});
+
+ if(visible) {
+ coerceAxis('side');
+ coerceAxis('angle', sector[0]);
+
+ coerceAxis('title.text');
+ Lib.coerceFont(coerceAxis, 'title.font', {
+ family: opts.font.family,
+ size: Math.round(opts.font.size * 1.2),
+ color: dfltFontColor
+ });
+ }
+ break;
+
+ case 'angularaxis':
+ // We do not support 'true' date angular axes yet,
+ // users can still plot dates on angular axes by setting
+ // `angularaxis.type: 'category'`.
+ //
+ // Here, if a date angular axes is detected, we make
+ // all its corresponding traces invisible, so that
+ // when we do add support for data angular axes, the new
+ // behavior won't conflict with existing behavior
+ if(axType === 'date') {
+ Lib.log('Polar plots do not support date angular axes yet.');
+
+ for(var j = 0; j < subplotData.length; j++) {
+ subplotData[j].visible = false;
+ }
+
+ // turn this into a 'dummy' linear axis so that
+ // the subplot still renders ok
+ axType = axIn.type = axOut.type = 'linear';
+ }
+
+ if(axType === 'linear') {
+ coerceAxis('thetaunit');
+ } else {
+ coerceAxis('period');
+ }
+
+ var direction = coerceAxis('direction');
+ coerceAxis('rotation', {counterclockwise: 0, clockwise: 90}[direction]);
+ break;
+ }
+
+ if(visible) {
+ handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type);
+ handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
+ tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined
+ });
+ handleTickMarkDefaults(axIn, axOut, coerceAxis, {outerTicks: true});
+
+ var showTickLabels = coerceAxis('showticklabels');
+ if(showTickLabels) {
+ Lib.coerceFont(coerceAxis, 'tickfont', {
+ family: opts.font.family,
+ size: opts.font.size,
+ color: dfltFontColor
+ });
+ coerceAxis('tickangle');
+ coerceAxis('tickformat');
+ }
+
+ handleLineGridDefaults(axIn, axOut, coerceAxis, {
+ dfltColor: dfltColor,
+ bgColor: opts.bgColor,
+ // default grid color is darker here (60%, vs cartesian default ~91%)
+ // because the grid is not square so the eye needs heavier cues to follow
+ blend: 60,
+ showLine: true,
+ showGrid: true,
+ noZeroLine: true,
+ attributes: layoutAttributes[axName]
+ });
+
+ coerceAxis('layer');
+ }
+
+ if(axType !== 'category') coerceAxis('hoverformat');
+
+ axOut._input = axIn;
+ }
+
+ if(contOut.angularaxis.type === 'category') {
+ coerce('gridshape');
+ }
+}
+
+function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) {
+ var axType = coerce('type');
+
+ if(axType === '-') {
+ var trace;
+
+ for(var i = 0; i < subplotData.length; i++) {
+ if(subplotData[i].visible) {
+ trace = subplotData[i];
+ break;
+ }
+ }
+
+ if(trace && trace[dataAttr]) {
+ axOut.type = autoType(trace[dataAttr], 'gregorian');
+ }
+
+ if(axOut.type === '-') {
+ axOut.type = 'linear';
+ } else {
+ // copy autoType back to input axis
+ // note that if this object didn't exist
+ // in the input layout, we have to put it in
+ // this happens in the main supplyDefaults function
+ axIn.type = axOut.type;
+ }
+ }
+
+ return axOut.type;
+}
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
+ handleSubplotDefaults(layoutIn, layoutOut, fullData, {
+ type: constants.name,
+ attributes: layoutAttributes,
+ handleDefaults: handleDefaults,
+ font: layoutOut.font,
+ paper_bgcolor: layoutOut.paper_bgcolor,
+ fullData: fullData,
+ layoutOut: layoutOut
+ });
+};
diff --git a/pool/shard006/JavaScript/0041999_kick.js b/pool/shard006/JavaScript/0041999_kick.js
new file mode 100644
index 0000000000000000000000000000000000000000..819c1fca045fd3ae756cb97cc05958b9fa9e14a8
--- /dev/null
+++ b/pool/shard006/JavaScript/0041999_kick.js
@@ -0,0 +1,86 @@
+const { Command } = require('discord.js-commando');
+const { TagDB } = require('../../mysql.js');
+const config = require('../../config.json');
+const SqlTag = new TagDB(config.tagHost, config.tagUser, config.tagPassword, config.caseDatabase);
+const sql = SqlTag.getConnection();
+const Embed = require('../../embeds.js');
+
+
+module.exports = class BanCommand extends Command {
+ constructor(client) {
+ super(client, {
+ name: 'kick',
+ group: 'mod',
+ memberName: 'kick',
+ description: 'Kickt einen Nutzer vom Server',
+ format: ' ',
+ guildOnly: true,
+
+ args: [
+ {
+ key: 'user',
+ prompt: 'Bitte gebe einen Nutzer, der gekickt werden soll an',
+ type: 'user'
+ },
+ {
+ key: 'reason',
+ prompt: 'Bitte gebe einen Grund für den kick an.',
+ type: 'string',
+ default: '',
+ max: 200
+ }
+ ]
+ });
+ }
+
+ hasPermission(msg) {
+ return msg.member.roles.find('name', 'General');
+ }
+
+ async run(msg, args) {
+ if (!msg.guild.member(this.client.user.id).hasPermission('KICK_MEMBERS')) {
+ return msg.reply(`ich habe keine Rechte um zu kicken.`);
+ }
+
+ const user = args.user;
+ const reason = args.reason;
+ const member = msg.guild.member(this.client.users.get(user.id));
+ let caseNumber;
+
+ if (!member.kickable) return msg.reply('Ich kann dies nicht tun.');
+
+ // add query to save case in db
+
+ sql.query('INSERT INTO `cases`(`caseAction`,`caseUser`,`caseModerator`,`caseReason`,`caseMessageID`) VALUES ("Kick",?,?,?,"Placeholder")', [user.id, msg.author.id, reason.length === 0 ? 'None' : reason], (err, results) => {
+ if (err) return msg.reply(`Ups... es gab ein Error beim Hinzufügen des Log Cases ${err}, ${results}`);
+ caseNumber = results.insertId;
+ msg.channel.sendMessage(`Benutze jetzt \`!reason ${caseNumber} \` um den Grund zu ändern`);
+ this.message(caseNumber, msg);
+ member.kick();
+ });
+ }
+ // add code to write a modlog
+ async message(caseNumber, msg) {
+ sql.query('SELECT * FROM `cases` WHERE `caseNumber` = ?', [caseNumber], (err, results) => {
+ if (err) msg.reply('es gab einen Error bei der query für den modlog: ${err}');
+ let caseNum = results[0].caseNumber;
+ let action = results[0].caseAction;
+ let UserID = results[0].caseUser;
+ let ModID = results[0].caseModerator;
+ let reason = results[0].caseReason;
+ let user = msg.client.users.get(UserID);
+ let mod = msg.client.users.get(ModID);
+
+ const newEmbed = new Embed(this.client, msg, caseNum, action, user, mod, reason, null, null, null);
+ let embed = newEmbed.banCase();
+
+ let modChannel = msg.guild.channels.find('name', 'mod_protokoll');
+ return modChannel.sendMessage('', { embed })
+ .then(message => {
+ sql.query('UPDATE `cases` SET `caseMessageID` = ? WHERE `caseNumber` = ?', [message.id, caseNum], (er, res) => {
+ if (err) return msg.reply(`Ups es ist ein Fehler Aufgetreten. ERROR ADDING MESSAGE ID TO CASE : ${er} ${res}`);
+ });
+ });
+ });
+ }
+};
diff --git a/pool/shard006/JavaScript/0042000_auth-reducer.js b/pool/shard006/JavaScript/0042000_auth-reducer.js
new file mode 100644
index 0000000000000000000000000000000000000000..6c5f0401d85ee527c96650118d17715f18d1ef07
--- /dev/null
+++ b/pool/shard006/JavaScript/0042000_auth-reducer.js
@@ -0,0 +1,28 @@
+import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS } from '../actions/types';
+
+const initialState = {
+ isFetching: false,
+ isAuthenticated: localStorage.getItem('id_token') ? true : false,
+ id: localStorage.getItem('id'),
+ role: localStorage.getItem('role'),
+ user_name: localStorage.getItem('user_name')
+};
+
+export default function(state=initialState, action) {
+
+ switch (action.type) {
+ case LOGIN_REQUEST:
+ let { creds } = action.payload;
+ return { ...state, isFetching: true, isAuthenticated: false, user: creds };
+ case LOGIN_SUCCESS:
+ let { id, role, user_name } = action.payload;
+ return { ...state, isFetching: false, isAuthenticated: true, errorMessage: '', id, role, user_name };
+ case LOGIN_FAILURE:
+ let { message } = action.payload;
+ return { ...state, isFetching: false, isAuthenticated: false, errorMessage: message };
+ case LOGOUT_SUCCESS:
+ return { ...state, isFetching: true, isAuthenticated: false, id: null, role: null, user_name: null };
+ default:
+ return state;
+ }
+}
diff --git a/pool/shard006/JavaScript/0042003_static-cache.js b/pool/shard006/JavaScript/0042003_static-cache.js
new file mode 100644
index 0000000000000000000000000000000000000000..d62d8f057d62ab4e894c1132da8762b412597baf
--- /dev/null
+++ b/pool/shard006/JavaScript/0042003_static-cache.js
@@ -0,0 +1,34 @@
+const path = require('path')
+const fs = require('fs')
+
+var cached = {}
+var staticPath = path.join(__dirname, 'static/')
+if (!staticPath.match(/\/$/)) {
+ staticPath = staticPath + '/'
+}
+
+module.exports = function (requestPath, set, done) {
+ requestPath = decodeURIComponent(requestPath)
+ var fpath = path.join(staticPath, requestPath)
+
+ if (requestPath.match(/(^|\/)\.\.($|\/)/) || fpath.substr(0, staticPath.length) !== staticPath) {
+ return done(new Error('Path not valid.'))
+ }
+ var fileName = fpath.substr(staticPath.length)
+ if (cached[fileName]) {
+ done(null, cached[fileName])
+ } else {
+ fs.readFile(fpath, { encoding: 'utf-8' }, function (err, data) {
+ if (err) {
+ return done()
+ }
+ set(fileName, data, function (err, processedData) {
+ if (err) {
+ return done(err)
+ }
+ cached[fileName] = processedData
+ done(null, processedData)
+ })
+ })
+ }
+}
diff --git a/pool/shard006/JavaScript/0042004_isstream-compiled.js b/pool/shard006/JavaScript/0042004_isstream-compiled.js
new file mode 100644
index 0000000000000000000000000000000000000000..8fb3df59865544710589edd9733f988580af56fb
--- /dev/null
+++ b/pool/shard006/JavaScript/0042004_isstream-compiled.js
@@ -0,0 +1,26 @@
+'use strict';
+
+var stream = require('stream');
+
+function isStream(obj) {
+ return obj instanceof stream.Stream;
+}
+
+function isReadable(obj) {
+ return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object';
+}
+
+function isWritable(obj) {
+ return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object';
+}
+
+function isDuplex(obj) {
+ return isReadable(obj) && isWritable(obj);
+}
+
+module.exports = isStream;
+module.exports.isReadable = isReadable;
+module.exports.isWritable = isWritable;
+module.exports.isDuplex = isDuplex;
+
+//# sourceMappingURL=isstream-compiled.js.map
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042007_dropdown.js b/pool/shard006/JavaScript/0042007_dropdown.js
new file mode 100644
index 0000000000000000000000000000000000000000..6a1bbaf7a4c2d9945d5c88bc3a9680023ef1cc44
--- /dev/null
+++ b/pool/shard006/JavaScript/0042007_dropdown.js
@@ -0,0 +1,26 @@
+(function(Dropdown, $) {
+ Dropdown.setup = function(link) {
+ var menuToWrap = Dropdown.findMenu(link);
+ if ($(menuToWrap).parent("div").length == 0) {
+ menuToWrap.wrap("
");
+
+ $(link).on('click', function (event) {
+ event.preventDefault();
+ $(this).toggleClass('selected');
+ Dropdown.findMenu(this).closest('.dropdown_wrapper').slideToggle();
+ })
+ }
+ }
+
+ Dropdown.findMenu = function(link) {
+ var match = $(link).attr('href').match(/#(.+)$/)[1];
+ return $('#' + match);
+ }
+
+}(window.Dropdown = window.Dropdown || {}, jQuery));
+
+$(function () {
+ $('a.dropdown').each(function(){
+ Dropdown.setup(this);
+ });
+});
diff --git a/pool/shard006/JavaScript/0042010_protractor.js b/pool/shard006/JavaScript/0042010_protractor.js
new file mode 100644
index 0000000000000000000000000000000000000000..56608b30ab55744d06910007baadc22b4425d72b
--- /dev/null
+++ b/pool/shard006/JavaScript/0042010_protractor.js
@@ -0,0 +1,36 @@
+// Copyright 2014 The Oppia Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS-IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @fileoverview Utilities for using the Image component during end-to-end
+ * testing with Protractor.js
+ */
+
+var objects = require('../../objects/protractor.js');
+
+var customizeComponent = function(modal, filepath, name) {
+ modal.element(by.tagName('button')).click();
+ var filepathEditor = objects.FilepathEditor(
+ modal.element(by.tagName('filepath-editor')));
+ filepathEditor.upload(filepath);
+ filepathEditor.setName(name);
+};
+
+var expectComponentDetailsToMatch = function(elem, name) {
+ // The original filepath is not recorded and so cannot be checked.
+ expect(elem.getAttribute('filepath-with-value')).toMatch(name);
+};
+
+exports.customizeComponent = customizeComponent;
+exports.expectComponentDetailsToMatch = expectComponentDetailsToMatch;
diff --git a/pool/shard006/JavaScript/0042011_ServiceBase.js b/pool/shard006/JavaScript/0042011_ServiceBase.js
new file mode 100644
index 0000000000000000000000000000000000000000..46d4745df79d7db108c514bb3906d50b43956c65
--- /dev/null
+++ b/pool/shard006/JavaScript/0042011_ServiceBase.js
@@ -0,0 +1,60 @@
+/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved.
+ * This program are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
+import L from "leaflet";
+
+/**
+ * @class L.supermap.ServiceBase
+ * @classdesc L.supermap 服务基类。
+ * @category iServer
+ * @param {string} url - 与客户端交互的服务地址。
+ * @param {Object} options - 参数。
+ * @param {string} [options.proxy] - 服务代理地址。
+ * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。
+ * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
+ * @param {Object} [options.headers] - 请求头。
+ * @fires L.supermap.ServiceBase#initialized
+ * @fires L.supermap.ServiceBase#destroy
+ * @extends {L.Evented}
+ */
+export var ServiceBase = L.Evented.extend({
+
+ options: {
+ url: null,
+
+ proxy: null,
+
+ withCredentials: false,
+ crossOrigin: null
+ },
+
+ initialize: function (url, options) {
+ if (url) {
+ url = (url.indexOf("/") !== url.length - 1) ?
+ url : url.substr(0, url.length - 1);
+ }
+ this.url = url;
+ L.setOptions(this, options);
+ /**
+ * @event L.supermap.ServiceBase#initialized
+ * @description 构造函数构造成功后触发。
+ * @property {L.supermap.ServiceBase} this - this 对象。
+ */
+ this.fire("initialized", this);
+ },
+
+ /**
+ * @function L.supermap.ServiceBase.prototype.destroy
+ * @description 释放资源,将引用的资源属性置空。
+ */
+ destroy: function () {
+ /**
+ * @event L.supermap.ServiceBase#destroy
+ * @description 资源释放成功后触发。
+ * @property {L.supermap.ServiceBase} this - this 对象。
+ */
+ this.fire("destroy", this);
+ }
+
+});
+L.supermap.ServiceBase = ServiceBase;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042012_fix-permissions.js b/pool/shard006/JavaScript/0042012_fix-permissions.js
new file mode 100644
index 0000000000000000000000000000000000000000..66660d37eb66efc6d3eb3730e0aa99d0720c6f90
--- /dev/null
+++ b/pool/shard006/JavaScript/0042012_fix-permissions.js
@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+
+/**
+ Fixes file system permissions for all files in a directory (recursively). All folders get 0755 mask and files 0664 mask
+*/
+
+var fs = require('fs')
+
+var dir = process.argv[2]
+
+fs.stat(dir, function (err, stats) {
+ if (err) {
+ console.error(err)
+ } else {
+ if (!stats.isDirectory()) {
+ console.error(dir + ' is not a directory')
+ } else {
+ traverseDirectory(dir)
+ }
+ }
+})
+
+function traverseDirectory (dir) {
+ fs.readdir(dir, function (err, files) {
+ if (err) {
+ console.error(err)
+ } else {
+ files.forEach(function (element, index, array) {
+ fs.stat(dir + '/' + element, function (err, stats) {
+ if (err) {
+ console.error(err)
+ } else {
+ if (stats.isDirectory()) {
+ fs.chmod(dir + '/' + element, 0755, function (err) {
+ if (err) {
+ console.error('Failed to fix permissions for directory: ' + dir + '/' + element + ', error: ' + err)
+ }
+ })
+ traverseDirectory(dir + '/' + element) // recurse here
+ } else {
+ fs.chmod(dir + '/' + element, 0644, function (err) {
+ if (err) {
+ console.error('Failed to fix permissions for file: ' + dir + '/' + element + ', error: ' + err)
+ }
+ })
+ }
+ }
+ })
+ })
+ }
+ })
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042013_graphe.js b/pool/shard006/JavaScript/0042013_graphe.js
new file mode 100644
index 0000000000000000000000000000000000000000..600aa4060847c64854cc060a8d3f69b8d9c02c78
--- /dev/null
+++ b/pool/shard006/JavaScript/0042013_graphe.js
@@ -0,0 +1,179 @@
+$(function () {
+
+ /**
+ * Highcharts X-range series plugin
+ */
+ (function (H) {
+ var defaultPlotOptions = H.getOptions().plotOptions,
+ columnType = H.seriesTypes.column,
+ each = H.each;
+
+ defaultPlotOptions.xrange = H.merge(defaultPlotOptions.column, {});
+ H.seriesTypes.xrange = H.extendClass(columnType, {
+ type: 'xrange',
+ parallelArrays: ['x', 'x2', 'y'],
+ animate: H.seriesTypes.line.prototype.animate,
+
+ /**
+ * Borrow the column series metrics, but with swapped axes. This gives free access
+ * to features like groupPadding, grouping, pointWidth etc.
+ */
+ getColumnMetrics: function () {
+ var metrics,
+ chart = this.chart,
+ swapAxes = function () {
+ each(chart.series, function (s) {
+ var xAxis = s.xAxis;
+ s.xAxis = s.yAxis;
+ s.yAxis = xAxis;
+ });
+ };
+
+ swapAxes();
+
+ this.yAxis.closestPointRange = 1;
+ metrics = columnType.prototype.getColumnMetrics.call(this);
+
+ swapAxes();
+
+ return metrics;
+ },
+ translate: function () {
+ columnType.prototype.translate.apply(this, arguments);
+ var series = this,
+ xAxis = series.xAxis,
+ yAxis = series.yAxis,
+ metrics = series.columnMetrics;
+
+ H.each(series.points, function (point) {
+ barWidth = xAxis.translate(H.pick(point.x2, point.x + (point.len || 0))) - point.plotX;
+ point.shapeArgs = {
+ x: point.plotX,
+ y: point.plotY + metrics.offset,
+ width: barWidth,
+ height: metrics.width
+ };
+ point.tooltipPos[0] += barWidth / 2;
+ point.tooltipPos[1] -= metrics.width / 2;
+ });
+ }
+ });
+
+ /**
+ * Max x2 should be considered in xAxis extremes
+ */
+ H.wrap(H.Axis.prototype, 'getSeriesExtremes', function (proceed) {
+ var axis = this,
+ dataMax = Number.MIN_VALUE;
+
+ proceed.call(this);
+ if (this.isXAxis) {
+ each(this.series, function (series) {
+ each(series.x2Data || [], function (val) {
+ if (val > dataMax) {
+ dataMax = val;
+ }
+ });
+ });
+ if (dataMax > Number.MIN_VALUE) {
+ axis.dataMax = dataMax;
+ }
+ }
+ });
+ }(Highcharts));
+
+ /*$.ajax({
+ type:'get',
+ url:"http://localhost/AfriqueIsol/web/app_dev.php/chartPlan/"+ $(this).val(),
+ beforeSend:function (){
+ console.log('ça change ! ');
+ },
+ success: function (data){
+ $(".plan").val(data.plan);
+ console.log("plan ok !")
+ }
+ });*/
+
+ // THE CHART
+ $('#container').highcharts({
+
+
+
+ chart: {
+ type: 'xrange'
+
+ },
+ title: {
+ text: 'Highcharts X-range study'
+ },
+ xAxis: {
+ type: 'datetime',
+ },
+ yAxis: {
+ title: '',
+ class:'plan',
+ categories: [$(this).val(), 'Development', 'Testing'],
+ min: 0,
+ max: 2
+ },
+ plotOptions: {
+ series: {
+ grouping: false
+ }
+ },
+
+ series: [{
+ name: 'Project 1',
+ // pointPadding: 0,
+ // groupPadding: 0,
+ // borderRadius: 5,
+ pointWidth: 20,
+ data: [{
+ x: new Date(2014, 11, 1),
+ x2: Date.UTC(2014, 11, 2),
+ y: 0
+ }, {
+ x: Date.UTC(2014, 11, 2),
+ x2: Date.UTC(2014, 11, 5),
+ y: 2
+ }, {
+ x: Date.UTC(2014, 11, 15),
+ x2: Date.UTC(2014, 11, 20),
+ y: 1
+ }]
+ }, {
+ name: 'Fat line',
+ pointWidth: 20,
+ data: [{
+ x: Date.UTC(2014, 11, 5),
+ x2: Date.UTC(2014, 11, 8),
+ y: 0
+ },{
+ x: Date.UTC(2014, 11, 8),
+ x2: Date.UTC(2014, 11, 15),
+ y: 1
+ }, {
+ x: Date.UTC(2014, 11, 15),
+ x2: Date.UTC(2014, 11, 23),
+ y: 2
+ }]
+ },{
+ name: 'test',
+ pointWidth: 20,
+ data: [{
+ x: Date.UTC(2014, 11, 8),
+ x2: Date.UTC(2014, 11,15),
+ y: 0
+ },{
+ x: Date.UTC(2014, 11, 22),
+ x2: Date.UTC(2014, 11, 25),
+ y: 1
+ }, {
+ x: Date.UTC(2014, 11, 25),
+ x2: Date.UTC(2014, 11, 30),
+ y: 2
+ }]
+ }]
+
+ });
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042014_client.js b/pool/shard006/JavaScript/0042014_client.js
new file mode 100644
index 0000000000000000000000000000000000000000..574a00c32e2510b13d8077fec61a3ff2478ac4d9
--- /dev/null
+++ b/pool/shard006/JavaScript/0042014_client.js
@@ -0,0 +1,33 @@
+Questions = new Meteor.Collection("questions");
+
+Router.map(function() {
+ this.route('home', {path: '/'});
+ this.route('schedule');
+ this.route('pastInterviews');
+ this.route('help');
+ this.route('about');
+
+ this.route('interview');
+});
+
+Router.configure({
+ layout: 'layout'
+});
+
+Template.newQuestions.questions = function () {
+ console.log(Questions.find({}, {sort: {date: -1}}));
+ return Questions.find({}, {sort: {date: -1}});
+}
+
+Template.topQuestions.questions = function () {
+ return Questions.find({}, {sort: {up: -1}});
+}
+
+Template.bottomQuestions.questions = function () {
+ return Questions.find({}, {sort: {down: 1}});
+}
+
+Template.currentQuestion.questions = function () {
+ return Questions.find({addressed: 'in_progress'});
+}
+
diff --git a/pool/shard006/JavaScript/0042022_selector.js b/pool/shard006/JavaScript/0042022_selector.js
new file mode 100644
index 0000000000000000000000000000000000000000..191a39bdab3c9cfedd33360e50af387fbe519920
--- /dev/null
+++ b/pool/shard006/JavaScript/0042022_selector.js
@@ -0,0 +1,109 @@
+var _ = require('_'),
+ exists = require('is/exists'),
+ isNodeList = require('is/nodeList'),
+ isElement = require('is/element'),
+ REGEX = require('REGEX'),
+ matches = require('matchesSelector'),
+ uniqueId = require('util/uniqueId').seed(0, '_D' + Date.now()),
+
+ GET_ELEMENT_BY_ID = 'getElementById',
+ GET_ELEMENTS_BY_TAG_NAME = 'getElementsByTagName',
+ GET_ELEMENTS_BY_CLASS_NAME = 'getElementsByClassName',
+ QUERY_SELECTOR_ALL = 'querySelectorAll';
+
+var determineMethod = (selector) =>
+ REGEX.isStrictId(selector) ? GET_ELEMENT_BY_ID :
+ REGEX.isClass(selector) ? GET_ELEMENTS_BY_CLASS_NAME :
+ REGEX.isTag(selector) ? GET_ELEMENTS_BY_TAG_NAME :
+ QUERY_SELECTOR_ALL,
+
+ processQuerySelection = (selection) =>
+ // No selection or a Nodelist without a length
+ // should result in nothing
+ !selection || (isNodeList(selection) && !selection.length) ? [] :
+ // If it's an id selection, return it as an array
+ isElement(selection) || !selection.length ? [selection] :
+ // ensure it's an array and not an HTMLCollection
+ _.toArray(selection),
+
+ childOrSiblingQuery = function(context, method, selector) {
+ // Child select - needs special help so that "> div" doesn't break
+ var idApplied = false,
+ newId,
+ id;
+
+ id = context.id;
+ if (id === '' || !exists(id)) {
+ newId = uniqueId();
+ context.id = newId;
+ idApplied = true;
+ }
+
+ var selection = document[method](
+ // tailor the child selector
+ `#${idApplied ? newId : id} ${selector}`
+ );
+
+ if (idApplied) {
+ context.id = id;
+ }
+
+ return processQuerySelection(selection);
+ },
+
+ classQuery = function(context, method, selector) {
+ // Class search, don't start with '.'
+ var selector = selector.substr(1),
+ selection = context[method](selector);
+
+ return processQuerySelection(selection);
+ },
+
+ idQuery = function(context, method, selector) {
+ var sel = selector.substr(1),
+ selection = document[method](sel);
+
+ return processQuerySelection(selection);
+ },
+
+ defaultQuery = function(context, method, selector) {
+ var selection = context[method](selector);
+ return processQuerySelection(selection);
+ },
+
+ determineQuery = (isChildOrSiblingSelect, isClassSearch, isIdSearch) =>
+ isChildOrSiblingSelect ? childOrSiblingQuery :
+ isClassSearch ? classQuery :
+ isIdSearch ? idQuery :
+ defaultQuery;
+
+module.exports = function Selector(str) {
+ var selector = str.trim(),
+ isChildOrSiblingSelect = selector[0] === '>' || selector[0] === '+',
+ method = isChildOrSiblingSelect ? QUERY_SELECTOR_ALL : determineMethod(selector),
+ isIdSearch = method === GET_ELEMENT_BY_ID,
+ isClassSearch = !isIdSearch && method === GET_ELEMENTS_BY_CLASS_NAME;
+
+ var query = determineQuery(
+ isChildOrSiblingSelect,
+ isClassSearch,
+ isIdSearch
+ );
+
+ return {
+ str: str,
+
+ match: function(context) {
+ // No neeed to check, a match will fail if it's
+ // child or sibling
+ return !isChildOrSiblingSelect ? matches(context, selector) : false;
+ },
+
+ exec: function(context) {
+ // these are the types we're expecting to fall through
+ // isElement(context) || isNodeList(context) || isCollection(context)
+ // if no context is given, use document
+ return query(context || document, method, selector);
+ }
+ };
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042026_server.js b/pool/shard006/JavaScript/0042026_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..bad97792178fbce55f332b00010bb259c21a7ad0
--- /dev/null
+++ b/pool/shard006/JavaScript/0042026_server.js
@@ -0,0 +1,62 @@
+import 'shelljs/global'
+import nssocket from 'nssocket'
+import findParentDir from 'find-parent-dir'
+import {spawn} from 'child_process'
+import md5 from 'md5'
+import path from 'path'
+import fs from 'fs'
+import run from './run'
+import cache from './cache'
+
+const workingDir = findParentDir.sync(process.cwd() + '/', '.flowconfig')
+
+if (workingDir == null) {
+ console.log('Run `flow-babel babel-server` from a flow project!')
+ process.exit()
+}
+
+const server = nssocket.createServer(socket => {
+ console.log('Client connected')
+
+ socket.data(['run'], ({ workingDir, argv, stdin }) => {
+ run(workingDir, argv, stdin, data => {
+ socket.send(['stdout'], { data })
+ }, data => {
+ socket.send(['stderr'], { data: data.toString() })
+ }, () => {
+ socket.end()
+ })
+ })
+})
+
+server.listen(5004)
+
+console.log('flow-babel server listening on 5004')
+
+// start babel watch
+const targetDir = cache.get(`targetDir:${workingDir}`, () => path.join('/tmp/flow-babel/', md5(workingDir)))
+rm('-rf', targetDir)
+mkdir('-p', targetDir)
+ln('-sf', path.join(workingDir, '.flowconfig'), path.join(targetDir, '.flowconfig'))
+ln('-sf', path.join(workingDir, 'node_modules/'), path.join(targetDir, 'node_modules'))
+
+const babelCmd = spawn('babel', [
+ '-D',
+ '--stage',
+ '0',
+ '--whitelist',
+ 'es6.constants,es7.classProperties,es7.comprehensions,es7.decorators,es7.exportExtensions,es7.functionBind,es7.objectRestSpread,es7.trailingFunctionCommas,es6.blockScoping',
+ '--source-maps',
+ '--optional',
+ 'runtime',
+ '--ignore',
+ 'node_modules',
+ '--plugins',
+ path.join(__dirname, '/babel-plugin.js'),
+ '--watch',
+ '--out-dir',
+ targetDir,
+ './',
+], { cwd: workingDir })
+babelCmd.stderr.pipe(process.stderr)
+babelCmd.stdout.pipe(process.stdout)
diff --git a/pool/shard006/JavaScript/0042029_app.js b/pool/shard006/JavaScript/0042029_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..b29b0a1fe122237659308d323eb360973d1dfac3
--- /dev/null
+++ b/pool/shard006/JavaScript/0042029_app.js
@@ -0,0 +1,38 @@
+//app.js
+import Token from 'utils/token.js'
+
+App({
+ onLaunch: function () {
+ this._getUserInfo();
+ const token = new Token();
+ token.verify();
+ },
+
+ _getUserInfo() {
+ let userInfoStorage = wx.getStorageSync('user');
+ const that = this
+
+ if (!userInfoStorage) {
+ // 缓存中没有用户信息,那么获取用户信息
+ wx.getUserInfo({
+ success: function (res) {
+ that.globalData.userInfo = res.userInfo;
+ // 将用户信息保存到缓存中
+ wx.setStorageSync('user', res.userInfo);
+ },
+ fail: function (res) {
+ console.log(res);
+ }
+ })
+ } else {
+ // 如果缓存中存在用户基本信息,则将其保存到全局变量中
+ that.globalData.userInfo = userInfoStorage;
+ }
+
+ },
+
+ globalData: {
+ userInfo: null,
+ token: null
+ }
+})
diff --git a/pool/shard006/JavaScript/0042030_grade.js b/pool/shard006/JavaScript/0042030_grade.js
new file mode 100644
index 0000000000000000000000000000000000000000..697d6031d4d8c13ba2dd75d7d3df22cbb804fed4
--- /dev/null
+++ b/pool/shard006/JavaScript/0042030_grade.js
@@ -0,0 +1,18 @@
+/**
+ * Created by Sean on 2014/7/6.
+ */
+var update = function (_id) {
+ $('#form').attr('action', '/grade/update/' + _id);
+ $('#modal-title').text('修改成绩');
+ var id = '#' + _id;
+ $('#cno').val($($(id + ' td')[0]).text());
+ $('#cname').val($($(id + ' td')[1]).text());
+ $('#score').val($($(id + ' td')[4]).text());
+};
+var add = function () {
+ $('#form').attr('action', '/grade/add');
+ $('#modal-title').text('添加成绩');
+ cno.options[0].selected=true;
+ cname.options[0].selected=true;
+ $('#score').val($($(id + ' td')[4]).text());
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042032_tubular-reporting-bundle.js b/pool/shard006/JavaScript/0042032_tubular-reporting-bundle.js
new file mode 100644
index 0000000000000000000000000000000000000000..08811f3b22ecbd1fe87a0350fe78233b4e7eb1c1
--- /dev/null
+++ b/pool/shard006/JavaScript/0042032_tubular-reporting-bundle.js
@@ -0,0 +1,243 @@
+(function (angular) {
+ 'use strict';
+
+ angular.module('tubular-reporting.directives', ['tubular.services'])
+ /**
+ * @ngdoc directive
+ * @name tbReporting
+ * @restrict E
+ *
+ * @description
+ * The `tbReporting` directive is the base to create reports using the .NET proxy service.
+ *
+ * @scope
+ *
+ * @param {string} serverDataSourceUrl Set the HTTP URL where the data source comes.
+ * @param {string} serverMarkupUrl Defines the Tubular Generator URL.
+ * @param {bool} requireAuthentication Set if authentication check must be executed, default true.
+ */
+ .directive('tbReporting', [
+ function() {
+ return {
+ template: '' +
+ '
' +
+ ' ' +
+ ' ' +
+ ' ' +
+ ' ' +
+ '
' +
+ '
' +
+ '
',
+ restrict: 'E',
+ replace: true,
+ scope: {
+ serverDataSourceUrl: '@',
+ serverMarkupUrl: '@',
+ requireAuthentication: '=?'
+ },
+ controller: [
+ '$scope', 'tubularHttp', 'localStorageService',
+ function($scope, tubularHttp, localStorageService) {
+ $scope.isShowing = true;
+ $scope.showLoading = true;
+
+ // Setup require authentication
+ $scope.requireAuthentication = angular.isUndefined($scope.requireAuthentication) ? true : $scope.requireAuthentication;
+ $scope.items = [];
+ $scope.reports = localStorageService.get('reports') || [];
+
+ tubularHttp.setRequireAuthentication($scope.requireAuthentication);
+
+ tubularHttp.get($scope.serverDataSourceUrl || 'api/reports/datasources').promise.then(function(data) {
+ $scope.dataSources = data.DataSources;
+ $scope.aggregationFunctions = data.AggregationFunctions;
+ $scope.types = data.Types;
+ }, function (error) {
+ $scope.$emit('tbReporting_OnConnectionError', error);
+ }).then(function() {
+ $scope.showLoading = false;
+ });
+
+ $scope.addItem = function() {
+ $scope.items.push({
+ DataSource: $scope.Model.DataSource.Name,
+ Column: $scope.Model.Column.Name,
+ DataType: $scope.Model.DataType,
+ Aggregation: $scope.Model.AggregationFunction,
+ Filter: $scope.Model.Filter
+ });
+
+ $scope.Model.Filter = '';
+ };
+
+ $scope.removeItem = function(item) {
+ var index = $scope.items.indexOf(item);
+ if (index > -1) {
+ $scope.items.splice(index, 1);
+ }
+ };
+
+ $scope.moveItem = function(from, to) {
+ $scope.items.splice(to, 0, $scope.items.splice(from, 1)[0]);
+ }
+
+ $scope.up = function(item) {
+ var oldIndex = $scope.items.indexOf(item);
+
+ $scope.moveItem(oldIndex, oldIndex - 1);
+ };
+
+ $scope.down = function(item) {
+ var oldIndex = $scope.items.indexOf(item);
+
+ $scope.moveItem(oldIndex, oldIndex + 1);
+ };
+
+ $scope.saveReport = function() {
+ $scope.reports.push({ Name: $scope.Model.CurrentReport, Data: $scope.items });
+ localStorageService.set('reports', $scope.reports);
+
+ $scope.$emit('tbReporting_OnSuccessfulSave', "Report saved");
+ };
+
+ $scope.removeReport = function() {
+ var report = $scope.reports.filter(function(el) { return el.Name === $scope.Model.CurrentReport.Name; });
+
+ if (report && report[0]) {
+ var index = $scope.reports.indexOf(report[0]);
+
+ if (index > -1) {
+ $scope.reports.splice(index, 1);
+ localStorageService.set('reports', $scope.reports);
+ $scope.$emit('tbReporting_OnRemoved', "Report removed");
+ }
+ } else {
+ $scope.$emit('tbReporting_OnConnectionError', "Unknown report");
+ }
+ };
+
+ $scope.loadReport = function() {
+ var report = $scope.reports.filter(function(el) { return el.Name === $scope.Model.CurrentReport.Name; });
+
+ if (report && report[0]) {
+ $scope.items = report[0].Data;
+ } else {
+ $scope.$emit('tbReporting_OnConnectionError', "Unknown report");
+ }
+ };
+
+ $scope.isValid = function() {
+ return $scope.items.length > 0;
+ };
+
+ $scope.generate = function() {
+ tubularHttp.setRequireAuthentication($scope.requireAuthentication);
+
+ tubularHttp.post($scope.serverMarkupUrl || 'api/reports/getmarkup', $scope.items).promise.then(function(data) {
+ $scope.autoCode = window.URL.createObjectURL(new Blob([data], { type: "text/html" }));
+ }, function(error) {
+ $scope.$emit('tbReporting_OnConnectionError', error);
+ }).then(function () {
+ $scope.showLoading = false;
+ });
+ };
+ }
+ ]
+ };
+ }
+ ])
+ /**
+ * @ngdoc directive
+ * @name tbReportingToolbar
+ * @restrict E
+ *
+ * @description
+ * Use `tbReportingToolbar` directive to show a common toolbar to load/save reports and generate them.
+ * You can use your own UI if you prefer using the available methods in the parent controller.
+ */
+ .directive('tbReportingToolbar', [
+ function() {
+ return {
+ template: '' +
+ '
' +
+ '
' +
+ ' ' +
+ '
' +
+ '
' +
+ '
' +
+ '
' +
+ '' +
+ ' {{\'CAPTION_LOAD\' | translate}}' +
+ ' ' +
+ '' +
+ ' {{\'CAPTION_SAVE\' | translate}}' +
+ ' ' +
+ '' +
+ ' {{\'CAPTION_REMOVE\' | translate}}' +
+ ' ' +
+ '
' +
+ '
' +
+ '
' +
+ '' +
+ ' {{\'UI_GENERATEREPORT\' | translate}}' +
+ ' ' +
+ '
',
+ restrict: 'E',
+ replace: true,
+ scope: false
+ };
+ }
+ ])
+ /**
+ * @ngdoc directive
+ * @name tbReportingColumnsSelector
+ * @restrict E
+ *
+ * @description
+ * Use `tbReportingColumnsSelector` directive to display a table to allow the user to add and remove
+ * columns and generate a Report Model.
+ */
+ .directive('tbReportingColumnsSelector', [
+ function () {
+ return {
+ template: '',
+ restrict: 'E',
+ replace: true,
+ scope: false
+ };
+ }
+ ]).config([
+ '$sceDelegateProvider', function($sceDelegateProvider) {
+ // We need to allow blobs to run
+ $sceDelegateProvider.resourceUrlWhitelist(['self', 'blob:**']);
+ }
+ ]);
+})(window.angular);
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042034_resetforcefromword.js b/pool/shard006/JavaScript/0042034_resetforcefromword.js
new file mode 100644
index 0000000000000000000000000000000000000000..cec0071aa47ef7d44486bacac3abf2281501cdfb
--- /dev/null
+++ b/pool/shard006/JavaScript/0042034_resetforcefromword.js
@@ -0,0 +1,80 @@
+/* exported testScenario */
+
+'use strict';
+
+// Scenario is a sequence (array) of pasted to be fired. True (1) means paste from word, false (0) means regular paste.
+function testScenario( scenario, filterPath ) {
+ bender.editor = {
+ config: {
+ pasteFromWordCleanupFile: filterPath
+ }
+ };
+
+ var stub;
+
+ bender.test( {
+ tearDown: function() {
+ if ( stub ) {
+ stub.restore();
+ stub = null;
+ }
+ },
+
+ // #10032
+ 'test reset forceFromWord': function() {
+ var editor = this.editor,
+ pasteHtml = 'foo
',
+ i = 0;
+
+
+ stub = sinon.stub( editor, 'getClipboardData', function( options, callback ) {
+ if ( callback ) {
+ callback( { dataValue: pasteHtml } );
+ }
+ } );
+
+ editor.once( 'paste', paste, null, null, 999 );
+
+ firePaste( editor, scenario[ i ] );
+
+ wait();
+
+ function paste( evt ) {
+ resume( function() {
+ assertPaste( evt.data.dataValue, scenario[ i ], i );
+
+ if ( i == scenario.length ) {
+ return;
+ }
+
+ editor.once( 'paste', paste, null, null, 999 );
+
+ i++;
+
+ firePaste( editor, scenario[ i ] );
+
+ wait();
+ } );
+ }
+
+ function firePaste( editor, fromWord ) {
+ if ( fromWord ) {
+ editor.execCommand( 'pastefromword' );
+ } else {
+ editor.fire( 'paste', { dataValue: pasteHtml } );
+ }
+ }
+
+ function assertPaste( value, fromWord, index ) {
+ var expectedFromWord = 'ok',
+ expectedNotFromWord = 'foo
';
+
+ if ( fromWord ) {
+ assert.areSame( expectedFromWord, value, 'Paste nr ' + index + ' should be from word.' );
+ } else {
+ assert.areSame( expectedNotFromWord, value, 'Paste nr ' + index + ' should NOT be from word.' );
+ }
+ }
+ }
+ } );
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042035_ea7f4b5e370adbfb305c06e346cd699f3236b8a8.js b/pool/shard006/JavaScript/0042035_ea7f4b5e370adbfb305c06e346cd699f3236b8a8.js
new file mode 100644
index 0000000000000000000000000000000000000000..e7504d9650a6d3a1efddb71d19ba9321aaf38ced
--- /dev/null
+++ b/pool/shard006/JavaScript/0042035_ea7f4b5e370adbfb305c06e346cd699f3236b8a8.js
@@ -0,0 +1,65 @@
+var app = account_app || {};
+
+(function(){
+ var Action_btn = account_app.Action_btn = React.createClass({displayName: "Action_btn",
+ handleClick:function(){
+ this.props.perform_action();
+ },
+ render:function(){
+ return (React.createElement("button", {className: "btn btn-primary", onClick: this.handleClick}, this.props.content));
+ }
+ });
+ var Username_field = account_app.Username_field = React.createClass({displayName: "Username_field",
+ handleChange:function(){
+ this.props.update_username(this.refs.username.value);
+ },
+ render:function(){
+ return (React.createElement("input", {className: "input-base input-username", ref: "username", placeholder: this.props.hint, onChange: this.handleChange}));
+ }
+ });
+ var Password_field = account_app.Password_field = React.createClass({displayName: "Password_field",
+ handleChange:function(){
+ this.props.update_password(this.refs.pass.value);
+ },
+ render:function(){
+ return (React.createElement("input", {className: "input-base input-password", ref: "pass", type: "password", placeholder: this.props.hint, onChange: this.handleChange}))
+ }
+ });
+ account_app.RegisterWindow = React.createClass({displayName: "RegisterWindow",
+ render:function(){
+ return (
+ React.createElement("div", {className: "register-area"},
+ React.createElement("div", {className: "register-item"},
+ React.createElement(Username_field, {hint: "Username"})
+ ),
+ React.createElement("div", {className: "register-item"},
+ React.createElement(Password_field, {hint: "Password"})
+ ),
+ React.createElement("div", {className: "register-item"},
+ React.createElement(Password_field, {hint: "Confirm Your Password"})
+ ),
+ React.createElement("div", {className: "register-item right-align"},
+ React.createElement(Action_btn, {content: "Register"})
+ )
+ )
+ );
+ }
+ });
+ account_app.LoginWindow = React.createClass({displayName: "LoginWindow",
+ render:function(){
+ return (
+ React.createElement("div", {className: "login-area"},
+ React.createElement("div", {className: "login-item"},
+ React.createElement(Username_field, {hint: "Username"})
+ ),
+ React.createElement("div", {className: "login-item"},
+ React.createElement(Password_field, {hint: "Password"})
+ ),
+ React.createElement("div", {className: "login-item right-align"},
+ React.createElement(Action_btn, {content: "Login"})
+ )
+ )
+ );
+ }
+ });
+})();
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042037_genotype-genomic-attributes-widget.js b/pool/shard006/JavaScript/0042037_genotype-genomic-attributes-widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..253cb961eb531df1c8582782cc5219f7816f23f5
--- /dev/null
+++ b/pool/shard006/JavaScript/0042037_genotype-genomic-attributes-widget.js
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2012 Francisco Salavert (ICM-CIPF)
+ * Copyright (c) 2012 Ruben Sanchez (ICM-CIPF)
+ * Copyright (c) 2012 Ignacio Medina (ICM-CIPF)
+ *
+ * This file is part of JS Common Libs.
+ *
+ * JS Common Libs 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.
+ *
+ * JS Common Libs 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 JS Common Libs. If not, see .
+ */
+
+GenotypeGenomicAttributesWidget.prototype.draw = GenomicAttributesWidget.prototype.draw;
+GenotypeGenomicAttributesWidget.prototype.render = GenomicAttributesWidget.prototype.render;
+GenotypeGenomicAttributesWidget.prototype.drawKaryotype = GenomicAttributesWidget.prototype.drawKaryotype;
+GenotypeGenomicAttributesWidget.prototype.makeGrid = GenomicAttributesWidget.prototype.makeGrid;
+GenotypeGenomicAttributesWidget.prototype.getKaryotypePanelId = GenomicAttributesWidget.prototype.getKaryotypePanelId;
+GenotypeGenomicAttributesWidget.prototype.dataChange = GenomicAttributesWidget.prototype.dataChange;
+GenotypeGenomicAttributesWidget.prototype.fill = GenomicAttributesWidget.prototype.fill;
+GenotypeGenomicAttributesWidget.prototype.onAdditionalInformationClick = GenomicAttributesWidget.prototype.onAdditionalInformationClick;
+
+function GenotypeGenomicAttributesWidget(species, args){
+ if (args == null){
+ args = new Object();
+ }
+ args.title = "Genotype";
+ args.tags = ["genotype"];
+ args.featureType = 'snp';
+ args.listWidgetArgs = {title:'Filter',action:'filter', gridFields:["name", "variantAlleles", "ancestralAllele", "mapWeight", "position", "sequence"]};
+ GenomicAttributesWidget.prototype.constructor.call(this, species, args);
+};
+
+
diff --git a/pool/shard006/JavaScript/0042041_feedback.js b/pool/shard006/JavaScript/0042041_feedback.js
new file mode 100644
index 0000000000000000000000000000000000000000..494adab5da89abd5b5c4f53934a4b6872d04487e
--- /dev/null
+++ b/pool/shard006/JavaScript/0042041_feedback.js
@@ -0,0 +1,66 @@
+import Service, { inject as service } from '@ember/service';
+import { get, set } from '@ember/object';
+import callableType from 'consul-ui/utils/callable-type';
+
+const TYPE_SUCCESS = 'success';
+const TYPE_ERROR = 'error';
+const defaultStatus = function(type, obj) {
+ return type;
+};
+const notificationDefaults = function() {
+ return {
+ timeout: 6000,
+ extendedTimeout: 300,
+ };
+};
+export default Service.extend({
+ notify: service('flashMessages'),
+ logger: service('logger'),
+ execute: function(handle, action, status = defaultStatus, controller) {
+ set(controller, 'isLoading', true);
+ const getAction = callableType(action);
+ const getStatus = callableType(status);
+ const notify = get(this, 'notify');
+ return (
+ handle()
+ //TODO: pass this through to getAction..
+ .then(item => {
+ // returning exactly `false` for a feedback action means even though
+ // its successful, please skip this notification and don't display it
+ if (item !== false) {
+ notify.clearMessages();
+ // TODO right now the majority of `item` is a Transition
+ // but you can resolve an object
+ notify.add({
+ ...notificationDefaults(),
+ type: getStatus(TYPE_SUCCESS),
+ // here..
+ action: getAction(),
+ item: item,
+ });
+ }
+ })
+ .catch(e => {
+ notify.clearMessages();
+ get(this, 'logger').execute(e);
+ if (e.name === 'TransitionAborted') {
+ notify.add({
+ ...notificationDefaults(),
+ type: getStatus(TYPE_SUCCESS),
+ // and here
+ action: getAction(),
+ });
+ } else {
+ notify.add({
+ ...notificationDefaults(),
+ type: getStatus(TYPE_ERROR, e),
+ action: getAction(),
+ });
+ }
+ })
+ .finally(function() {
+ set(controller, 'isLoading', false);
+ })
+ );
+ },
+});
diff --git a/pool/shard006/JavaScript/0042042_Template.js b/pool/shard006/JavaScript/0042042_Template.js
new file mode 100644
index 0000000000000000000000000000000000000000..d7ee6e85b11920241a633cc86b4806f5776f31f7
--- /dev/null
+++ b/pool/shard006/JavaScript/0042042_Template.js
@@ -0,0 +1,166 @@
+/*
+ MIT License http://www.opensource.org/licenses/mit-license.php
+ Author Tobias Koppers @sokra
+*/
+"use strict";
+
+const Tapable = require("tapable");
+const ConcatSource = require("webpack-sources").ConcatSource;
+
+const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
+const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
+const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
+
+module.exports = class Template extends Tapable {
+ constructor(outputOptions) {
+ super();
+ this.outputOptions = outputOptions || {};
+ }
+
+ static getFunctionContent(fn) {
+ return fn.toString().replace(/^function\s?\(\)\s?\{\n?|\n?\}$/g, "").replace(/^\t/mg, "");
+ }
+
+ static toIdentifier(str) {
+ if(typeof str !== "string") return "";
+ return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_");
+ }
+
+ static toPath(str) {
+ if(typeof str !== "string") return "";
+ return str.replace(/[^a-zA-Z0-9_!§$()=\-\^°]+/g, "-").replace(/^-|-$/, "");
+ }
+
+ // map number to a single character a-z, A-Z or <_ + number> if number is too big
+ static numberToIdentifer(n) {
+ // lower case
+ if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
+
+ // upper case
+ n -= DELTA_A_TO_Z;
+ if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
+
+ // fall back to _ + number
+ n -= DELTA_A_TO_Z;
+ return "_" + n;
+ }
+
+ indent(str) {
+ if(Array.isArray(str)) {
+ return str.map(this.indent.bind(this)).join("\n");
+ } else {
+ str = str.trimRight();
+ if(!str) return "";
+ var ind = (str[0] === "\n" ? "" : "\t");
+ return ind + str.replace(/\n([^\n])/g, "\n\t$1");
+ }
+ }
+
+ prefix(str, prefix) {
+ if(Array.isArray(str)) {
+ str = str.join("\n");
+ }
+ str = str.trim();
+ if(!str) return "";
+ const ind = (str[0] === "\n" ? "" : prefix);
+ return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
+ }
+
+ asString(str) {
+ if(Array.isArray(str)) {
+ return str.join("\n");
+ }
+ return str;
+ }
+
+ getModulesArrayBounds(modules) {
+ if(!modules.every(moduleIdIsNumber))
+ return false;
+ var maxId = -Infinity;
+ var minId = Infinity;
+ modules.forEach(function(module) {
+ if(maxId < module.id) maxId = module.id;
+ if(minId > module.id) minId = module.id;
+ });
+ if(minId < 16 + ("" + minId).length) {
+ // add minId x ',' instead of 'Array(minId).concat(...)'
+ minId = 0;
+ }
+ var objectOverhead = modules.map(function(module) {
+ var idLength = (module.id + "").length;
+ return idLength + 2;
+ }).reduce(function(a, b) {
+ return a + b;
+ }, -1);
+ var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
+ return arrayOverhead < objectOverhead ? [minId, maxId] : false;
+ }
+
+ renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) {
+ if(!prefix) prefix = "";
+ var source = new ConcatSource();
+ if(chunk.getNumberOfModules() === 0) {
+ source.add("[]");
+ return source;
+ }
+ var removedModules = chunk.removedModules;
+ var allModules = chunk.mapModules(function(module) {
+ return {
+ id: module.id,
+ source: moduleTemplate.render(module, dependencyTemplates, chunk)
+ };
+ });
+ if(removedModules && removedModules.length > 0) {
+ removedModules.forEach(function(id) {
+ allModules.push({
+ id: id,
+ source: "false"
+ });
+ });
+ }
+ var bounds = this.getModulesArrayBounds(allModules);
+
+ if(bounds) {
+ // Render a spare array
+ var minId = bounds[0];
+ var maxId = bounds[1];
+ if(minId !== 0) source.add("Array(" + minId + ").concat(");
+ source.add("[\n");
+ var modules = {};
+ allModules.forEach(function(module) {
+ modules[module.id] = module;
+ });
+ for(var idx = minId; idx <= maxId; idx++) {
+ var module = modules[idx];
+ if(idx !== minId) source.add(",\n");
+ source.add("/* " + idx + " */");
+ if(module) {
+ source.add("\n");
+ source.add(module.source);
+ }
+ }
+ source.add("\n" + prefix + "]");
+ if(minId !== 0) source.add(")");
+ } else {
+ // Render an object
+ source.add("{\n");
+ allModules.sort(function(a, b) {
+ var aId = a.id + "";
+ var bId = b.id + "";
+ if(aId < bId) return -1;
+ if(aId > bId) return 1;
+ return 0;
+ }).forEach(function(module, idx) {
+ if(idx !== 0) source.add(",\n");
+ source.add("\n/***/ " + JSON.stringify(module.id) + ":\n");
+ source.add(module.source);
+ });
+ source.add("\n\n" + prefix + "}");
+ }
+ return source;
+ }
+};
+
+function moduleIdIsNumber(module) {
+ return typeof module.id === "number";
+}
diff --git a/pool/shard006/JavaScript/0042043_index.js b/pool/shard006/JavaScript/0042043_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..4c60b3459400218a7f579d1ad2974af38e0a458c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042043_index.js
@@ -0,0 +1,95 @@
+/**
+ * @overview Inventory Import Module
+ *
+ * This module implements the logic for importing the inventory into the application. It provides
+ * a template file to show how the inventory schema must be modeled for the user to fill out.
+ */
+const path = require('path');
+const debug = require('debug')('bhima:inventory');
+const db = require('../../../lib/db');
+const util = require('../../../lib/util');
+const BadRequest = require('../../../lib/errors/BadRequest');
+
+
+exports.downloadTemplate = downloadTemplate;
+exports.importInventories = importInventories;
+
+/**
+ * @method downloadTemplate
+ *
+ * @description send to the client the template file for inventory import
+*/
+function downloadTemplate(req, res, next) {
+ try {
+ const file = path.join(__dirname, '../../../resources/templates/import-inventory-template.csv');
+ res.download(file);
+ } catch (error) {
+ next(error);
+ }
+}
+
+/**
+ * @method importInventories
+ *
+ * @description this method allow to do an import of inventory and stock
+ */
+async function importInventories(req, res, next) {
+ try {
+ if (!req.files || req.files.length === 0) {
+ const errorDescription = 'Expected at least one file upload but did not receive any files.';
+ throw new BadRequest(errorDescription, 'ERRORS.MISSING_UPLOAD_FILES');
+ }
+
+ const filePath = req.files[0].path;
+
+ const data = await util.formatCsvToJson(filePath);
+ if (!hasValidDataFormat(data)) {
+ throw new BadRequest('The given file has a bad data format for inventories', 'ERRORS.BAD_DATA_FORMAT');
+ }
+
+ const transaction = db.transaction();
+ const query = 'CALL ImportInventory(?, ?, ?, ?, ?, ?, ?);';
+
+ data.forEach(item => {
+ const queryParams = [
+ req.session.enterprise.id,
+ item.inventory_group_name,
+ item.inventory_code,
+ item.inventory_text,
+ item.inventory_type,
+ item.inventory_unit,
+ item.inventory_unit_price,
+ ];
+
+ transaction.addQuery(query, queryParams);
+ });
+
+ await transaction.execute();
+ res.sendStatus(200);
+ } catch (e) {
+ next(e);
+ }
+}
+
+/**
+ * @function hasValidDataFormat
+ *
+ * @description check if data has a valid format for inventories
+ *
+ * @param {Array} data - array of objects to check for valid properties
+ *
+ * @returns {boolean} - true if data is valid
+ */
+function hasValidDataFormat(data = []) {
+ return data.every(item => {
+ const bool = item.inventory_code && item.inventory_group_name
+ && item.inventory_text && item.inventory_type && item.inventory_unit
+ && item.inventory_unit_price;
+
+ if (!bool) {
+ debug('#import(): invalid data format:', item);
+ }
+
+ return bool;
+ });
+}
diff --git a/pool/shard006/JavaScript/0042046_OvsdbComponentTest.js b/pool/shard006/JavaScript/0042046_OvsdbComponentTest.js
new file mode 100644
index 0000000000000000000000000000000000000000..8a02a2b7f8551026afc242fbbf40b8d6fcb5c595
--- /dev/null
+++ b/pool/shard006/JavaScript/0042046_OvsdbComponentTest.js
@@ -0,0 +1,22 @@
+/*eslint-env node, mocha */
+/*global expect */
+/*eslint no-console: 0*/
+'use strict';
+
+// Uncomment the following lines to use the react test utilities
+// import TestUtils from 'react-addons-test-utils';
+import createComponent from 'helpers/shallowRenderHelper';
+
+import OvsdbComponent from 'components/playground/OvsdbComponent.js';
+
+describe('OvsdbComponent', () => {
+ let component;
+
+ beforeEach(() => {
+ component = createComponent(OvsdbComponent);
+ });
+
+ it('should have its component name as default className', () => {
+ expect(component.props.className).to.equal('ovsdb-component');
+ });
+});
diff --git a/pool/shard006/JavaScript/0042048_Fixtures.js b/pool/shard006/JavaScript/0042048_Fixtures.js
new file mode 100644
index 0000000000000000000000000000000000000000..f41be8303a57c8f5f18315f55aefbdf1a7f58828
--- /dev/null
+++ b/pool/shard006/JavaScript/0042048_Fixtures.js
@@ -0,0 +1,196 @@
+ (function() {
+ function Fixtures() {
+ var Fixtures = {};
+
+
+ // ALBUM 01
+ var albumPicasso = {
+ name: 'The Colors',
+ artist: 'Pablo Picasso',
+ label: 'Cubism',
+ year: '1881',
+ genre: 'Classical',
+ styles: 'Chamber Music',
+ albumArtUrl: '/assets/images/album_covers/01.png',
+ songs: [
+ {name: 'Blue', length: 161.71, audioUrl: '/assets/music/bloc_jams_music/blue' },//161.71 seconds
+ {name: 'Green', length: 103.96, audioUrl: '/assets/music/bloc_jams_music/green' },
+ {name: 'Red', length: 268.45, audioUrl: '/assets/music/bloc_jams_music/red' },
+ {name: 'Pink', length: 153.14, audioUrl: '/assets/music/bloc_jams_music/pink' },
+ {name: 'Magenta', length: 374.22, audioUrl: '/assets/music/bloc_jams_music/magenta' },
+ ]
+ };
+ // ALBUM 20
+ var albumMarconi = {
+ name: 'The Telephone',
+ artist: 'Guglielmo Marconi',
+ label: 'EM',
+ genre: 'Classical',
+ styles: 'Chamber Music',
+ year: '1909',
+ albumArtUrl: '/assets/images/album_covers/20.png',
+ songs: [
+ {name: 'Hello, Operator?', length: '1:01'},
+ {name: 'Ring, ring, ring', length: '5:01'},
+ {name: 'Fits in your pocket', length: '3:21'},
+ {name: 'Can you hear me now?', length: '3:14'},
+ {name: 'Wrong phone number', length: '2:15'},
+ {name: 'Last Song', length: '6:15'}
+ ]
+ };
+ // ALBUM http://www.allmusic.com/album/the-buffet-mw0002896346
+ var mw0002896346 = {
+ name: 'The Buffet',
+ artist: 'R. Kelly',
+ label: 'RCA',
+ year: '2015',
+ genre: 'R&B',
+ styles: 'Contemporary R&B, Adult Contemporary R&B',
+ albumArtUrl: 'http://cps-static.rovicorp.com/3/JPG_400/MI0003/984/MI0003984115.jpg?partner=allrovi.com',
+ songs: [
+ {name: 'The Poem', length: '1:19'},
+ {name: 'Poetic Sex', length: '4:21'},
+ {name: 'Anything Goes', length: '4:35'},
+ {name: "Let's Make Some Noise", length: '4:14'},
+ {name: 'Marching Band', length: '3:56'},
+ {name: 'Switch Up', length: '3:24'},
+ {name: 'Wanna Be There', length: '4:15'},
+ {name: 'All My Fault', length: '3:25'},
+ {name: 'Wake Up Everybody', length: '3:41'},
+ {name: 'Backyard Party', length: '3:32'},
+ {name: 'Sextime', length: '4:14'},
+ {name: "Let's Be Real Now", length: '3:05'}
+ ]
+ };
+
+ // ALBUM http://www.allmusic.com/album/the-moving-sidewalk-mw0002083060
+ var mw0002083060 = {
+ name: 'The Moving Sidewalk',
+ artist: 'Alan Hampton',
+ label: 'RCA',
+ year: '2011',
+ genre: 'Pop/Rock',
+ styles: 'Alternative Singer/Songwriter, Alternative/Indie Rock',
+ albumArtUrl: 'http://cps-static.rovicorp.com/3/JPG_400/MI0003/125/MI0003125428.jpg?partner=allrovi.com',
+ songs: [
+ {name: 'Staring at the Sun', length: '4:09'},
+ {name: 'Change Your Mind', length: '2:47'},
+ {name: 'Home to You', length: '2:44'},
+ {name: "Loud and Clear", length: '3:27'},
+ {name: 'Kaleidscope', length: '2:51'},
+ {name: 'Where Did You Go?', length: '4:01'},
+ {name: 'Oh My God', length: '3:10'},
+ {name: 'Undercover', length: '2:31'},
+ {name: "There's This Side", length: '3:43'},
+ {name: 'Travel', length: '3:01'}
+ ]
+ };
+
+ // ALBUM http://www.allmusic.com/album/death-of-a-bachelor-mw0002891900
+ var mw0002891900 = {
+ name: 'Death of a Bachelor',
+ artist: 'Panic! At the Disco',
+ label: 'RCA',
+ year: '2000',
+ genre: 'Pop/Rock',
+ styles: 'Alternative/Indie Rock, Emo-Pop, Punk-Pop',
+ albumArtUrl: 'http://cps-static.rovicorp.com/3/JPG_400/MI0003/955/MI0003955172.jpg?partner=allrovi.com',
+ songs: [
+ {name: 'Victorious', length: '4:09'},
+ {name: "Don't Threaten Me with a Good Time", length: '2:47'},
+ {name: 'Hallelujah', length: '2:44'},
+ {name: "Emperor's New Clothes", length: '3:27'},
+ {name: 'Death of a Bachelor', length: '2:51'},
+ {name: 'Crazy=Genius', length: '4:01'},
+ {name: 'LA Devotee', length: '3:10'},
+ {name: 'Golden Days', length: '2:31'},
+ {name: "The Good, the Bad and the Dirty", length: '3:43'},
+ {name: 'House of Memories', length: '3:01'},
+ {name: 'Impossible Year', length: '3:01'}
+ ]
+ };
+
+ // ALBUM http://www.allmusic.com/album/untamed-mw0002896652
+ var mw0002896652 = {
+ name: 'Untamed',
+ artist: 'Cam / Camaron Ochs',
+ label: 'RCA',
+ year: '2015',
+ genre: 'Country',
+ styles: 'Contemporary Country, Country-Pop',
+ albumArtUrl: 'http://cps-static.rovicorp.com/3/JPG_400/MI0003/979/MI0003979990.jpg?partner=allrovi.com',
+ songs: [
+ {name: 'Untamed', length: '3:30'},
+ {name: "Hungover on Heartache", length: '3:13'},
+ {name: 'Mayday', length: '3:36'},
+ {name: "Burning House", length: '3:51'},
+ {name: 'Cold in California', length: '3:10'},
+ {name: 'My Mistake', length: '3:20'},
+ {name: 'Runaway Train', length: '2:57'},
+ {name: 'Half Broke Heart', length: '3:04'},
+ {name: "Want It All", length: '3:09'},
+ {name: "Country Ain't Never Been Pretty", length: '3:39'},
+ {name: 'Village', length: '3:55'}
+ ]
+ };
+
+ // album http://www.allmusic.com/album/no-pads-no-helmetsjust-balls-mw0000658489
+ var mw0000658489 = {
+ name: 'No Pads, No Helmets...Just Balls',
+ artist: 'Simple Plan',
+ label: 'Atlantic',
+ year: '2002',
+ genre: 'Pop/Rock',
+ styles: 'Alternative/Indie Rock, Punk-Pop',
+ albumArtUrl: 'http://cps-static.rovicorp.com/3/JPG_400/MI0001/890/MI0001890206.jpg?partner=allrovi.com',
+ songs: [
+ {name: "I'd Do Anything", length: '3:17'},
+ {name: "The Worst Day Ever", length: '3:27'},
+ {name: "You Don't Mean Anything", length: '2:28'},
+ {name: "I'm Just a Kid", length: '3:18'},
+ {name: "When I'm With You", length: '2:37'},
+ {name: "Meet You There", length: '4:14'},
+ {name: "Addicted", length: '3:52'},
+ {name: "My Alien", length: '3:08'},
+ {name: "God Must Hate Me", length: '2:44'},
+ {name: "I Won't Be There", length: '3:09'},
+ {name: "One Day", length: '3:15'},
+ {name: "Perfect", length: '4:37'}
+ ]
+ };
+
+
+
+
+ Fixtures.getAlbum = function() {
+ return albumPicasso;
+ };
+
+
+
+
+//assignment6Services: Add a second public method to the Fixtures service named getCollection. This method takes one argument, numberOfAlbums, and returns an array with the specified number of albumPicasso objects pushed to it.
+// Fixtures.getCollection = function(numberOfAlbums) {
+// var albums = [];
+// for (var i=0; i < numberOfAlbums; i++) {
+// albums.push(angular.copy(albumPicasso));
+// };
+// return albums;
+// };
+//angular.copy is one of several global function components on the angular object. We add an albums property and set its value to an empty array. Within the for loop, we use angular.copy to make copies of albumPicasso and push them to the array.
+
+ Fixtures.getCollection = function() {
+ var albums = [albumPicasso, albumMarconi, mw0002896346, mw0002083060, mw0002891900, mw0002896652, mw0000658489];
+ return albums;
+ }
+
+
+
+
+ return Fixtures;
+ }
+
+ angular
+ .module('blocJams')
+ .factory('Fixtures', Fixtures); //register a Fixtures service using the Factory recipe
+ })();
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042049_createProjectProgram.js b/pool/shard006/JavaScript/0042049_createProjectProgram.js
new file mode 100644
index 0000000000000000000000000000000000000000..b5da63153b8b3781479e679886810775194d037c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042049_createProjectProgram.js
@@ -0,0 +1,61 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.createProjectProgram = void 0;
+const debug_1 = __importDefault(require("debug"));
+const path_1 = __importDefault(require("path"));
+const createWatchProgram_1 = require("./createWatchProgram");
+const node_utils_1 = require("../node-utils");
+const shared_1 = require("./shared");
+const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createProjectProgram');
+const DEFAULT_EXTRA_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
+/**
+ * @param code The code of the file being linted
+ * @param createDefaultProgram True if the default program should be created
+ * @param extra The config object
+ * @returns If found, returns the source file corresponding to the code and the containing program
+ */
+function createProjectProgram(code, createDefaultProgram, extra) {
+ log('Creating project program for: %s', extra.filePath);
+ const astAndProgram = (0, node_utils_1.firstDefined)((0, createWatchProgram_1.getProgramsForProjects)(code, extra.filePath, extra), currentProgram => (0, shared_1.getAstFromProgram)(currentProgram, extra));
+ if (!astAndProgram && !createDefaultProgram) {
+ // the file was either not matched within the tsconfig, or the extension wasn't expected
+ const errorLines = [
+ '"parserOptions.project" has been set for @typescript-eslint/parser.',
+ `The file does not match your project config: ${path_1.default.relative(extra.tsconfigRootDir || process.cwd(), extra.filePath)}.`,
+ ];
+ let hasMatchedAnError = false;
+ const extraFileExtensions = extra.extraFileExtensions || [];
+ extraFileExtensions.forEach(extraExtension => {
+ if (!extraExtension.startsWith('.')) {
+ errorLines.push(`Found unexpected extension "${extraExtension}" specified with the "extraFileExtensions" option. Did you mean ".${extraExtension}"?`);
+ }
+ if (DEFAULT_EXTRA_FILE_EXTENSIONS.includes(extraExtension)) {
+ errorLines.push(`You unnecessarily included the extension "${extraExtension}" with the "extraFileExtensions" option. This extension is already handled by the parser by default.`);
+ }
+ });
+ const fileExtension = path_1.default.extname(extra.filePath);
+ if (!DEFAULT_EXTRA_FILE_EXTENSIONS.includes(fileExtension)) {
+ const nonStandardExt = `The extension for the file (${fileExtension}) is non-standard`;
+ if (extraFileExtensions.length > 0) {
+ if (!extraFileExtensions.includes(fileExtension)) {
+ errorLines.push(`${nonStandardExt}. It should be added to your existing "parserOptions.extraFileExtensions".`);
+ hasMatchedAnError = true;
+ }
+ }
+ else {
+ errorLines.push(`${nonStandardExt}. You should add "parserOptions.extraFileExtensions" to your config.`);
+ hasMatchedAnError = true;
+ }
+ }
+ if (!hasMatchedAnError) {
+ errorLines.push('The file must be included in at least one of the projects provided.');
+ }
+ throw new Error(errorLines.join('\n'));
+ }
+ return astAndProgram;
+}
+exports.createProjectProgram = createProjectProgram;
+//# sourceMappingURL=createProjectProgram.js.map
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042050_logout.service.js b/pool/shard006/JavaScript/0042050_logout.service.js
new file mode 100644
index 0000000000000000000000000000000000000000..c9c4f2d6eeade0ba374b3b1c537f0a4c1451ac59
--- /dev/null
+++ b/pool/shard006/JavaScript/0042050_logout.service.js
@@ -0,0 +1,28 @@
+(function() {
+ 'use strict';
+
+ angular
+ .module('reservation')
+ .service('logoutService', logoutService);
+
+ logoutService.inject = ['userState', '$kinvey', '$q'];
+
+ function logoutService(userState, $kinvey, $q) {
+
+ this.logoutUser = logoutUser;
+
+ function logoutUser() {
+ return $kinvey.User.logout().then(
+ function(response) {
+ userState.userName = null;
+ userState.id = null;
+ userState.isloggedIn = false;
+ console.log(response);
+ },
+ function(error) {
+
+ return console.log(error);
+ });
+ }
+ }
+})();
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042052_query-geometry-model.js b/pool/shard006/JavaScript/0042052_query-geometry-model.js
new file mode 100644
index 0000000000000000000000000000000000000000..a092c52084e9c60e6a6afcb197e484ecfbb8ab7c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042052_query-geometry-model.js
@@ -0,0 +1,146 @@
+var _ = require('underscore');
+var Backbone = require('backbone');
+var BaseModel = require('./query-base-model');
+var STATUS = require('./query-base-status');
+/* eslint-disable */
+var template = _.template('' +
+ 'SELECT CASE LOWER(ST_GeometryType(<%= geom_column %>)) ' +
+ " WHEN 'st_polygon' THEN 'polygon' " +
+ " WHEN 'st_multipolygon' THEN 'polygon' " +
+ " WHEN 'st_multilinestring' THEN 'line' " +
+ " WHEN 'st_linestring' THEN 'line' " +
+ " WHEN 'st_multipoint' THEN 'point' " +
+ " WHEN 'st_point' THEN 'point' " +
+ " ELSE '' " +
+ ' END AS the_geom FROM (<%= sql %>) __wrapped WHERE <%= geom_column %> IS NOT NULL'
+/* eslint-enable */
+);
+
+var THE_GEOM_NOT_FOUND_ERROR = 'column \"the_geom\" does not exist';
+var PARAMS = {
+ sort_order: 'asc',
+ rows_per_page: 40,
+ page: 0
+};
+
+/**
+ * Model to represent a schema of a SQL query.
+ */
+module.exports = BaseModel.extend({
+
+ defaults: {
+ query: '',
+ status: STATUS.unavailable,
+ simple_geom: '', // , 'point', 'polygon', 'line'
+ ready: false // until true there's no data available on the table(s) used in the query
+ },
+
+ initialize: function (attrs, opts) {
+ if (!opts.configModel) throw new Error('configModel is required');
+ BaseModel.prototype.initialize.call(this, attrs, opts);
+
+ this._configModel = opts.configModel;
+
+ this._addChangeListener();
+ },
+
+ url: function () {
+ return this._configModel.getSqlApiUrl();
+ },
+
+ fetch: function (opts) {
+ if (!this.canFetch()) return;
+
+ this.set('status', STATUS.fetching);
+
+ opts = opts || {};
+ var errorCallback = opts && opts.error;
+ var successCallback = opts && (opts.success || opts.complete);
+
+ opts.data = _.extend(
+ opts.data || {},
+ {
+ api_key: this._configModel.get('api_key'),
+ q: this._getSqlApiQueryParam(opts.geomColumnName)
+ },
+ PARAMS
+ );
+
+ opts.method = this._httpMethod();
+
+ opts.success = function (model, response) {
+ this._resetRepeatedError();
+ successCallback && successCallback(response);
+ }.bind(this);
+
+ opts.error = function (model, response) {
+ if (response && response.statusText !== 'abort') {
+ var error = response.responseText ? JSON.parse(response.responseText).error : [];
+ // in case we get an error of the_geom does not exists try with the_geom_webmercator to get the geometry type
+ if (error.length === 1 && error[0] === THE_GEOM_NOT_FOUND_ERROR) {
+ this.fetch(_.extend({}, opts, { geomColumnName: 'the_geom_webmercator' }));
+ } else {
+ this._incrementRepeatedError();
+
+ this.set({
+ simple_geom: '',
+ query_errors: error,
+ status: this.hasRepeatedErrors() ? STATUS.errored : STATUS.unavailable
+ });
+
+ errorCallback && errorCallback({
+ status: response.status || 'Unknown',
+ error: error
+ });
+ }
+ }
+ }.bind(this);
+
+ return Backbone.Model.prototype.fetch.call(this, opts);
+ },
+
+ parse: function (r) {
+ var simpleGeom;
+
+ _.some(r.rows, function (row) {
+ return !!(simpleGeom = row.the_geom); // to stop when found a valid simple geom
+ });
+
+ return {
+ status: STATUS.fetched,
+ simple_geom: simpleGeom || ''
+ };
+ },
+
+ hasValue: function () {
+ return !!this.get('simple_geom');
+ },
+
+ _onChange: function () {
+ this._removeChangeListener();
+
+ if (!this.hasChanged('status') && this.get('status') === STATUS.fetching) {
+ // If it is already fetching just redo the fetch with latest attrs
+ // in case the query has changed
+ if (this.hasChanged('query')) {
+ this.fetch();
+ }
+ } else if (this.hasChanged('query') || this.hasChanged('ready')) {
+ this.set('status', this.get('query') ? STATUS.unfetched : STATUS.unavailable, { silent: true });
+ }
+
+ this._addChangeListener();
+ },
+
+ _getSqlApiQueryParam: function (geomColumnName) {
+ if (this.get('query').indexOf('_raster') > 0) {
+ return this.get('query');
+ } else {
+ return template({
+ geom_column: geomColumnName || 'the_geom',
+ sql: this.get('query')
+ });
+ }
+ }
+
+});
diff --git a/pool/shard006/JavaScript/0042054_Analytics.js b/pool/shard006/JavaScript/0042054_Analytics.js
new file mode 100644
index 0000000000000000000000000000000000000000..3b270c65bd8c95016cc0ee60627458a110906ed8
--- /dev/null
+++ b/pool/shard006/JavaScript/0042054_Analytics.js
@@ -0,0 +1,55 @@
+module.exports = function () {
+
+ this.sendEndorsementEvent = function(techName, endorsedEmail){
+ ga('send', 'event', 'Endorsement', techName, endorsedEmail);
+ }
+
+ this.sendLinkEvent = function(techName){
+ ga('send', 'event', 'Link', 'link_add', techName);
+ }
+
+ this.sendSkillEvent = function(name, skill){
+ if(skill){
+ if(skill === 1){
+ ga('send', 'event', 'Skill', name, 'Newbie');
+ }
+ if(skill === 2){
+ ga('send', 'event', 'Skill', name, 'Initiate');
+ }
+ if(skill === 3){
+ ga('send', 'event', 'Skill', name, 'Padawan');
+ }
+ if(skill === 4){
+ ga('send', 'event', 'Skill', name, 'Knight');
+ }
+ if(skill === 5){
+ ga('send', 'event', 'Skill', name, 'Jedi');
+ }
+ }
+ }
+
+ this.sendCommentEvent = function(techName){
+ ga('send', 'event', 'Comment', 'comment_add', techName);
+ }
+
+ this.sendRecommendationEvent = function(techName, recommend){
+ if(recommend === true){
+ ga('send', 'event', 'Recommendation', 'recommendation_positive', techName);
+ }
+ if(recommend === false){
+ ga('send', 'event', 'Recommendation', 'recommendation_negative', techName);
+ }
+ }
+
+ this.trackUser = function(userEmail) {
+ ga('create', 'UA-60744312-3', 'auto');
+ ga('set', '&uid', userEmail);
+ ga('set', 'contentGroup1', userEmail);
+ ga('set', 'dimension1', userEmail);
+ ga('send', 'pageview');
+ }
+
+ this.trackTechnologyAcess = function(techId){
+ ga('send', 'event', 'TechGalleryEvents', 'technology_acess', techId);
+ }
+}
diff --git a/pool/shard006/JavaScript/0042056_user.js b/pool/shard006/JavaScript/0042056_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..173ccbb71131d96fb7c2f3a41fd224f6837d854c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042056_user.js
@@ -0,0 +1,77 @@
+define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
+
+ var Controller = {
+ index: function () {
+ // 初始化表格参数配置
+ Table.api.init({
+ extend: {
+ index_url: 'user/index',
+ add_url: 'user/add',
+ edit_url: 'user/edit',
+ del_url: 'user/del',
+ multi_url: 'user/multi',
+ table: 'user',
+ }
+ });
+
+ var table = $("#table");
+
+ // 初始化表格
+ table.bootstrapTable({
+ url: $.fn.bootstrapTable.defaults.extend.index_url,
+ pk: 'id',
+ sortName: 'id',
+ columns: [
+ [
+ {checkbox: true},
+ {field: 'id', title: __('Id')},
+ {field: 'img', title: __('Preview'), formatter: Controller.api.formatter.thumb},
+ {field: 'name', title: __('Name')},
+ {field: 'sex', title: __('Sex'),formatter: function (value) {
+ return value=='1'? '男' : '女';
+ }},
+ {field: 'phone', title: __('Phone')},
+ // {field: 'room', title: __('Room')},
+ // {field: 'mettingadd', title: __('Mettingadd')},
+ {field: 'seatnum', title: __('Seatnum')},
+ // {field: 'groupnum', title: __('Groupnum')},
+ // {field: 'groupadd', title: __('Groupadd')},
+ // {field: 'th', title: __('Th')},
+ {field: 'fv', title: __('Fv')},
+ // {field: 'six', title: __('Six')},
+ {field: 'isload', title: __('Isload'),formatter:function (value) {
+ return value=='1' ? '已到场' : '未到场'
+ }},
+ {field: 'loadtime', title: __('Loadtime'), formatter: Table.api.formatter.datetime},
+ {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
+ ]
+ ]
+ });
+
+ // 为表格绑定事件
+ Table.api.bindevent(table);
+ },
+ add: function () {
+ Controller.api.bindevent();
+ },
+ edit: function () {
+ Controller.api.bindevent();
+ },
+ api: {
+ bindevent: function () {
+ Form.api.bindevent($("form[role=form]"));
+ },
+ formatter: {
+ thumb: function (value, row, index) {
+ var style = value == 'upyun' ? '!/fwfh/120x90' : '';
+ return ' ';
+
+ },
+ url: function (value, row, index) {
+ return '' + value + ' ';
+ },
+ }
+ }
+ };
+ return Controller;
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042058_bezier.js b/pool/shard006/JavaScript/0042058_bezier.js
new file mode 100644
index 0000000000000000000000000000000000000000..472f95fcfb07766cf69ebf83ae8ba232d254967d
--- /dev/null
+++ b/pool/shard006/JavaScript/0042058_bezier.js
@@ -0,0 +1,340 @@
+// Copyright 2007 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 Represents a cubic Bezier curve.
+ *
+ * Uses the deCasteljau algorithm to compute points on the curve.
+ * http://en.wikipedia.org/wiki/De_Casteljau's_algorithm
+ *
+ * Currently it uses an unrolled version of the algorithm for speed. Eventually
+ * it may be useful to use the loop form of the algorithm in order to support
+ * curves of arbitrary degree.
+ *
+ * @author robbyw@google.com (Robby Walker)
+ * @author wcrosby@google.com (Wayne Crosby)
+ */
+
+goog.provide('goog.math.Bezier');
+
+goog.require('goog.math');
+goog.require('goog.math.Coordinate');
+
+
+
+/**
+ * Object representing a cubic bezier curve.
+ * @param {number} x0 X coordinate of the start point.
+ * @param {number} y0 Y coordinate of the start point.
+ * @param {number} x1 X coordinate of the first control point.
+ * @param {number} y1 Y coordinate of the first control point.
+ * @param {number} x2 X coordinate of the second control point.
+ * @param {number} y2 Y coordinate of the second control point.
+ * @param {number} x3 X coordinate of the end point.
+ * @param {number} y3 Y coordinate of the end point.
+ * @constructor
+ * @final
+ */
+goog.math.Bezier = function(x0, y0, x1, y1, x2, y2, x3, y3) {
+ /**
+ * X coordinate of the first point.
+ * @type {number}
+ */
+ this.x0 = x0;
+
+ /**
+ * Y coordinate of the first point.
+ * @type {number}
+ */
+ this.y0 = y0;
+
+ /**
+ * X coordinate of the first control point.
+ * @type {number}
+ */
+ this.x1 = x1;
+
+ /**
+ * Y coordinate of the first control point.
+ * @type {number}
+ */
+ this.y1 = y1;
+
+ /**
+ * X coordinate of the second control point.
+ * @type {number}
+ */
+ this.x2 = x2;
+
+ /**
+ * Y coordinate of the second control point.
+ * @type {number}
+ */
+ this.y2 = y2;
+
+ /**
+ * X coordinate of the end point.
+ * @type {number}
+ */
+ this.x3 = x3;
+
+ /**
+ * Y coordinate of the end point.
+ * @type {number}
+ */
+ this.y3 = y3;
+};
+
+
+/**
+ * Constant used to approximate ellipses.
+ * See: http://canvaspaint.org/blog/2006/12/ellipse/
+ * @type {number}
+ */
+goog.math.Bezier.KAPPA = 4 * (Math.sqrt(2) - 1) / 3;
+
+
+/**
+ * @return {!goog.math.Bezier} A copy of this curve.
+ */
+goog.math.Bezier.prototype.clone = function() {
+ return new goog.math.Bezier(this.x0, this.y0, this.x1, this.y1, this.x2,
+ this.y2, this.x3, this.y3);
+};
+
+
+/**
+ * Test if the given curve is exactly the same as this one.
+ * @param {goog.math.Bezier} other The other curve.
+ * @return {boolean} Whether the given curve is the same as this one.
+ */
+goog.math.Bezier.prototype.equals = function(other) {
+ return this.x0 == other.x0 && this.y0 == other.y0 && this.x1 == other.x1 &&
+ this.y1 == other.y1 && this.x2 == other.x2 && this.y2 == other.y2 &&
+ this.x3 == other.x3 && this.y3 == other.y3;
+};
+
+
+/**
+ * Modifies the curve in place to progress in the opposite direction.
+ */
+goog.math.Bezier.prototype.flip = function() {
+ var temp = this.x0;
+ this.x0 = this.x3;
+ this.x3 = temp;
+ temp = this.y0;
+ this.y0 = this.y3;
+ this.y3 = temp;
+
+ temp = this.x1;
+ this.x1 = this.x2;
+ this.x2 = temp;
+ temp = this.y1;
+ this.y1 = this.y2;
+ this.y2 = temp;
+};
+
+
+/**
+ * Computes the curve's X coordinate at a point between 0 and 1.
+ * @param {number} t The point on the curve to find.
+ * @return {number} The computed coordinate.
+ */
+goog.math.Bezier.prototype.getPointX = function(t) {
+ // Special case start and end.
+ if (t == 0) {
+ return this.x0;
+ } else if (t == 1) {
+ return this.x3;
+ }
+
+ // Step one - from 4 points to 3
+ var ix0 = goog.math.lerp(this.x0, this.x1, t);
+ var ix1 = goog.math.lerp(this.x1, this.x2, t);
+ var ix2 = goog.math.lerp(this.x2, this.x3, t);
+
+ // Step two - from 3 points to 2
+ ix0 = goog.math.lerp(ix0, ix1, t);
+ ix1 = goog.math.lerp(ix1, ix2, t);
+
+ // Final step - last point
+ return goog.math.lerp(ix0, ix1, t);
+};
+
+
+/**
+ * Computes the curve's Y coordinate at a point between 0 and 1.
+ * @param {number} t The point on the curve to find.
+ * @return {number} The computed coordinate.
+ */
+goog.math.Bezier.prototype.getPointY = function(t) {
+ // Special case start and end.
+ if (t == 0) {
+ return this.y0;
+ } else if (t == 1) {
+ return this.y3;
+ }
+
+ // Step one - from 4 points to 3
+ var iy0 = goog.math.lerp(this.y0, this.y1, t);
+ var iy1 = goog.math.lerp(this.y1, this.y2, t);
+ var iy2 = goog.math.lerp(this.y2, this.y3, t);
+
+ // Step two - from 3 points to 2
+ iy0 = goog.math.lerp(iy0, iy1, t);
+ iy1 = goog.math.lerp(iy1, iy2, t);
+
+ // Final step - last point
+ return goog.math.lerp(iy0, iy1, t);
+};
+
+
+/**
+ * Computes the curve at a point between 0 and 1.
+ * @param {number} t The point on the curve to find.
+ * @return {!goog.math.Coordinate} The computed coordinate.
+ */
+goog.math.Bezier.prototype.getPoint = function(t) {
+ return new goog.math.Coordinate(this.getPointX(t), this.getPointY(t));
+};
+
+
+/**
+ * Changes this curve in place to be the portion of itself from [t, 1].
+ * @param {number} t The start of the desired portion of the curve.
+ */
+goog.math.Bezier.prototype.subdivideLeft = function(t) {
+ if (t == 1) {
+ return;
+ }
+
+ // Step one - from 4 points to 3
+ var ix0 = goog.math.lerp(this.x0, this.x1, t);
+ var iy0 = goog.math.lerp(this.y0, this.y1, t);
+
+ var ix1 = goog.math.lerp(this.x1, this.x2, t);
+ var iy1 = goog.math.lerp(this.y1, this.y2, t);
+
+ var ix2 = goog.math.lerp(this.x2, this.x3, t);
+ var iy2 = goog.math.lerp(this.y2, this.y3, t);
+
+ // Collect our new x1 and y1
+ this.x1 = ix0;
+ this.y1 = iy0;
+
+ // Step two - from 3 points to 2
+ ix0 = goog.math.lerp(ix0, ix1, t);
+ iy0 = goog.math.lerp(iy0, iy1, t);
+
+ ix1 = goog.math.lerp(ix1, ix2, t);
+ iy1 = goog.math.lerp(iy1, iy2, t);
+
+ // Collect our new x2 and y2
+ this.x2 = ix0;
+ this.y2 = iy0;
+
+ // Final step - last point
+ this.x3 = goog.math.lerp(ix0, ix1, t);
+ this.y3 = goog.math.lerp(iy0, iy1, t);
+};
+
+
+/**
+ * Changes this curve in place to be the portion of itself from [0, t].
+ * @param {number} t The end of the desired portion of the curve.
+ */
+goog.math.Bezier.prototype.subdivideRight = function(t) {
+ this.flip();
+ this.subdivideLeft(1 - t);
+ this.flip();
+};
+
+
+/**
+ * Changes this curve in place to be the portion of itself from [s, t].
+ * @param {number} s The start of the desired portion of the curve.
+ * @param {number} t The end of the desired portion of the curve.
+ */
+goog.math.Bezier.prototype.subdivide = function(s, t) {
+ this.subdivideRight(s);
+ this.subdivideLeft((t - s) / (1 - s));
+};
+
+
+/**
+ * Computes the position t of a point on the curve given its x coordinate.
+ * That is, for an input xVal, finds t s.t. getPointX(t) = xVal.
+ * As such, the following should always be true up to some small epsilon:
+ * t ~ solvePositionFromXValue(getPointX(t)) for t in [0, 1].
+ * @param {number} xVal The x coordinate of the point to find on the curve.
+ * @return {number} The position t.
+ */
+goog.math.Bezier.prototype.solvePositionFromXValue = function(xVal) {
+ // Desired precision on the computation.
+ var epsilon = 1e-6;
+
+ // Initial estimate of t using linear interpolation.
+ var t = (xVal - this.x0) / (this.x3 - this.x0);
+ if (t <= 0) {
+ return 0;
+ } else if (t >= 1) {
+ return 1;
+ }
+
+ // Try gradient descent to solve for t. If it works, it is very fast.
+ var tMin = 0;
+ var tMax = 1;
+ for (var i = 0; i < 8; i++) {
+ var value = this.getPointX(t);
+ var derivative = (this.getPointX(t + epsilon) - value) / epsilon;
+ if (Math.abs(value - xVal) < epsilon) {
+ return t;
+ } else if (Math.abs(derivative) < epsilon) {
+ break;
+ } else {
+ if (value < xVal) {
+ tMin = t;
+ } else {
+ tMax = t;
+ }
+ t -= (value - xVal) / derivative;
+ }
+ }
+
+ // If the gradient descent got stuck in a local minimum, e.g. because
+ // the derivative was close to 0, use a Dichotomy refinement instead.
+ // We limit the number of interations to 8.
+ for (var i = 0; Math.abs(value - xVal) > epsilon && i < 8; i++) {
+ if (value < xVal) {
+ tMin = t;
+ t = (t + tMax) / 2;
+ } else {
+ tMax = t;
+ t = (t + tMin) / 2;
+ }
+ value = this.getPointX(t);
+ }
+ return t;
+};
+
+
+/**
+ * Computes the y coordinate of a point on the curve given its x coordinate.
+ * @param {number} xVal The x coordinate of the point on the curve.
+ * @return {number} The y coordinate of the point on the curve.
+ */
+goog.math.Bezier.prototype.solveYValueFromXValue = function(xVal) {
+ return this.getPointY(this.solvePositionFromXValue(xVal));
+};
diff --git a/pool/shard006/JavaScript/0042060_spanning-trees.test.js b/pool/shard006/JavaScript/0042060_spanning-trees.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..c19b4bc5c7fe89af958bd068178a92b939615314
--- /dev/null
+++ b/pool/shard006/JavaScript/0042060_spanning-trees.test.js
@@ -0,0 +1,49 @@
+var self = require('../../../index');
+var expect = require('chai').expect;
+var fs = require('fs');
+
+describe('findSpanningTree', function(){
+ it('fails if the graph is empty', function(){
+ expect(function(){
+ var graph = new self.graph.Graph({
+ nodes: []
+ });
+ self.tree.spanningTrees(graph);
+ }).to.throw(Error);
+ });
+
+ /*
+ it('converts trivial graphs', function(){
+ var graph = new self.graph.Graph({
+ nodes: [{
+ value: 'one',
+ neighbours: []
+ }]
+ });
+ var tree = self.tree.spanningTrees(graph);
+ expect(tree).to.be.eql({
+ nodes: [{
+ value: 'one',
+ children: []
+ }],
+ rootNode: 0
+ });
+ });
+ */
+
+ it('fails if graph has disconnected components', function(){
+ expect(function(){
+ var graph = new self.graph.Graph(
+ self.graph.readGraph(fs.readFileSync(
+ __dirname + '/resources/disconnected.graph', {encoding: 'ascii'})));
+ self.tree.spanningTrees(graph);
+ }).to.throw(Error);
+ });
+
+ it('finds spanning trees of triple triangle graph', function(){
+ var graph = new self.graph.Graph(
+ self.graph.readGraph(fs.readFileSync(__dirname + '/resources/triple-tri.graph', {encoding: 'ascii'})));
+ self.tree.spanningTrees(graph);
+ //expect(spanningTree).to.be.eql(expectedResult);
+ });
+});
diff --git a/pool/shard006/JavaScript/0042062_passport.js b/pool/shard006/JavaScript/0042062_passport.js
new file mode 100644
index 0000000000000000000000000000000000000000..82d81da222887697c5094b59ac9e9d6ee8e76785
--- /dev/null
+++ b/pool/shard006/JavaScript/0042062_passport.js
@@ -0,0 +1,42 @@
+var passport=require('passport'),
+ mysql=require('mysql'),
+ LocalStrategy =require('passport-local').Strategy;
+
+module.exports=function(config){
+ var connection = mysql.createConnection(config.db);
+ var bcrypt = require('bcrypt-nodejs');
+ passport.use(new LocalStrategy(function(username,password,done){
+ connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, user){
+ if (user[0] && bcrypt.compareSync(password, user[0].password)){
+ return done(null, user[0]);
+ }
+ else {
+ return done(null, false); // req.flash is the way to set flashdata using connect-flash
+ }
+
+ });
+ }
+ ));
+
+
+
+ passport.serializeUser(function(user, done) {
+ if(user) {
+ done(null, user.id);
+ }
+ });
+
+ passport.deserializeUser(function(id, done) {
+ connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, user){
+ //done(err, rows[0]);
+ if(user[0]) {
+ return done(null, user[0]);
+ } else {
+ return done(null, false);
+ }
+
+ });
+ });
+
+
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042069_SailsGenerator.js b/pool/shard006/JavaScript/0042069_SailsGenerator.js
new file mode 100644
index 0000000000000000000000000000000000000000..1f983446cd0657e9d28d8d85d20614119d02a1c7
--- /dev/null
+++ b/pool/shard006/JavaScript/0042069_SailsGenerator.js
@@ -0,0 +1,192 @@
+/**
+ * Module dependencies
+ */
+
+var util = require('util');
+var _ = require('lodash');
+var bower = require('bower');
+var fsx = require('fs-extra');
+var async = require('async');
+var npm = require("npm");
+
+/**
+ * Update client-side dependencies
+ */
+
+
+/**
+ * sails-generate-angel
+ *
+ * Usage:
+ * `sails generate angel`
+ *
+ * @description Generates a angel
+ * @help See http://links.sailsjs.org/docs/generators
+ */
+
+module.exports = {
+
+ /**
+ * `before()` is run before executing any of the `targets`
+ * defined below.
+ *
+ * This is where we can validate user input, configure default
+ * scope variables, get extra dependencies, and so on.
+ *
+ * @param {Object} scope
+ * @param {Function} cb [callback]
+ */
+
+ before: function (scope, cb) {
+
+ // scope.args are the raw command line arguments.
+ //
+ // e.g. if someone runs:
+ // $ sails generate angel user find create update
+ // then `scope.args` would be `['user', 'find', 'create', 'update']`
+
+ if (!scope.args[0]) {
+ return cb( new Error('Please provide a name for this angel.') );
+ }
+
+ // scope.rootPath is the base path for this generator
+ //
+ // e.g. if this generator specified the target:
+ // './Foobar.md': { copy: 'Foobar.md' }
+ //
+ // And someone ran this generator from `/Users/dbowie/sailsStuff`,
+ // then `/Users/dbowie/sailsStuff/Foobar.md` would be created.
+ if (!scope.rootPath) {
+ return cb( INVALID_SCOPE_VARIABLE('rootPath') );
+ }
+
+
+ // Decide the output filename for use in targets below:
+ scope.appName = scope.args[0];
+
+ async.auto({
+ 'angular-ui-router': function(callback) {
+ cb.log.info("Downloading dependencies");
+ bower.commands
+ .install(['angular-ui-router'], {
+ save: false
+ }, { /* custom config */ })
+ .on('end', function(installed) {
+ callback();
+ });
+ },
+ // ... future front-end dependencies here ...
+ },
+
+ function done(err, async_data) {
+ if(err) cb.log.error(err);
+ cb();
+ });
+ },
+
+ after: function(scope, cb) {
+ fsx.copy('bower_components', scope.appName + '/www/bower_components', function() {
+ fsx.removeSync('bower_components');
+ npm.load(scope.appName + '/www/package.json', function (err) {
+ if (err) return cb( new Error(err));
+ cb.log.info("Installing npm modules");
+ npm.commands.install([], function (err, data) {
+ if (err) {
+ fsx.removeSync('node_modules');
+ fsx.removeSync('package.json');
+ return cb( new Error(err));
+ }
+ cb.log.info('Copy npm modules');
+ fsx.copy('node_modules', scope.appName + '/www/node_modules', function() {
+ fsx.removeSync('node_modules');
+ fsx.removeSync('package.json');
+ fsx.copySync(scope.appName + '/www/bower_components/angular/angular.js', scope.appName + '/www//assets/js/dependencies/angular.js');
+ fsx.copySync(scope.appName + '/www/bower_components/angular-ui-router/release/angular-ui-router.js', scope.appName + '/www/assets/js/dependencies/release/angular-ui-router.js');
+ cb();
+ });
+ });
+ //npm.on("log", function (message) { cb.log.info(message)});
+ });
+ });
+ },
+
+ /**
+ * The files/folders to generate.
+ * @type {Object}
+ */
+
+ targets: {
+
+ // Usage:
+ // './path/to/destination.foo': { someHelper: opts }
+
+ // Creates a dynamically-named file relative to `scope.rootPath`
+ // (defined by the `filename` scope variable).
+ //
+ // The `template` helper reads the specified template, making the
+ // entire scope available to it (uses underscore/JST/ejs syntax).
+ // Then the file is copied into the specified destination (on the left).
+
+
+ '.': ['new'],
+ './:appName/www/assets': { folder: {} },
+ './:appName/www/assets/js': { folder: {} },
+ './:appName/www/assets/css': { folder: {} },
+ './:appName/www/assets/images': { folder: {} },
+ './:appName/www/assets/js/min': { folder: {} },
+ './:appName/www/assets/js/dependencies/release': { folder: {} },
+ './:appName/www/assets/css/min': { folder: {} },
+
+ './:appName/www/index.html': { template: 'www/index.html' },
+ './:appName/www/assets/js/app.js': { template: 'www/assets/js/app.js' },
+ './:appName/www/assets/js/components/home/home.js': { template: 'www/assets/js/components/home/home.js' },
+ './:appName/www/assets/js/components/home/home-controller.js': { template: 'www/assets/js/components/home/home-controller.js' },
+ './:appName/www/assets/js/components/home/home-service.js': { template: 'www/assets/js/components/home/home-service.js' },
+ './:appName/www/assets/js/components/home/templates/home.html': { template: 'www/assets/js/components/home/templates/home.html' },
+
+ './:appName/www/Gruntfile.js': { template: 'www/Gruntfile.js' },
+ './:appName/www/package.json': { template: 'www/_package.json' },
+
+ './package.json': { template: 'www/_package.json' },
+ },
+
+
+ /**
+ * The absolute path to the `templates` for this generator
+ * (for use with the `template` helper)
+ *
+ * @type {String}
+ */
+ templatesDirectory: require('path').resolve(__dirname, '../templates')
+};
+
+
+
+
+
+/**
+ * INVALID_SCOPE_VARIABLE()
+ *
+ * Helper method to put together a nice error about a missing or invalid
+ * scope variable. We should always validate any required scope variables
+ * to avoid inadvertently smashing someone's filesystem.
+ *
+ * @param {String} varname [the name of the missing/invalid scope variable]
+ * @param {String} details [optional - additional details to display on the console]
+ * @param {String} message [optional - override for the default message]
+ * @return {Error}
+ * @api private
+ */
+
+function INVALID_SCOPE_VARIABLE (varname, details, message) {
+ var DEFAULT_MESSAGE =
+ 'Issue encountered in generator "angel":\n'+
+ 'Missing required scope variable: `%s`"\n' +
+ 'If you are the author of `sails-generate-angel`, please resolve this '+
+ 'issue and publish a new patch release.';
+
+ message = (message || DEFAULT_MESSAGE) + (details ? '\n'+details : '');
+ message = util.inspect(message, varname);
+
+ return new Error(message);
+}
diff --git a/pool/shard006/JavaScript/0042071_user.js b/pool/shard006/JavaScript/0042071_user.js
new file mode 100644
index 0000000000000000000000000000000000000000..238324da3d2e9ddb8de727db1c8319a13f2e3023
--- /dev/null
+++ b/pool/shard006/JavaScript/0042071_user.js
@@ -0,0 +1,97 @@
+'use strict';
+
+var database = require('../database').db;
+var speaker = require('../speaker');
+
+/**
+ * Create or get a new User.
+ * @param telegramId
+ * @param telegramBot
+ * @constructor
+ */
+var User = function (telegramId, telegramBot) {
+ this.telegramBot = telegramBot;
+ this.telegramId = telegramId;
+ this.collection = database.collection('users');
+};
+
+/**
+ * Get the user dipartimento. If it's undefined ask the user for it.
+ * @returns {Promise}
+ */
+User.prototype.getDipartimento = function () {
+ var that = this;
+ return this.getUser().then(function (user) {
+ if (!user['dipartimentoId']) {
+ return speaker.ask('dipartimento', that.telegramId, that.telegramBot).then(function (dipartimentoId) {
+ return that.update({dipartimentoId: dipartimentoId}).then(function () {
+ return Promise.resolve(dipartimentoId);
+ });
+ });
+ }
+ return Promise.resolve(user.dipartimentoId);
+ });
+};
+
+User.prototype.update = function (update) {
+ return this.collection.updateOne({telegramId: this.telegramId}, {$set: update});
+};
+
+/**
+ * Access to Database and return the User Object if found else null
+ *
+ * @param {number} id of the user
+ * @returns {Promise}
+ */
+/*User.prototype.getUserById = function (id) {
+ return this.collection.findOne({_id: id});
+ };*/
+
+/**
+ * Access to Database and return the User Object or create it
+ *
+ * @returns {Promise}
+ */
+User.prototype.getUser = function () {
+ var collection = this.collection;
+ var telegramId = this.telegramId;
+ return collection.find({telegramId: telegramId}).limit(1).next().then(function (user) {
+ if (user == null) {
+ return collection.insertOne({
+ telegramId: telegramId
+ });
+ }
+ return Promise.resolve(user);
+ });
+};
+
+/**
+ * Forget everything about this user
+ *
+ * @returns {Promise}
+ */
+User.prototype.forget = function () {
+ return this.collection.removeOne({telegramId: this.telegramId});
+};
+
+/**
+ * This function searches in all users and returns only the items that match the query
+ *
+ * @param {object} query The cursor query object.
+ * @returns {Cursor}
+ */
+/*User.prototype.getUserList = function (query) {
+ return this.collection.find(query);
+ };*/
+
+/**
+ * Add new user in Database
+ *
+ * @param {object} user Object User
+ * @returns {Promise}
+ */
+/*User.prototype.newUser = function (user) {
+ return this.collection.insertOne(user);
+ };*/
+
+module.exports = User;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042072_selectall.js b/pool/shard006/JavaScript/0042072_selectall.js
new file mode 100644
index 0000000000000000000000000000000000000000..f8bd4786179c0e377c3ed0b5ec8cd3e0f613e471
--- /dev/null
+++ b/pool/shard006/JavaScript/0042072_selectall.js
@@ -0,0 +1,51 @@
+jQuery("#selall").jqGrid({
+ url:'server.php?q=1',
+ datatype: "xml",
+ colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
+ colModel:[
+ {name:'id',index:'id', width:55},
+ {name:'invdate',index:'invdate', width:90},
+ {name:'name',index:'name', width:100},
+ {name:'amount',index:'amount', width:80, align:"right"},
+ {name:'tax',index:'tax', width:80, align:"right"},
+ {name:'total',index:'total', width:80,align:"right"},
+ {name:'note',index:'note', width:150, sortable:false}
+ ],
+ rowNum:10,
+ rowList:[10,20,30],
+ pager: '#pselall',
+ sortname: 'id',
+ viewrecords: true,
+ sortorder: "desc",
+ multiselect: true,
+ caption:"onSelectAll Event",
+ onSelectAll : function(aSel,selected) {
+ if(selected){
+ var value =0;
+ for(var i=0;i {
+ // If the prop 'onCancel' is provided, it overrides the default.
+ return {
+ handleCancel() {
+ if (typeof props.onCancel === 'function') {
+ props.onCancel();
+ } else {
+ actions.hideModal(dispatch);
+ }
+ }
+ };
+ }
+)(props => {
+ return (
+
+
+ {$t('client.general.cancel')}
+
+
+ {$t('client.confirmdeletemodal.confirm')}
+
+
+ );
+});
+
+CancelAndDelete.propTypes = {
+ // A function to be called when clicking on the delete button.
+ onDelete: PropTypes.func.isRequired,
+
+ // A function to be called when clicking on the cancel button.
+ onCancel: PropTypes.func
+};
+
+export default CancelAndDelete;
diff --git a/pool/shard006/JavaScript/0042076_uri.js b/pool/shard006/JavaScript/0042076_uri.js
new file mode 100644
index 0000000000000000000000000000000000000000..931954ba3e6721788d369a419abe5386b944bdfc
--- /dev/null
+++ b/pool/shard006/JavaScript/0042076_uri.js
@@ -0,0 +1,290 @@
+/*
+ * Copyright © 2007 Dominic Mitchell
+ *
+ * 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 Dominic Mitchell nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * An URI datatype. Based upon examples in RFC3986.
+ *
+ * TODO %-escaping
+ * TODO split apart authority
+ * TODO split apart query_string (on demand, anyway)
+ * TODO handle parameters containing empty strings properly
+ * TODO keyword escaping
+ *
+ * @(#) $Id$
+ */
+
+// Introduce a new scope to define some private helper functions.
+(function (exports) {
+
+ var URI;
+ var URIQuery;
+
+ //// HELPER FUNCTIONS /////
+
+ // RFC3986 §5.2.3 (Merge Paths)
+ function merge(base, rel_path) {
+ var dirname = /^(.*)\//;
+ if (base.authority && !base.path) {
+ return "/" + rel_path;
+ }
+ else {
+ return base.getPath().match(dirname)[0] + rel_path;
+ }
+ }
+
+ // Match two path segments, where the second is ".." and the first must
+ // not be "..".
+ var DoubleDot = /\/((?!\.\.\/)[^\/]*)\/\.\.\//;
+
+ function remove_dot_segments(path) {
+ if (!path) {
+ return "";
+ }
+ // Remove any single dots
+ var newpath = path.replace(/\/\.\//g, '/');
+ // Remove any trailing single dots.
+ newpath = newpath.replace(/\/\.$/, '/');
+ // Remove any double dots and the path previous. NB: We can't use
+ // the "g", modifier because we are changing the string that we're
+ // matching over.
+ while (newpath.match(DoubleDot)) {
+ newpath = newpath.replace(DoubleDot, '/');
+ }
+ // Remove any trailing double dots.
+ newpath = newpath.replace(/\/([^\/]*)\/\.\.$/, '/');
+ // If there are any remaining double dot bits, then they're wrong
+ // and must be nuked. Again, we can't use the g modifier.
+ while (newpath.match(/\/\.\.\//)) {
+ newpath = newpath.replace(/\/\.\.\//, '/');
+ }
+ return newpath;
+ }
+
+ // give me an ordered list of keys of this object
+ function hashkeys(obj) {
+ var list = [];
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ list.push(key);
+ }
+ }
+ return list.sort();
+ }
+
+ // TODO: Make these do something
+ function uriEscape(source) {
+ return source;
+ }
+
+ function uriUnescape(source) {
+ return source;
+ }
+
+
+ //// URI CLASS /////
+
+ // Constructor for the URI object. Parse a string into its components.
+ URI = function (str) {
+ if (!str) {
+ str = "";
+ }
+ // Based on the regex in RFC2396 Appendix B.
+ var parser = /^(?:([^:\/?\#]+):)?(?:\/\/([^\/?\#]*))?([^?\#]*)(?:\?([^\#]*))?(?:\#(.*))?/;
+ var result = str.match(parser);
+
+ // Keep the results in private variables.
+ var scheme = result[1] || null;
+ var authority = result[2] || null;
+ var path = result[3] || null;
+ var query = result[4] || null;
+ var fragment = result[5] || null;
+
+ // Set up accessors.
+ this.getScheme = function () {
+ return scheme;
+ };
+ this.setScheme = function (newScheme) {
+ scheme = newScheme;
+ };
+ this.getAuthority = function () {
+ return authority;
+ };
+ this.setAuthority = function (newAuthority) {
+ authority = newAuthority;
+ };
+ this.getPath = function () {
+ return path;
+ };
+ this.setPath = function (newPath) {
+ path = newPath;
+ };
+ this.getQuery = function () {
+ return query;
+ };
+ this.setQuery = function (newQuery) {
+ query = newQuery;
+ };
+ this.getFragment = function () {
+ return fragment;
+ };
+ this.setFragment = function (newFragment) {
+ fragment = newFragment;
+ };
+ };
+
+ // Restore the URI to it's stringy glory.
+ URI.prototype.toString = function () {
+ var str = "";
+ if (this.getScheme()) {
+ str += this.getScheme() + ":";
+ }
+ if (this.getAuthority()) {
+ str += "//" + this.getAuthority();
+ }
+ if (this.getPath()) {
+ str += this.getPath();
+ }
+ if (this.getQuery()) {
+ str += "?" + this.getQuery();
+ }
+ if (this.getFragment()) {
+ str += "#" + this.getFragment();
+ }
+ return str;
+ };
+
+ // RFC3986 §5.2.2. Transform References;
+ URI.prototype.resolve = function (base) {
+ var target = new URI();
+ if (this.getScheme()) {
+ target.setScheme(this.getScheme());
+ target.setAuthority(this.getAuthority());
+ target.setPath(remove_dot_segments(this.getPath()));
+ target.setQuery(this.getQuery());
+ }
+ else {
+ if (this.getAuthority()) {
+ target.setAuthority(this.getAuthority());
+ target.setPath(remove_dot_segments(this.getPath()));
+ target.setQuery(this.getQuery());
+ }
+ else {
+ // XXX Original spec says "if defined and empty"…;
+ if (!this.getPath()) {
+ target.setPath(base.getPath());
+ if (this.getQuery()) {
+ target.setQuery(this.getQuery());
+ }
+ else {
+ target.setQuery(base.getQuery());
+ }
+ }
+ else {
+ if (this.getPath().charAt(0) === '/') {
+ target.setPath(remove_dot_segments(this.getPath()));
+ } else {
+ target.setPath(merge(base, this.getPath()));
+ target.setPath(remove_dot_segments(target.getPath()));
+ }
+ target.setQuery(this.getQuery());
+ }
+ target.setAuthority(base.getAuthority());
+ }
+ target.setScheme(base.getScheme());
+ }
+
+ target.setFragment(this.getFragment());
+
+ return target;
+ };
+
+ URI.prototype.parseQuery = function () {
+ return URIQuery.fromString(this.getQuery(), this.querySeparator);
+ };
+
+ //// URIQuery CLASS /////
+
+ URIQuery = function () {
+ this.params = {};
+ this.separator = "&";
+ };
+
+ URIQuery.fromString = function (sourceString, separator) {
+ var result = new URIQuery();
+ if (separator) {
+ result.separator = separator;
+ }
+ result.addStringParams(sourceString);
+ return result;
+ };
+
+
+ // From http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
+ // (application/x-www-form-urlencoded).
+ //
+ // NB: The user can get this.params and modify it directly.
+ URIQuery.prototype.addStringParams = function (sourceString) {
+ var kvp = sourceString.split(this.separator);
+ var list, key, value;
+ for (var i = 0; i < kvp.length; i++) {
+ // var [key,value] = kvp.split("=", 2) only works on >= JS 1.7
+ list = kvp[i].split("=", 2);
+ key = uriUnescape(list[0].replace(/\+/g, " "));
+ value = uriUnescape(list[1].replace(/\+/g, " "));
+ if (!this.params.hasOwnProperty(key)) {
+ this.params[key] = [];
+ }
+ this.params[key].push(value);
+ }
+ };
+
+ URIQuery.prototype.getParam = function (key) {
+ if (this.params.hasOwnProperty(key)) {
+ return this.params[key][0];
+ }
+ return null;
+ };
+
+ URIQuery.prototype.toString = function () {
+ var kvp = [];
+ var keys = hashkeys(this.params);
+ var ik, ip;
+ for (ik = 0; ik < keys.length; ik++) {
+ for (ip = 0; ip < this.params[keys[ik]].length; ip++) {
+ kvp.push(keys[ik].replace(/ /g, "+") + "=" + this.params[keys[ik]][ip].replace(/ /g, "+"));
+ }
+ }
+ return kvp.join(this.separator);
+ };
+
+ exports.URI = URI;
+ exports.URIQuery = URIQuery;
+
+}((typeof exports === 'undefined') ? window : exports));
diff --git a/pool/shard006/JavaScript/0042077_atan2.test.js b/pool/shard006/JavaScript/0042077_atan2.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..aaa779ede2b50c5f72fc741f0d394e16e3d06770
--- /dev/null
+++ b/pool/shard006/JavaScript/0042077_atan2.test.js
@@ -0,0 +1,106 @@
+// test atan2
+var assert = require('assert'),
+ error = require('../../../lib/error/index'),
+ math = require('../../../index'),
+ approx = require('../../../tools/approx'),
+ pi = math.pi,
+ complex = math.complex,
+ matrix = math.matrix,
+ unit = math.unit,
+ divide = math.divide,
+ atan2 = math.atan2,
+ bigmath = math.create({precision: 20}),
+ Big = bigmath.bignumber,
+ atan2Big = bigmath.atan2;
+
+describe('atan2', function() {
+
+ it('should calculate atan2 correctly', function() {
+ approx.equal(atan2(0, 0) / pi, 0);
+ approx.equal(atan2(0, 1) / pi, 0);
+ approx.equal(atan2(1, 1) / pi, 0.25);
+ approx.equal(atan2(1, 0) / pi, 0.5);
+ approx.equal(atan2(1, -1) / pi, 0.75);
+ approx.equal(atan2(0, -1) / pi, 1);
+ approx.equal(atan2(-1, -1) / pi, -0.75);
+ approx.equal(atan2(-1, 0) / pi, -0.5);
+ approx.equal(atan2(-1, 1) / pi, -0.25);
+ });
+
+ it('should calculate atan2 for booleans', function() {
+ assert.equal(atan2(true, true), 0.25 * pi);
+ assert.equal(atan2(true, false), 0.5 * pi);
+ assert.equal(atan2(false, true), 0);
+ assert.equal(atan2(false, false), 0);
+ });
+
+ it('should calculate atan2 with mixed numbers and booleans', function() {
+ assert.equal(atan2(1, true), 0.25 * pi);
+ assert.equal(atan2(1, false), 0.5 * pi);
+ assert.equal(atan2(true, 1), 0.25 * pi);
+ assert.equal(atan2(false, 1), 0);
+ });
+
+ it('should calculate atan2 with mixed numbers and null', function() {
+ assert.equal(atan2(1, null), 0.5 * pi);
+ assert.equal(atan2(null, 1), 0);
+ });
+
+ it('should return the arctan of for bignumbers', function() {
+ assert.deepEqual(atan2Big(Big(0), Big(0)), Big(NaN));
+ assert.deepEqual(atan2Big(Big(0), Big(1)), Big(0));
+ assert.deepEqual(atan2Big(Big(1), Big(1)), Big('0.7853981633974483096'));
+ assert.deepEqual(atan2Big(Big(1), Big(0)), Big('1.5707963267948966192'));
+ assert.deepEqual(atan2Big(Big(1), Big(-1)), Big('2.3561944901923449288'));
+ assert.deepEqual(atan2Big(Big(0), Big(-1)), Big('3.1415926535897932385'));
+ assert.deepEqual(atan2Big(Big(-1), Big(-1)), Big('-2.3561944901923449288'));
+ assert.deepEqual(atan2Big(Big(-1), Big(0)), Big('-1.5707963267948966192'));
+ assert.deepEqual(atan2Big(Big(-1), Big(1)), Big('-0.7853981633974483096'));
+ });
+
+ it('should return the arctan of for mixed numbers and bignumbers', function() {
+ assert.deepEqual(atan2Big(1, Big(1)), Big('0.7853981633974483096'));
+ assert.deepEqual(atan2Big(Big(1), 1), Big('0.7853981633974483096'));
+ });
+
+ it('should return the arctan of for mixed bignumbers and booleans', function() {
+ assert.deepEqual(atan2Big(Big(1), true), Big('0.7853981633974483096'));
+ assert.deepEqual(atan2Big(Big(1), false), Big('1.5707963267948966192'));
+ assert.deepEqual(atan2Big(true, Big(1)), Big('0.7853981633974483096'));
+ assert.deepEqual(atan2Big(false, Big(1)), Big(0));
+ });
+
+ it('should calculate atan2 with mixed bignumbers and null', function() {
+ assert.deepEqual(atan2Big(Big(1), null), Big('1.5707963267948966192'));
+ assert.deepEqual(atan2Big(null, Big(1)), Big(0));
+ });
+
+ it('should throw an error if called with a complex', function() {
+ assert.throws(function () {atan2(complex('2+3i'), complex('1-2i')); });
+ });
+
+ it('should throw an error if called with a string', function() {
+ assert.throws(function () {atan2('string', 1)});
+ });
+
+ it('should throw an error if called with a unit', function() {
+ assert.throws(function () {atan2(unit('5cm'), 1)});
+ });
+
+ it('should calculate the atan2 element-wise for arrays and matrices', function() {
+ // array, matrix, range
+ approx.deepEqual(divide(atan2([1,0,-1], [1,0,-1]), pi), [0.25, 0, -0.75]);
+ approx.deepEqual(divide(atan2(
+ matrix([1,0,-1]),
+ matrix([1,0,-1])), pi),
+ matrix([0.25, 0, -0.75]));
+ approx.equal(atan2(0, 2) / pi, 0);
+ approx.equal(atan2(0, -2) / pi, 1);
+ });
+
+ it('should throw an error in case of invalid number of arguments', function() {
+ assert.throws(function () {atan2(1)}, error.ArgumentsError);
+ assert.throws(function () {atan2(1, 2, 3)}, error.ArgumentsError);
+ });
+
+});
diff --git a/pool/shard006/JavaScript/0042078_pgui.shortcuts.js b/pool/shard006/JavaScript/0042078_pgui.shortcuts.js
new file mode 100644
index 0000000000000000000000000000000000000000..5a4c7ff55d6321d203b831c8c4724f19f057ba00
--- /dev/null
+++ b/pool/shard006/JavaScript/0042078_pgui.shortcuts.js
@@ -0,0 +1,33 @@
+define(function(require, exports)
+{
+
+ require('jquery/jquery.hotkeys');
+ var inputControlFocused = false;
+
+ $(function()
+ {
+ $('input').blur(function() {
+ inputControlFocused = false;
+ });
+ $('input').focus(function() {
+ inputControlFocused = true;
+ });
+ });
+
+ exports.initializeShortCuts = function(container)
+ {
+ container.find('[pgui-shortcut]').each(function() {
+
+ var item = $(this);
+ var shortCut = item.attr('pgui-shortcut');
+
+ $(document).bind('keydown', shortCut, function() {
+ if (!inputControlFocused) {
+ if (item.is('a'))
+ window.location.href = item.attr('href');
+ }
+ });
+
+ });
+ };
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042080_benchmark.native.js b/pool/shard006/JavaScript/0042080_benchmark.native.js
new file mode 100644
index 0000000000000000000000000000000000000000..79f325470ce4c6963bca722d3bcdfeb96dfabb7b
--- /dev/null
+++ b/pool/shard006/JavaScript/0042080_benchmark.native.js
@@ -0,0 +1,60 @@
+/**
+* @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 resolve = require( 'path' ).resolve;
+var bench = require( '@stdlib/bench' );
+var randu = require( '@stdlib/random/base/randu' );
+var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
+var tryRequire = require( '@stdlib/utils/try-require' );
+var pkg = require( './../package.json' ).name;
+
+
+// VARIABLES //
+
+var floorf = tryRequire( resolve( __dirname, './../lib/native.js' ) );
+var opts = {
+ 'skip': ( floorf instanceof Error )
+};
+
+
+// MAIN //
+
+bench( pkg+'::native', opts, function benchmark( b ) {
+ var x;
+ var y;
+ var i;
+
+ b.tic();
+ for ( i = 0; i < b.iterations; i++ ) {
+ x = ( randu()*1000.0 ) - 500.0;
+ y = floorf( x );
+ if ( isnanf( y ) ) {
+ b.fail( 'should not return NaN' );
+ }
+ }
+ b.toc();
+ if ( isnanf( y ) ) {
+ b.fail( 'should not return NaN' );
+ }
+ b.pass( 'benchmark finished' );
+ b.end();
+});
diff --git a/pool/shard006/JavaScript/0042088_grunt-suitcss.js b/pool/shard006/JavaScript/0042088_grunt-suitcss.js
new file mode 100644
index 0000000000000000000000000000000000000000..b222e12d11964f756888e5c9579f8a364f8777fb
--- /dev/null
+++ b/pool/shard006/JavaScript/0042088_grunt-suitcss.js
@@ -0,0 +1,157 @@
+/*
+ * grunt-suitcss
+ * Build, preprocess and validate SUIT CSS components
+ * https://github.com/simonsmith/grunt-suitcss
+ *
+ * Copyright (c) 2014 Simon Smith
+ * Licensed under the MIT license.
+ */
+
+'use strict';
+
+var path = require('path');
+var rework = require('rework');
+var conformance = require('rework-suit-conformance');
+var suitcss = require('suitcss-preprocessor');
+var resolve = require('component-resolver');
+var Build = require('component-build');
+var flatten = require('component-flatten');
+var Q = require('q');
+var grunt = require('grunt');
+
+var options;
+module.exports = task;
+
+function task() {
+ grunt.registerMultiTask('suitcss', 'Preprocess and validate SUIT CSS components', function() {
+ options = this.options({
+ separator: grunt.util.linefeed,
+ conform: true,
+ resolveOpts: {
+ install: true
+ },
+ preprocessOpts: {}
+ });
+
+ // Ensure always verbose for CLI output
+ options.resolveOpts.verbose = true;
+
+ var taskDone = this.async();
+
+ this.files.forEach(function(f) {
+ var files = f.src.filter(checkFileExists).map(getFileContents);
+
+ Q.all(files)
+ .done(function(files) {
+ writeFile(f.dest, files);
+ taskDone();
+ }, failTask);
+ });
+ });
+}
+
+function checkFileExists(filepath) {
+ if (!grunt.file.exists(filepath)) {
+ grunt.log.warn('Source file "' + filepath + '" not found.');
+ return false;
+ } else {
+ return true;
+ }
+}
+
+function getFileContents(filepath) {
+ if (isComponent(filepath)) {
+ return buildComponentAndCheckConformance(filepath);
+ } else {
+ return checkConformance(filepath);
+ }
+}
+
+/**
+ * Builds a component package based on a component.json file.
+ * Will install packages if they don't exist locally.
+ * Validate each component before returning built files
+ */
+function buildComponentAndCheckConformance(filepath) {
+ var componentDir = path.join(process.cwd(), path.dirname(filepath));
+ var deferred = Q.defer();
+
+ resolve(componentDir, options.resolveOpts, function(err, tree) {
+ if (err) {
+ return deferred.reject(err);
+ }
+
+ var build = Build(flatten(tree));
+
+ build.stylePlugins = function(build) {
+ build.use('styles', function(file, done) {
+ file.read(function(err, string) {
+ if (err) {
+ return deferred.reject(err);
+ }
+
+ if (options.conform) {
+ try {
+ file.string = conform(string);
+ } catch (e) {
+ return deferred.reject(e);
+ }
+ }
+
+ done();
+ });
+ });
+ };
+
+ build.styles(function(err, builtCSS) {
+ if (err) {
+ return deferred.reject(err);
+ }
+
+ deferred.resolve(builtCSS);
+ });
+ });
+
+ return deferred.promise;
+}
+
+/**
+ * Run on individual components
+ */
+function checkConformance(filepath) {
+ var file = grunt.file.read(filepath);
+ var deferred = Q.defer();
+
+ if (options.conform) {
+ try {
+ conform(file);
+ } catch (e) {
+ deferred.reject(e);
+ return deferred.promise;
+ }
+ }
+
+ deferred.resolve(file);
+ return deferred.promise;
+}
+
+function isComponent(filepath) {
+ return /component.json$/.test(filepath);
+}
+
+function conform(string) {
+ return rework(string).use(conformance);
+}
+
+function writeFile(dest, files) {
+ var file = files.join(grunt.util.normalizelf(options.separator));
+
+ file = suitcss(file, options.preprocessOpts);
+
+ grunt.file.write(dest, file);
+ grunt.log.writeln('File "' + dest + '" created.');
+}
+
+function failTask(error) {
+ grunt.fail.fatal(error);
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042093_index.js b/pool/shard006/JavaScript/0042093_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..2f98f6234f36001b4aa3f397074310d7dc30049c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042093_index.js
@@ -0,0 +1,59 @@
+/**
+*
+* MIDDLEWARE: error
+*
+*
+* DESCRIPTION:
+* - Generic error handling middleware.
+*
+*
+* NOTES:
+* [1]
+*
+*
+* TODO:
+* [1]
+*
+*
+* LICENSE:
+* MIT
+*
+* Copyright (c) 2015. Athan Reines.
+*
+*
+* AUTHOR:
+* Athan Reines. kgryte@gmail.com. 2015.
+*
+*/
+
+'use strict';
+
+/**
+* FUNCTION: onError( error, request, response, next )
+* Middleware for error handling.
+*
+* @param {Error|Object} error - error object
+* @param {Object} request - HTTP request object
+* @param {Object} response - HTTP response object
+* @param {Function} next - callback to invoke after handling the error
+*/
+function onError( error, request, response, next ) {
+ var err = error;
+ request.logger.info({ 'error': error });
+ if ( err instanceof Error ) {
+ err = {
+ 'status': 500,
+ 'message': error.message
+ };
+ }
+ response
+ .status( err.status )
+ .json( err );
+
+ next();
+} // end FUNCTION onError()
+
+
+// EXPORTS //
+
+module.exports = onError;
diff --git a/pool/shard006/JavaScript/0042095_utils.js b/pool/shard006/JavaScript/0042095_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..48aa7987adfc7f49017d7afe5b5c2cdcc575f5a5
--- /dev/null
+++ b/pool/shard006/JavaScript/0042095_utils.js
@@ -0,0 +1,19 @@
+var IoC = require('electrolyte');
+var path = require('path');
+var fs = require('fs');
+var async = require('async');
+
+var modelsPath = path.join(__dirname, '..', 'app', 'models');
+
+var files = fs.readdirSync(modelsPath);
+var models = [];
+for (var i = 0; i < files.length; i++) {
+ var model = IoC.create('models/'+path.basename(files[i], '.js'));
+ models.push(model);
+}
+
+exports.cleanDatabase = function(callback) {
+ async.eachSeries(models, function(model, next) {
+ model.remove({}, next);
+ }, callback);
+};
diff --git a/pool/shard006/JavaScript/0042096_funnel.js b/pool/shard006/JavaScript/0042096_funnel.js
new file mode 100644
index 0000000000000000000000000000000000000000..df4958e50755a9ed204e1b357f53b84687c227bb
--- /dev/null
+++ b/pool/shard006/JavaScript/0042096_funnel.js
@@ -0,0 +1,125 @@
+var EventEmitter = require('events').EventEmitter,
+ util = require('util'),
+ User = require('./schemas/user'),
+ Account = require('./schemas/account');
+
+
+var Funnel = module.exports = function (users) {
+ var that = this;
+ this._users = [];
+ this.users = [];
+ // keymap
+ this.user_map = {};
+
+ EventEmitter.call(this);
+
+ /**
+ * Init
+ */
+ this.init = function () {
+ if (typeof users === 'undefined' || users.length == 0) return;
+ for (var x = 0; x < users.length; x++) {
+ that.addUser(users[x]);
+ }
+ };
+
+ /**
+ * Add new user
+ * @param user
+ */
+ this.addUser = function (user) {
+ this._users.push(user);
+ var u = new User(user);
+ var l = this.users.push(u);
+ this.user_map[user.user.id] = l - 1;
+
+ /**
+ * Message structure:
+ * {
+ * user: {instance of User},
+ * account: {instance of Account},
+ * message: {instance of Message}
+ * }
+ */
+ u.on('message', function (message) {
+ that.emit('message', message);
+ });
+ u.on('sent', function (message) {
+ that.emit('sent', message);
+ });
+ u.on('error', function (message) {
+ that.emit('error', message);
+ });
+ u.on('connected', function (message) {
+ that.emit('connected', message);
+ });
+ u.addAccounts();
+ return u;
+ };
+
+ /**
+ * Remove user
+ * @param user_id
+ * @returns {boolean}
+ */
+ this.removeUser = function (user_id) {
+ if (typeof this.users[this.user_map[user_id]] === 'undefined')
+ return false;
+ this.users[this.user_map[user_id]].removeAllAccounts();
+ delete this.users[this.user_map[user_id]];
+ delete this._users[this.user_map[user_id]];
+ delete this.user_map[user_id];
+ return true;
+ };
+
+ /**
+ * Connect to all users and all their accounts
+ */
+ this.connectAllUsers = function () {
+ if (this.users.length == 0) return;
+ for (var x = 0; x < this.users.length; x++) {
+ this.connectAllAccounts(this.users[x].user.id);
+ }
+ };
+
+ /**
+ * Connect users accounts
+ * @param user_id
+ * @returns {boolean}
+ */
+ this.connectAllAccounts = function (user_id) {
+ if (typeof this.user_map[user_id] === 'undefined')
+ return false;
+ this.users[this.user_map[user_id]].connectAllAccounts();
+ return true;
+ };
+
+ /**
+ * Connect to specific account of specific user
+ * @param user_id
+ * @param account_id
+ * @returns {boolean}
+ */
+ this.connectAccount = function(user_id, account_id){
+ if (typeof this.user_map[user_id] === 'undefined')
+ return false;
+ return this.users[this.user_map[user_id]].connect(account_id);
+ }
+
+ /**
+ * Test new connections
+ * @param settings
+ * @param callback
+ */
+ this.testConnection = function(settings, callback){
+ var a = new Account(settings);
+ a.testConnection(settings, callback);
+ };
+
+ if(typeof users !== 'undefined' && users.length > 0)
+ {
+ this.init();
+ }
+};
+util.inherits(Funnel, EventEmitter);
+
diff --git a/pool/shard006/JavaScript/0042099_15.2.3.6-4-112.js b/pool/shard006/JavaScript/0042099_15.2.3.6-4-112.js
new file mode 100644
index 0000000000000000000000000000000000000000..993240de38f088d0ea6122a91d1ae66d6ae1560a
--- /dev/null
+++ b/pool/shard006/JavaScript/0042099_15.2.3.6-4-112.js
@@ -0,0 +1,43 @@
+// Copyright (c) 2012 Ecma International. All rights reserved.
+// Ecma International makes this code available under the terms and conditions set
+// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
+// "Use Terms"). Any redistribution of this code must retain the above
+// copyright and this notice and otherwise comply with the Use Terms.
+
+/*---
+es5id: 15.2.3.6-4-112
+description: >
+ Object.defineProperty - 'name' and 'desc' are accessor properties,
+ name.[[Set]] is undefined and desc.[[Set]] is function (8.12.9
+ step 12)
+includes: [propertyHelper.js]
+---*/
+
+
+var obj = {};
+
+function getFunc() {
+ return 10;
+}
+
+Object.defineProperty(obj, "foo", {
+ set: undefined,
+ get: getFunc,
+ enumerable: true,
+ configurable: true
+});
+
+function setFunc(value) {
+ obj.setVerifyHelpProp = value;
+}
+
+Object.defineProperty(obj, "foo", {
+ set: setFunc
+});
+verifyEqualTo(obj, "foo", getFunc());
+
+verifyWritable(obj, "foo", "setVerifyHelpProp");
+
+verifyEnumerable(obj, "foo");
+
+verifyConfigurable(obj, "foo");
diff --git a/pool/shard006/JavaScript/0042100_patternSpec.js b/pool/shard006/JavaScript/0042100_patternSpec.js
new file mode 100644
index 0000000000000000000000000000000000000000..21bae0eab30c235f9fd129a8bf8250a0b172dfcc
--- /dev/null
+++ b/pool/shard006/JavaScript/0042100_patternSpec.js
@@ -0,0 +1,35 @@
+'use strict';
+
+var _validate = require('validate.js');
+
+var _validate2 = _interopRequireDefault(_validate);
+
+require('./pattern');
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+describe('Validator Adapter - pattern', function () {
+ var constraints = void 0;
+
+ beforeEach(function () {
+ constraints = {
+ pattern: {
+ pattern: "^[A-Za-z0-9._'%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$|^$",
+ message: '^does not match pattern'
+ }
+ };
+ });
+
+ it('SHOULD return error message WHEN pattern does not match', function () {
+ var hasErrorMsg = _validate2.default.single('123', constraints);
+ expect(hasErrorMsg).toBeDefined();
+ expect(hasErrorMsg).toBeArrayOfStrings();
+ expect(hasErrorMsg).toContain('does not match pattern');
+ });
+
+ it('SHOULD return undefined WHEN value matches the pattern', function () {
+ var hasErrorMsg = _validate2.default.single('kb@gmail.com', constraints);
+ expect(hasErrorMsg).toBeUndefined();
+ });
+});
+//# sourceMappingURL=patternSpec.js.map
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042104_auth-login-error.js b/pool/shard006/JavaScript/0042104_auth-login-error.js
new file mode 100644
index 0000000000000000000000000000000000000000..dbef91581a8a570cc069eaf4cd104c0a1e07029d
--- /dev/null
+++ b/pool/shard006/JavaScript/0042104_auth-login-error.js
@@ -0,0 +1,18 @@
+module.exports = function(e, error, request, action) {
+ //set the error to true
+ request.error = true;
+
+ //is there a message
+ if(error.message) {
+ request.error = error.message;
+ }
+
+ //recall the form
+ if(error.validation) {
+ //set the field errors
+ request.errors = error.validation;
+ }
+
+ //recall the response
+ action.response(request);
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042107_nodesFromRect.js b/pool/shard006/JavaScript/0042107_nodesFromRect.js
new file mode 100644
index 0000000000000000000000000000000000000000..2315f51ffac883ff0db3e76e46192d168fc9b221
--- /dev/null
+++ b/pool/shard006/JavaScript/0042107_nodesFromRect.js
@@ -0,0 +1,141 @@
+/*
+ * Contributors:
+ * * Antonio Gomes
+ * * Allan Sandfeld Jensen
+**/
+
+function nodeToString(node) {
+ var str = "";
+ if (node.nodeType == Node.ELEMENT_NODE) {
+ str += node.nodeName;
+ if (node.id)
+ str += '#' + node.id;
+ else if (node.class)
+ str += '.' + node.class;
+ } else if (node.nodeType == Node.TEXT_NODE) {
+ str += "'" + node.data + "'";
+ } else if (node.nodeType == Node.DOCUMENT_NODE) {
+ str += "#document";
+ }
+ return str;
+}
+
+function nodeListToString(nodes) {
+ var nodeString = "";
+
+ for (var i = 0; i < nodes.length; i++) {
+ var str = nodeToString(nodes[i]);
+ if (!str)
+ continue;
+ nodeString += str;
+ if (i + 1 < nodes.length)
+ nodeString += ", ";
+ }
+ return nodeString;
+}
+
+function check(x, y, topPadding, rightPadding, bottomPadding, leftPadding, list, doc)
+{
+ if (!window.internals)
+ return;
+
+ if (!doc)
+ doc = document;
+
+ var nodes = internals.nodesFromRect(doc, x, y, topPadding, rightPadding, bottomPadding, leftPadding, true /* ignoreClipping */, false /* allow child-frame content */);
+ if (!nodes)
+ return;
+
+ if (nodes.length != list.length) {
+ testFailed("Different number of nodes for rect" +
+ "[" + x + "," + y + "], " +
+ "[" + topPadding + "," + rightPadding +
+ "," + bottomPadding + "," + leftPadding +
+ "]: '" + list.length + "' vs '" + nodes.length +
+ "', found: " + nodeListToString(nodes));
+ return;
+ }
+
+ for (var i = 0; i < nodes.length; i++) {
+ if (nodes[i] != list[i]) {
+ testFailed("Unexpected node #" + i + " for rect " +
+ "[" + x + "," + y + "], " +
+ "[" + topPadding + "," + rightPadding +
+ "," + bottomPadding + "," + leftPadding + "]" +
+ " - " + nodeToString(nodes[i]));
+ return;
+ }
+ }
+
+ testPassed("All correct nodes found for rect");
+}
+
+function checkRect(left, top, width, height, expectedNodeString, doc)
+{
+ if (!window.internals)
+ return;
+
+ if (height <=0 || width <= 0)
+ return;
+
+ if (!doc)
+ doc = document;
+
+ var topPadding = height / 2;
+ var leftPadding = width / 2;
+ // FIXME: When nodesFromRect is changed to not add 1 to width and height, remove the correction here.
+ var bottomPadding = (height - 1) - topPadding;
+ var rightPadding = (width - 1) - leftPadding;
+
+ var nodeString = nodesFromRectAsString(doc, left + leftPadding, top + topPadding, topPadding, rightPadding, bottomPadding, leftPadding);
+
+ if (nodeString == expectedNodeString) {
+ testPassed("All correct nodes found for rect");
+ } else {
+ testFailed("NodesFromRect should be [" + expectedNodeString + "] was [" + nodeString + "]");
+ }
+}
+
+function checkPoint(left, top, expectedNodeString, doc)
+{
+ if (!window.internals)
+ return;
+
+ if (!doc)
+ doc = document;
+
+ var nodeString = nodesFromRectAsString(doc, left, top, 0, 0, 0, 0);
+
+ if (nodeString == expectedNodeString) {
+ testPassed("Correct node found for point");
+ } else {
+ testFailed("NodesFromRect should be [" + expectedNodeString + "] was [" + nodeString + "]");
+ }
+}
+
+function nodesFromRectAsString(doc, x, y, topPadding, rightPadding, bottomPadding, leftPadding)
+{
+ var nodes = internals.nodesFromRect(doc, x, y, topPadding, rightPadding, bottomPadding, leftPadding, true /* ignoreClipping */, true /* allow child-frame content */);
+ if (!nodes)
+ return "";
+
+ return nodeListToString(nodes);
+}
+
+function getCenterFor(element)
+{
+ var rect = element.getBoundingClientRect();
+ return { x : parseInt((rect.left + rect.right) / 2) , y : parseInt((rect.top + rect.bottom) / 2)};
+}
+
+function getTopFor(element)
+{
+ var rect = element.getBoundingClientRect();
+ return { x : parseInt((rect.left + rect.right) / 2) , y : parseInt(rect.top)};
+}
+
+function getBottomFor(element)
+{
+ var rect = element.getBoundingClientRect();
+ return { x : parseInt((rect.left + rect.right) / 2) , y : parseInt(rect.bottom)};
+}
diff --git a/pool/shard006/JavaScript/0042116_clean.js b/pool/shard006/JavaScript/0042116_clean.js
new file mode 100644
index 0000000000000000000000000000000000000000..ac03f17bd3b6699f6a6e5d7260c8b882ca8c07f5
--- /dev/null
+++ b/pool/shard006/JavaScript/0042116_clean.js
@@ -0,0 +1,21 @@
+var config = require('../config').html;
+var del = require('del');
+var gulp = require('gulp');
+
+var cleanDevTask = function(cb) {
+ var files = ['dev/assets/{css,js}/**'];
+ if (config.nunjucks) files = ['dist/**/*'];
+
+ del(files).then(function() {
+ cb();
+ });
+}
+
+var cleanTask = function(cb) {
+ del('dist/**/*').then(function() {
+ cb();
+ });
+}
+
+gulp.task('clean:dev', cleanDevTask);
+gulp.task('clean', cleanTask);
diff --git a/pool/shard006/JavaScript/0042117_app.js b/pool/shard006/JavaScript/0042117_app.js
new file mode 100644
index 0000000000000000000000000000000000000000..583ecbfdb27e04c08ea415c35d1053f84985ccbd
--- /dev/null
+++ b/pool/shard006/JavaScript/0042117_app.js
@@ -0,0 +1,23 @@
+'use strict';
+
+angular.module('phonecat', [])
+ .controller('Home', function($scope, $http) {
+ $http.get('data/phones/phones.json').then(function(response){
+ $scope.telefones = response.data;
+ });
+
+ $scope.ui_estado = 'lista';
+ $scope.telefone = null;
+
+ $scope.mostrarDetalhes = function(telefone) {
+ $scope.ui_estado = 'detalhes';
+ $http.get('data/phones/' + telefone.id + '.json').then(
+ function(response){
+ $scope.telefone = response.data;
+ });
+ };
+
+ $scope.mostrarLista = function() {
+ $scope.ui_estado = 'lista';
+ };
+ });
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042118_multicast.js b/pool/shard006/JavaScript/0042118_multicast.js
new file mode 100644
index 0000000000000000000000000000000000000000..241969b39fc5223713c2ef8c40606e25e473e978
--- /dev/null
+++ b/pool/shard006/JavaScript/0042118_multicast.js
@@ -0,0 +1,116 @@
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@most/prelude')) :
+ typeof define === 'function' && define.amd ? define(['exports', '@most/prelude'], factory) :
+ (factory((global.mostMulticast = global.mostMulticast || {}),global.mostPrelude));
+}(this, (function (exports,_most_prelude) { 'use strict';
+
+var MulticastDisposable = function MulticastDisposable (source, sink) {
+ this.source = source
+ this.sink = sink
+ this.disposed = false
+};
+
+MulticastDisposable.prototype.dispose = function dispose () {
+ if (this.disposed) {
+ return
+ }
+ this.disposed = true
+ var remaining = this.source.remove(this.sink)
+ return remaining === 0 && this.source._dispose()
+};
+
+function tryEvent (t, x, sink) {
+ try {
+ sink.event(t, x)
+ } catch (e) {
+ sink.error(t, e)
+ }
+}
+
+function tryEnd (t, x, sink) {
+ try {
+ sink.end(t, x)
+ } catch (e) {
+ sink.error(t, e)
+ }
+}
+
+var dispose = function (disposable) { return disposable.dispose(); }
+
+var emptyDisposable = {
+ dispose: function dispose$1 () {}
+}
+
+var MulticastSource = function MulticastSource (source) {
+ this.source = source
+ this.sinks = []
+ this._disposable = emptyDisposable
+};
+
+MulticastSource.prototype.run = function run (sink, scheduler) {
+ var n = this.add(sink)
+ if (n === 1) {
+ this._disposable = this.source.run(this, scheduler)
+ }
+ return new MulticastDisposable(this, sink)
+};
+
+MulticastSource.prototype._dispose = function _dispose () {
+ var disposable = this._disposable
+ this._disposable = emptyDisposable
+ return Promise.resolve(disposable).then(dispose)
+};
+
+MulticastSource.prototype.add = function add (sink) {
+ this.sinks = _most_prelude.append(sink, this.sinks)
+ return this.sinks.length
+};
+
+MulticastSource.prototype.remove = function remove$1 (sink) {
+ var i = _most_prelude.findIndex(sink, this.sinks)
+ // istanbul ignore next
+ if (i >= 0) {
+ this.sinks = _most_prelude.remove(i, this.sinks)
+ }
+
+ return this.sinks.length
+};
+
+MulticastSource.prototype.event = function event (time, value) {
+ var s = this.sinks
+ if (s.length === 1) {
+ return s[0].event(time, value)
+ }
+ for (var i = 0; i < s.length; ++i) {
+ tryEvent(time, value, s[i])
+ }
+};
+
+MulticastSource.prototype.end = function end (time, value) {
+ var s = this.sinks
+ for (var i = 0; i < s.length; ++i) {
+ tryEnd(time, value, s[i])
+ }
+};
+
+MulticastSource.prototype.error = function error (time, err) {
+ var s = this.sinks
+ for (var i = 0; i < s.length; ++i) {
+ s[i].error(time, err)
+ }
+};
+
+function multicast (stream) {
+ var source = stream.source
+ return source instanceof MulticastSource
+ ? stream
+ : new stream.constructor(new MulticastSource(source))
+}
+
+exports['default'] = multicast;
+exports.MulticastSource = MulticastSource;
+
+Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
+//# sourceMappingURL=multicast.js.map
diff --git a/pool/shard006/JavaScript/0042120_namespace.js b/pool/shard006/JavaScript/0042120_namespace.js
new file mode 100644
index 0000000000000000000000000000000000000000..38ed5995191977ac442b77be9bc4b30dc3e2f498
--- /dev/null
+++ b/pool/shard006/JavaScript/0042120_namespace.js
@@ -0,0 +1,37 @@
+
+function Namespace(prefix, href) {
+ if(prefix)
+ this.prefix = prefix;
+ this.href = href;
+}
+
+function Namespaces() {
+ this.nsList = [];
+ this.nsMap = {};
+ this.nsHrefMap = {};
+}
+
+Namespaces.prototype.addNS = function(prefix, href) {
+ if(href == null) {
+ href = prefix;
+ prefix = null;
+ }
+ var ns = new Namespace(prefix, href);
+ this.nsList.push(ns);
+ if(prefix) this.nsMap[prefix] = ns;
+ this.nsHrefMap[href] = ns;
+ return ns;
+};
+
+Namespaces.prototype.getNS = function(prefix) {
+ return this.nsMap[prefix];
+};
+
+Namespaces.prototype.getNSByHref = function(href) {
+ return this.nsHrefMap[href];
+};
+
+Namespaces.prototype.forEach = function(callback) {
+ this.nsList.forEach(callback);
+};
+module.exports = Namespaces;
diff --git a/pool/shard006/JavaScript/0042121_sharding_migrate_cursor1.js b/pool/shard006/JavaScript/0042121_sharding_migrate_cursor1.js
new file mode 100644
index 0000000000000000000000000000000000000000..71981027b0941dbf3cb74587f33ecc55212a7a41
--- /dev/null
+++ b/pool/shard006/JavaScript/0042121_sharding_migrate_cursor1.js
@@ -0,0 +1,65 @@
+
+chunksize = 25
+
+s = new ShardingTest( "migrate_cursor1" , 2 , 1 , 1 , { chunksize : chunksize } );
+
+s.config.settings.update( { _id: "balancer" }, { $set : { stopped: true } } , true );
+
+s.adminCommand( { enablesharding : "test" } );
+db = s.getDB( "test" )
+t = db.foo
+
+bigString = ""
+stringSize = 1024;
+
+while ( bigString.length < stringSize )
+ bigString += "asdasdas";
+
+stringSize = bigString.length
+docsPerChunk = Math.ceil( ( chunksize * 1024 * 1024 ) / ( stringSize - 12 ) )
+numChunks = 5
+numDocs = 20 * docsPerChunk
+
+print( "stringSize: " + stringSize + " docsPerChunk: " + docsPerChunk + " numDocs: " + numDocs )
+
+for ( i=0; i 0; } , "XXX" , 30000 , 1 )
+
+
+print( "itcount: " + x.itcount() )
+x = null;
+for ( i=0; i<5; i++ ) gc()
+
+print( "cursor should be gone" )
+
+join();
+
+//assert.soon( function(){ return numDocs == t.count(); } , "at end 1" )
+sleep( 5000 )
+assert.eq( numDocs , t.count() , "at end 2" )
+assert.eq( numDocs , primary.count() + secondary.count() , "at end 3" )
+
+s.stop()
diff --git a/pool/shard006/JavaScript/0042122_strategy.profile.test.js b/pool/shard006/JavaScript/0042122_strategy.profile.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..b7ea4e4c9d6238f1df9afb76c4059251213ec301
--- /dev/null
+++ b/pool/shard006/JavaScript/0042122_strategy.profile.test.js
@@ -0,0 +1,73 @@
+var fs = require('fs');
+var GitBookStrategy = require('../lib/strategy');
+
+describe('Strategy#userProfile', function() {
+ var strategy = new GitBookStrategy({
+ clientID: 'ABC123',
+ clientSecret: 'secret'
+ },
+ function() {});
+
+ // mock
+ strategy._oauth2.get = function(url, accessToken, callback) {
+ if (url != 'https://api.gitbook.com/account') { return callback(new Error('wrong url argument')); }
+ if (accessToken != 'token') { return callback(new Error('wrong token argument')); }
+
+ var body = fs.readFileSync('test/data/example.json', 'utf8');
+
+ callback(null, body, undefined);
+ };
+
+ describe('loading profile', function() {
+ var profile;
+
+ before(function(done) {
+ strategy.userProfile('token', function(err, p) {
+ if (err) { return done(err); }
+ profile = p;
+ done();
+ });
+ });
+
+ it('should parse profile', function() {
+ expect(profile.provider).to.equal('gitbook');
+
+ expect(profile.id).to.equal('55c7c38d86606665de70a555');
+ expect(profile.username).to.equal('samypesse');
+ expect(profile.displayName).to.equal('Samy Pessé');
+ expect(profile.profileUrl).to.equal('https://www.gitbook.com/@samypesse');
+ expect(profile.emails).to.have.length(1);
+ expect(profile.emails[0].value).to.equal('samypesse@gmail.com');
+ });
+
+ it('should set raw property', function() {
+ expect(profile._raw).to.be.a('string');
+ });
+
+ it('should set json property', function() {
+ expect(profile._json).to.be.an('object');
+ });
+ });
+
+ describe('encountering an error', function() {
+ var err, profile;
+
+ before(function(done) {
+ strategy.userProfile('wrong-token', function(e, p) {
+ err = e;
+ profile = p;
+ done();
+ });
+ });
+
+ it('should error', function() {
+ expect(err).to.be.an.instanceOf(Error);
+ expect(err.constructor.name).to.equal('InternalOAuthError');
+ expect(err.message).to.equal('Failed to fetch user profile');
+ });
+
+ it('should not load profile', function() {
+ expect(profile).to.be.undefined;
+ });
+ });
+});
diff --git a/pool/shard006/JavaScript/0042123_defaults.js b/pool/shard006/JavaScript/0042123_defaults.js
new file mode 100644
index 0000000000000000000000000000000000000000..332117da1c436bec166c45c7b1748be10e06924b
--- /dev/null
+++ b/pool/shard006/JavaScript/0042123_defaults.js
@@ -0,0 +1,60 @@
+/**
+* Copyright 2012-2017, Plotly, Inc.
+* 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.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var handleXYDefaults = require('./xy_defaults');
+var handleABDefaults = require('./ab_defaults');
+var setConvert = require('./set_convert');
+var attributes = require('./attributes');
+var colorAttrs = require('../../components/color/attributes');
+
+module.exports = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) {
+ function coerce(attr, dflt) {
+ return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+ }
+
+ var defaultColor = coerce('color', colorAttrs.defaultLine);
+ Lib.coerceFont(coerce, 'font');
+
+ coerce('carpet');
+
+ handleABDefaults(traceIn, traceOut, fullLayout, coerce, defaultColor);
+
+ if(!traceOut.a || !traceOut.b) {
+ traceOut.visible = false;
+ return;
+ }
+
+ if(traceOut.a.length < 3) {
+ traceOut.aaxis.smoothing = 0;
+ }
+
+ if(traceOut.b.length < 3) {
+ traceOut.baxis.smoothing = 0;
+ }
+
+ // NB: the input is x/y arrays. You should know that the *first* dimension of x and y
+ // corresponds to b and the second to a. This sounds backwards but ends up making sense
+ // the important part to know is that when you write y[j][i], j goes from 0 to b.length - 1
+ // and i goes from 0 to a.length - 1.
+ var len = handleXYDefaults(traceIn, traceOut, coerce);
+
+ setConvert(traceOut);
+
+ if(traceOut._cheater) {
+ coerce('cheaterslope');
+ }
+
+ if(!len) {
+ traceOut.visible = false;
+ return;
+ }
+};
diff --git a/pool/shard006/JavaScript/0042130_overlayscrollbars-react.js b/pool/shard006/JavaScript/0042130_overlayscrollbars-react.js
new file mode 100644
index 0000000000000000000000000000000000000000..6573f297fcefad316f90f553f5e840b9b3f6145c
--- /dev/null
+++ b/pool/shard006/JavaScript/0042130_overlayscrollbars-react.js
@@ -0,0 +1,127 @@
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('overlayscrollbars')) :
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'overlayscrollbars'], factory) :
+ (global = global || self, factory(global.OverlayScrollbarsReact = {}, global.React, global.OverlayScrollbars));
+}(this, (function (exports, React, OverlayScrollbars) { 'use strict';
+
+ var React__default = 'default' in React ? React['default'] : React;
+ OverlayScrollbars = OverlayScrollbars && Object.prototype.hasOwnProperty.call(OverlayScrollbars, 'default') ? OverlayScrollbars['default'] : OverlayScrollbars;
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation. 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
+
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+ MERCHANTABLITY OR NON-INFRINGEMENT.
+
+ See the Apache Version 2.0 License for specific language governing permissions
+ and limitations under the License.
+ ***************************************************************************** */
+ /* global Reflect, Promise */
+
+ var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+
+ function __extends(d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ }
+
+ var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+
+ function __rest(s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ }
+
+ var OverlayScrollbarsComponent = (function (_super) {
+ __extends(OverlayScrollbarsComponent, _super);
+ function OverlayScrollbarsComponent(props) {
+ var _this = _super.call(this, props) || this;
+ _this._osInstance = null;
+ _this._osTargetRef = React__default.createRef();
+ return _this;
+ }
+ OverlayScrollbarsComponent.prototype.osInstance = function () {
+ return this._osInstance;
+ };
+ OverlayScrollbarsComponent.prototype.osTarget = function () {
+ return this._osTargetRef.current || null;
+ };
+ OverlayScrollbarsComponent.prototype.componentDidMount = function () {
+ this._osInstance = OverlayScrollbars(this.osTarget(), this.props.options || {}, this.props.extensions);
+ mergeHostClassNames(this._osInstance, this.props.className);
+ };
+ OverlayScrollbarsComponent.prototype.componentWillUnmount = function () {
+ if (OverlayScrollbars.valid(this._osInstance)) {
+ this._osInstance.destroy();
+ this._osInstance = null;
+ }
+ };
+ OverlayScrollbarsComponent.prototype.componentDidUpdate = function (prevProps) {
+ if (OverlayScrollbars.valid(this._osInstance)) {
+ this._osInstance.options(this.props.options);
+ if (prevProps.className !== this.props.className) {
+ mergeHostClassNames(this._osInstance, this.props.className);
+ }
+ }
+ };
+ OverlayScrollbarsComponent.prototype.render = function () {
+ var _a = this.props, options = _a.options, extensions = _a.extensions, children = _a.children, className = _a.className, divProps = __rest(_a, ["options", "extensions", "children", "className"]);
+ return (React__default.createElement("div", __assign({ className: "os-host" }, divProps, { ref: this._osTargetRef }),
+ React__default.createElement("div", { className: "os-resize-observer-host" }),
+ React__default.createElement("div", { className: "os-padding" },
+ React__default.createElement("div", { className: "os-viewport" },
+ React__default.createElement("div", { className: "os-content" }, this.props.children))),
+ React__default.createElement("div", { className: "os-scrollbar os-scrollbar-horizontal " },
+ React__default.createElement("div", { className: "os-scrollbar-track" },
+ React__default.createElement("div", { className: "os-scrollbar-handle" }))),
+ React__default.createElement("div", { className: "os-scrollbar os-scrollbar-vertical" },
+ React__default.createElement("div", { className: "os-scrollbar-track" },
+ React__default.createElement("div", { className: "os-scrollbar-handle" }))),
+ React__default.createElement("div", { className: "os-scrollbar-corner" })));
+ };
+ return OverlayScrollbarsComponent;
+ }(React.Component));
+ function mergeHostClassNames(osInstance, className) {
+ if (OverlayScrollbars.valid(osInstance)) {
+ var host = osInstance.getElements().host;
+ var regex_1 = new RegExp("(^os-host([-_].+|)$)|" + osInstance.options().className.replace(/\s/g, "$|") + "$", 'g');
+ var osClassNames = host.className.split(' ')
+ .filter(function (name) { return name.match(regex_1); })
+ .join(' ');
+ host.className = osClassNames + " " + (className || '');
+ }
+ }
+
+ exports.OverlayScrollbarsComponent = OverlayScrollbarsComponent;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
+//# sourceMappingURL=overlayscrollbars-react.js.map
diff --git a/pool/shard006/JavaScript/0042131_application.js b/pool/shard006/JavaScript/0042131_application.js
new file mode 100644
index 0000000000000000000000000000000000000000..f956ddf4eeb502a0dc043c26bc0397e9dd9a08a3
--- /dev/null
+++ b/pool/shard006/JavaScript/0042131_application.js
@@ -0,0 +1,16 @@
+// Place your application-specific JavaScript functions and classes here
+// This file is automatically included by javascript_include_tag :defaults
+
+Element.observe(window, 'load', function(){
+ // This is for slow forms (like the signup one),
+ // so the user doesn't click 'Submit' twice.
+ $$('form.enhanced').each(function(frm){
+ $(frm).observe('submit', function(e){
+ var sub = frm.down("input[type='submit']");
+ if(sub){
+ sub.disabled = 'disabled';
+ sub.value = 'Working...';
+ }
+ });
+ });
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0042133_index.test.js b/pool/shard006/JavaScript/0042133_index.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..c65fe6ce2229a69f42779299a48ab849fc5520e9
--- /dev/null
+++ b/pool/shard006/JavaScript/0042133_index.test.js
@@ -0,0 +1,184 @@
+// eslint-disable no-process-env
+const assert = require('assert');
+const { expect } = require('chai');
+const sinon = require('sinon');
+const appPromise = require('../../../src/app');
+const { Configuration } = require('@hpi-schul-cloud/commons');
+
+describe('helpdesk service', function test() {
+ this.timeout(10000);
+ let app;
+ let helpdeskService;
+ let logger;
+ let originalMailService;;
+
+ const testProblem = {
+ type: 'contactAdmin',
+ _id: '5836bb5664582c35df3bc214',
+ subject: 'Dies ist ein Titel',
+ currentState: 'Dies ist der CurrentState',
+ targetState: 'Dies ist der TargetState',
+ schoolId: '5836bb5664582c35df3bc000',
+ };
+
+ function MockMailService() {
+ return {
+ create: sinon.fake.returns(Promise.resolve()),
+ };
+ }
+
+ before(async () => {
+ app = await appPromise;
+ originalMailService = app.service('mails');
+ helpdeskService = app.service('helpdesk');
+ ({ logger } = app);
+ await helpdeskService.create(testProblem);
+ });
+
+ after((done) => {
+ app.use('/mails', originalMailService);
+ helpdeskService
+ .remove(testProblem)
+ .then((result) => {
+ done();
+ })
+ .catch((error) => {
+ logger.info(`Could not remove: ${error}`);
+ done();
+ });
+ });
+
+ it('registered the helpdesk service', () => {
+ assert.ok(helpdeskService);
+ });
+
+ it('POST /helpdesk to admin with valid data', () => {
+ const postBody = {
+ type: 'contactAdmin',
+ subject: 'Dies ist ein Titel 2',
+ currentState: 'Dies ist der CurrentState',
+ targetState: 'Dies ist der TargetState',
+ schoolId: '5836bb5664582c35df3bc000',
+ };
+
+ return helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).then((result) => {
+ expect(result.subject).to.equal('Dies ist ein Titel 2');
+ expect(result.currentState).to.equal('Dies ist der CurrentState');
+ expect(result.targetState).to.equal('Dies ist der TargetState');
+ });
+ });
+
+ it('POST /helpdesk to admin without schoolId', () => {
+ const postBody = {
+ type: 'contactAdmin',
+ subject: 'Dies ist ein Titel 3',
+ currentState: 'Dies ist der CurrentState 2',
+ targetState: 'Dies ist der TargetState 2',
+ };
+
+ helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).catch((err) => {
+ expect(err).to.not.be.undefined;
+ expect(err.code).to.equal(400);
+ });
+ });
+
+ it('POST /helpdesk to admin without data', () => {
+ const postBody = {
+ type: 'contactAdmin',
+ subject: 'Dies ist ein Titel 3',
+ schoolId: '5836bb5664582c35df3bc000',
+ };
+ helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).catch((err) => {
+ expect(err).to.not.be.undefined;
+ expect(err.code).to.equal(400);
+ });
+ });
+
+ it('POST /helpdesk to schoolcloud with problem, valid data', () => {
+ const postBody = {
+ type: 'contactHPI',
+ subject: 'Dies ist ein Titel 4',
+ problemDescription: 'Dies ist die Problembeschreibung 1',
+ replyEmail: 'test@mail.de',
+ };
+ helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).then((result) => {
+ expect(result).to.equal({});
+ expect(result.replyTo).to.equal('test@mail.de');
+ });
+ });
+
+ it('POST /helpdesk to schoolcloud with problem and without theme should pass proper email in argument', async () => {
+ const postBody = {
+ type: 'contactHPI',
+ supportType: 'problem',
+ subject: 'Dies ist ein Titel 4',
+ problemDescription: 'Dies ist die Problembeschreibung 1',
+ replyEmail: 'test@mail.de',
+ };
+ const mailService = new MockMailService();
+ app.use('/mails', mailService);
+ await helpdeskService.create(postBody, { account: { userId: '0000d213816abba584714c0a' } });
+ expect(mailService.create.firstArg.email).to.equal('ticketsystem@schul-cloud.org');
+ });
+
+ it('POST /helpdesk to schoolcloud with problem should be send to specified in configuration email address if supportType is specified', async () => {
+ const postBody = {
+ type: 'contactHPI',
+ supportType: 'problem',
+ subject: 'Dies ist ein Titel 4',
+ problemDescription: 'Dies ist die Problembeschreibung 1',
+ replyEmail: 'test@mail.de',
+ };
+ const mailService = new MockMailService();
+ app.use('/mails', mailService);
+ const tempScTheme = Configuration.get('SUPPORT_PROBLEM_EMAIL_ADDRESS');
+ Configuration.set('SUPPORT_PROBLEM_EMAIL_ADDRESS', 'nbc-support@netz-21.de');
+ await helpdeskService.create(postBody, { account: { userId: '0000d213816abba584714c0a' } });
+ expect(mailService.create.firstArg.email).to.equal('nbc-support@netz-21.de');
+ Configuration.set('SUPPORT_PROBLEM_EMAIL_ADDRESS', tempScTheme);
+ });
+
+ it('POST /helpdesk to schoolcloud with wish should be send to specified in configuration email address if supportType is specified', async () => {
+ const postBody = {
+ type: 'contactHPI',
+ supportType: 'wish',
+ subject: 'Dies ist ein Titel 4',
+ problemDescription: 'Dies ist die Problembeschreibung 1',
+ replyEmail: 'test@mail.de',
+ };
+ const mailService = new MockMailService();
+ app.use('/mails', mailService);
+ const tempScTheme = Configuration.get('SUPPORT_WISH_EMAIL_ADDRESS');
+ Configuration.set('SUPPORT_WISH_EMAIL_ADDRESS', 'nbc-wunsch@netz-21.de');
+ await helpdeskService.create(postBody, { account: { userId: '0000d213816abba584714c0a' } });
+ expect(mailService.create.firstArg.email).to.equal('nbc-wunsch@netz-21.de');
+ Configuration.set('SUPPORT_WISH_EMAIL_ADDRESS', tempScTheme);
+ });
+
+ it('POST /helpdesk to schoolcloud with feedback, valid data', () => {
+ const postBody = {
+ type: 'contactHPI',
+ subject: 'Dies ist ein Titel 4',
+ role: 'Meine Rolle',
+ desire: 'Dies ist Desire 1',
+ benefit: 'Dies ist Benefit 1',
+ acceptanceCriteria: 'Dies sind acceptanceCriteria',
+ replyEmail: 'test@mail.de',
+ };
+ helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).then((result) => {
+ expect(result).to.equal({});
+ expect(result.replyTo).to.equal('test@mail.de');
+ });
+ });
+
+ it('POST /helpdesk to schoolcloud without data', () => {
+ const postBody = {
+ type: 'contactHPI',
+ subject: 'Dies ist ein Titel 4',
+ };
+ helpdeskService.create(postBody, { payload: { userId: '0000d213816abba584714c0a' } }).catch((err) => {
+ expect(err).to.not.be.undefined;
+ expect(err.code).to.equal(400);
+ });
+ });
+});
diff --git a/pool/shard006/JavaScript/0042134_fckconfig.js b/pool/shard006/JavaScript/0042134_fckconfig.js
new file mode 100644
index 0000000000000000000000000000000000000000..58fdff1f770dacce07d3d85af283c4896310d5d0
--- /dev/null
+++ b/pool/shard006/JavaScript/0042134_fckconfig.js
@@ -0,0 +1,238 @@
+/*
+ * FCKeditor - The text editor for Internet - http://www.fckeditor.net
+ * Copyright (C) 2003-2008 Frederico Caldeira Knabben
+ *
+ * == BEGIN LICENSE ==
+ *
+ * Licensed under the terms of any of the following licenses at your
+ * choice:
+ *
+ * - GNU General Public License Version 2 or later (the "GPL")
+ * http://www.gnu.org/licenses/gpl.html
+ *
+ * - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * - Mozilla Public License Version 1.1 or later (the "MPL")
+ * http://www.mozilla.org/MPL/MPL-1.1.html
+ *
+ * == END LICENSE ==
+ *
+ * Creates and initializes the FCKConfig object.
+ */
+
+var FCKConfig = FCK.Config = new Object() ;
+
+/*
+ For the next major version (probably 3.0) we should move all this stuff to
+ another dedicated object and leave FCKConfig as a holder object for settings only).
+*/
+
+// Editor Base Path
+if ( document.location.protocol == 'file:' )
+{
+ FCKConfig.BasePath = decodeURIComponent( document.location.pathname.substr(1) ) ;
+ FCKConfig.BasePath = FCKConfig.BasePath.replace( /\\/gi, '/' ) ;
+
+ // The way to address local files is different according to the OS.
+ // In Windows it is file:// but in MacOs it is file:/// so let's get it automatically
+ var sFullProtocol = document.location.href.match( /^(file\:\/{2,3})/ )[1] ;
+ // #945 Opera does strange things with files loaded from the disk, and it fails in Mac to load xml files
+ if ( FCKBrowserInfo.IsOpera )
+ sFullProtocol += 'localhost/' ;
+
+ FCKConfig.BasePath = sFullProtocol + FCKConfig.BasePath.substring( 0, FCKConfig.BasePath.lastIndexOf( '/' ) + 1) ;
+ FCKConfig.FullBasePath = FCKConfig.BasePath ;
+}
+else
+{
+ FCKConfig.BasePath = document.location.pathname.substring( 0, document.location.pathname.lastIndexOf( '/' ) + 1) ;
+ FCKConfig.FullBasePath = document.location.protocol + '//' + document.location.host + FCKConfig.BasePath ;
+}
+
+FCKConfig.EditorPath = FCKConfig.BasePath.replace( /editor\/$/, '' ) ;
+
+// There is a bug in Gecko. If the editor is hidden on startup, an error is
+// thrown when trying to get the screen dimensions.
+try
+{
+ FCKConfig.ScreenWidth = screen.width ;
+ FCKConfig.ScreenHeight = screen.height ;
+}
+catch (e)
+{
+ FCKConfig.ScreenWidth = 800 ;
+ FCKConfig.ScreenHeight = 600 ;
+}
+
+// Override the actual configuration values with the values passed throw the
+// hidden field "___Config".
+FCKConfig.ProcessHiddenField = function()
+{
+ this.PageConfig = new Object() ;
+
+ // Get the hidden field.
+ var oConfigField = window.parent.document.getElementById( FCK.Name + '___Config' ) ;
+
+ // Do nothing if the config field was not defined.
+ if ( ! oConfigField ) return ;
+
+ var aCouples = oConfigField.value.split('&') ;
+
+ for ( var i = 0 ; i < aCouples.length ; i++ )
+ {
+ if ( aCouples[i].length == 0 )
+ continue ;
+
+ var aConfig = aCouples[i].split( '=' ) ;
+ var sKey = decodeURIComponent( aConfig[0] ) ;
+ var sVal = decodeURIComponent( aConfig[1] ) ;
+
+ if ( sKey == 'CustomConfigurationsPath' ) // The Custom Config File path must be loaded immediately.
+ FCKConfig[ sKey ] = sVal ;
+
+ else if ( sVal.toLowerCase() == "true" ) // If it is a boolean TRUE.
+ this.PageConfig[ sKey ] = true ;
+
+ else if ( sVal.toLowerCase() == "false" ) // If it is a boolean FALSE.
+ this.PageConfig[ sKey ] = false ;
+
+ else if ( sVal.length > 0 && !isNaN( sVal ) ) // If it is a number.
+ this.PageConfig[ sKey ] = parseInt( sVal, 10 ) ;
+
+ else // In any other case it is a string.
+ this.PageConfig[ sKey ] = sVal ;
+ }
+}
+
+function FCKConfig_LoadPageConfig()
+{
+ var oPageConfig = FCKConfig.PageConfig ;
+ for ( var sKey in oPageConfig )
+ FCKConfig[ sKey ] = oPageConfig[ sKey ] ;
+}
+
+function FCKConfig_PreProcess()
+{
+ var oConfig = FCKConfig ;
+
+ // Force debug mode if fckdebug=true in the QueryString (main page).
+ if ( oConfig.AllowQueryStringDebug )
+ {
+ try
+ {
+ if ( (/fckdebug=true/i).test( window.top.location.search ) )
+ oConfig.Debug = true ;
+ }
+ catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ }
+ }
+
+ // Certifies that the "PluginsPath" configuration ends with a slash.
+ if ( !oConfig.PluginsPath.EndsWith('/') )
+ oConfig.PluginsPath += '/' ;
+
+ // If no ToolbarComboPreviewCSS, point it to EditorAreaCSS.
+ var sComboPreviewCSS = oConfig.ToolbarComboPreviewCSS ;
+ if ( !sComboPreviewCSS || sComboPreviewCSS.length == 0 )
+ oConfig.ToolbarComboPreviewCSS = oConfig.EditorAreaCSS ;
+
+ // Turn the attributes that will be removed in the RemoveFormat from a string to an array
+ oConfig.RemoveAttributesArray = (oConfig.RemoveAttributes || '').split( ',' );
+
+ if ( !FCKConfig.SkinEditorCSS || FCKConfig.SkinEditorCSS.length == 0 )
+ FCKConfig.SkinEditorCSS = FCKConfig.SkinPath + 'fck_editor.css' ;
+
+ if ( !FCKConfig.SkinDialogCSS || FCKConfig.SkinDialogCSS.length == 0 )
+ FCKConfig.SkinDialogCSS = FCKConfig.SkinPath + 'fck_dialog.css' ;
+}
+
+// Define toolbar sets collection.
+FCKConfig.ToolbarSets = new Object() ;
+
+// Defines the plugins collection.
+FCKConfig.Plugins = new Object() ;
+FCKConfig.Plugins.Items = new Array() ;
+
+FCKConfig.Plugins.Add = function( name, langs, path )
+{
+ FCKConfig.Plugins.Items.AddItem( [name, langs, path] ) ;
+}
+
+// FCKConfig.ProtectedSource: object that holds a collection of Regular
+// Expressions that defined parts of the raw HTML that must remain untouched
+// like custom tags, scripts, server side code, etc...
+FCKConfig.ProtectedSource = new Object() ;
+
+// Generates a string used to identify and locate the Protected Tags comments.
+FCKConfig.ProtectedSource._CodeTag = (new Date()).valueOf() ;
+
+// Initialize the regex array with the default ones.
+FCKConfig.ProtectedSource.RegexEntries = [
+ // First of any other protection, we must protect all comments to avoid
+ // loosing them (of course, IE related).
+ //g ,
+
+ // Script tags will also be forced to be protected, otherwise IE will execute them.
+ /
+ *
+ * var chart = bb.generate({
+ * data: {
+ * columns: [ ... ],
+ * type: "bubble"
+ * }
+ * ...
+ * plugins: [
+ * new bb.plugin.bubblecompare({
+ * minR: 11,
+ * maxR: 74,
+ * expandScale: 1.1
+ * }),
+ * ]
+ * });
+ * @example
+ * import {bb} from "billboard.js";
+ * import BubbleCompare from "billboard.js/dist/billboardjs-plugin-bubblecompare";
+ *
+ * bb.generate({
+ * plugins: [
+ * new BubbleCompare({ ... })
+ * ]
+ * })
+ */
+
+var BubbleCompare = /*#__PURE__*/function (_Plugin) {
+ _inheritsLoose(BubbleCompare, _Plugin);
+
+ function BubbleCompare(options) {
+ var _this = _Plugin.call(this, options) || this;
+
+ _this.$$ = void 0;
+ return _assertThisInitialized(_this) || _assertThisInitialized(_this);
+ }
+
+ var _proto = BubbleCompare.prototype;
+
+ _proto.$init = function $init() {
+ var $$ = this.$$;
+ $$.findClosest = this.findClosest.bind(this);
+ $$.getBubbleR = this.getBubbleR.bind(this);
+ $$.pointExpandedR = this.pointExpandedR.bind(this);
+ };
+
+ _proto.pointExpandedR = function pointExpandedR(d) {
+ var baseR = this.getBubbleR(d),
+ _this$options$expandS = this.options.expandScale,
+ expandScale = _this$options$expandS === void 0 ? 1 : _this$options$expandS;
+ BubbleCompare.raiseFocusedBubbleLayer(d);
+ this.changeCursorPoint();
+ return baseR * expandScale;
+ };
+
+ BubbleCompare.raiseFocusedBubbleLayer = function raiseFocusedBubbleLayer(d) {
+ d.raise && (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(d.node().parentNode.parentNode).raise();
+ };
+
+ _proto.changeCursorPoint = function changeCursorPoint() {
+ this.$$.$el.svg.select(".bb-event-rect").style("cursor", "pointer");
+ };
+
+ _proto.findClosest = function findClosest(values, pos) {
+ var _this2 = this,
+ $$ = this.$$;
+
+ return values.filter(function (v) {
+ return v && !$$.isBarType(v.id);
+ }).reduce(function (acc, cur) {
+ var d = $$.dist(cur, pos);
+ return d < _this2.getBubbleR(cur) ? cur : acc;
+ }, 0);
+ };
+
+ _proto.getBubbleR = function getBubbleR(d) {
+ var _this3 = this,
+ _this$options = this.options,
+ minR = _this$options.minR,
+ maxR = _this$options.maxR,
+ curVal = this.getZData(d);
+
+ if (!curVal) return minR;
+
+ var _this$$$$data$targets = this.$$.data.targets.reduce(function (_ref, cur) {
+ var accMin = _ref[0],
+ accMax = _ref[1],
+ val = _this3.getZData(cur.values[0]);
+
+ return [Math.min(accMin, val), Math.max(accMax, val)];
+ }, [1e4, 0]),
+ min = _this$$$$data$targets[0],
+ max = _this$$$$data$targets[1],
+ size = min > 0 && max === min ? 0 : curVal / max;
+
+ return Math.abs(size) * (maxR - minR) + minR;
+ };
+
+ _proto.getZData = function getZData(d) {
+ return this.$$.isBubbleZType(d) ? this.$$.getBubbleZData(d.value, "z") : d.value;
+ };
+
+ return BubbleCompare;
+}(Plugin);
+
+BubbleCompare.version = "0.0.1";
+
+}();
+__webpack_exports__ = __webpack_exports__["default"];
+/******/ return __webpack_exports__;
+/******/ })()
+;
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043048_SubmissionStatus.js b/pool/shard006/JavaScript/0043048_SubmissionStatus.js
new file mode 100644
index 0000000000000000000000000000000000000000..900439ff2c1dfaf7fe0273e18bd22e39ec455493
--- /dev/null
+++ b/pool/shard006/JavaScript/0043048_SubmissionStatus.js
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2017 - 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 .
+ */
+
+import React from 'react'
+import {bool, instanceOf, number, shape, string} from 'prop-types'
+import I18n from 'i18n!gradebook'
+import {View} from '@instructure/ui-layout'
+import {Pill} from '@instructure/ui-elements'
+import Message from './SubmissionStatus/Message'
+import {isPostable} from '../../../grading/helpers/SubmissionHelper'
+
+export default class SubmissionStatus extends React.Component {
+ static defaultProps = {
+ submission: {
+ drop: false
+ }
+ }
+
+ static propTypes = {
+ assignment: shape({
+ muted: bool.isRequired,
+ postManually: bool.isRequired,
+ published: bool.isRequired
+ }).isRequired,
+ isConcluded: bool.isRequired,
+ isInClosedGradingPeriod: bool.isRequired,
+ isInNoGradingPeriod: bool.isRequired,
+ isInOtherGradingPeriod: bool.isRequired,
+ isNotCountedForScore: bool.isRequired,
+ postPoliciesEnabled: bool.isRequired,
+ submission: shape({
+ drop: bool,
+ excused: bool,
+ hasPostableComments: bool,
+ postedAt: instanceOf(Date),
+ score: number,
+ workflowState: string.isRequired
+ }).isRequired
+ }
+
+ getStatusPills() {
+ const {assignment, postPoliciesEnabled, submission} = this.props
+ const statusPillComponents = []
+
+ if (postPoliciesEnabled) {
+ if (isPostable(submission)) {
+ statusPillComponents.push(
+
+ )
+ }
+ } else if (assignment.muted) {
+ statusPillComponents.push(
+
+ )
+ }
+
+ if (!assignment.published) {
+ statusPillComponents.push(
+
+ )
+ }
+
+ if (submission.drop) {
+ statusPillComponents.push(
+
+ )
+ }
+
+ if (submission.excused) {
+ statusPillComponents.push(
+
+ )
+ }
+
+ return statusPillComponents
+ }
+
+ getStatusNotifications() {
+ const statusNotificationComponents = []
+ const statusNotificationContainerStyle = {
+ display: 'flex'
+ }
+
+ if (this.props.isConcluded) {
+ const concludedEnrollmentStatusMessage = I18n.t(
+ "This student's enrollment has been concluded"
+ )
+
+ statusNotificationComponents.push(
+
+
+
+ )
+ }
+
+ const gradingPeriodStatusMessage = this.gradingPeriodStatusMessage()
+ if (gradingPeriodStatusMessage) {
+ statusNotificationComponents.push(
+
+
+
+ )
+ }
+
+ if (this.props.isNotCountedForScore) {
+ const isNotCountedForScoreMessage = I18n.t('Not calculated in final grade')
+
+ statusNotificationComponents.push(
+
+
+
+ )
+ }
+
+ return statusNotificationComponents
+ }
+
+ gradingPeriodStatusMessage() {
+ const {isInOtherGradingPeriod, isInClosedGradingPeriod, isInNoGradingPeriod} = this.props
+ let message
+
+ if (isInOtherGradingPeriod) {
+ message = I18n.t('This submission is in another grading period')
+ } else if (isInClosedGradingPeriod) {
+ message = I18n.t('This submission is in a closed grading period')
+ } else if (isInNoGradingPeriod) {
+ message = I18n.t('This submission is not in any grading period')
+ }
+
+ return message
+ }
+
+ render() {
+ const statusPillComponents = this.getStatusPills()
+ const statusNotificationComponents = this.getStatusNotifications()
+ const statusContainerStyle = {
+ display: 'flex',
+ justifyContent: 'left'
+ }
+
+ return (
+
+
+ {statusPillComponents}
+
+
+ {statusNotificationComponents}
+
+ )
+ }
+}
diff --git a/pool/shard006/JavaScript/0043049_game_manager.js b/pool/shard006/JavaScript/0043049_game_manager.js
new file mode 100644
index 0000000000000000000000000000000000000000..acdb58fd8bd005f59bf09edb05032770b6fdc204
--- /dev/null
+++ b/pool/shard006/JavaScript/0043049_game_manager.js
@@ -0,0 +1,23 @@
+pc.script.create('game_manager', function (context) {
+ // Creates a new Game_manager instance
+ var Game_manager = function (entity) {
+ this.entity = entity;
+ this.paused = false;
+ this.correctKeystrokes = 0;
+ this.wrongKeystrokes = 0;
+ this.damageTaken = 0;
+ this.enemySelected = null;
+ };
+
+ Game_manager.prototype = {
+ // Called once after all resources are loaded and before the first update
+ initialize: function () {
+ },
+
+ // Called every frame, dt is time in seconds since last update
+ update: function (dt) {
+ }
+ };
+
+ return Game_manager;
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043051_index.js b/pool/shard006/JavaScript/0043051_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..c8c14c9aa5440923be457b5b92a9886be9e6977e
--- /dev/null
+++ b/pool/shard006/JavaScript/0043051_index.js
@@ -0,0 +1,264 @@
+import { Socket } from 'net';
+import promisifyEvent from 'promisify-event';
+import EventEmitter from 'events';
+import delay from '../../../../../../utils/delay';
+import { GET_WINDOW_DIMENSIONS_INFO_SCRIPT } from '../../../../utils/client-functions';
+import COMMANDS from './commands';
+
+
+const CONNECTION_TIMEOUT = 30000;
+const CONNECTION_RETRY_DELAY = 300;
+const MAX_RESIZE_RETRY_COUNT = 2;
+const HEADER_SEPARATOR = ':';
+
+module.exports = class MarionetteClient {
+ constructor (port = 2828, runtimeInfo, host = '127.0.0.1') {
+ this.currentPacketNumber = 1;
+ this.events = new EventEmitter();
+ this.port = port;
+ this.host = host;
+ this.socket = new Socket();
+ this.buffer = Buffer.alloc(0);
+ this.getPacketPromise = Promise.resolve();
+ this.sendPacketPromise = Promise.resolve();
+
+ this._runtimeInfo = runtimeInfo;
+ this._windowHandles = {};
+
+ this.protocolInfo = {
+ applicationType: '',
+ marionetteProtocol: '',
+ };
+
+ this.sessionInfo = null;
+ }
+
+ get activeWindowId () {
+ return this._runtimeInfo.activeWindowId;
+ }
+
+ async _attemptToConnect (port, host) {
+ this.socket.connect(port, host);
+
+ const connectionPromise = Promise.race([
+ promisifyEvent(this.socket, 'connect'),
+ promisifyEvent(this.socket, 'error'),
+ ]);
+
+ return await connectionPromise
+ .then(() => true)
+ .catch(() => {
+ this.socket.removeAllListeners('connect');
+ return delay(CONNECTION_RETRY_DELAY);
+ });
+ }
+
+ async _connectSocket (port, host) {
+ const connectionStartTime = Date.now();
+
+ let connected = await this._attemptToConnect(port, host);
+
+ while (!connected && Date.now() - connectionStartTime < CONNECTION_TIMEOUT)
+ connected = await this._attemptToConnect(port, host);
+
+ if (!connected)
+ throw new Error('Unable to connect');
+
+ this.socket.on('data', data => this._handleNewData(data));
+ }
+
+ async _writeSocket (message) {
+ if (!this.socket.write(message))
+ await promisifyEvent(this.socket, 'drain');
+ }
+
+ _handleNewData (data) {
+ if (!data)
+ return;
+
+ this.buffer = Buffer.concat([this.buffer, data]);
+
+ this.events.emit('new-data');
+ }
+
+ _getPacket () {
+ this.getPacketPromise = this.getPacketPromise.then(async () => {
+ let headerEndIndex = this.buffer.indexOf(HEADER_SEPARATOR);
+
+ while (headerEndIndex < 0) {
+ await promisifyEvent(this.events, 'new-data');
+
+ headerEndIndex = this.buffer.indexOf(HEADER_SEPARATOR);
+ }
+
+ const packet = {
+ length: NaN,
+ body: null,
+ };
+
+ packet.length = parseInt(this.buffer.toString('utf8', 0, headerEndIndex), 10) || 0;
+
+ const bodyStartIndex = headerEndIndex + HEADER_SEPARATOR.length;
+ const bodyEndIndex = bodyStartIndex + packet.length;
+
+ if (packet.length) {
+ while (this.buffer.length < bodyEndIndex)
+ await promisifyEvent(this.events, 'new-data');
+
+ packet.body = JSON.parse(this.buffer.toString('utf8', bodyStartIndex, bodyEndIndex));
+ }
+
+ this.buffer = this.buffer.slice(bodyEndIndex);
+
+ return packet;
+ });
+
+ return this.getPacketPromise;
+ }
+
+ _sendPacket (payload) {
+ this.sendPacketPromise = this.sendPacketPromise.then(async () => {
+ const body = [0, this.currentPacketNumber++, payload.command, payload.parameters];
+ const serialized = JSON.stringify(body);
+ const message = Buffer.byteLength(serialized, 'utf8') + HEADER_SEPARATOR + serialized;
+
+ this._writeSocket(message);
+ });
+
+ return this.sendPacketPromise;
+ }
+
+ _throwMarionetteError (error) {
+ throw new Error(`${error.error}${error.message ? ': ' + error.message : ''}`);
+ }
+
+ async _switchToWindow (windowHandle) {
+ await this._getResponse({
+ command: COMMANDS.switchToWindow,
+ parameters: { handle: windowHandle },
+ });
+ }
+
+ async _getActiveWindowHandle () {
+ const windowHandles = await this._getResponse({
+ command: COMMANDS.getWindowHandles,
+ });
+
+ for (const handle of windowHandles) {
+ await this._switchToWindow(handle);
+
+ const title = await this._getResponse({ command: COMMANDS.getTitle });
+
+ if (title.value.includes(this.activeWindowId))
+ return handle;
+ }
+
+ return null;
+ }
+
+ async _ensureActiveWindow () {
+ let handle = this._windowHandles[this.activeWindowId];
+
+ if (handle) {
+ await this._switchToWindow(handle);
+
+ return;
+ }
+
+ handle = await this._getActiveWindowHandle();
+
+ if (handle)
+ this._windowHandles[this.activeWindowId] = handle;
+ }
+
+ async _request (packet) {
+ await this._ensureActiveWindow();
+
+ return this._getResponse(packet);
+ }
+
+ async _getResponse (packet) {
+ const packetNumber = this.currentPacketNumber;
+
+ await this._sendPacket(packet);
+
+ let responsePacket = await this._getPacket();
+
+ while (!responsePacket.body || responsePacket.body[1] !== packetNumber)
+ responsePacket = await this._getPacket();
+
+ if (responsePacket.body[2])
+ this._throwMarionetteError(responsePacket.body[2]);
+
+ return responsePacket.body[3];
+ }
+
+ async _getScreenshotRawData (fullPage = false) {
+ return await this._request({
+ command: COMMANDS.takeScreenshot,
+ parameters: {
+ full: fullPage,
+ hash: false,
+ scroll: false,
+ },
+ });
+ }
+
+ async connect () {
+ await this._connectSocket(this.port, this.host);
+
+ const infoPacket = await this._getPacket();
+
+ this.protocolInfo = {
+ applicationType: infoPacket.body.applicationType,
+ marionetteProtocol: infoPacket.body.marionetteProtocol,
+ };
+
+ this.sessionInfo = await this._getResponse({ command: COMMANDS.newSession });
+ }
+
+ dispose () {
+ this.socket.end();
+ this.buffer = null;
+ }
+
+ async executeScript (code) {
+ return await this._request({
+ command: COMMANDS.executeScript,
+ parameters: { script: `return (${code})()` },
+ });
+ }
+
+ async getScreenshotData (fullPage) {
+ const frameData = await this._getScreenshotRawData(fullPage);
+
+ return Buffer.from(frameData.value, 'base64');
+ }
+
+ async setWindowSize (width, height) {
+ let { value: pageRect } = await this.executeScript(GET_WINDOW_DIMENSIONS_INFO_SCRIPT);
+ let attemptCounter = 0;
+
+ while (attemptCounter++ < MAX_RESIZE_RETRY_COUNT && (pageRect.width !== width || pageRect.height !== height)) {
+ const currentRect = await this._request({ command: COMMANDS.getWindowRect });
+
+ await this._request({
+ command: COMMANDS.setWindowRect,
+
+ parameters: {
+ x: currentRect.x,
+ y: currentRect.y,
+ width: width + (currentRect.width - pageRect.width),
+ height: height + (currentRect.height - pageRect.height),
+ },
+ });
+
+ ({ value: pageRect } = await this.executeScript(GET_WINDOW_DIMENSIONS_INFO_SCRIPT));
+ }
+ }
+
+ async quit () {
+ await this._request({ command: COMMANDS.quit });
+ }
+};
+
diff --git a/pool/shard006/JavaScript/0043053_fcktoolbar.js b/pool/shard006/JavaScript/0043053_fcktoolbar.js
new file mode 100644
index 0000000000000000000000000000000000000000..d80551ad9c65086bd58edb4dcc549ad2df5c4cd2
--- /dev/null
+++ b/pool/shard006/JavaScript/0043053_fcktoolbar.js
@@ -0,0 +1,116 @@
+/*
+ * FCKeditor - The text editor for internet
+ * Copyright (C) 2003-2006 Frederico Caldeira Knabben
+ *
+ * Licensed under the terms of the GNU Lesser General Public License:
+ * http://www.opensource.org/licenses/lgpl-license.php
+ *
+ * For further information visit:
+ * http://www.fckeditor.net/
+ *
+ * "Support Open Source software. What about a donation today?"
+ *
+ * File Name: fcktoolbar.js
+ * FCKToolbar Class: represents a toolbar in the toolbarset. It is a group of
+ * toolbar items.
+ *
+ * File Authors:
+ * Frederico Caldeira Knabben (fredck@fckeditor.net)
+ */
+
+var FCKToolbar = function()
+{
+ this.Items = new Array() ;
+
+ if ( FCK.IECleanup )
+ FCK.IECleanup.AddItem( this, FCKToolbar_Cleanup ) ;
+}
+
+FCKToolbar.prototype.AddItem = function( item )
+{
+ return this.Items[ this.Items.length ] = item ;
+}
+
+FCKToolbar.prototype.AddButton = function( name, label, tooltip, iconPathOrStripInfoArrayOrIndex, style, state )
+{
+ if ( typeof( iconPathOrStripInfoArrayOrIndex ) == 'number' )
+ iconPathOrStripInfoArrayOrIndex = [ this.DefaultIconsStrip, this.DefaultIconSize, iconPathOrStripInfoArrayOrIndex ] ;
+
+ var oButton = new FCKToolbarButtonUI( name, label, tooltip, iconPathOrStripInfoArrayOrIndex, style, state ) ;
+ oButton._FCKToolbar = this ;
+ oButton.OnClick = FCKToolbar_OnItemClick ;
+
+ return this.AddItem( oButton ) ;
+}
+
+function FCKToolbar_OnItemClick( item )
+{
+ var oToolbar = item._FCKToolbar ;
+
+ if ( oToolbar.OnItemClick )
+ oToolbar.OnItemClick( oToolbar, item ) ;
+}
+
+FCKToolbar.prototype.AddSeparator = function()
+{
+ this.AddItem( new FCKToolbarSeparator() ) ;
+}
+
+FCKToolbar.prototype.Create = function( parentElement )
+{
+ if ( this.MainElement )
+ {
+// this._Cleanup() ;
+ if ( this.MainElement.parentNode )
+ this.MainElement.parentNode.removeChild( this.MainElement ) ;
+ this.MainElement = null ;
+ }
+
+ var oDoc = FCKTools.GetElementDocument( parentElement ) ;
+
+ var e = this.MainElement = oDoc.createElement( 'table' ) ;
+ e.className = 'TB_Toolbar' ;
+ e.style.styleFloat = e.style.cssFloat = ( FCKLang.Dir == 'ltr' ? 'left' : 'right' ) ;
+ e.dir = FCKLang.Dir ;
+ e.cellPadding = 0 ;
+ e.cellSpacing = 0 ;
+
+ this.RowElement = e.insertRow(-1) ;
+
+ // Insert the start cell.
+ var eCell ;
+
+ if ( !this.HideStart )
+ {
+ eCell = this.RowElement.insertCell(-1) ;
+ eCell.appendChild( oDoc.createElement( 'div' ) ).className = 'TB_Start' ;
+ }
+
+ for ( var i = 0 ; i < this.Items.length ; i++ )
+ {
+ this.Items[i].Create( this.RowElement.insertCell(-1) ) ;
+ }
+
+ // Insert the ending cell.
+ if ( !this.HideEnd )
+ {
+ eCell = this.RowElement.insertCell(-1) ;
+ eCell.appendChild( oDoc.createElement( 'div' ) ).className = 'TB_End' ;
+ }
+
+ parentElement.appendChild( e ) ;
+}
+
+function FCKToolbar_Cleanup()
+{
+ this.MainElement = null ;
+ this.RowElement = null ;
+}
+
+var FCKToolbarSeparator = function()
+{}
+
+FCKToolbarSeparator.prototype.Create = function( parentElement )
+{
+ FCKTools.AppendElement( parentElement, 'div' ).className = 'TB_Separator' ;
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043054_Layout.js b/pool/shard006/JavaScript/0043054_Layout.js
new file mode 100644
index 0000000000000000000000000000000000000000..e0545aad1f1c9682a09914e0d643374938070195
--- /dev/null
+++ b/pool/shard006/JavaScript/0043054_Layout.js
@@ -0,0 +1,48 @@
+import React from "react"
+import { connect } from "react-redux"
+
+import { fetchWelcomeText } from "../actions/welcomeTextActions"
+import NavigationBar from "../components/NavigationBar"
+
+
+@connect((store) => {
+ return {
+ welcomeText: store.welcomeText.welcomeText
+ };
+})
+
+export default class Layout extends React.Component {
+ componentWillMount() {
+ this.props.dispatch(fetchWelcomeText());
+ }
+
+ render() {
+ const { welcomeText } = this.props;
+ const { location } = this.props;
+
+ const containerStyle = {
+ marginTop: "60px"
+ };
+
+ return (
+
+
+
+
+
+
+
+
{welcomeText.welcomeText}
+
+ {this.props.children}
+
+
+
+
+
+
+
+
+ );
+ }
+}
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043061_W.Router.js b/pool/shard006/JavaScript/0043061_W.Router.js
new file mode 100644
index 0000000000000000000000000000000000000000..4dfcecbbd1d5c46dd0af8348993987f280e56226
--- /dev/null
+++ b/pool/shard006/JavaScript/0043061_W.Router.js
@@ -0,0 +1,94 @@
+/*
+The following router is designed to show how the component hierarchy can be made to match
+1:1 with the hash path that controls it. That is, instead of mapping routes to functions
+in various object, we design our object hierarchy to match our routes.
+
+NOTE: Please note that the routes defined below are not best-practice and are meant to serve
+as an illustration of nested components.
+*/
+W.Router = Backbone.Router.extend({
+ // Define the valid routes that our application will respond to
+ routes: {
+ "*path": "showComponent"
+ },
+
+ /*
+ Given the assumption that we've designed our component hierarchy to match our
+ hash path, find the component that should be shown according to the hash path
+ */
+ showComponent: function(path) {
+ // For the home page, do nothing. Components are already shown
+ if (!path) {
+ return;
+ }
+
+ // Get each folder in the hash path
+ var hashParts = path.split('/');
+
+ // Starting with our app, drill into the hierarchy to find the component
+ // that matches the hash path
+ var component = W;
+ _.some(hashParts, function(part) {
+ if (component[part]) {
+ component = component[part];
+
+ // Show each component along the way
+ component.show();
+ }
+ else {
+ console.warn('W.Router: route specifies an invalid part: %s', path);
+ return true;
+ }
+ });
+
+ // Show the component if it has a show() method
+ if (component && component.show) {
+ component.show();
+ }
+ else {
+ console.warn('W.Router: ended up at a component with no show method: %s', path);
+ }
+ },
+
+ /*
+ The above is an example meant to illustrate the power of nested components, and
+ is not what you would do in practice.
+
+ In practice, you would do something like what is below for every step and part.
+ It may take more code, but it is more direct and allows you to pass named parameters.
+ */
+ /*
+ routes: {
+ "wizard": "showWizard",
+
+ "wizard/step1": "showStep1",
+
+ "wizard/step2": "showStep2",
+
+ "wizard/step2/part1": "showStep2Part1",
+
+ "wizard/step2/part2": "showStep2Part2",
+
+ "wizard/step3": "showStep3"
+ },
+
+ showWizard: function() {
+ W.wizard.show();
+ },
+ showStep1: function() {
+ W.wizard.step1.show();
+ },
+ showStep2: function() {
+ W.wizard.step2.show();
+ },
+ showStep2Part1: function() {
+ W.wizard.step2.part1.show();
+ },
+ showStep2Part2: function() {
+ W.wizard.step2.part2.show();
+ },
+ showStep3: function() {
+ W.wizard.step3.show();
+ }
+ */
+});
diff --git a/pool/shard006/JavaScript/0043064_togglemode.js b/pool/shard006/JavaScript/0043064_togglemode.js
new file mode 100644
index 0000000000000000000000000000000000000000..9b59c92e77e22e18a62019f16fc62c379e6792e3
--- /dev/null
+++ b/pool/shard006/JavaScript/0043064_togglemode.js
@@ -0,0 +1,26 @@
+var togglemode = function (argument) {
+ var doc = document;
+ var togglemodeItems = doc.querySelectorAll(".js-togglemode");
+
+ var toggleButton = doc.createElement("button");
+ toggleButton.innerHTML = "ON OFF ";
+ toggleButton.classList.add("js-blendmode-control");
+
+
+ for (var i = 0; i < togglemodeItems.length; i++) {
+ var item = togglemodeItems[i];
+ var itemStyle = getComputedStyle(item, '');
+
+ var clonedButton = toggleButton.cloneNode(true);
+
+ var switchButton = item.appendChild(clonedButton);
+
+ switchButton.onclick = function(){
+ this.parentNode.classList.toggle("js-blendmode--off");
+ };
+
+ };
+};
+
+togglemode();
+
diff --git a/pool/shard006/JavaScript/0043067_academic-plan-viewer-widget.js b/pool/shard006/JavaScript/0043067_academic-plan-viewer-widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..ca6702bcbf4d90876d557b79eef82133cfa4329a
--- /dev/null
+++ b/pool/shard006/JavaScript/0043067_academic-plan-viewer-widget.js
@@ -0,0 +1,29 @@
+import { Template } from 'meteor/templating';
+import { ReactiveVar } from 'meteor/reactive-var';
+import { AcademicPlans } from '../../../api/degree-plan/AcademicPlanCollection';
+import { Users } from '../../../api/user/UserCollection';
+import { getUserIdFromRoute } from '../shared/get-user-id-from-route';
+
+Template.Academic_Plan_Viewer_Widget.onCreated(function academicPlanWidgetOnCreated() {
+ this.plan = new ReactiveVar('');
+});
+
+Template.Academic_Plan_Viewer_Widget.helpers({
+ getPlan() {
+ if (getUserIdFromRoute()) {
+ const studentID = getUserIdFromRoute();
+ const profile = Users.getProfile(studentID);
+ if (profile.academicPlanID) {
+ Template.instance()
+ .plan
+ .set(AcademicPlans.findDoc(profile.academicPlanID));
+ }
+ }
+ return Template.instance().plan;
+ },
+});
+
+Template.Academic_Plan_Viewer_Widget.onRendered(function academicPlanWidgetOnRendered() {
+ this.$('.dropdown').dropdown({
+ });
+});
diff --git a/pool/shard006/JavaScript/0043072_utils.js b/pool/shard006/JavaScript/0043072_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..a5f69983339a5791ece3c9bf7df277456c8ab8fc
--- /dev/null
+++ b/pool/shard006/JavaScript/0043072_utils.js
@@ -0,0 +1,234 @@
+var Route = require('./route');
+var parseURL = require('./url').parse;
+
+/**
+ * Prints out debugging to console if `ghosttrain.get('debug')` is true
+ *
+ * @param {GhostTrain} gt
+ * @param {String} out
+ */
+
+function debug (gt) {
+ var args = arrayify(arguments);
+ args.splice(0, 1); // Pop first `gt` argument
+ if (gt.get('debug'))
+ console.log.apply(console, ['GhostTrain debug: '].concat(args));
+}
+exports.debug = debug;
+
+/**
+ * `findRoute` takes a verb and a `url` and returns a matching
+ * GhostTrain.Route, or `null` if no matches. `url` can be a string
+ * that gets parsed, or an already parsed (./lib/url#parse) URL object.
+ *
+ * @param {GhostTrain} ghosttrain
+ * @param {String} verb
+ * @param {String|Object} url
+ * @return {Route|null}
+ */
+
+function findRoute (ghosttrain, verb, url) {
+ // Extract path from the object or string
+ var path = url.pathname ? url.pathname : parseURL(url);
+
+ var routes = ghosttrain.routes[verb.toLowerCase()];
+ if (!routes) return null;
+ for (var i = 0; i < routes.length; i++)
+ if (routes[i].match(path))
+ return routes[i];
+ return null;
+};
+exports.findRoute = findRoute;
+
+/**
+ * Clones an object properties onto a new object
+ *
+ * @param {Object} obj
+ * @return {Object}
+ */
+
+function clone (obj) {
+ var newObj = {};
+
+ // Return a new obj if no `obj` passed in
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj))
+ return newObj;
+
+ for (var prop in obj)
+ newObj[prop] = obj[prop];
+ return newObj;
+}
+exports.clone = clone;
+
+/**
+ * Turns a url string or a parsed url object (./lib/url#parse)
+ * into a string of the URL with host/port/protocol info stripped
+ *
+ * requestURL('http://localhost:9999/search?q=myquery'); // '/search?q=myquery'
+ *
+ * @param {String|Object} url
+ * @return {String}
+ */
+
+function requestURL (url) {
+ var parsedURL = url.pathname ? url : parseURL(url, true);
+
+ return parsedURL.pathname + (parsedURL.search || '');
+}
+exports.requestURL = requestURL;
+
+/**
+ * Returns a function that acts as `app.VERB(path, route)`; helper function
+ * used in `./lib/ghosttrain.js`.
+ *
+ * @param {String} verb
+ * @return {Function{
+ */
+
+function addRoute (verb) {
+ return function (path, fn) {
+ // Support all HTTP verbs
+ if (!this.routes[verb])
+ this.routes[verb] = [];
+
+ this.routes[verb].push(new Route(verb, path, fn, {
+ sensitive: this.settings['case sensitive routing'],
+ strict: this.settings['strict routing']
+ }));
+ };
+}
+exports.addRoute = addRoute;
+
+/**
+ * A function that takes a `name` that returns a function
+ * that throws an error regarding an unsupported function of `name`,
+ * to be called when invoking an unsupported function.
+ *
+ * @param {String} name
+ * @return {Function}
+ */
+
+function unsupported (name) {
+ return function () {
+ throw new Error('`' + name + '` is currently unsupported');
+ };
+}
+exports.unsupported = unsupported;
+
+/**
+ * Arrayify `arguments`
+ *
+ * @param {Argument} args
+ * @return {Array}
+ */
+
+function arrayify (args) {
+ return Array.prototype.slice.call(args, 0);
+}
+exports.arrayify = arrayify;
+
+/**
+ * From Express:
+ * Normalize the given path string,
+ * returning a regular expression.
+ *
+ * An empty array should be passed,
+ * which will contain the placeholder
+ * key names. For example "/user/:id" will
+ * then contain ["id"].
+ *
+ * @param {String|RegExp|Array} path
+ * @param {Array} keys
+ * @param {Boolean} sensitive
+ * @param {Boolean} strict
+ * @return {RegExp}
+ */
+
+function pathRegexp (path, keys, sensitive, strict) {
+ if (Object.prototype.toString.call(path) == '[object RegExp]') return path;
+ if (Array.isArray(path)) path = '(' + path.join('|') + ')';
+
+ path = path
+ .concat(strict ? '' : '/?')
+ .replace(/\/\(/g, '(?:/')
+ .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
+ keys.push({ name: key, optional: !! optional });
+ slash = slash || '';
+ return ''
+ + (optional ? '' : slash)
+ + '(?:'
+ + (optional ? slash : '')
+ + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ + (optional || '')
+ + (star ? '(/*)?' : '');
+ })
+ .replace(/([\/.])/g, '\\$1')
+ .replace(/\*/g, '(.*)');
+
+ return new RegExp('^' + path + '$', sensitive ? '' : 'i');
+}
+exports.pathRegexp = pathRegexp;
+
+/**
+ * Status codes from Node core
+ * https://github.com/joyent/node/blob/master/lib/_http_server.js
+ */
+
+var STATUS_CODES = exports.STATUS_CODES = {
+ 100 : 'Continue',
+ 101 : 'Switching Protocols',
+ 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
+ 200 : 'OK',
+ 201 : 'Created',
+ 202 : 'Accepted',
+ 203 : 'Non-Authoritative Information',
+ 204 : 'No Content',
+ 205 : 'Reset Content',
+ 206 : 'Partial Content',
+ 207 : 'Multi-Status', // RFC 4918
+ 300 : 'Multiple Choices',
+ 301 : 'Moved Permanently',
+ 302 : 'Moved Temporarily',
+ 303 : 'See Other',
+ 304 : 'Not Modified',
+ 305 : 'Use Proxy',
+ 307 : 'Temporary Redirect',
+ 400 : 'Bad Request',
+ 401 : 'Unauthorized',
+ 402 : 'Payment Required',
+ 403 : 'Forbidden',
+ 404 : 'Not Found',
+ 405 : 'Method Not Allowed',
+ 406 : 'Not Acceptable',
+ 407 : 'Proxy Authentication Required',
+ 408 : 'Request Time-out',
+ 409 : 'Conflict',
+ 410 : 'Gone',
+ 411 : 'Length Required',
+ 412 : 'Precondition Failed',
+ 413 : 'Request Entity Too Large',
+ 414 : 'Request-URI Too Large',
+ 415 : 'Unsupported Media Type',
+ 416 : 'Requested Range Not Satisfiable',
+ 417 : 'Expectation Failed',
+ 418 : 'I\'m a teapot', // RFC 2324
+ 422 : 'Unprocessable Entity', // RFC 4918
+ 423 : 'Locked', // RFC 4918
+ 424 : 'Failed Dependency', // RFC 4918
+ 425 : 'Unordered Collection', // RFC 4918
+ 426 : 'Upgrade Required', // RFC 2817
+ 428 : 'Precondition Required', // RFC 6585
+ 429 : 'Too Many Requests', // RFC 6585
+ 431 : 'Request Header Fields Too Large',// RFC 6585
+ 500 : 'Internal Server Error',
+ 501 : 'Not Implemented',
+ 502 : 'Bad Gateway',
+ 503 : 'Service Unavailable',
+ 504 : 'Gateway Time-out',
+ 505 : 'HTTP Version Not Supported',
+ 506 : 'Variant Also Negotiates', // RFC 2295
+ 507 : 'Insufficient Storage', // RFC 4918
+ 509 : 'Bandwidth Limit Exceeded',
+ 510 : 'Not Extended', // RFC 2774
+ 511 : 'Network Authentication Required' // RFC 6585
+};
diff --git a/pool/shard006/JavaScript/0043074_settings.js b/pool/shard006/JavaScript/0043074_settings.js
new file mode 100644
index 0000000000000000000000000000000000000000..993b3b9e2e0d58cf8a5a66c09126d0f346b774cd
--- /dev/null
+++ b/pool/shard006/JavaScript/0043074_settings.js
@@ -0,0 +1,41 @@
+import { EDIT_SETTINGS, RELOAD_STORE } from '../actionTypes'
+import { saveFile } from 'utils/file'
+
+const editSettings = (key, value) => ({
+ type: EDIT_SETTINGS,
+ payload: { key, value }
+})
+
+const reloadStore = (store) => ({
+ type: RELOAD_STORE,
+ payload: store
+})
+
+const uploadBackground = (files) =>
+ (dispatch, getState) => {
+ if (!files || !files[0]) return
+ var reader = new FileReader()
+ reader.onload = (e) =>
+ dispatch(editSettings('background', reader.result))
+ reader.readAsDataURL(files[0])
+ }
+
+const exportStore = () =>
+ (dispatch, getState) =>
+ saveFile(`todo_backup_${+new Date()}`, JSON.stringify(getState()))
+
+const importStore = (files) =>
+ (dispatch, getState) => {
+ if (!files || !files[0]) return
+ var reader = new FileReader()
+ reader.onload = (e) =>
+ dispatch(reloadStore(JSON.parse(reader.result)))
+ reader.readAsText(files[0])
+ }
+
+export default {
+ editSettings,
+ uploadBackground,
+ exportStore,
+ importStore
+}
diff --git a/pool/shard006/JavaScript/0043077_script.js b/pool/shard006/JavaScript/0043077_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..cf2141f34ec377f9b8d8f6c29ff8c9a93e2026cd
--- /dev/null
+++ b/pool/shard006/JavaScript/0043077_script.js
@@ -0,0 +1,71 @@
+// Variables
+var expand_documentation = false;
+
+// Function: Anchor links creations
+function anchorizejekyll()
+{
+ 'use strict';
+
+ var headingNodes = [];
+ var results;
+ var link;
+ var tags = ['h2', 'h3', 'h4', 'h5', 'h6'];
+
+ tags.forEach(function(tag){
+ results = document.getElementsByTagName(tag);
+ Array.prototype.push.apply(headingNodes, results);
+ });
+
+ headingNodes.forEach(function(node){
+ link = document.createElement('a');
+ link.innerHTML = ' ∞';
+ link.href = '#' + node.getAttribute('id');
+ link.style.position = "absolute";
+ link.style.visibility = "hidden";
+ node.className = 'anchor-item';
+ node.appendChild(link);
+ });
+}
+
+// Function: Toggle all documentation details
+function toggle_documentation(button)
+{
+ var details = document.querySelectorAll('details.group_details');
+ expand_documentation = !expand_documentation;
+
+ Array.from(details).forEach(function(obj, idx) {
+ obj.open = expand_documentation;
+ });
+}
+
+// Function: Expands details wrapping an anchor
+function anchor_expands(id)
+{
+ // Find element by tag
+ var title = document.getElementById(id);
+ if (title) {
+
+ // Find related details
+ var details = title.closest("details");
+ if (details) {
+
+ // Expand related details
+ details.open = true;
+ }
+ }
+}
+
+// Page loaded event
+window.onload = function()
+{
+ // Start anchor links creations
+ anchorizejekyll();
+
+ // Acquire anchor tag
+ var anchor_tag = window.location.hash.substr(1);
+
+ // Apply anchor expands
+ if (anchor_tag && anchor_tag.length !== 0) {
+ anchor_expands(anchor_tag);
+ }
+}
diff --git a/pool/shard006/JavaScript/0043079_entry-detail.controller.spec.js b/pool/shard006/JavaScript/0043079_entry-detail.controller.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..348526f899ca390cdba175b9fec28b509d1cf8fd
--- /dev/null
+++ b/pool/shard006/JavaScript/0043079_entry-detail.controller.spec.js
@@ -0,0 +1,46 @@
+'use strict';
+
+describe('Controller Tests', function() {
+
+ describe('Entry Detail Controller', function() {
+ var $scope, $rootScope;
+ var MockEntity, MockEntry, MockType, MockUser;
+ var createController;
+
+ beforeEach(inject(function($injector) {
+ $rootScope = $injector.get('$rootScope');
+ $scope = $rootScope.$new();
+ MockEntity = jasmine.createSpy('MockEntity');
+ MockEntry = jasmine.createSpy('MockEntry');
+ MockType = jasmine.createSpy('MockType');
+ MockUser = jasmine.createSpy('MockUser');
+
+
+ var locals = {
+ '$scope': $scope,
+ '$rootScope': $rootScope,
+ 'entity': MockEntity ,
+ 'Entry': MockEntry,
+ 'Type': MockType,
+ 'User': MockUser
+ };
+ createController = function() {
+ $injector.get('$controller')("EntryDetailController", locals);
+ };
+ }));
+
+
+ describe('Root Scope Listening', function() {
+ it('Unregisters root scope listener upon scope destruction', function() {
+ var eventType = 'jexpensesApp:entryUpdate';
+
+ createController();
+ expect($rootScope.$$listenerCount[eventType]).toEqual(1);
+
+ $scope.$destroy();
+ expect($rootScope.$$listenerCount[eventType]).toBeUndefined();
+ });
+ });
+ });
+
+});
diff --git a/pool/shard006/JavaScript/0043082_deleteModule.js b/pool/shard006/JavaScript/0043082_deleteModule.js
new file mode 100644
index 0000000000000000000000000000000000000000..bc46882758c8aeed71f3b130fe6737506689fcb8
--- /dev/null
+++ b/pool/shard006/JavaScript/0043082_deleteModule.js
@@ -0,0 +1,124 @@
+const shell = require('shelljs');
+const fs = require('fs');
+const chalk = require('chalk');
+const {
+ getModulePackageName,
+ computeModulePath,
+ getModulesEntryPoint,
+ computeRootModulesPath,
+ computePackagePath,
+ computeModulePackageName,
+ removeSymlink,
+ runPrettier
+} = require('../helpers/util');
+
+/**
+ * Removes the module from client, server or both locations and removes the module from the module list.
+ *
+ * @param logger - The Logger
+ * @param packageName - Name of the package the module adding to ([client|server])
+ * @param moduleName - The name of a new module
+ * @param old - The flag that describes if the command invoked for a new structure or not
+ */
+function deleteModule({ logger, packageName, moduleName, old }) {
+ const modulePackageName = getModulePackageName(packageName, old);
+ const modulePath = computeModulePath(modulePackageName, old, moduleName);
+ const params = { logger, moduleName, modulePath, packageName, modulePackageName, old };
+
+ if (fs.existsSync(modulePath)) {
+ deleteTemplates(params);
+ removeFromModules(params);
+ if (!old) removeDependency(params);
+
+ logger.info(chalk.green(`✔ Module ${moduleName} for package ${packageName} successfully deleted!`));
+ } else {
+ logger.info(chalk.red(`✘ Module ${moduleName} for package ${packageName} not found!`));
+ }
+}
+
+////////// DELETE MODULE STEPS //////////
+
+/**
+ * Removes templates from the module.
+ */
+function deleteTemplates({ logger, moduleName, modulePath, modulePackageName, old }) {
+ logger.info(`Deleting ${modulePackageName} files…`);
+ // remove module directory
+ shell.rm('-rf', modulePath);
+
+ // in new module structure remove root dir if no submodules exist
+ if (!old) {
+ const rootModulePath = computeRootModulesPath(moduleName);
+ if (!shell.ls(rootModulePath).length) {
+ shell.rm('-rf', rootModulePath);
+ }
+ }
+ logger.info(chalk.green(`✔ The ${modulePackageName} files of the module ${moduleName} have been deleted!`));
+}
+
+/**
+ * Removes module from modules entry file.
+ */
+function removeFromModules({ logger, moduleName, packageName, modulePackageName, old }) {
+ // Gets modules entry point file path
+ const modulesEntry = getModulesEntryPoint(packageName, old);
+
+ let indexContent;
+
+ try {
+ indexContent = fs.readFileSync(modulesEntry);
+ } catch (e) {
+ logger.error(chalk.red(`Failed to read ${modulesEntry} file`));
+ process.exit();
+ }
+
+ // Extract application modules
+ const appModuleRegExp = /Module\(([^()]+)\)/g;
+ const [, appModules] = appModuleRegExp.exec(indexContent) || ['', ''];
+ const appModulesWithoutDeleted = appModules.split(',').filter(appModule => appModule.trim() !== moduleName);
+
+ const contentWithoutDeletedModule = indexContent
+ .toString()
+ // Remove module from modules list
+ .replace(appModuleRegExp, `Module(${appModulesWithoutDeleted.toString().trim()})`)
+ // Remove module import
+ .replace(
+ RegExp(`import ${moduleName} from '${computeModulePackageName(moduleName, modulePackageName, old)}';\n`, 'g'),
+ ''
+ );
+
+ fs.writeFileSync(modulesEntry, contentWithoutDeletedModule);
+ runPrettier(modulesEntry);
+}
+
+/**
+ * Removes the module from the dependencies list.
+ */
+function removeDependency({ moduleName, packageName, modulePackageName, old }) {
+ // Get package content
+ const packagePath = computePackagePath(packageName);
+ const packageContent = `` + fs.readFileSync(packagePath);
+
+ // Extract dependencies
+ const dependenciesRegExp = /"dependencies":\s\{([^()]+)\},\n\s+"devDependencies"/g;
+ const [, dependencies] = dependenciesRegExp.exec(packageContent) || ['', ''];
+
+ // Remove package
+ const dependenciesWithoutDeleted = dependencies
+ .split(',')
+ .filter(pkg => !pkg.includes(computeModulePackageName(moduleName, modulePackageName, old)));
+
+ // Remove module from package list
+ shell
+ .ShellString(
+ packageContent.replace(
+ RegExp(dependenciesRegExp, 'g'),
+ `"dependencies": {${dependenciesWithoutDeleted}},\n "devDependencies"`
+ )
+ )
+ .to(packagePath);
+
+ removeSymlink(moduleName, modulePackageName);
+}
+
+module.exports = deleteModule;
diff --git a/pool/shard006/JavaScript/0043085_utils.js b/pool/shard006/JavaScript/0043085_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..46d15851bfd53284af156b30c31b0f480960594d
--- /dev/null
+++ b/pool/shard006/JavaScript/0043085_utils.js
@@ -0,0 +1,92 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0;
+const slice_ansi_1 = __importDefault(require("slice-ansi"));
+const string_width_1 = __importDefault(require("string-width"));
+const strip_ansi_1 = __importDefault(require("strip-ansi"));
+const getBorderCharacters_1 = require("./getBorderCharacters");
+/**
+ * Converts Windows-style newline to Unix-style
+ *
+ * @internal
+ */
+const normalizeString = (input) => {
+ return input.replace(/\r\n/g, '\n');
+};
+exports.normalizeString = normalizeString;
+/**
+ * Splits ansi string by newlines
+ *
+ * @internal
+ */
+const splitAnsi = (input) => {
+ const lengths = strip_ansi_1.default(input).split('\n').map(string_width_1.default);
+ const result = [];
+ let startIndex = 0;
+ lengths.forEach((length) => {
+ result.push(length === 0 ? '' : slice_ansi_1.default(input, startIndex, startIndex + length));
+ // Plus 1 for the newline character itself
+ startIndex += length + 1;
+ });
+ return result;
+};
+exports.splitAnsi = splitAnsi;
+/**
+ * Merges user provided border characters with the default border ("honeywell") characters.
+ *
+ * @internal
+ */
+const makeBorderConfig = (border) => {
+ return {
+ ...getBorderCharacters_1.getBorderCharacters('honeywell'),
+ ...border,
+ };
+};
+exports.makeBorderConfig = makeBorderConfig;
+/**
+ * Groups the array into sub-arrays by sizes.
+ *
+ * @internal
+ * @example
+ * groupBySizes(['a', 'b', 'c', 'd', 'e'], [2, 1, 2]) = [ ['a', 'b'], ['c'], ['d', 'e'] ]
+ */
+const groupBySizes = (array, sizes) => {
+ let startIndex = 0;
+ return sizes.map((size) => {
+ const group = array.slice(startIndex, startIndex + size);
+ startIndex += size;
+ return group;
+ });
+};
+exports.groupBySizes = groupBySizes;
+/**
+ * Counts the number of continuous spaces in a string
+ *
+ * @internal
+ * @example
+ * countGroupSpaces('a bc de f') = 3
+ */
+const countSpaceSequence = (input) => {
+ var _a, _b;
+ return (_b = (_a = input.match(/\s+/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
+};
+exports.countSpaceSequence = countSpaceSequence;
+/**
+ * Creates the non-increasing number array given sum and length
+ * whose the difference between maximum and minimum is not greater than 1
+ *
+ * @internal
+ * @example
+ * distributeUnevenly(6, 3) = [2, 2, 2]
+ * distributeUnevenly(8, 3) = [3, 3, 2]
+ */
+const distributeUnevenly = (sum, length) => {
+ const result = Array.from({ length }).fill(Math.floor(sum / length));
+ return result.map((element, index) => {
+ return element + (index < sum % length ? 1 : 0);
+ });
+};
+exports.distributeUnevenly = distributeUnevenly;
diff --git a/pool/shard006/JavaScript/0043086_App.js b/pool/shard006/JavaScript/0043086_App.js
new file mode 100644
index 0000000000000000000000000000000000000000..5eabb9dcb69f457f214b386117da529df3cdec33
--- /dev/null
+++ b/pool/shard006/JavaScript/0043086_App.js
@@ -0,0 +1,110 @@
+/**
+ * Sample React Native App
+ * https://github.com/facebook/react-native
+ *
+ * @format
+ * @flow
+ */
+
+import React, {Component, Fragment} from 'react';
+import {
+ SafeAreaView,
+ StyleSheet,
+ ScrollView,
+ View,
+ Text,
+ StatusBar,
+} from 'react-native';
+
+import {Header, Colors} from 'react-native/Libraries/NewAppScreen';
+
+import LinearGradient from 'react-native-linear-gradient';
+
+class App extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ count: 0,
+ colorTop: '#000000',
+ colorBottom: '#cccccc',
+ };
+ }
+
+ incrementColor = (color, step) => {
+ const intColor = parseInt(color.substr(1), 16);
+ const newIntColor = (intColor + step).toString(16);
+ return `#${'0'.repeat(6 - newIntColor.length)}${newIntColor}`;
+ };
+
+ componentDidMount() {
+ setInterval(() => {
+ this.setState({
+ count: this.state.count + 1,
+ colorTop: this.incrementColor(this.state.colorTop, 1),
+ colorBottom: this.incrementColor(this.state.colorBottom, -1),
+ });
+ }, 20);
+ }
+
+ render() {
+ return (
+
+
+
+
+
+ {global.HermesInternal == null ? null : (
+
+ Engine: Hermes
+
+ )}
+
+
+
+ {this.state.colorTop}
+
+
+ {this.state.colorBottom}
+
+
+
+
+
+ );
+ }
+}
+
+const styles = StyleSheet.create({
+ scrollView: {
+ backgroundColor: Colors.lighter,
+ },
+ engine: {
+ position: 'absolute',
+ right: 0,
+ },
+ body: {
+ backgroundColor: Colors.white,
+ },
+ highlight: {
+ fontWeight: '700',
+ },
+ gradient: {
+ width: 200,
+ height: 200,
+ },
+ footer: {
+ color: Colors.dark,
+ fontSize: 12,
+ fontWeight: '600',
+ padding: 4,
+ paddingRight: 12,
+ textAlign: 'right',
+ },
+});
+
+export default App;
diff --git a/pool/shard006/JavaScript/0043087_index.js b/pool/shard006/JavaScript/0043087_index.js
new file mode 100644
index 0000000000000000000000000000000000000000..04f1596d12b8c8ba476a383a633549394742790f
--- /dev/null
+++ b/pool/shard006/JavaScript/0043087_index.js
@@ -0,0 +1,41 @@
+import BillIndex from 'components/bill/bill-index.vue';
+
+const scrollBehavior = (to, from, savedPosition) => {
+ if (savedPosition) {
+ return savedPosition
+ } else {
+ const position = {}
+
+ if (to.hash) {
+ position.selector = to.hash
+ }
+ if (to.matched.some(m => m.meta.scrollToTop)) {
+ position.x = 0
+ position.y = 0
+ }
+ return position
+ }
+}
+
+const routes = [
+ {path: '/', component: BillIndex},
+ {path: '*', component: BillIndex},
+]
+
+const router = new VueRouter({
+ routes,
+})
+
+const app = new Vue({
+ router,
+ watch: {
+ '$route' (to, from) {
+ console.log(to)
+ if (to.path=="/bill"){
+ document.title = "账单";
+ } else if(to.path=="/bill/billDetails"){
+ document.title = "账单详情";
+ }
+ }
+ },
+}).$mount('#container')
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043088_server.js b/pool/shard006/JavaScript/0043088_server.js
new file mode 100644
index 0000000000000000000000000000000000000000..44ffc5e30d7b425942d8a53964a180be1cd35c5e
--- /dev/null
+++ b/pool/shard006/JavaScript/0043088_server.js
@@ -0,0 +1,281 @@
+//
+// Created by Stefan Kramreither & Kirkland Landry on 12/3/2015 15:17
+//
+
+var express = require('express'),
+ mysql = require('mysql'),
+ sequence = require('sequence').Sequence;
+
+var db = mysql.createConnection({
+ host: '',
+ user: '',
+ password: '',
+ database: 'se3309project'
+});
+
+var app = express();
+
+// Set view engine
+app.set('views', __dirname + '/views');
+app.set('view engine', 'ejs');
+
+// Set express added functionality
+app.use(require('cookie-parser')());
+app.use(require('body-parser').urlencoded({extended: false}));
+app.use(require('express-session')({secret: 'session', resave: true, saveUninitialized: true}));
+app.use(express.static(__dirname + '/public'));
+
+app.post('/login', function (req, res) {
+
+ var email = req.body.email,
+ password = req.body.password;
+
+ db.query(
+ "SELECT userId " +
+ "FROM User " +
+ "WHERE email = '" + email + "' AND passSalt = '" + password + "'",
+ function (err, rows) {
+ if (!err && rows.length === 1) {
+ req.session.userId = rows[0].userId;
+ }
+ res.redirect('/');
+ });
+});
+
+app.get('/signup', function (req, res) {
+ res.render('signup');
+});
+
+app.post('/signup', function (req, res) {
+
+ var firstName = req.body.firstname,
+ lastName = req.body.lastname,
+ username = req.body.username,
+ email = req.body.email,
+ passHash = "Hash",
+ passSalt = req.body.password,
+ description = req.body.description;
+
+ db.query(
+ "INSERT INTO User" +
+ "(firstName, lastName, username, email, passHash, passSalt, description) " +
+ "VALUES " +
+ "('" + firstName + "', '" + lastName + "', '" + username + "', '" + email +
+ "', '" + passHash + "', '" + passSalt + "', '" + description + "')",
+ function (err, rows) {
+ if (err) {
+ res.redirect('/signup');
+ } else {
+ res.redirect('/');
+ }
+ });
+});
+
+app.get('/', function (req, res) {
+
+ if (req.session.userId) {
+
+ var seq = sequence.create(),
+ IDs = [req.session.userId],
+ songs = [];
+
+ seq.then(function (next) {
+ db.query(
+ "SELECT userSubscribed " +
+ "FROM Subscription " +
+ "WHERE userSubscriber = " + req.session.userId,
+ function (err, rows) {
+ for (var i = 0; i < rows.length; i++) {
+ IDs.push(rows[i].userSubscribed);
+ }
+ next();
+ });
+ })
+ .then(function (next) {
+ db.query(
+ "SELECT User.username, Song.songId, Song.title, Song.description, Song.image, Song.audio, Song.likes, Song.createdAt " +
+ "FROM Song " +
+ "JOIN User ON User.userId = Song.userId " +
+ "WHERE Song.userId IN (" + IDs.join(",") + ") " +
+ "ORDER BY createdAt DESC",
+ function (err, rows) {
+ for (var i = 0; i < rows.length; i++) {
+ songs.push(rows[i]);
+ }
+ next();
+ });
+ })
+ .then(function (next) {
+
+ if (songs.length === 0) next();
+
+ for (var i = 0; i < songs.length; i++) {
+ (function (i) {
+ songs[i].comments = [];
+ db.query(
+ "SELECT User.image, User.username, User.userId, SongComment.comment, SongComment.createdAt " +
+ "FROM SongComment " +
+ "JOIN User ON User.userId = SongComment.userId " +
+ "WHERE songId = " + songs[i].songId + " ORDER BY SongComment.createdAt",
+ function (err, rows) {
+ for (var j = 0; j < rows.length; j++) {
+ songs[i].comments.push(rows[j]);
+ }
+
+ if (i == songs.length - 1) next();
+ });
+ })(i);
+ }
+ })
+ .then(function () {
+ res.render('feed', {
+ songs: songs,
+ userId: req.session.userId
+ });
+ });
+ } else {
+ res.render('login');
+ }
+});
+
+app.post('/like', function (req, res) {
+
+ db.query("INSERT INTO SongLike " +
+ "(userId, songId) " +
+ "VALUES (" + req.session.userId + ", " + req.body.songId + ")",
+ function (err, rows) {});
+
+ res.redirect('/');
+});
+
+app.post('/comment', function (req, res) {
+
+ db.query("INSERT INTO SongComment " +
+ "(userId, songId, comment) " +
+ "VALUES (" + req.session.userId + ", " + req.body.songId + ", '" + req.body.comment + "')",
+ function (err, rows) {});
+
+ res.redirect('/');
+});
+
+app.post('/delete/comment', function (req, res) {
+
+ var comment = req.body.comment,
+ songId = req.body.songId,
+ userId = req.session.userId;
+
+ db.query(
+ "DELETE FROM SongComment WHERE " +
+ "comment = '" + comment + "' AND " +
+ "songId = " + songId + " AND " +
+ "userId = " + userId,
+ function (err, rows) {
+ if (err) {
+ console.log()
+ }
+ res.redirect('/');
+ });
+});
+
+app.get('/search', function (req, res) {
+ if (req.session.userId) {
+ res.render('search', {
+ results: req.session.results
+ });
+ } else {
+ res.redirect('/');
+ }
+});
+
+app.post('/search', function (req, res) {
+
+ var results = [];
+
+ db.query(
+ "(SELECT image, User.username AS header, 'user' AS type, description " +
+ "FROM User " +
+ "WHERE username LIKE '%" + req.body.search + "%') " +
+ "UNION " +
+ "(SELECT image, Song.title AS header, 'song' AS type, description " +
+ "FROM Song " +
+ "WHERE title LIKE '%" + req.body.search + "%')",
+ function (err, rows) {
+ for (var i = 0; i < rows.length; i++) {
+ results.push(rows[i]);
+ }
+ req.session.results = results;
+ res.redirect('/search');
+ });
+});
+
+app.get('/subscriptions', function (req, res) {
+ if (req.session.userId) {
+
+ var subs = [];
+
+ db.query(
+ "SELECT image, userId, firstName, lastName, username, description " +
+ "FROM Subscription " +
+ "JOIN User ON User.userId = Subscription.userSubscribed " +
+ "WHERE userSubscriber = " + req.session.userId,
+ function (err, rows) {
+ for (var i = 0; i < rows.length; i++) {
+ subs.push(rows[i]);
+ }
+ res.render('subscriptions', {
+ subs: subs
+ });
+ });
+ } else {
+ res.redirect('/');
+ }
+});
+
+app.get('/account', function (req, res) {
+ if (req.session.userId) {
+ db.query(
+ "SELECT firstName, lastName, username, email, description, image " +
+ "FROM User " +
+ "WHERE userId = " + req.session.userId,
+ function (err, rows) {
+ res.render('account', {
+ userData: rows[0]
+ });
+ });
+ } else {
+ res.redirect('/');
+ }
+});
+
+app.post('/update/account', function (req, res) {
+
+ var firstName = req.body.firstName,
+ lastName = req.body.lastName,
+ email = req.body.email,
+ username = req.body.username,
+ description = req.body.description;
+
+ db.query(
+ "UPDATE User SET " +
+ "firstName = '" + firstName + "', " +
+ "lastName = '" + lastName + "', " +
+ "email = '" + email + "', " +
+ "username = '" + username + "', " +
+ "description = '" + description + "' " +
+ "WHERE userId = " + req.session.userId,
+ function (err, rows) {
+ res.redirect("/account");
+ });
+});
+
+app.get('/logout', function (req, res) {
+
+ delete req.session.results;
+ delete req.session.userId;
+
+ res.redirect('/');
+});
+
+app.listen(3000, function () {
+ console.log("Listening on port 3000...");
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043089_misc.js b/pool/shard006/JavaScript/0043089_misc.js
new file mode 100644
index 0000000000000000000000000000000000000000..aa2e60b6abe5142c6983fec3d1b33f459cbc966e
--- /dev/null
+++ b/pool/shard006/JavaScript/0043089_misc.js
@@ -0,0 +1,69 @@
+/* This file is part of Indico.
+ * Copyright (C) 2002 - 2015 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 .
+ */
+
+(function(global) {
+ 'use strict';
+
+ global.confirmPrompt = function confirmPrompt(message, title) {
+ var dfd = $.Deferred();
+ message = $('', {width: 400, html: message});
+ new ConfirmPopup(title || $T('Please confirm'), message, function(confirmed) {
+ if (confirmed) {
+ dfd.resolve();
+ } else {
+ dfd.reject();
+ }
+ }).open();
+ return dfd.promise();
+ };
+
+ global.alertPopup = function alertPopup(message, title) {
+ var dfd = $.Deferred();
+ new AlertPopup(title, message, function(){
+ dfd.resolve();
+ }).open();
+ return dfd;
+ };
+
+ global.handleFlashes = function handleFlashes(data, clear, element) {
+ var container;
+ if (!element || !element.length) {
+ container = $('#flashed-messages');
+ } else if (element.hasClass('flashed-messages')) {
+ container = element;
+ } else {
+ container = element.closest('.ui-dialog-content').find('.flashed-messages');
+ if (!container.length) {
+ container = element.closest('.page-content').find('.flashed-messages');
+ }
+ }
+ if (!container.length) {
+ container = $('#flashed-messages');
+ }
+ if (clear === undefined || clear) {
+ container.empty();
+ }
+ if (data.flashed_messages) {
+ var flashed = $(data.flashed_messages.trim()).children();
+ container.append(flashed);
+ }
+ };
+
+ global.uniqueId = function uniqueId() {
+ return '' + Math.round(new Date().getTime() + (Math.random() * 100));
+ };
+})(window);
diff --git a/pool/shard006/JavaScript/0043094_utils.js b/pool/shard006/JavaScript/0043094_utils.js
new file mode 100644
index 0000000000000000000000000000000000000000..689de08d680d1688c991680a726df2e54229cae8
--- /dev/null
+++ b/pool/shard006/JavaScript/0043094_utils.js
@@ -0,0 +1,78 @@
+'use strict';
+
+Object.defineProperty(exports, '__esModule', {
+ value: true
+});
+exports.hasMagic = hasMagic;
+exports.getSource = getSource;
+exports.interpolateString = interpolateString;
+exports.isAbsoluteURL = isAbsoluteURL;
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _minimatch = require('minimatch');
+
+var _path = require('path');
+
+var _path2 = _interopRequireDefault(_path);
+
+var isAbsolutePath = _path2['default'].isAbsolute;
+
+// Based on https://github.com/isaacs/node-glob/blob/master/glob.js#L83
+// (glob.hasMagic)
+
+function hasMagic(pattern, options) {
+ // Support RegExp as well as glob
+ if (pattern instanceof RegExp) {
+ return {
+ match: function match(str) {
+ return pattern.test(str);
+ }
+ };
+ }
+
+ var minimatch = new _minimatch.Minimatch(pattern, options);
+ var set = minimatch.set;
+
+ if (set.length > 1) {
+ return minimatch;
+ }
+
+ for (var j = 0; j < set[0].length; j++) {
+ if (typeof set[0][j] !== 'string') {
+ return minimatch;
+ }
+ }
+
+ return false;
+}
+
+function getSource(_source) {
+ return {
+ source: function source() {
+ return _source;
+ },
+ size: function size() {
+ return Buffer.byteLength(_source, 'utf8');
+ }
+ };
+}
+
+function interpolateString(string, data) {
+ var hasOwnProperty = ({}).hasOwnProperty;
+
+ return (string + '').replace(/\[(\w+?)\]/g, function (match, key) {
+ if (hasOwnProperty.call(data, key)) {
+ return data[key];
+ }
+
+ return '';
+ });
+}
+
+function isAbsoluteURL(url) {
+ return (/^(?:\w+:)?\/\//.test(url)
+ );
+}
+
+exports.isAbsolutePath = isAbsolutePath;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043096_Z60.js b/pool/shard006/JavaScript/0043096_Z60.js
new file mode 100644
index 0000000000000000000000000000000000000000..48b6bffa4d86d15eb35f860e87947f50b84eb97b
--- /dev/null
+++ b/pool/shard006/JavaScript/0043096_Z60.js
@@ -0,0 +1,24 @@
+// Copyright 2020 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.
+'use strict'
+
+const i = require('./../index.js')
+const c = i.constants
+
+const construct = text => ({
+ Z1K1: c.CHARACTER,
+ Z60K1: text
+})
+
+exports.construct = construct
diff --git a/pool/shard006/JavaScript/0043097_noResizable.js b/pool/shard006/JavaScript/0043097_noResizable.js
new file mode 100644
index 0000000000000000000000000000000000000000..78f251299617f5f44c787665123350a7f02bbb74
--- /dev/null
+++ b/pool/shard006/JavaScript/0043097_noResizable.js
@@ -0,0 +1,48 @@
+angular.module('noResizable', []).directive('noResizable', [
+ '$document', '$parse', function($document, $parse) {
+ return function(scope, element, attr) {
+ var image, mousemove, mouseup, offset, resize;
+ offset = 8;
+ offset = attr.noResizableOffset || 8;
+ image = attr.noResizableImage || '/assets/vendor/noToolbox/dist/img/resize-white.png';
+ resize = document.createElement('img');
+ resize.setAttribute('src', image);
+ resize.style.width = '20px';
+ resize.style.height = '20px';
+ resize.style.right = offset + 'px';
+ resize.style.bottom = offset + 'px';
+ resize.style.zIndex = 9999;
+ resize.style.position = 'absolute';
+ element.append(resize);
+ element.css({
+ position: 'relative',
+ cursor: 'pointer'
+ });
+ mousemove = function(event) {
+ var h, w;
+ w = event.pageX - element.offset().left + offset;
+ h = event.pageY - element.offset().top + offset;
+ if (w < 50) {
+ w = 50;
+ }
+ if (h < 50) {
+ h = 50;
+ }
+ return element.css({
+ width: w + 'px',
+ height: h + 'px'
+ });
+ };
+ mouseup = function() {
+ $document.unbind('mousemove', mousemove);
+ return $document.unbind('mouseup', mouseup);
+ };
+ return resize.onmousedown = function(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ $document.on('mousemove', mousemove);
+ return $document.on('mouseup', mouseup);
+ };
+ };
+ }
+]);
diff --git a/pool/shard006/JavaScript/0043100_im_odoo_support.js b/pool/shard006/JavaScript/0043100_im_odoo_support.js
new file mode 100644
index 0000000000000000000000000000000000000000..dcb5002c696ad302521c82d6098f73006c15e2bc
--- /dev/null
+++ b/pool/shard006/JavaScript/0043100_im_odoo_support.js
@@ -0,0 +1,141 @@
+(function(){
+
+ "use strict";
+
+ var _t = openerp._t;
+ openerp.im_odoo_support = {};
+ var COOKIE_NAME = 'livechat_conversation';
+ var SERVICE_URL = 'https://services.odoo.com/';
+
+ openerp.im_odoo_support.OdooSupport = openerp.Widget.extend({
+ init: function(login, uuid, params, options){
+ var self = this;
+ this._super();
+ this.login = login;
+ this.uuid = uuid;
+
+ this.options = _.extend(options || {}, {'defaultUsername' : login});
+ this.params = _.extend(params || {}, {'database_uuid' : uuid});
+
+ this.assets_loaded = false;
+ this.session = false;
+ // bind event
+ $(window).on("odoo_support_ready_to_bind", this, _.bind(this.bind_actions, this));
+ },
+ bind_actions: function(event, button){
+ if(button === 'usermenu'){
+ openerp.client.$('.oe_user_menu_placeholder .odoo_support_contact').on('click', this, _.bind(this.click_action, this));
+ // check auto start if cookie
+ var session = openerp.get_cookie(COOKIE_NAME);
+ if(session){
+ this.start_support();
+ }
+ }
+ if(button === 'im_contact'){
+ if(openerp.im_chat && openerp.im_chat.single){
+ openerp.im_chat.single.$('.odoo_support_contact').on('click',this, _.bind(this.click_action, this));
+ }
+ }
+ },
+ click_action: function(){
+ var session = openerp.get_cookie(COOKIE_NAME);
+ if(!session){
+ this.start_support();
+ }
+ },
+ start_support: function(){
+ var self = this;
+ if(!this.assets_loaded){
+ this.load_assets().then(function(){
+ try{
+ odoo_support.im_livechat.support = new odoo_support.im_livechat.LiveSupport(self.options, self.params);
+ // bind event change status
+ odoo_support.im_livechat.support.on('im_odoo_support_status', this, function(is_online){
+ if(openerp.im_chat && openerp.im_chat.single){
+ openerp.im_chat.single.support_user.$(".oe_im_user_online").toggle(is_online);
+ }
+ });
+ }catch(e){
+ self.error_on_start(e);
+ }
+ }).fail(function(e){
+ self.error_on_start(e);
+ });
+ }else{
+ odoo_support.im_livechat.support.start();
+ }
+ },
+ error_on_start: function(e){
+ self.assets_loaded = false;
+ openerp.client.do_warn(_t("Error"), _t("The connection with the Odoo Support Server failed. Please retry in a few minutes, or send an email to support@odoo.com ."));
+ },
+ load_assets: function(){
+ var self = this;
+ var add_asset = function(file_url, type) {
+ var def = $.Deferred();
+ if(type === 'js'){
+ $.getScript( file_url, function( data, textStatus, jqxhr ) {
+ def.resolve();
+ }).fail(function(){
+ def.reject();
+ });
+ return def;
+ }else{
+ $(' ').appendTo($("head")).ready(function() {
+ def.resolve();
+ });
+ return def;
+ }
+ };
+ var defs = [];
+ defs.push(add_asset(SERVICE_URL+"odoo-livechat/assets/js", 'js'));
+ defs.push(add_asset(SERVICE_URL+"odoo-livechat/assets/css", 'css'));
+ return $.when.apply($, defs).then(function(res){
+ self.assets_loaded = true;
+ return res;
+ }, function(){
+ self.error_on_start();
+ });
+ },
+ });
+
+ // display support contact button (in chat user list, if installed) and in dropdown user menu.
+ if(openerp.im_chat){
+ openerp.im_chat.InstantMessaging.include({
+ start: function(){
+ this._super.apply(this, arguments);
+ var user = {
+ "id" : -1,
+ "name": _t('Odoo Support'),
+ "im_status": 'online',
+ "image_url": "/im_odoo_support/static/img/odoo_o_small.png"
+ };
+ var widget = new openerp.im_chat.UserWidget(self, user);
+ widget.prependTo(self.$(".oe_im_users"));
+ widget.$el.addClass('odoo_support_contact');
+ this.support_user = widget;
+
+ $(window).trigger('odoo_support_ready_to_bind','im_contact');
+ },
+ search_users_status: function(e){
+ var self = this;
+ this._super.apply(this, arguments).then(function(res){
+ if(self.$('.oe_im_searchbox').val().length === 0 || _t("Odoo Support").toLowerCase().indexOf(self.$('.oe_im_searchbox').val().toLowerCase()) != -1){
+ self.support_user.$el.show();
+ }else{
+ self.support_user.$el.hide();
+ }
+ return res;
+ });
+ }
+ });
+ }
+
+ openerp.web.UserMenu.include({
+ do_update: function(){
+ $(window).trigger('odoo_support_ready_to_bind', 'usermenu');
+ return this._super.apply(this, arguments);
+ },
+ });
+
+})();
diff --git a/pool/shard006/JavaScript/0043103_build.js b/pool/shard006/JavaScript/0043103_build.js
new file mode 100644
index 0000000000000000000000000000000000000000..dabe1237c1329ce5e77d8f3363ceb0c63d8d5212
--- /dev/null
+++ b/pool/shard006/JavaScript/0043103_build.js
@@ -0,0 +1,155 @@
+/* */
+"format global";
+var root = require('find-parent-dir').sync(__dirname, 'package.json');
+var build = require(root + 'lib/build');
+var expect = require('expect.js');
+
+describe('cli/build', function() {
+
+ it('should build without error', function() {
+ expect(function() {build();}).to.not.throwError();
+ });
+
+ describe('custom builds', function(done) {
+
+ it('should build without errors when using a custom build', function() {
+ expect(function() {
+ build({'feature-detects': ['css/boxsizing']}, done);
+ }).to.not.throwError();
+ });
+
+ it('should include the requested options', function(done) {
+ build({'feature-detects': ['css/boxsizing']}, function(file) {
+ expect(file).to.contain('boxsizing');
+ done();
+ });
+ });
+
+ it('should exclude options that are not requested', function(done) {
+ build({'feature-detects': ['dom/classlist']}, function(file) {
+ expect(file).to.contain('classlist');
+ expect(file).to.not.contain('boxsizing');
+ done();
+ });
+ });
+
+ it('should strip out DOC comments when `uglify`ing', function(done) {
+ var config = {
+ minify: true,
+ 'feature-detects': ['css/boxsizing']
+ };
+
+ build(config, function(file) {
+ expect(file).to.not.contain('Box Sizing');
+ done();
+ });
+ });
+
+ it('should inject the proper classPath when configured', function(done) {
+ var prefix = 'TEST_PREFIX';
+ var config = {
+ classPrefix: prefix,
+ setClasses: true
+ };
+ var configRE = /_config:\s*?({[^}]*})/m;
+
+ build(config, function(file) {
+ var parsedConfig = file.match(configRE);
+ parsedConfig = JSON.parse(parsedConfig[1].replace(/'/g, '"'));
+ expect(parsedConfig.classPrefix).to.be(prefix);
+ done();
+ });
+ });
+
+ it('should inject the proper classPath when configured and minified', function(done) {
+ var prefix = 'TEST_PREFIX';
+ var config = {
+ classPrefix: prefix,
+ setClasses: true,
+ minify: true
+ };
+ var configRE = /_config:\s*?({[^}]*})/m;
+
+ build(config, function(file) {
+ var parsedConfig = file.match(configRE);
+ //use eval becuase the minified code creates non valid JSON.
+ parsedConfig = eval('(' + parsedConfig[1].replace(/'/g, '"') + ')');
+ expect(parsedConfig.classPrefix).to.be(prefix);
+ done();
+ });
+ });
+
+ describe('unminified', function() {
+ var output;
+
+ before(function(done) {
+ var config = {
+ 'feature-detects': ['css/boxsizing']
+ };
+
+ build(config, function(file) {
+ output = file;
+ done();
+ });
+ });
+
+ it('strips out the modernizr-init/build `define` section', function() {
+ var defineRe = /define\("modernizr-(init|build)"\)/m;
+ expect(defineRe.test(output)).to.be(false);
+ });
+
+ it('strips out the `define` section', function() {
+ var docRe = /define\(.*?\{/;
+ expect(docRe.test(output)).to.be(false);
+ });
+
+ it('strips out the `require` section', function() {
+ var requireRe = /require[^\{\r\n]+\{/;
+ expect(requireRe.test(output)).to.be(false);
+ });
+
+ it('replaces __VERSION__ ', function() {
+ expect(output).to.not.contain('__VERSION__');
+ });
+
+ });
+
+ describe('minified', function() {
+ var output;
+
+ before(function(done) {
+ var config = {
+ 'feature-detects': ['css/boxsizing'],
+ minify: true
+ };
+
+ build(config, function(file) {
+ output = file;
+ done();
+ });
+ });
+
+ it('strips out the modernizr-init/build `define` section', function() {
+ var defineRe = /define\("modernizr-(init|build)"\)/m;
+ expect(defineRe.test(output)).to.be(false);
+ });
+
+ it('strips out the `define` section', function() {
+ var docRe = /define\(.*?\{/;
+ expect(docRe.test(output)).to.be(false);
+ });
+
+ it('strips out the `require` section', function() {
+ var requireRe = /require[^\{\r\n]+\{/;
+ expect(requireRe.test(output)).to.be(false);
+ });
+
+ it('replaces __VERSION__ ', function() {
+ expect(output).to.not.contain('__VERSION__');
+ });
+
+ });
+
+ });
+
+});
diff --git a/pool/shard006/JavaScript/0043104_recognize.v1p1beta1.test.js b/pool/shard006/JavaScript/0043104_recognize.v1p1beta1.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..aadbe26545d355756ce4f7dd6b89491419525fd8
--- /dev/null
+++ b/pool/shard006/JavaScript/0043104_recognize.v1p1beta1.test.js
@@ -0,0 +1,31 @@
+// Copyright 2016 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+'use strict';
+
+const path = require('path');
+const {assert} = require('chai');
+const {describe, it} = require('mocha');
+const cp = require('child_process');
+
+const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
+const cmd = 'node recognize.v1p1beta1.js';
+const filepath = path.join(__dirname, '..', 'resources', 'audio.raw');
+
+describe('Recognize v1p1beta1', () => {
+ it('should run sync recognize with metadata', async () => {
+ const output = execSync(`${cmd} ${filepath}`);
+ assert.match(output, /how old is the Brooklyn Bridge/);
+ });
+});
diff --git a/pool/shard006/JavaScript/0043107_Conversation.js b/pool/shard006/JavaScript/0043107_Conversation.js
new file mode 100644
index 0000000000000000000000000000000000000000..765e447bc88d19c3101f873a8f8c0c7fc997255e
--- /dev/null
+++ b/pool/shard006/JavaScript/0043107_Conversation.js
@@ -0,0 +1,272 @@
+
+include('tesla/Delegate.js');
+include('tesla/node.js');
+
+var TEST_TIME = 5E4;
+var TEST_MSG = '\ufffb\ubfff';
+
+/**
+ * @class tesla.client.Conversation.private$parser
+ * @extends Object
+ * @createTime 2012-03-08
+ * @author louis.tru
+ * @copyright (C) 2011 louis.tru, http://mooogame.com
+ * Released under MIT license, http://license.mooogame.com
+ * @version 1.0
+ */
+
+var private$parser =
+
+Class('private$parser', {
+
+ buffer: '',
+ i: 0,
+
+ private$parser: function() {
+ this.onclose = new Delegate(this, 'close');
+ this.ondata = new Delegate(this, 'data');
+ this.onerror = new Delegate(this, 'error');
+ },
+
+ add: function(data) {
+ this.buffer += data;
+ this.parse();
+ },
+
+ parse: function() {
+ for (var i = this.i, chr, l = this.buffer.length; i < l; i++) {
+
+ chr = this.buffer[i];
+
+ if (this.buffer.length == 2 && this.buffer[1] == '\u0000') {
+ this.onclose.emit();
+ this.buffer = '';
+ this.i = 0;
+ return;
+ }
+
+ if (i === 0) {
+ if (chr != '\u0000')
+ this.error('Bad framing. Expected null byte as first frame');
+ else
+ continue;
+ }
+
+ if (chr == '\ufffd') {
+ var buffer = this.buffer.substr(1, i - 1);
+ if (buffer[0] != '\ufffb' && buffer[1] != '\ubfff')
+ this.ondata.emit(buffer);
+
+ this.buffer = this.buffer.substr(i + 1);
+ this.i = 0;
+ return this.parse();
+ }
+ }
+ },
+
+ error: function(reason) {
+ this.buffer = '';
+ this.i = 0;
+ this.onerror.emit(reason);
+ return this;
+ }
+});
+
+/**
+ * @class tesla.client.Conversation
+ * @extends Object
+ * @createTime 2012-03-08
+ * @author louis.tru
+ * @copyright (C) 2011 louis.tru, http://mooogame.com
+ * Released under MIT license, http://license.mooogame.com
+ * @version 1.0
+ */
+
+/*
+ * Send a test signal
+ */
+function sendTest(_this) {
+ Function.undelay(_this._test_timeout);
+ _this._test_timeout = _this.send.delay(_this, TEST_TIME, TEST_MSG);
+}
+
+Class('tesla.client.Conversation', {
+
+ //private:
+ _connect: false,
+ _socket: null,
+ _url: '',
+ _message: null,
+ _test_timeout: 0,
+
+
+ //public:
+ /**
+ * open status
+ * @type Boolean
+ */
+ open: false,
+
+ /**
+ * @event onselected
+ */
+ onopen: null,
+
+ /**
+ * @event onselected
+ */
+ onmessage: null,
+
+ /**
+ * @event onselected
+ */
+ onerror: null,
+
+ /**
+ * @event onselected
+ */
+ onclose: null,
+
+ /**
+ * constructor function
+ * @constructor
+ */
+ Conversation: function(url) {
+ var _this = this;
+ this._url = url;
+ this._message = [];
+
+ Delegate.def(this, 'open', 'message', 'error', 'close');
+ nextTick(this, this.connect);
+
+ this.onopen.on(function() {
+ _this.open = true;
+ _this._connect = false;
+ });
+
+ this.onclose.on(function() {
+ _this.open = false;
+ _this._connect = false;
+ });
+
+ this.onerror.on(function() {
+ _this._connect = false;
+ });
+ },
+
+ /**
+ * connercion server
+ */
+ connect: function() {
+ if (!this.open && !this._connect) {
+ this._connect = true;
+ this.init();
+ }
+ },
+
+ /**
+ * init conversation
+ */
+ init: function() {
+ var _this = this;
+ var mat = this._url.match(/^wss?:\/\/([^\/:]+)(:(\d+))?(\/.+)$/i);
+
+ // make a request
+ var options = {
+ port: parseInt(mat[3]) || 80,
+ host: mat[1],
+ path: mat[4] || '/',
+ headers: {
+ 'Connection': 'Upgrade',
+ 'Upgrade': 'websocket'
+ }
+ };
+
+ var req = tesla.node.http.request(options);
+ req.end();
+
+ req.on('upgrade', function(res, socket, upgradeHead) {
+ _this._socket = socket;
+
+ socket.setNoDelay(true);
+ socket.setEncoding('utf8');
+
+ socket.on('end', function() {
+ console.log('client socket end close');
+ _this.close();
+ });
+
+ socket.on('close', function() {
+ console.log('client socket close');
+ _this.close();
+ });
+
+ socket.on('error', function(e) {
+ console.error(e);
+ _this.onerror.emit(e);
+ _this.close();
+ _this._socket.destroy();
+ });
+
+ var parser = new private$parser();
+ socket.on('data', parser.add.bind(parser));
+
+ _this.onmessage.shell(parser.ondata);
+
+ parser.onclose.on(function() {
+ console.log('websocket parser close');
+ _this.close();
+ });
+
+ parser.onerror.on(function(e) {
+ var data = e.data;
+ console.error(data);
+ _this.onerror.emit(data);
+ _this.close();
+ });
+
+ var msg = _this._message;
+ _this._message = [];
+ _this.onopen.emit();
+
+ for (var i = 0, l = msg.length; i < l; i++)
+ socket.write(msg[i]);
+
+ sendTest(_this);
+ });
+ },
+
+ /**
+ * send message to server
+ * @param {String} msg
+ */
+ send: function(msg) {
+ msg = '\u0000' + msg + '\ufffd';
+
+ if (this.open) {
+
+ this._socket.write(msg);
+ sendTest(this);
+ }
+ else if (msg != TEST_MSG) {
+ this._message.push(msg);
+ this.connect();
+ }
+ },
+
+ /**
+ * close conversation connection
+ */
+ close: function() {
+ if (this.open) {
+ var socket = this._socket;
+ socket.removeAllListeners('end');
+ socket.removeAllListeners('close');
+ socket.removeAllListeners('error');
+ socket.removeAllListeners('data');
+ socket.end();
+ this.onclose.emit();
+ }
+ }
+
+});
diff --git a/pool/shard006/JavaScript/0043108_accounts-controller.js b/pool/shard006/JavaScript/0043108_accounts-controller.js
new file mode 100644
index 0000000000000000000000000000000000000000..0013e6ca80aca9e9e3f2aff6a75ce5f7ec390d74
--- /dev/null
+++ b/pool/shard006/JavaScript/0043108_accounts-controller.js
@@ -0,0 +1,25 @@
+var Account = require('../models/account');
+
+module.exports = {
+ all: function(req, res) {
+ console.log('get all accounts');
+ console.log(res.body);
+ },
+
+ create: function(req, res) {
+ console.log('create new account:');
+ console.log(req.body);
+ var account = new Account(req.body);
+ account.save();
+ },
+
+ update: function(req, res) {
+ console.log('update account:');
+ console.log(req.body);
+ },
+
+ delete: function(req, res) {
+ console.log('delete account:');
+ console.log(req.body);
+ }
+};
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043109_resources.react.js b/pool/shard006/JavaScript/0043109_resources.react.js
new file mode 100644
index 0000000000000000000000000000000000000000..7f2d5138ae20df4584991b9164aeb497eed3c29a
--- /dev/null
+++ b/pool/shard006/JavaScript/0043109_resources.react.js
@@ -0,0 +1,59 @@
+'use strict';
+
+const defaultLang = 'en';
+let lang = defaultLang;//navigator.language || navigator.browserLanguage;
+
+const locales = [{
+ lang: 'en',
+ locales: 'en-US',
+ formats: {
+ number: {
+ USD: {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }
+ }
+ },
+ messages: {
+ Date: 'Date',
+ LoginFormTitle: 'Please sign in or register',
+ Expenses: 'Expenses',
+ Total: '{length, plural, one{# expense} other{# expenses}}, Sum:{sum, number, USD}, AVG: {avg, number, USD}, AVG by day:{dayAvg, number, USD}({days}), by week:{weekAvg, number, USD}({weeks}), by month:{monthAvg, number, USD}({months}), by year:{yearAvg, number, USD}({years})',
+ expenseDeleted: 'Expense deleted',
+ expensesLoaded: 'Expenses data loaded',
+ expenseInserted: 'Expense inserted',
+ expenseUpdated: 'Expense updated',
+ Error: '{error}{errorName}{errorPassword}'
+ }
+},
+{
+ lang: 'ru',
+ locales: 'ru-RU',
+ formats: {
+ number: {
+ USD: {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }
+ }
+ },
+ messages: {
+ Date: 'Дата',
+ LoginFormTitle: 'Войдите или зарегистрируйтесь',
+ Expenses: 'Расходы',
+ Total: '{length, plural, one{# запись} other{# записи}}, Сумма:{sum, number, USD}, Среднее за день:{dayAvg, number, USD}, в неделю:{weekAvg, number, USD}, в месяц:{monthAvg, number, USD}, в год:{yearAvg, number, USD}'
+ }
+}];
+
+const filter = item => item.lang === lang;
+const isSupported = locales.filter(filter).length;
+
+lang = isSupported ? lang : defaultLang;
+
+const data = locales.filter(filter).shift();
+
+export default data;
diff --git a/pool/shard006/JavaScript/0043110_claim-award.js b/pool/shard006/JavaScript/0043110_claim-award.js
new file mode 100644
index 0000000000000000000000000000000000000000..fdfdd5633c96152651da3689bbe729f4a27e506b
--- /dev/null
+++ b/pool/shard006/JavaScript/0043110_claim-award.js
@@ -0,0 +1,37 @@
+(function claimAward($) {
+ var $form = $('.js-confirm-form');
+ var $emailInput = $form.find('.js-email-input');
+ var where = $form.prop('action');
+ var method = $form.prop('method');
+ var code = $form.find('input[name="code"]').val();
+ var csrfToken = $form.find('input[name="csrf"]').val();
+
+ jQuery.ajaxSetup({
+ headers: {'x-csrf-token': csrfToken}
+ });
+
+ function getAssertion(email, callback) {
+ var data = { email: email, code: code};
+ jQuery.post('/claim/confirm', data)
+ .success(function (data) { callback(null, data) })
+ .error(function (err) { callback(err.statusText) });
+ }
+
+ $form.on('submit', function (e) {
+ var $this = $(this);
+ var email = $emailInput.val().trim();
+ var url;
+ getAssertion(email, function (err, data) {
+ if (err || data.status === 'not-found')
+ return window.alert('There was an error trying to claim the badge');
+
+ if (data.status === 'already-claimed')
+ return window.alert('This badge has already been claimed by someone');
+
+ url = data.assertionUrl;
+ OpenBadges.issue([url]);
+ });
+
+ return (e.preventDefault(), false);
+ });
+})(jQuery);
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043112_script.js b/pool/shard006/JavaScript/0043112_script.js
new file mode 100644
index 0000000000000000000000000000000000000000..c4afd30bd74d9c9597c0f9b084d7e6ba32d24875
--- /dev/null
+++ b/pool/shard006/JavaScript/0043112_script.js
@@ -0,0 +1,48 @@
+$(function() {
+
+ $(".ajax-profile-link").click(function() {
+
+ var wrapper = $(".ajax-wrapper");
+ var target = $(this).data("target");
+
+ $.ajax({
+ url: target,
+ type: "POST",
+ context: document.body,
+ success: function(data){
+ $(wrapper).html(data);
+ }
+ });
+ $(".ajax-profile-link").removeClass("active");
+ $(this).addClass("active");
+
+ return false;
+
+ });
+
+ $("body").on("submit", ".ajax-submission-form", function() {
+ var wrapper = $(".ajax-wrapper");
+ var form = $(this);
+ var target = $(".ajax-profile-link.active").data("target");
+
+ $.ajax({
+ url: target,
+ type: "POST",
+ data: new FormData(this),
+ context: document.body,
+ success: function(data){
+ $(wrapper).html(data);
+ },
+ processData: false,
+ contentType: false
+ });
+
+ return false;
+ });
+
+ $("body").on("click", ".switch-to-form", function() {
+ $(this).parent().addClass("hide");
+ $(".create-profile-block").addClass("show");
+ return false;
+ });
+});
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043113_FirstPageView.js b/pool/shard006/JavaScript/0043113_FirstPageView.js
new file mode 100644
index 0000000000000000000000000000000000000000..3bda21f7b13a8e65989340fdcef37e876f89206a
--- /dev/null
+++ b/pool/shard006/JavaScript/0043113_FirstPageView.js
@@ -0,0 +1,96 @@
+function FirstPageView(){
+ var LevelView = require('LevelView');
+
+ var firstPageView = this;
+
+ firstPageView.main = Ti.UI.createWindow({
+ title: "Test",
+ backgroundColor: "#FFFFFF",
+ orientationModes: [Ti.UI.PORTRAIT],
+ width: Ti.Platform.displayCaps.platformWidth,
+ exitOnClose: true,
+ navBarHidden: true,
+ fullscreen: true
+ });
+
+ firstPageView.header = Ti.UI.createLabel({
+ text: "LOGO KVIZ SRBIJA",
+ color: "#000000",
+ backgroundColor: "#dfedd6",
+ font: { fontSize:56 },
+ textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
+ top: 0,
+ left: 0,
+ height: "10%",
+ width: Ti.Platform.displayCaps.platformWidth
+ });
+
+ firstPageView.play = Ti.UI.createButton({
+ title: "Igraj",
+ top: "30%",
+ width: "60%"
+ });
+
+ firstPageView.statistic = Ti.UI.createButton({
+ title: "Statistika",
+ top: "45%",
+ width: "60%"
+ });
+
+ firstPageView.option = Ti.UI.createButton({
+ title: "Opcije",
+ top: "60%",
+ width: "60%"
+ });
+
+ firstPageView.bottomImage = Ti.UI.createLabel({
+ text: "Neka slika",
+ color: "#000000",
+ font: { fontSize: 56 },
+ textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
+ backgroundColor: "#dfedd6",
+ bottom: 0,
+ left: 0,
+ height: "15%",
+ width: Ti.Platform.displayCaps.platformWidth
+ });
+
+ /*
+ * All first page events
+ */
+ firstPageView.addEvents = function(){
+ firstPageView.play.addEventListener("click", function(){
+ firstPageView.levelView = new LevelView();
+ firstPageView.levelView.open();
+ });
+ }
+
+ /*
+ * Adding fields to window
+ */
+ firstPageView.addToWindow = function(){
+ firstPageView.main.add(firstPageView.header);
+ firstPageView.main.add(firstPageView.play);
+ firstPageView.main.add(firstPageView.statistic);
+ firstPageView.main.add(firstPageView.option);
+ firstPageView.main.add(firstPageView.bottomImage);
+ }
+
+ /*
+ * Initialize all main functions
+ */
+ firstPageView.initPage = function(){
+ firstPageView.addEvents();
+ firstPageView.addToWindow();
+ }
+
+ /*
+ * Start the window
+ */
+ firstPageView.open = function(){
+ firstPageView.initPage();
+ firstPageView.main.open();
+ }
+}
+
+module.exports = FirstPageView;
\ No newline at end of file
diff --git a/pool/shard006/JavaScript/0043115_HTMLFormatter.js b/pool/shard006/JavaScript/0043115_HTMLFormatter.js
new file mode 100644
index 0000000000000000000000000000000000000000..9514125d6380f3628bd902c5cc6a59dbb938da3a
--- /dev/null
+++ b/pool/shard006/JavaScript/0043115_HTMLFormatter.js
@@ -0,0 +1,77 @@
+// Copyright 2016 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
+ * @param {!WebInspector.FormattedContentBuilder} builder
+ */
+WebInspector.HTMLFormatter = function(builder)
+{
+ this._builder = builder;
+}
+
+/**
+ * @constructor
+ * @param {string} tagName
+ * @param {number} offset
+ */
+WebInspector.HTMLFormatter.Result = function(tagName, offset)
+{
+ this.tagName = tagName;
+ this.offset = offset;
+}
+
+WebInspector.HTMLFormatter.prototype = {
+ /**
+ * @param {string} text
+ * @param {!Array} lineEndings
+ * @param {number} fromOffset
+ * @return {!WebInspector.HTMLFormatter.Result}
+ */
+ format: function(text, lineEndings, fromOffset)
+ {
+ var content = text.substring(fromOffset);
+ var tagName = "";
+ var accumulatedTokenValue = "";
+ var lastOffset = fromOffset;
+
+ /**
+ * @param {string} tokenValue
+ * @param {?string} type
+ * @param {number} tokenStart
+ * @param {number} tokenEnd
+ * @return {(!Object|undefined)}
+ * @this {WebInspector.HTMLFormatter}
+ */
+ function processToken(tokenValue, type, tokenStart, tokenEnd)
+ {
+ tokenStart += fromOffset;
+ tokenEnd += fromOffset;
+ lastOffset = tokenEnd;
+ this._builder.addToken(tokenValue, tokenStart);
+
+ if (!type)
+ return;
+ var tokenType = type.split(" ").keySet();
+ if (!tokenType["tag"])
+ return;
+
+ if (tokenType["bracket"] && (tokenValue === "<" || tokenValue === "")) {
+ accumulatedTokenValue = tokenValue;
+ return;
+ }
+
+ if (tagName && tokenValue === ">")
+ return WebInspector.AbortTokenization;
+
+ accumulatedTokenValue = accumulatedTokenValue + tokenValue.toLowerCase();
+ if (accumulatedTokenValue === "