diff --git a/pool/shard006/JavaScript/0041688_mustHaveAccountLinkedToPlex.js b/pool/shard006/JavaScript/0041688_mustHaveAccountLinkedToPlex.js new file mode 100644 index 0000000000000000000000000000000000000000..67f694419737d8274a6bda59ce1267d327e0d22c --- /dev/null +++ b/pool/shard006/JavaScript/0041688_mustHaveAccountLinkedToPlex.js @@ -0,0 +1,31 @@ +const establishedDatabase = require('src/database/database'); + +const mustHaveAccountLinkedToPlex = (req, res, next) => { + let database = establishedDatabase; + const loggedInUser = req.loggedInUser; + + if (loggedInUser === undefined) { + return res.status(401).send({ + success: false, + message: 'You must have your account linked to a plex account.', + }); + } else { + database.get(`SELECT plex_userid FROM settings WHERE user_name IS ?`, loggedInUser.username) + .then(row => { + const plex_userid = row.plex_userid; + + if (plex_userid === null || plex_userid === undefined) { + return res.status(403).send({ + success: false, + message: 'No plex account user id found for your user. Please authenticate your plex account at /user/authenticate.' + }) + } else { + req.loggedInUser.plex_userid = plex_userid; + return next(); + } + }) + } + +}; + +module.exports = mustHaveAccountLinkedToPlex; diff --git a/pool/shard006/JavaScript/0041691_smallSearch_en.js b/pool/shard006/JavaScript/0041691_smallSearch_en.js new file mode 100644 index 0000000000000000000000000000000000000000..720389f1b14fe649d872507dfc13df848ac3c905 --- /dev/null +++ b/pool/shard006/JavaScript/0041691_smallSearch_en.js @@ -0,0 +1,113 @@ + +//***************************************************************************************** +//This file is used as javascript plugging with the top-header part of small search option +//of new design template, here few document objects name are dependent on the header html text. +//So any change in the header html, should be reviewed in context with this javascript plugging. +//........[sc74193] + +//***************************************************************************************** +try{ + //form object defind in the top-header section. [sc74193] + var oForm = document.getElementById("form-search-location"); + + //oForm.elements["maplink"].href="http://maps.scotiabank.com/en/"; + document.getElementById("maplink").href="http://maps.scotiabank.com/en/"; + + + oForm.elements["search-location"].onkeypress = function(e) + { + //for IE + try + { + if(window.event.keyCode == 13) + { + validatetopAddress(); + return false; + } + } + catch(err) {} + + try + { + if(e.which == 13) + { + validatetopAddress(); + return false; + } + } + catch(err) {} + } + + var topaddressField = oForm.elements["search-location"]; + //top search implemented [sc74193] + + document.getElementById("top-submit").onclick = validatetopAddress; + //oForm.elements["top-submit"].onclick = validatetopAddress; + + + topaddressField.onclick = function() { focusInput(this); } + + function focusInput(input) { + input.value = ""; + var curClass = input.className.split(" "); + } + +} +catch(e) {} + +//******************************************************************************* +// This script for Google autocomplete functionality for the Canada region +// Canada's Geographic region falls on lat 36, lng -50 NE and lat 85 ,lng -140 SW +// Date: 6th Oct 2011 [sc74193] +//******************************************************************************* +// var defaultBounds = new google.maps.LatLngBounds( +// new google.maps.LatLng(36, -50), +// new google.maps.LatLng(85, -140)); +// var input = topaddressField; +// var options = { bounds: defaultBounds }; +// var autocomplete = new google.maps.places.Autocomplete(input, options); +// +//******************************************************************************* + + //This function call the google map API to generate the lat lng value. + //And pass all values to result page of branch locator section.[sc74193] + + function validatetopAddress() + { + + var addressField = oForm.elements["search-location"]; + + if(!addressField.value) { + + addressField.value = "Error: Please enter a valid location"; + + + return false; + } + + var topgeocoder = new google.maps.Geocoder(); + var address = addressField.value; + + topgeocoder.geocode({address: address, region: "CA"}, function(results, status) { + if (status == google.maps.GeocoderStatus.OK) { + searchLocationsNear(results[0].geometry.location); + } else { + addressField.value = "Error: Unable to find the specified address"; + return false; + } + });//end of funtion. + + function searchLocationsNear(center) { + + var topaddress = escape(addressField.value); + addressField.value = ""; + + var url = "http://maps.scotiabank.com/en/results.php" + "?address=" + topaddress + "&lat=" + center.lat() +"&lng=" + center.lng(); + + oForm.action = url; + oForm.submit(); + + return false; + } + return false; + } diff --git a/pool/shard006/JavaScript/0041692_AlongTheRiverOfGold.js b/pool/shard006/JavaScript/0041692_AlongTheRiverOfGold.js new file mode 100644 index 0000000000000000000000000000000000000000..f35a25a81678a2bc233130c13aee744dab9b2979 --- /dev/null +++ b/pool/shard006/JavaScript/0041692_AlongTheRiverOfGold.js @@ -0,0 +1,26 @@ +const ProvinceCard = require('../../provincecard.js'); +const { CardTypes } = require('../../Constants'); + +class AlongTheRiverOfGold extends ProvinceCard { + setupCardAbilities(ability) { + this.action({ + title: 'switch a character\'s base skills', + condition: () => this.game.currentConflict && this.game.currentConflict.conflictProvince.getElement() === 'water', + target: { + cardType: CardTypes.Character, + cardCondition: card => card.isParticipating() && !card.hasDash(), + gameAction: ability.actions.cardLastingEffect(context => ({ + effect: [ + ability.effects.modifyBaseMilitarySkill(context.target.basePoliticalSkill - context.target.baseMilitarySkill), + ability.effects.modifyBasePoliticalSkill(context.target.baseMilitarySkill - context.target.basePoliticalSkill) + ] + })) + }, + effect: 'switch {0}\'s military and political skill' + }); + } +} + +AlongTheRiverOfGold.id = 'along-the-river-of-gold'; + +module.exports = AlongTheRiverOfGold; diff --git a/pool/shard006/JavaScript/0041694_Chat.js b/pool/shard006/JavaScript/0041694_Chat.js new file mode 100644 index 0000000000000000000000000000000000000000..18bdfccec87eb6b9517fd5553e6124ef625f83a8 --- /dev/null +++ b/pool/shard006/JavaScript/0041694_Chat.js @@ -0,0 +1,79 @@ +const React = require('react'); + +const ChatStore = require('../../stores/chat-store.js'); + +const Tab = require('./Tab.js'); +const ChatWindow = require('./ChatWindow.js'); +const MessageComposer = require('./MessageComposer.js'); + +class Chat extends React.Component { + constructor(props) { + super(props); + + this.state = { + chats: ChatStore.getAll() + }; + + this._onChange = this._onChange.bind(this); + } + + _tabbedCount() { + let count = 0; + + for(const id in this.state.chats) { + if(this.state.chats[id].tabbed) { + count++; + } + } + + return count; + } + + _onChange() { + this.setState({ chats: ChatStore.getAll() }); + } + + _createTabs() { + const self = this; + + if(self._tabbedCount() > 0) { + const tabs = Object.keys(self.state.chats).map((id) => { + // 'id' is SteamID64 + if(self.state.chats[id].tabbed) { + return ; + } + }); + + return ( +
+ {tabs} +
+ ); + } + + return
; + } + + + componentDidMount() { + ChatStore.addChangeListener(this._onChange); + } + + componentWillUnmount() { + ChatStore.removeChangeListener(this._onChange); + } + + render() { + const tabs = this._createTabs(); + + return ( +
+ {tabs} + + +
+ ); + } +} + +module.exports = Chat; diff --git a/pool/shard006/JavaScript/0041695_validations.js b/pool/shard006/JavaScript/0041695_validations.js new file mode 100644 index 0000000000000000000000000000000000000000..490b42826ab4980a11513922e128fa89f011a81b --- /dev/null +++ b/pool/shard006/JavaScript/0041695_validations.js @@ -0,0 +1,102 @@ +//returns 0 if the integer is NOT valid +function checkInteger(inputInteger) { + let outputValue = inputInteger; + if (inputInteger == "") { + outputValue = 0; + } + if (inputInteger === undefined) { + outputValue = 0; + } + if (inputInteger == null) { + outputValue = 0; + } + if (!Number.isInteger(inputInteger)) { + outputValue = 0; + } + return outputValue; +} +//returns empty string if the string is NOT valid +function checkString(inputString) { + let outputText = inputString; + if (inputString === undefined) { + outputText = ""; + } + if (inputString == null) { + outputText = ""; + } + if (inputString == "") { + outputText = ""; + } + if (typeof inputString !== 'string') { + outputText = ""; + } + return outputText; +} +//returns / if the url is NOT valid +function checkURL(inputURL) { + let outputURL = inputURL; + if (inputURL === undefined) { + outputURL = "/"; + } + if (inputURL == null) { + outputURL = "/"; + } + if (inputURL == "") { + outputURL = "/"; + } + return outputURL; +} +//returns a "no-image" image if the image is NOT valid +function checkEmptyImage(inputEmptyImage) { + let outputEmptyImage = inputEmptyImage + if (inputEmptyImage === undefined) { + outputEmptyImage = "https://legacytaylorsville.com/wp-content/uploads/2015/07/No-Image-Available1.png" + } + if (inputEmptyImage == null) { + outputEmptyImage = "https://legacytaylorsville.com/wp-content/uploads/2015/07/No-Image-Available1.png" + } + if (inputEmptyImage == "") { + outputEmptyImage = "https://legacytaylorsville.com/wp-content/uploads/2015/07/No-Image-Available1.png" + } + return outputEmptyImage +} +//returns empty string if the email is NOT valid +function validateEmail(inputEmail) { + let outputEmail = inputEmail; + //basic email validation + let mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; + if (!inputEmail.match(mailformat)) { + outputEmail = "" + } + return outputEmail +} +//returns empty string if the username is NOT valid +function validateUsername(inputUsername) { + let outputUsername = inputUsername; + // only lowercase and uppercase letters and dash + let userformat = /^[a-zA-Z\-]+$/; + if (!inputUsername.match(userformat)) { + outputUsername = "" + } + return outputUsername +} +//returns empty string if the password is NOT valid +function validatePassword(inputPassword) { + let outputPassword = inputPassword; + // at least one number, one lowercase and one uppercase letter + // at least eight characters that are letters, numbers or the underscore + let passwordformat = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/; + if (!inputPassword.match(passwordformat)) { + outputPassword = "" + } + return outputPassword +} + +// how to use +console.log(checkInteger(25)); +console.log(checkString("hey")); +console.log(checkURL("google.com")); +console.log(checkEmptyImage("something.jpg")); +console.log(validateEmail("hey@gmail.com")); +console.log(validateUsername("Abcde-fg")); +console.log(validatePassword("Ab1234_6")); diff --git a/pool/shard006/JavaScript/0041700_clientSideValidation.js b/pool/shard006/JavaScript/0041700_clientSideValidation.js new file mode 100644 index 0000000000000000000000000000000000000000..f47c5b83e58e110e86e88ffb5eed4af7a34b26a0 --- /dev/null +++ b/pool/shard006/JavaScript/0041700_clientSideValidation.js @@ -0,0 +1,113 @@ +var coupons = ["nvojubmq", +"emph", +"sfwmjt", +"faopsc", +"fopttfsq", +"pxuttfsq"]; + + +function isValidCoupon(coupon) { + coupon = coupon.toUpperCase(); + for(var i=0; i= 0;i--){ + + for (j = 0;j + ) : ( + + )} +
+
+ {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 ( + + ); +}; 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')} + + +