code
stringlengths
2
1.05M
/** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ import { typedDependencies } from './dependenciesTyped.generated' import { createFilterTransform } from '../../factoriesNumber.js' export const filterTransformDependencies = { typedDependencies, createFilterTransform }
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Holodeck = require('../../../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../../../lib'); /* jshint ignore:line */ var client; var holodeck; describe('Member', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should generate valid fetch request', function(done) { holodeck.mock(new Response(500, {})); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch(); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var serviceSid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var channelSid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var sid = 'MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function(done) { var body = { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; holodeck.mock(new Response(200, body)); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid create request', function(done) { holodeck.mock(new Response(500, {})); var opts = {'identity': 'identity', 'xTwilioWebhookEnabled': 'true'}; var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.create(opts); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var serviceSid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var channelSid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members`; var values = {'Identity': 'identity', }; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, data: values })); var headers = {'X-Twilio-Webhook-Enabled': 'true'}; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, headers: headers })); } ); it('should generate valid create response', function(done) { var body = { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; holodeck.mock(new Response(201, body)); var opts = {'identity': 'identity'}; var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.create(opts); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should treat the first each arg as a callback', function(done) { var body = { 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'next_page_url': null, 'key': 'members' }, 'members': [ { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } ] }; holodeck.mock(new Response(200, body)); client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.each(() => done()); } ); it('should treat the second arg as a callback', function(done) { var body = { 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'next_page_url': null, 'key': 'members' }, 'members': [ { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } ] }; holodeck.mock(new Response(200, body)); client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.each({pageSize: 20}, () => done()); holodeck.assertHasRequest(new Request({ method: 'GET', url: 'https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members', params: {PageSize: 20}, })); } ); it('should find the callback in the opts object', function(done) { var body = { 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'next_page_url': null, 'key': 'members' }, 'members': [ { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } ] }; holodeck.mock(new Response(200, body)); client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.each({callback: () => done()}, () => fail('wrong callback!')); } ); it('should generate valid list request', function(done) { holodeck.mock(new Response(500, {})); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.list(); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var serviceSid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var channelSid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members`; holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function(done) { var body = { 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'next_page_url': null, 'key': 'members' }, 'members': [ { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': null, 'last_consumption_timestamp': null, 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:50Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } ] }; holodeck.mock(new Response(200, body)); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid read_empty response', function(done) { var body = { 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members?PageSize=50&Page=0', 'next_page_url': null, 'key': 'members' }, 'members': [] }; holodeck.mock(new Response(200, body)); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid remove request', function(done) { holodeck.mock(new Response(500, {})); var opts = {'xTwilioWebhookEnabled': 'true'}; var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove(opts); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var serviceSid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var channelSid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var sid = 'MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; var headers = {'X-Twilio-Webhook-Enabled': 'true'}; holodeck.assertHasRequest(new Request({ method: 'DELETE', url: url, headers: headers })); } ); it('should generate valid delete response', function(done) { var body = null; holodeck.mock(new Response(204, body)); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove(); promise.then(function(response) { expect(response).toBe(true); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid update request', function(done) { holodeck.mock(new Response(500, {})); var opts = {'xTwilioWebhookEnabled': 'true'}; var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var serviceSid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var channelSid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var sid = 'MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://ip-messaging.twilio.com/v2/Services/${serviceSid}/Channels/${channelSid}/Members/${sid}`; var headers = {'X-Twilio-Webhook-Enabled': 'true'}; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, headers: headers })); } ); it('should generate valid update_role_sid response', function(done) { var body = { 'sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'identity': 'jing', 'role_sid': 'RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'last_consumed_message_index': 20, 'last_consumption_timestamp': '2016-03-24T21:05:52Z', 'date_created': '2016-03-24T21:05:50Z', 'date_updated': '2016-03-24T21:05:51Z', 'attributes': '{}', 'url': 'https://ip-messaging.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; holodeck.mock(new Response(200, body)); var promise = client.ipMessaging.v2.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .members('MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); });
import BmiCalculator from './scripts/components/BmiCalculator.jsx'; export default BmiCalculator;
'use strict'; var _ = require('lodash'); var Page = require('./form-field-page'); var FormFieldResultsPage = Page.extend({ url: 'http://127.0.0.1:3000/form-fields-results', els: _.extend(Page.prototype.els, { 'radio-field': by.id('radio-field'), results: by.id('results') }) }); module.exports = FormFieldResultsPage;
const toUpper = (str) => { let newString = "" for (var letter of str) { var num = letter.charCodeAt() if ( num > 96 && num < 123 ) { num -= 32 newString += String.fromCharCode(num) } else { newString += letter } } return newString } export default toUpper
/** * Datasource for client-side grouping of an in-memory datasource. */ define(['../utils'], function (utils) { function GroupingDataSource(delegate, options) { utils.Evented.apply(this); this.delegate = delegate; this.options = options; for (var x in this.delegate) { if (!this[x] && (typeof this.delegate[x] === "function")) { this[x] = this.delegate[x].bind(this.delegate); } } this.passthroughFrom(delegate, "datachanged"); delegate.on("dataloaded", this.load.bind(this)); this.groups = []; utils.passthrough(this, delegate, ['commitRow','startEdit','rollbackRow','replace']); } GroupingDataSource.prototype = { load: function () { this.updateView(); }, getRecordCount: function() { return this.delegate.recordCount(); }, getRootNodes: function(start, end) { return this.view.slice(start || 0, end); }, children: function(row, start, end) { switch(arguments.length) { case 1: return row.children; case 2: return row.children.slice(start); case 3: return row.children.slice(start, end); } }, countRootNodes: function() { return this.view.length; }, countChildren: function(row) { return row.recordCount; }, filter: function(settings, predicate) { this.filterPredicate = predicate; this.updateView(); }, _applySorting: function(nodes) { nodes.sort(this.sortComparator); if(nodes.length && nodes[0].groupRow === true) { for(var x=0,l=nodes.length;x<l;x++) { this._applySorting(nodes[x].children); } } }, sort: function(comparator, settings) { var self = this; this.sortComparator = comparator; if(this.view) { this._applySorting(this.view); this.trigger('dataloaded'); } }, updateView: function () { var ds = this; var groupRows = this.groupRows = {}; var rowToGroupMap = {}; var DISCARD_GROUP = {}; this.parentByIdMap = {}; function group(nodes, groupings, parentGroupId, level) { if (groupings && groupings.length) { var groupMap = {}, groups = [], col = groupings[0], groupProjection = col.groupProjection && col.groupProjection(nodes), nextGroupings = groupings.slice(1); for (var x = 0, l = nodes.length; x < l; x++) { var baseValue = utils.getValue(nodes[x], col.key); var g = groupProjection ? groupProjection(baseValue) : baseValue; var r = groupMap[g]; if(r === DISCARD_GROUP) { continue; } if(ds.filterPredicate) { var filterResult = ds.filterPredicate(nodes[x]); if(filterResult < 0) { if(r) { groups.splice(groups.indexOf(r), 1); } groupMap[g] = DISCARD_GROUP; continue; } else if(filterResult == 0) { continue; } } if (!r) { groups.push(groupMap[g] = r = { groupRow: true, id: parentGroupId + g + ":", description: g, children: [], _groupColumn: col, _groupLevel: level, parent: level > 0 ? parentGroupId : null }); r[col.key] = baseValue; } r.children.push(nodes[x]); ds.parentByIdMap[nodes[x].id] = r; groupRows[r.id] = r; } groups = groups.filter(function(g) { return g !== DISCARD_GROUP; }); for (var x = 0, l = groups.length; x < l; x++) { groups[x].recordCount = ds.groupRecordCount(groups[x]); groups[x].children = group(groups[x].children, nextGroupings, groups[x].id, level + 1); ds.processGroup(groups[x]); } groups.sort(this.comparator); return groups; } else { for (var x = 0, l = nodes.length; x < l; x++) { rowToGroupMap[nodes[x].id] = parentGroupId; } if(ds.filterPredicate) { nodes = nodes.filter(ds.filterPredicate); } return nodes; } } if(this.groups && this.groups.length) { this.view = group(this.delegate.getData(), this.groups, "group:", 0); } else { this.view = this.delegate.getData().filter(function(row) { return !ds.filterPredicate || ds.filterPredicate(row) > 0; }); } if(this.sortComparator) { this._applySorting(this.view); } this.trigger("dataloaded"); }, groupRecordCount: function (group) { return group.children.length; }, group: function (groupings) { this.groups = groupings; if (this.isReady()) { this.updateView(); } }, getRecordById: function (id) { return this.groupRows[id] || this.delegate.getRecordById(id); }, recordCount: function () { this.assertReady(); return this.view.length; }, isReady: function () { return this.view !== undefined; }, assertReady: function () { if (!this.isReady()) { throw "Datasource not ready yet"; } }, parent: function (row) { var parentRow = this.parentByIdMap[row.id]; if(parentRow) { return parentRow.id; } }, hasChildren: function (row) { var groupRow = this.groupRows[row.id]; if (groupRow) { return groupRow.children && groupRow.children.length > 0; } else { return false; } }, /** * Invoked after a group is created, for optional postprocessing in a subclass. * @param group the group that was created */ processGroup: function(group) { }, hasSubView: function(record) { if(record.groupRow) { return false; } else if(typeof this.delegate.hasSubView === 'function') { return this.delegate.hasSubView(record); } }, /** * Returns the whole data set, ordered and filtered, but without regard for grouping. * @returns {*} */ queryForExport: function() { var data = this.delegate.getData(); if(this.filterPredicate) { data = data.filter(this.filterPredicate); } else { data = ([]).concat(data); } if(this.sortComparator) { data.sort(this.sortComparator); } return data; } }; return GroupingDataSource; });
require(["jQuery"],function(t){t(function(){var n=0,o=4,s=t("main .row a");setInterval(function(){t(".smoke").css({backgroundPosition:"0"+(n-=o)+"px"})},30),t(".jumbotron").mouseover(function(){t(this).css("backgroundPosition","0 -300px"),o=8}).mouseout(function(){t(this).css("backgroundPosition","0 0"),o=4}),t("[desc]").bind("mouseover",function(){var n=t(this),o=n.attr("desc");n.data("name",n.html()),""==o?0:n.html(o)}).bind("mouseout",function(){var n=t(this);n.attr("desc",n.html()),n.html(n.data("name"))}),t("[data-select]").bind("click",function(){s.css("display","none"),t(t(this).attr("data-select")).css("display","block")})})});
// MIT © 2017 azu "use strict"; const TextLintTester = require("textlint-tester"); const tester = new TextLintTester(); // rule const rule = require("../src/textlint-rule-google-possessives"); const defaultMessage = require("../src/textlint-rule-google-possessives").defaultMessage; // ruleName, rule, { valid, invalid } tester.run("textlint-rule-google-possessives", rule, { valid: [ "Each component has its own set of traits.", "This is business's book.", "alias's", "application's", "business's", "class's", "customer's", "Elvis's", "Liz's", "user's ", // singular "users'", // plural, "Elise Williams's", "the Williamses'", "women's" // < ], invalid: [ { text: "businesses's", errors: [ { index: 0 } ] }, { text: "Buzz'", errors: [ { index: 0 } ] }, { text: "Carlos'", errors: [ { index: 0, message: defaultMessage } ] }, { text: "class'", errors: [ { index: 0, message: defaultMessage } ] }, { text: "examples's", errors: [ { index: 0, message: defaultMessage } ] }, { text: "users's", errors: [ { index: 0, message: defaultMessage } ] }, { text: "values's", errors: [ { index: 0, message: defaultMessage } ] } ] });
'use strict'; var mongoose = require('mongoose'), Announcements = mongoose.model('Announcements'), Users = mongoose.model('User'), _ = require('lodash'); exports.create = function (req, res) { //create a new announcement var announcement = new Announcements(req.body); announcement.save(function(err) { if (err) { console.log(err); res.status(400).send(err); } else { res.json(announcement); } }); }; exports.listAll = function(req,res){ Announcements.find().exec(function(err,Announcements){ if(err){ return res.status(400).send(err); } else{ res.json(Announcements); } }); }; exports.listOne = function(req,res){ var announcement = req.announcement; res.json(announcement); }; exports.announcementByID = function(req,res,next,id){ if(!mongoose.Types.ObjectId.isValid(id)){ return res.status(400).send({ message:'AnnouncmentID is invalid' }); } Announcements.findById(id).populate('user','displayName').exec(function(err,announcement){ if(err){ return next(err); } else if(!announcement){ return res.status(404).send({ message:'No announcement with that id was found' }); } req.announcement = announcement; next(); }); }; exports.update = function(req,res){ var annoucement = req.announcement; annoucement.title = req.body.title; annoucement.message = req.body.message; annoucement.save(function(err){ if(err){ console.log(err); res.status(400).send(err); } else{ res.json(annoucement); } }); }; exports.delete = function (req, res) { var announcement = req.announcement; announcement.remove(function(err) { if(err){ res.status(400).send(err); } else { res.end(); } }); };
import fixture from 'can-fixture'; const store = fixture.store([{ id: 0, description: 'First item' }, { id: 1, description: 'Second item' }]); fixture({ 'GET /roomplan': store.findAll, 'GET /roomplan/{id}': store.findOne, 'POST /roomplan': store.create, 'PUT /roomplan/{id}': store.update, 'DELETE /roomplan/{id}': store.destroy }); export default store;
export {default as transform} from "./src/d3-transform"
'use strict'; var chai = require("chai"), sinon = require("sinon"), sinonChai = require("sinon-chai"), async = require('async'), _ = require('lodash'), request = require('supertest'); var expect = chai.expect; chai.use(sinonChai); /************************************************************************** * Begin of tests *************************************************************************/ var app = require('../../app'); var User = require('../../lib/models/user/user.model'); var UserMocks = require('../../lib/models/user/user.mocks'); var jwt = require('../../lib/jwt'); var jsonwebtoken = require('jsonwebtoken'); var config = require('../../config'); describe('api.auth.login', function() { describe('POST /api/auth/login', function () { var user; beforeEach(function (done) { User.remove({}, done); }); beforeEach(function (done) { user = new User(UserMocks.localDummy1); user.save(done); }); it('should return a new identity, access and refresh token for a valid login', function (done) { request(app) .post('/api/auth/login') .send({ email: UserMocks.localDummy1.identities.local.email, password: UserMocks.localDummy1.identities.local.secret }) .expect(200) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(Object.keys(res.body)).to.have.length(3); expect(res.body).to.contain.keys('it', 'at', 'rt'); async.series([ function (done) { var data = jsonwebtoken.verify(res.body.it, config.jwt.tokenSecret, { issuer: config.jwt.issuer, audience: config.jwt.audience, algorithm: config.jwt.algorithm }); expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud', 'identities'); expect(Object.keys(data)).to.have.length(6); done(); }, function (done) { var data = jsonwebtoken.verify(res.body.at, config.jwt.tokenSecret, { issuer: config.jwt.issuer, audience: config.jwt.audience, algorithm: config.jwt.algorithm }); expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud'); expect(Object.keys(data)).to.have.length(5); done(); }, function (done) { jwt.verifyRefreshToken(res.body.rt, function (err, data) { expect(err).to.not.exist; expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud'); done(err); }); } ], done); }); }); it('should send 401 when invalid credentials are sent', function (done) { request(app) .post('/api/auth/login') .send({ email: UserMocks.localDummy1.identities.local.email, password: 'wrongpassword' }) .expect(401) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(res.body).to.have.a.property('name', 'InvalidCredentialsError'); expect(res.body).to.have.a.property('message', 'Invalid credentials'); done() }) }); it('should handle weird requests', function (done) { request(app) .post('/api/auth/login') .send({ email: {'$or': [{1: 1}]}, password: {} }) .expect(422) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(res.body).to.have.a.property('name', 'ValidationError'); expect(res.body).to.have.a.property('message', 'Validation failed'); expect(res.body).to.have.a.deep.property('errors.email.kind', 'string.base'); expect(res.body).to.have.a.deep.property('errors.password.kind', 'string.base'); done() }) }); }); });
window.jQuery = window.$ = require("jquery"); require('foundation-sites/dist/js/foundation'); $(document).ready(function() { $(document).foundation(); /* $(document).foundation({ orbit: { animation: 'slide', timer_speed: 1000, pause_on_hover: true, animation_speed: 500, navigation_arrows: true, bullets: false } });*/ }); require('highlight.js/styles/railscasts.css'); require(['highlight.js/lib/highlight'], function(hljs) { hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash')); hljs.registerLanguage('cpp', require('highlight.js/lib/languages/cpp')); hljs.registerLanguage('cmake', require('highlight.js/lib/languages/cmake')); hljs.registerLanguage('java', require('highlight.js/lib/languages/java')); hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript')); hljs.registerLanguage('json', require('highlight.js/lib/languages/json')); hljs.registerLanguage('python', require('highlight.js/lib/languages/python')); hljs.initHighlightingOnLoad(); }); require('react-tagsinput/react-tagsinput.css'); require('fixed-data-table/dist/fixed-data-table.css');
version https://git-lfs.github.com/spec/v1 oid sha256:9a4c3800bcc1ce9138f70f63505cbb97b03c59b9441071aadf6fed8976be5df4 size 3696
var Type = require("@kaoscript/runtime").Type; module.exports = function() { function foobar() { } function quxbaz() { let x, __ks_0; if(Type.isValue(__ks_0 = foobar()) ? (x = __ks_0, false) : true) { throw new Error(); } return x.y; } };
define( [ "ui/loading/loading" ], function() { "use strict"; /** * example: * <s-loading class="global"></s-loading> * */ angular.module( "$ui.loading", [] ) .directive( "sLoading", function() { function link( $scope, $element, $attrs ) { var loading; $scope.controller = loading = $( $element ).loading(); if ( [ "1", "true" ].indexOf( $attrs.autoShow ) !== -1 ) { loading.show(); } } return { scope : { controller : "=", autoShow : "@" }, template : "<div class='ui loading'></div>", replace : true, restric : "E", link : link }; } ); } );
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. /** * Flagship class * * 設計: * * domへのattachと、data、optionの変更というinterface * dataが追加される / optionが変更されると、updateが呼ばれる * updateはdomにattachされていない状態でも失敗はしない * * @constructor */ function Flagship(graphSelector, tableSelector, dashboard) { /** * Constants / Configurations * */ // datasource url this.api = "/dashboard/api/flagship.json"; // select this.graph = undefined; this.table = undefined; this.dashboard = dashboard; // data holder this.data = undefined; if (this.dashboard) { this.margin = {top: 20, right: 20, bottom: 40, left: 100}; this.width = 540 - this.margin.left - this.margin.right; this.height = 230 - this.margin.top - this.margin.bottom; } else { this.margin = {top: 20, right: 20, bottom: 40, left: 100}; this.width = 1170 - this.margin.left - this.margin.right; this.height = 500 - this.margin.top - this.margin.bottom; } // d3 elements this.time_scale = d3.time.scale(); this.count_scale = d3.scale.linear() .range([this.height, 0]); this.color_scale = d3.scale.category20(); this.attachTo(graphSelector, tableSelector); this.load(); } /** * attachTo * */ Flagship.prototype.attachTo = function(graphSelector, tableSelector) { this.dateformat = d3.time.format('%Y/%m/%d'); if (graphSelector) { this.graph = d3.select(graphSelector); // clear this.graph.selectAll("div").remove(); var barchart = this.graph.append("div").attr("class", "tab-pane active").attr("id", "barchart").append("svg") .attr("width", this.width + this.margin.left + this.margin.right) .attr("height", this.height + this.margin.top + this.margin.bottom) .attr("class", "barchart") .append("g") .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")"); // initialize tooltip this.tooltip = this.graph .append("div") .style("position", "absolute") .style("z-index", "10") .style("visibility", "hidden") .text("a simple tooltip") .attr("class", "data-tooltip"); } else { this.graph = undefined; } if (tableSelector) { this.table = d3.select(tableSelector); // clear this.table.selectAll("table").remove(); var month_table = this.table.append("table").attr("class", "table table-bordered"); month_table.append("thead"); month_table.append("tfoot"); month_table.append("tbody"); } else { this.table = undefined; } } /** * load data * * @param {string} file * */ Flagship.prototype.load = function() { var self = this; var since = $("#since").val() || '2014-04-01'; var until = $("#until").val() || '2015-03-31'; var split = $("#split").val() || 'month'; var group = $("#group").val() || 'account'; this.since = since; this.until = until; this.split = split; this.group = group; d3.json(this.api + "?split=" + split + "&group=" + group + "&since=" + since + "&until=" + until, function(response) { self.data = response; self.update(); }); } /** * update visualize * * @param {Object} data * */ Flagship.prototype.update = function() { var format = d3.format(".2f"); var self = this; if(this.graph) { /* * barchart */ var duration = 1000; var stack = d3.layout.stack() .values(function(d) {return d.counts}) .x(function(d) {return d.until}) .y(function(d) {return d.count}); var since = $("#since").val() || '2014-04-01'; var until = $("#until").val() || '2015-03-31'; var split = $('#split').val() || 'month'; var zoom = $('#scale-checkbox').prop('checked'); var exclude = $('#exclude-checkbox').prop('checked') if (exclude) { console.log(this.data) var layers = stack(this.data.filter(function(e) { if (e.account == 'leicay') return false; else return true; })); } else { var layers = stack(this.data); } var dateformat = d3.time.format("%Y-%m-%d"); var num = this.data[0].counts.length; this.barWidth = this.width / (num + 1) * 0.8; this.time_scale .domain([dateformat.parse(since), dateformat.parse(until)]) .range([this.barWidth / 2 / 0.8, this.width - this.barWidth / 2 / 0.8]); if (zoom) { this.count_scale.domain([0, 2000]) } else { this.count_scale.domain([0, d3.max(layers, function(d) { return d3.max(d.counts, function(d) { return d.y0 + d.y}) })]) } var time_axis = d3.svg.axis() .scale(this.time_scale) .orient("bottom"); if(this.dashboard) { time_axis.tickFormat(d3.time.format('%-m')); } else { if (split == 'year') { time_axis.tickFormat(d3.time.format('%Y')); } else if (split == 'quarter') { time_axis.tickFormat(d3.time.format('%Y/%m')); } else if (split == 'month') { time_axis.tickFormat(d3.time.format('%Y/%m')); } else if (split == 'week') { time_axis.tickFormat(d3.time.format('%Y/%m/%d')); } else if (split == 'day') { time_axis.tickFormat(d3.time.format('%Y/%m/%d')); } // ticks var tickValues = []; this.data[0].counts.forEach(function(d) { console.log(d); tickValues.push(new Date(Date.parse(d.from))); }); if (tickValues.length < 20) { time_axis.tickValues(tickValues); } else { } } this.count_axis = d3.svg.axis() .scale(this.count_scale) .orient("left"); this.graph.select("svg.barchart").selectAll("g.x.axis").data(['']).enter().append("g") .attr("class", "x axis") .attr("transform", "translate(" + this.margin.left + "," + (this.height + this.margin.top )+ ")"); this.graph.select("svg.barchart g.x.axis") .call(time_axis); var yAxis = this.graph.select("svg.barchart").selectAll("g.y.axis").data(['']); yAxis.transition() .duration(duration) .call(this.count_axis); yAxis.enter().append("g") .attr("class", "y axis") .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")") .call(this.count_axis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .attr("text-anchor", "end") .text("Views"); this.graph.selectAll("svg.barchart g .layer").remove(); var layer = this.graph.select("svg.barchart g").selectAll(".layer") .data(layers) .enter().append("g") .attr("class", "layer") .style("fill", function(d, index) { return self.color_scale(index); }); var rect = layer.selectAll("rect") .data(function(d) { return d.counts.map(function(element) { element.label = d.label; element.account = d.account; element.service = d.service; return element; }) }) .enter().append("rect") .on("mouseover", function(d) { d3.select(this).transition().style("opacity", "0.8"); self.tooltip.style("visibility", "visible"); self.tooltip.html("<strong>" + d.label + "</strong><br />from " + d.account + " @ " + d.service + "<br />" + self.dateformat(new Date(d.from)) + " : " + d.count + " Views" ); }) .on("mousemove", function(d) { self.tooltip.style("top", (d3.event.pageY - 10) + "px") .style("left",(d3.event.pageX + 10) + "px"); }) .on("mouseout", function(d) { d3.select(this).transition().style("opacity", "1"); self.tooltip.style("visibility", "hidden"); }) this.graph.select("svg.barchart g").selectAll(".layer") .selectAll("rect") .transition() .duration(duration) .attr("x", function(d) { return self.time_scale(Date.parse(d.from)) - self.barWidth / 2 }) .attr("y", function(d) { return self.count_scale(d.y0 + d.y); }) .attr("width", function(d) { return self.barWidth }) .attr("height", function(d) { return self.count_scale(d.y0) - self.count_scale(d.y0 + d.y); }) } if(this.table) { var thead_tr = self.table.select("table thead").selectAll("tr").data([""]).enter().append("tr"); thead_tr.append("th").text("項目"); var th_item = self.table.select("table thead tr").selectAll("th.item").data(self.data[0].counts); th_item.enter().append("th").attr("class", "item"); th_item.exit().remove(); th_item.text(function(d) { return self.dateformat(new Date(d.from)); }); var tr = self.table.select('table tbody').selectAll("tr").data(self.data); tr.enter().append("tr").append("th"); tr.exit().remove(); tr.select('th').text(function(d) { return d.label; }); var td = tr.selectAll("td").data(function(d) { return d.counts; }); td.enter().append("td").classed("amount", true); td.exit().remove(); td.text(function(d) { return d.count; }); } } Flagship.prototype.change = function() { this.update(); }
import { getOrFetchEvents, getOrFetchEventsSuccess, getOrFetchEventsError } from 'actions/events'; import api from 'services/api'; import {eventsNormalizr} from 'utils/normalize'; export function getOrFetchEventsFlow(){ return function (dispatch){ dispatch(getOrFetchEvents()); api.fetchEvents() .then(({data}={})=>{ data = eventsNormalizr(data); dispatch(getOrFetchEventsSuccess(data)); }).catch(function (error) { dispatch(getOrFetchEventsError(error)); }); }; }
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define("require exports ../../../../core/tsSupport/declareExtendsHelper ../../../../core/tsSupport/decorateHelper ../../../../core/Accessor ../../../../core/Evented ../../../../core/MapUtils ../../../../core/mathUtils ../../../../core/maybe ../../../../core/accessorSupport/decorators ./Texture ../../../support/Scheduler ../../../webgl/Texture".split(" "),function(h,f,v,m,w,x,r,y,n,k,z,A,B){Object.defineProperty(f,"__esModule",{value:!0});h=function(h){function b(a){a=h.call(this,a)||this;a.events= new x;a.glTexture=null;a.dirty=!1;a.needsClear=!1;a.elementsToAddOrUpdate=new Map;a.elementsToRemove=new Map;a.elementsToRender=new Map;a.elements=new Map;a.stageObjects=new Map;return a}v(b,h);f=b;b.prototype.initialize=function(){this.id=z.idGen.gen(this.idHint);this.stage=this.view._stage;this.canvas=this.create2DCanvas();this.ctx=this.canvas.getContext("2d");this.stage.add(4,this);var a=this.computeAtlasResolution(this.view.width,this.view.height);this.createAtlasRegion(a);this.update2DCanvasSize(); this.resetAtlasCursor()};b.prototype.unload=function(){n.isSome(this.glTexture)&&(this.glTexture.dispose(),this.glTexture=null);this.events.emit("unloaded")};Object.defineProperty(b.prototype,"width",{get:function(){return this.atlas.size.width},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"height",{get:function(){return this.atlas.size.height},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"requiresFrameUpdates",{get:function(){return!1},enumerable:!0,configurable:!0}); b.prototype.createDescriptor=function(a){return{target:3553,pixelFormat:6408,dataType:5121,wrapMode:33071,flipped:!0,samplingMode:9987,hasMipmap:!0,preMultiplyAlpha:!0,maxAnisotropy:a.parameters.maxMaxAnisotropy}};b.prototype.load=function(a){var c=this;if(n.isSome(this.glTexture))return this.glTexture;this.glTexture=new B(a,this.createDescriptor(a),this.canvas);this.frameWorker=this.view.resourceController.scheduler.registerTask(A.Task.TEXT_TEXTURE_ATLAS,function(a){return c.run(c.makeRunContext(a))}, function(){return c.dirty});this.setDirty();return this.glTexture};b.prototype.dispose=function(){this.elementsToRender=this.elementsToRemove=this.elementsToAddOrUpdate=this.elements=null;this.frameWorker&&(this.frameWorker.remove(),this.frameWorker=null);this.glTexture&&(this.glTexture=null,this.stage.remove(4,this.id));this.canvas.width=0;this.canvas.height=0;this.ctx=this.canvas=null};b.prototype.create2DCanvas=function(){var a=document.createElement("canvas");a.setAttribute("id","canvas2d");a.setAttribute("style", "display:none");a.setAttribute("width",(512).toString());a.setAttribute("height",(512).toString());return a};b.prototype.update2DCanvasSize=function(){this.canvas.setAttribute("width",this.atlas.size.width.toString());this.canvas.setAttribute("height",this.atlas.size.height.toString())};b.prototype.createAtlasRegion=function(a){void 0===a&&(a=512);this.atlas={size:{width:a,height:a},cursor:{x:0,y:0},lineHeight:0}};b.prototype.computeAtlasResolution=function(a,c){a=Math.max(a,c);a=y.nextHighestPowerOfTwo(a+ 256);return a=Math.min(a,4096)};b.prototype.resizeAtlas=function(a,c){c=c||a;var d=this.atlas;d.size.width=a;d.size.height=c;n.isSome(this.glTexture)&&this.glTexture.resize(a,c);this.update2DCanvasSize()};b.prototype.resetAtlasCursor=function(){var a=this.atlas;a.cursor.x=l;a.cursor.y=l+t;a.lineHeight=0;this.needsClear=!0};b.prototype.getAtlasUsage=function(){var a=this.atlas;return(a.cursor.x+a.cursor.y*a.size.width)/(a.size.width*a.size.height)};b.prototype.getExpectedAtlasUsage=function(){var a= this.elementsToRemove.size,c=this.elementsToAddOrUpdate.size,d=this.elements.size;return this.getAtlasUsage()/d*(d+c-a)};b.prototype.addAtlasElement=function(a,c,d,b){var e=this.atlas,g=a.textRenderer,u=g.renderedWidth,f=g.renderedHeight,h=g.displayWidth,g=g.displayHeight;a.placement.offset.x=e.cursor.x;a.placement.offset.y=e.cursor.y;a.placement.size.width=u;a.placement.size.height=f;a.placement.size.displayWidth=h;a.placement.size.displayHeight=g;a.placement.uvMinMax=[a.placement.offset.x/e.size.width, 1-(a.placement.offset.y+f)/e.size.height,(a.placement.offset.x+u)/e.size.width,1-a.placement.offset.y/e.size.height];e.cursor.x+=d;e.lineHeight=Math.max(e.lineHeight,b);this.elements.set(c,a)};b.prototype.removeAtlasElement=function(a){if(a&&this.elements.has(a.textId)){var c=a.placement.offset,d=a.placement.size;this.ctx.clearRect(c.x,c.y,d.width,d.height);this.elements.delete(a.textId)}};b.prototype.ensureStageObjects=function(a){var c=this.stageObjects.get(a);if(c)return c;c=new Set;this.stageObjects.set(a, c);return c};b.prototype.addStageObject=function(a,c){this.ensureStageObjects(a).add(c)};b.prototype.removeStageObject=function(a,c){(a=this.stageObjects.get(a))&&a.delete(c)&&(c.geometries[0].data.vertexAttributes.size.data=new Float32Array([0,0]),c.geometryVertexAttrsUpdated(0))};b.prototype.processAdditionRequest=function(a,c){var d=this.atlas,b=a.textId,e=a.textRenderer.renderedWidth+l,p=a.textRenderer.renderedHeight+l+t;c=c.repackingEnabled;if(d.cursor.x+e<d.size.width&&d.cursor.y+p<d.size.height)this.addAtlasElement(a, b,e,p),this.elementsToRender.set(b,a),this.elementsToAddOrUpdate.delete(b);else if(d.cursor.y+p+d.lineHeight<d.size.height)d.cursor.x=l,d.cursor.y+=d.lineHeight,d.lineHeight=0,this.addAtlasElement(a,b,e,p),this.elementsToRender.set(b,a),this.elementsToAddOrUpdate.delete(b);else{a=this.getExpectedAtlasUsage();(b=.85<a&&4096>d.size.width)&&this.resizeAtlas(2*d.size.width,2*d.size.height);if(!c||!b&&.95<a&&4096===d.size.width)return this.processRemovals(),0;this.repack();return 1}return 0};b.prototype.processRemovals= function(){var a=this;this.elementsToRemove.forEach(function(c,d){var b=a.stageObjects.get(d);b&&0!==b.size||a.removeAtlasElement(c);b&&0===b.size&&a.stageObjects.delete(d)});this.elementsToRemove.clear()};b.prototype.repack=function(){var a=this;this.processRemovals();this.elements.forEach(function(c,b){c.rendered=!1;a.elementsToAddOrUpdate.set(b,c)});this.elements.clear();this.resetAtlasCursor();this.elementsToRender.clear()};b.prototype.processRenderingRequest=function(a){this.ctx.clearRect(a.placement.offset.x, a.placement.offset.y,a.placement.size.width,a.placement.size.height);a.textRenderer.render(this.ctx,a.placement.offset.x,a.placement.offset.y);var c=this.stageObjects.get(a.textId);c&&c.forEach(function(c){c.geometries[0].data.vertexAttributes.uv0.data=new Float32Array(a.placement.uvMinMax);c.geometries[0].data.vertexAttributes.size.data=new Float32Array([a.placement.size.displayWidth,a.placement.size.displayHeight]);c.geometryVertexAttrsUpdated(0)});a.rendered=!0};b.prototype.run=function(a){var c= this;if(this.glTexture){var b=a.budget,g=!1;r.someMap(this.elementsToAddOrUpdate,function(b,d){return(b=c.elements.get(d))&&b.rendered?((b=c.stageObjects.get(d))&&b.forEach(function(a){var b=a.geometries[0].data.vertexAttributes,e=c.elements.get(d);b.uv0.data=new Float32Array(e.placement.uvMinMax);b.size.data=new Float32Array([e.placement.size.displayWidth,e.placement.size.displayHeight]);a.geometryVertexAttrsUpdated(0)}),c.elementsToAddOrUpdate.delete(d),!1):1===c.processAdditionRequest(c.elementsToAddOrUpdate.get(d), a)?g=!0:!1});if(g)a.budget=null,a.repackingEnabled=!1,this.run(a);else{var e=!1;0<this.elementsToRender.size&&this.needsClear&&(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.needsClear=!1);r.someMap(this.elementsToRender,function(a,d){c.processRenderingRequest(a);c.elementsToRender.delete(d);e=!0;return b&&(b.madeProgress(),b.done)?!0:!1});e&&n.isSome(this.glTexture)&&this.glTexture.setData(this.canvas);this.dirty=0<this.elementsToRender.size;this.dirty||(f.test.orderedRepackingEnabled&& this.repackOrdered(),this.notifyChange("updating"))}}};b.prototype.makeRunContext=function(a){void 0===a&&(a=null);q.budget=a;q.repackingEnabled=!0;return q};b.prototype.addTextTexture=function(a,b){var c=a.key;this.elementsToAddOrUpdate.has(c)||this.elementsToAddOrUpdate.set(c,{textId:c,placement:{offset:{x:0,y:0},size:{width:0,height:0,displayWidth:0,displayHeight:0},uvMinMax:[]},textRenderer:a,rendered:!1});this.addStageObject(c,b);this.elementsToRemove.delete(c);this.setDirty()};b.prototype.removeTextTexture= function(a,b){a=a.key;this.elementsToRemove.set(a,this.elements.get(a));this.removeStageObject(a,b)};Object.defineProperty(b.prototype,"textureId",{get:function(){return this.id},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"isDirty",{get:function(){return this.dirty},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"updating",{get:function(){return this.dirty&&!!this.frameWorker},enumerable:!0,configurable:!0});b.prototype.setDirty=function(){this.dirty||(this.dirty= !0,this.notifyChange("updating"))};Object.defineProperty(b.prototype,"test",{get:function(){var a=this;return{elements:this.elements,stageObjects:this.stageObjects,elementsToRemove:this.elementsToRemove,atlas:this.atlas,resizeAtlas:function(b,d){return a.resizeAtlas(b,d)},run:function(b){return a.run(b)}}},enumerable:!0,configurable:!0});b.prototype.repackOrdered=function(){if(0!==this.elements.size){var a=[];this.elements.forEach(function(b,c){return a.push({element:b,key:c})});for(var b=!0,d=0;d< a.length-1;d++)if(0<a[d].key.localeCompare(a[d+1].key)){b=!1;break}if(!b){a.sort(function(a,b){return a.key.localeCompare(b.key)});this.elements.clear();for(b=0;b<a.length;b++)d=a[b],this.elements.set(d.key,d.element);this.repack();this.setDirty()}}};var f;b.test={orderedRepackingEnabled:!1};m([k.property({constructOnly:!0})],b.prototype,"idHint",void 0);m([k.property({constructOnly:!0})],b.prototype,"view",void 0);m([k.property({type:Boolean,readOnly:!0})],b.prototype,"updating",null);return b=f= m([k.subclass("esri.views.3d.webgl-engine.lib.TextTextureAtlas")],b)}(k.declared(w));f.TextTextureAtlas=h;var l=2,t=2,q={budget:null,repackingEnabled:!0};f.default=h});
(function ($) { $.fn.pBar = function (params) { var params = $.extend({ min: 0, max: 60, val: 50, tooltip: "Restan % días" }, params); var objs = $(this); var o = null; var wdt = 0; $.each(objs, function () { o = $(this); min = (typeof (o.data("min")) != "undefined") ? o.data("min") : min; max = (typeof (o.data("max")) != "undefined") ? o.data("max") : max; val = (typeof (o.data("val")) != "undefined") ? o.data("val") : val; var gray = $("<span />"); var label = $("<label />"); wdt = (((val * 100) / max)); gray.css({ width: wdt + "%" }); gray.addClass((wdt == 100) ? "empty" : (wdt >= 90 && wdt < 100) ? "full" : (wdt >= 70 && wdt < 90) ? "warning" : "ok"); label.text(max - val); if (params.tooltip != null) label.attr("title", params.tooltip.replace("%", max - val)); gray.appendTo(o); label.appendTo(o); }); return objs; } }(jQuery));
(function () { /** * The default state core singleton for {@link SceneJS.Flags} nodes */ var defaultCore = { stateId: SceneJS._baseStateId++, type: "flags", picking: true, // Picking enabled clipping: true, // User-defined clipping enabled enabled: true, // Node not culled from traversal transparent: false, // Node transparent - works in conjunction with matarial alpha properties backfaces: true, // Show backfaces frontface: "ccw", // Default vertex winding for front face reflective: true, // Reflects reflection node cubemap, if it exists, by default. solid: false, // When true, renders backfaces without texture or shading, for a cheap solid cross-section effect solidColor: [1.0, 1.0, 1.0],// Solid cap color skybox: false, // Treat as a skybox hash: "refl;;;" }; var coreStack = []; var stackLen = 0; SceneJS_events.addListener( SceneJS_events.SCENE_COMPILING, function (params) { params.engine.display.flags = defaultCore; stackLen = 0; }); /** * @class Scene graph node which sets rendering mode flags for its subgraph * @extends SceneJS.Node */ SceneJS.Flags = SceneJS_NodeFactory.createNodeType("flags"); SceneJS.Flags.prototype._init = function (params) { if (this._core.useCount == 1) { // This node is first to reference the state core, so sets it up this._core.picking = true; // Picking enabled this._core.clipping = true; // User-defined clipping enabled this._core.enabled = true; // Node not culled from traversal this._core.transparent = false; // Node transparent - works in conjunction with matarial alpha properties this._core.backfaces = true; // Show backfaces this._core.frontface = "ccw"; // Default vertex winding for front face this._core.reflective = true; // Reflects reflection node cubemap, if it exists, by default. this._core.solid = false; // Renders backfaces without texture or shading, for a cheap solid cross-section effect this._core.solidColor = [1.0, 1.0, 1.0 ]; // Solid cap color this._core.skybox = false; // Treat as a skybox if (params.flags) { // 'flags' property is actually optional in the node definition this.setFlags(params.flags); } } }; SceneJS.Flags.prototype.setFlags = function (flags) { var core = this._core; if (flags.picking != undefined) { core.picking = !!flags.picking; this._engine.display.drawListDirty = true; } if (flags.clipping != undefined) { core.clipping = !!flags.clipping; this._engine.display.imageDirty = true; } if (flags.enabled != undefined) { core.enabled = !!flags.enabled; this._engine.display.drawListDirty = true; } if (flags.transparent != undefined) { core.transparent = !!flags.transparent; this._engine.display.stateSortDirty = true; } if (flags.backfaces != undefined) { core.backfaces = !!flags.backfaces; this._engine.display.imageDirty = true; } if (flags.frontface != undefined) { core.frontface = flags.frontface; this._engine.display.imageDirty = true; } if (flags.reflective != undefined) { core.reflective = flags.reflective; this._engine.branchDirty(this); this._engine.display.imageDirty = true; } if (flags.solid != undefined) { core.solid = flags.solid; this._engine.branchDirty(this); this._engine.display.imageDirty = true; } if (flags.solidColor != undefined) { var defaultSolidColor = defaultCore.solidColor; var color = flags.solidColor; core.solidColor = color ? [ color.r != undefined && color.r != null ? color.r : defaultSolidColor[0], color.g != undefined && color.g != null ? color.g : defaultSolidColor[1], color.b != undefined && color.b != null ? color.b : defaultSolidColor[2] ] : defaultCore.solidColor; this._engine.display.imageDirty = true; } if (flags.skybox != undefined) { core.skybox = flags.skybox; this._engine.branchDirty(this); this._engine.display.imageDirty = true; } core.hash = getHash(core); return this; }; SceneJS.Flags.prototype.getFlags = function () { var core = this._core; return { picking: core.picking, clipping: core.clipping, enabled: core.enabled, transparent: core.transparent, backfaces: core.backfaces, frontface: core.frontface, reflective: core.reflective, solid: core.solid, solidColor: core.solidColor }; }; SceneJS.Flags.prototype.setPicking = function (picking) { picking = !!picking; if (this._core.picking != picking) { this._core.picking = picking; this._engine.display.drawListDirty = true; } return this; }; SceneJS.Flags.prototype.getPicking = function () { return this._core.picking; }; SceneJS.Flags.prototype.setClipping = function (clipping) { clipping = !!clipping; if (this._core.clipping != clipping) { this._core.clipping = clipping; this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getClipping = function () { return this._core.clipping; }; SceneJS.Flags.prototype.setEnabled = function (enabled) { enabled = !!enabled; if (this._core.enabled != enabled) { this._core.enabled = enabled; this._engine.display.drawListDirty = true; } return this; }; SceneJS.Flags.prototype.getEnabled = function () { return this._core.enabled; }; SceneJS.Flags.prototype.setTransparent = function (transparent) { transparent = !!transparent; if (this._core.transparent != transparent) { this._core.transparent = transparent; this._engine.display.stateOrderDirty = true; } return this; }; SceneJS.Flags.prototype.getTransparent = function () { return this._core.transparent; }; SceneJS.Flags.prototype.setBackfaces = function (backfaces) { backfaces = !!backfaces; if (this._core.backfaces != backfaces) { this._core.backfaces = backfaces; this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getBackfaces = function () { return this._core.backfaces; }; SceneJS.Flags.prototype.setFrontface = function (frontface) { if (this._core.frontface != frontface) { this._core.frontface = frontface; this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getFrontface = function () { return this._core.frontface; }; SceneJS.Flags.prototype.setReflective = function (reflective) { reflective = !!reflective; if (this._core.reflective != reflective) { this._core.reflective = reflective; this._core.hash = getHash(this._core); this._engine.branchDirty(this); this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getReflective = function () { return this._core.reflective; }; SceneJS.Flags.prototype.setSolid = function (solid) { solid = !!solid; if (this._core.solid != solid) { this._core.solid = solid; this._core.hash = getHash(this._core); this._engine.branchDirty(this); this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getSolid = function () { return this._core.solid; }; SceneJS.Flags.prototype.setSolidColor = function (color) { var defaultSolidColor = defaultCore.solidColor; this._core.solidColor = color ? [ color.r != undefined && color.r != null ? color.r : defaultSolidColor[0], color.g != undefined && color.g != null ? color.g : defaultSolidColor[1], color.b != undefined && color.b != null ? color.b : defaultSolidColor[2] ] : defaultCore.solidColor; this._engine.display.imageDirty = true; return this; }; SceneJS.Flags.prototype.getSolidColor = function () { return { r: this._core.solidColor[0], g: this._core.solidColor[1], b: this._core.solidColor[2] }; }; SceneJS.Flags.prototype.setSkybox = function (skybox) { skybox = !!skybox; if (this._core.skybox != skybox) { this._core.skybox = skybox; this._core.hash = getHash(this._core); this._engine.branchDirty(this); this._engine.display.imageDirty = true; } return this; }; SceneJS.Flags.prototype.getSkybox = function () { return this._core.skybox; }; SceneJS.Flags.prototype._compile = function (ctx) { this._engine.display.flags = coreStack[stackLen++] = this._core; this._compileNodes(ctx); this._engine.display.flags = (--stackLen > 0) ? coreStack[stackLen - 1] : defaultCore; coreStack[stackLen] = null; // Release memory }; function getHash(core) { return (core.reflective ? "refl" : "") + ";" + (core.solid ? "s" : "") + ";" + (core.skybox ? "sky" : "") + ";"; } })();
version https://git-lfs.github.com/spec/v1 oid sha256:8f3e6bee10adea1a6e17ff0bd1731d10c39f8907652b5148e7c3cc57eac6c88c size 25804
/** * @module Build * @submodule Build.Config * @class Build.Config.RequireJS * @static */ module.exports = function(config) { return { 'global': { 'options': { 'name': 'main', 'baseUrl': config.javascripts +'/app/', 'mainConfigFile': config.javascripts +'/app/main.js', // Exclusions from minconcat use empty: 'paths': { 'facebook': 'empty:', 'google-analytics': 'empty:', 'settings': 'empty:' }, 'has': { 'debugMode': false }, 'out': config.jsmin +'/app.min.js' } } }; };
!(function (factory) { if (typeof define === 'function') { define(['zepto'], factory); } else { factory(Zepto); } })(function ($) { return $; });
const React = require('react'); const { Bar } = require('react-chartjs'); export default class BarChart extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex((name) => name === props.username); if (teamIdx !== -1) { colors[teamIdx] = 'rgba(54, 162, 235, 0.2)'; } this.state = { datasets: [ { label: 'Problems solved', fillColor: colors, data: this.props.numSolved, }, ], labels: this.props.names, }; } render() { const that = this; const options = { responsive: true, showTooltips: true, tooltipTemplate: (v) => { const teamIdx = that.props.names.findIndex((name) => name === v.label); const time = that.props.scores[teamIdx]; return `Time: ${time} minutes`; }, }; return ( <div className='chart-wrapper'> <Bar type='bar' data={this.state} options={options} width='1000px' height='500px' /> </div> ); } } BarChart.propTypes = { names: React.PropTypes.array, numSolved: React.PropTypes.array, scores: React.PropTypes.array, username: React.PropTypes.string.isRequired, };
import URIjs from 'urijs'; export const parseSearchString = (string) => URIjs.parseQuery(string); export const calcSearchString = (params) => URIjs.buildQuery(params, true);
'use strict'; /*! * Collection * https://github.com/kobezzza/Collection * * Released under the MIT license * https://github.com/kobezzza/Collection/blob/master/LICENSE */ var _core = require("../core"); var _types = require("../helpers/types"); var _gcc = require("../helpers/gcc"); /** * Returns true if in the collection exists at least one element which matches by the specified condition * * @see Collection.prototype.forEach * @param {($$CollectionFilter|$$CollectionSingleBase)=} [opt_filter] - function filter or an array of functions * @param {?$$CollectionSingleBase=} [opt_params] - additional parameters * @return {(boolean|!Promise<boolean>)} */ _core.Collection.prototype.some = function (opt_filter, opt_params) { let p = opt_params || {}; if (!(0, _types.isArray)(opt_filter) && !(0, _types.isFunction)(opt_filter)) { p = opt_filter || p; opt_filter = null; } this._initParams(p, opt_filter); p = (0, _gcc.any)(Object.assign(Object.create(this.p), p, { mult: false, result: false })); const returnVal = (0, _gcc.any)(this.forEach(() => p.result = true, p)); if (returnVal !== this) { return returnVal; } return p.result; };
/** * @file UserAccount/actions.js * @fileoverview - Exports redux action creation methods for modifying the * application scope state from the UserAccount component. */ import { REQUEST_SAVE_PROFILE, RECEIVED_SAVE_PROFILE, FAILED_SAVE_PROFILE, REQUEST_LOAD_PROFILE, RECEIVED_LOAD_PROFILE, FAILED_LOAD_PROFILE, UPDATE_PROFILE } from '../../actionTypes'; import ReduxThunk from 'redux-thunk'; import {Actions} from 'react-native-router-flux'; import DeviceStorageService from '../../services/deviceStorage/DeviceStorageService'; import { dispatch } from 'react-redux'; /* ========================================================================== * * Async Action Creators * ========================================================================== */ export const saveProfile = (user) => { return (dispatch) => { const svc = new AsyncStorageService(); // Dispatch notification that a save is taking place. dispatch(requestSaveProfile); // Write the updated profile to the service. const wrPromise = svc.write(['profile', stuent]); // Handle Promise resolve and fails. wrPromise.then((res) => { dispatch(recievedSaveProfile(user)); }, (error) => { dispatch(failedSaveProfile(error)); }); } }; /* ========================================================================== * * Synchronous Action Creators * ========================================================================== */ export const requestSaveProfile = (user) => { return { type: REQUEST_SAVE_PROFILE, user: user } } export const updateProfile = () => { return { type: UPDATE_PROFILE } }; export const recievedSaveProfile = (user) => { } export const failedSaveProfile = (user) => { }
/* * Codice javascript per l'applicazione */ // All'interno del file index.html il luogo migliore per inserire ed eseguire il codice javascript // è l'header della pagina, all'interno del tag <head>. Ma effettuare subito operazioni sul DOM all'interno // del tag <body> prima ancora che sia caricato interamente non è una buona idea... // // Inseriamo quindi tutto il codice in una funzione di callback e passiamola come argomento alla funzione speciale di jQuery, "$()". // La nostra funzione sarà così eseguita automaticamente non appena il caricamento della pagina sarà completato // e il DOM pronto per essere manipolato. // $(function() { // La libreria d3 espone un oggetto accessibile globalmente: d3. // L'uso della libreria d3 richiede quindi l'esecuzione opportuna dei metodi dell'oggetto d3. // // In questo caso il metodo select([selettore]) seleziona l'elemento in base al selettore passato ("body") // e ritorna un oggetto "selezione" (assegnato alla variabile "container"). // // Una selezione d3 a sua volta possiede il metodo append([tag]) che crea un nuovo // nodo del tipo specificato ("div") nel DOM all'interno del nodo selezionato in precedenza ("body"). // // Anche append() torna una selezione (questa volta "div", non più "body"), // per cui è possibile accedere immediatamente al metodo attr([string],[string]) // sfruttando un pattern di programmazione noto con il nome di chaining. La stringa passata come secondo argomento // ("container-fluid") viene dunque inserita come classe all'interno dell'attributo "class" del nodo selezionato ("div"). // // Creiamo subito un contenitore della pagina, figlio del body per usare al meglio bootstrap. // var container = d3.select("body") .append("div") .attr("class","container-fluid"); // Inseriamo il titolo in un contenitore che funga da "header" con classe "row", sempre per sfruttare bootstrap. var header = container.append("header") // Definiamo semanticamente le parti della pagina con i nuovi tag dell'HTML5 .attr("class","row page-header"); header.append("figure") // HTML5 .append("a") // Figlio di "h1" .attr("href","http://www.sergiobonelli.it/sezioni/18/dampyr") .attr("target","_blank") .append("img") // Figlio di "a" (e nipote di "h1") .attr("class","img-responsive center-block") .attr("src","http://www.sergiobonelli.it/images/personaggi/principali/dampyr_personaggio.png") .attr("alt","Dampyr"); // Rendiamo il tutto ricercabile mediante shufflejs attraverso un campo di input testuale header.append("nav") .append("input") .attr("id","search") .attr("class","center-block input-lg") .attr("placeholder","Cerca per autore...") .attr("value",""); // Abbiamo ora bisogno di dati memorizzati in un file tsv (Tab-separated values), // per cui dobbiamo recuperarli con una chiamata AJAX. Il metodo tsv([url], callback) di d3 // pensa a tutto: chiamata asincrona, gestione della risposta (evetuali errori in "error" e parsing dei dati testuali // dal tsv a un array di oggetti (passato in "data"). // d3.tsv("data/Bonelli-Collezione-Dampyr-Marzo-2015.tsv", function(error, data) { // Gestione di eventuali errori (es. file non trovato, ecc.), // se c'è qualche problema l'esecuzione si blocca e viene notificato un messaggio in console. if (error) { throw "Error in loading data..."; } // Assicuriamoci che tutto sia ordinato per numero di albo (e quindi per data di uscita) // e per ora limitiamoci ai primi 20 albi per non sovraccaricare di richieste il server della Bonelli // (le immagini sono linkate direttamente dal sito ufficiale). // data = data.sort(function(a,b) { // Il metodo sort() passa alla callback una coppia di elementi // Bisogna indicare dei due elementi quale viene prima e quale dopo, // in questo ci aiuta un metodo di d3 già predisposto allo scopo per semplici ordinamenti. // // Ovviamente dobbiamo confrontare il valore degli attributi "Numero" degli oggetti "a" e "b" e non gli oggetti in sé // e prima di farlo li convertiamo a interi (inizialmente sono letti come stringhe) anteponendo un "+". return d3.ascending(+a["Numero"],+b["Numero"]); }).slice(0,20); // Il metodo slice() applicato a un array prende 20 elementi consecutivi a partire dal numero 0 (il primo) // Per aggiungere la funzionalità di autocomplete al form di ricerca, // ricaviamo la lista dei nomi di tutti gli autori degli albi. // Soggetto Sceneggiatura Disegni Copertina var authors = _.uniq(_.flatten(data.map(function(el) { var groups = []; return groups .concat(el["Soggetto"].split(",")) .concat(el["Sceneggiatura"].split(",")) .concat(el["Disegni"].split(",")) .concat(el["Copertina"].split(",")); }))); // Qui uno dei pilastri concettuali della libreria d3: // prendiamo la variabile container (è una selezione del div contenitore globale), poi selezioniamo tutti gli elementi "div" // in esso contenuti con il metodo selectAll([selettore]). // Inizialmente non ce ne sono, quindi la selezione è vuota, ma esiste. // // A questa selezione (vuota) associamo il nostro array per posizione con il metodo data([array]): // il primo oggetto con il primo div (che non esiste), // il secondo oggetto con il secondo div (che sempre non esiste), ecc. // // Il metodo enter() opera la magia: esegue tutto ciò che viene dopo tante volte quanti sono i dati // che non sono stati assegnati ad alcun elemento del DOM, nel nostro caso tutti. Per cui append("div") // viene eseguito per tutti i dati e così vengono creati nel DOM tanti paragrafi quanti sono i dati // e a essi vengono associati in ordine i dati uno a uno. // // Il metodo append("div") torna una selezione, per cui possiamo subito impostare gli attributi e i contenuti dei div, // che non sono fissi, ma dipendono dai dati: la funzione di callback, infatti, viene eseguita passandole // il dato associato all'elemento corrente: "d" è un oggetto che rappresenta una riga del dataset originario // (una riga del file tsv), con le chiavi uguali ai nomi delle colonne e i valori quelli delle celle della riga. // // Questa funzione di callback deve ritornare un valore compatibile con il metodo che l'ha chiamata: nel nostro caso // per lo più stringhe con cui valorizzare gli attributi nominati. // var albi = container.append("section") .attr("id","grid") .attr("class","row page-body") // Dopo l'header, un'altra "row", ma con classe "body" .selectAll("div") // La selezione dei "div" contenitori viene assegnata alla variabile "albi" e poi riutilizzata successivamente. .data(data) .enter() .append("div") .attr("class","comics-container col-lg-2 col-md-3 col-sm-4 col-xs-6") // Associamo una classe ai div contenitori degli albi per sfruttare la grid di bootstrap che ci assicura la responsiveness .attr("data-groups", function(d) { // Shufflejs effettua il filtro su categorie personalizzate che vanno definite nell'attributo data-groups var groups = []; // Nel nostro caso le categorie sono i nomi degli autori e devono comparire come json di un array di stringhe: ["nome1","nome2",...] // Sappiamo però che nelle nostre colonne ci possono essere più nomi, che divideremo in un array con split() usando la virgola come separatore. // Non possiamo tornare però un array, perché l'attributo si aspetta una stringa, per cui... stringify, non prima di aver eliminato dall'array // gli elementi duplicati. return JSON.stringify(_.uniq(groups.concat(d["Soggetto"].split(",")).concat(d["Sceneggiatura"].split(",")).concat(d["Disegni"].split(",")).concat(d["Copertina"].split(",")))).replace(/"/g,"'"); }) .attr("data-title", function(d) { // Perché allora non inserire tutte e informazioni negli attributi data-? return d["Titolo"].replace(/"/g,""); }) .attr("data-summary", function(d) { return d["Sinossi"].replace(/"/g,""); }) .append("article") // Perché due div uno dentro l'altro? Perché vogliamo il bordo di ogni elemento e una certa distanza tra l'uno e l'altro .attr("class","comics"); // Da qui in poi tutti gli elementi vanno creati all'interno dei div contenitori creati precedentemente. // La variabile "albi" è un array e tutti i metodi invocati si applicano a tutti gli elementi dell'array. // Noi lo scriviamo una sola volta, ma il tutto è eseguito per tutti gli elementi, tanti quanti sono i dati. var header_albi = albi.append("header"); header_albi.append("p") .attr("class","number") .text(function(d) { return "Dampyr n. "+d["Numero"]; // Concatenazione di stringhe, sempre con il "+". }); header_albi.append("h4") // Titolo di quarto livello, sempre figlio del div, ma fratello del paragrafo precedente .attr("class","title") .text(function(d) { return d["Titolo"]; }); albi.append("figure") .append("a") // Questa volta inseriamo nel DOM un link alla scheda dell'albo sul sito ufficiale .attr("href", function(d) { // L'URL del link va inserita nell'attributo "href" mediante il metodo "attr" return d["Immagine"]; //return d["Scheda"]; }) .attr("target","_blank") // Il link si apre in un'altra finestra .attr("data-lightbox","cover") .attr("data-title", function(d) { return d["Sinossi"].replace(/"/g,""); }) .append("img") // Ora l'append è consecutivo al precedente, quindi agisce su "a" (non su "div"), inserendo al suo interno un'immagine .attr("class","cover img-responsive center-block") // Associamo la classe "cover" e alcune classi utili definite da bootstrap .attr("src", function(d) { // La sua URL va inserita nell'attributo "src" mediante il metodo "attr" return d["Immagine"]; }) .attr("alt", function(d) { return d["Titolo"]; }); albi.append("footer") .append("p") .attr("class","date") .html(function(d) { return 'Uscito il <a href="'+d["Scheda"]+'" target="_blank">'+d["Data di uscita"]+'</a>'; }); // E infine un footer a chiudere la pagina container.append("footer") .attr("class","row page-footer") .append("figure") .append("a") .attr("href","http://www.sergiobonelli.it/") .attr("target","_blank") .append("img") .attr("class","img-responsive center-block") .attr("src","http://www.sergiobonelli.it/images/sergio_bonelli_editore.png") .attr("alt","Sergio Bonelli Editore"); // // Il DOM è pronto con tutti gli elementi // Ora possiamo agire su quegli elementi, inizializzando la grid dei comics con shufflejs // $("#grid").shuffle({ itemSelector: ".comics-container" }); // Attacchiamo una funzione di callback a un evento del form di input: viene eseguita ogni volta che il contenuto cambia // a causa della digitazione di un testo all'interno da parte dell'utente $("#search").on('keyup change', function() { // Eventi "rilascio di un pulsante della tastiera" e "cambio del contenuto" // Effettuando una ricerca in data-groups è necessario ripulire un po' sia le stringa di ricerca // (ignorando per esempio le maiuscole e altri caratteri non letterali) che quella in cui viene effettuata // la ricerca (che è il json di un array di stringhe) var val = this.value.toLowerCase().replace(/[^a-z] /g,""); // Il valore digitato corrente $('#grid').shuffle('shuffle', function($el, shuffle) { // La funzione viene valutata per ogni elemento della grid: // se vera l'elemento viene tenuto, altrimenti viene nascosto return $el.data('groups').toLowerCase().indexOf(val) > -1; }); }); $("#search").autocomplete({ source: authors }); }); });
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import uniqueId from 'lodash/uniqueId'; import WixComponent from '../BaseComponents/WixComponent'; import styles from './ToggleSwitch.scss'; /** * Controlled switch */ class ToggleSwitch extends WixComponent { constructor(params) { super(params); this.id = uniqueId(); } render() { const {checked, onChange, size, disabled} = this.props; const id = this.id; const rootClassName = classnames(styles.toggleSwitch, { [styles.toggleSwitchSmall]: size === 'small', [styles.toggleSwitchXSmall]: size === 'x-small', [styles.disabled]: disabled }); const outerLabel = classnames(styles.outerLabel, { [styles.disabled]: disabled }); const innerLabel = classnames(styles.innerLabel, { [styles.disabled]: disabled }); const toggleActive = classnames(styles.toggleActive, { [styles.disabled]: disabled }); const toggleInactive = classnames(styles.toggleInactive, { [styles.disabled]: disabled }); return ( <div className={rootClassName}> <input type="checkbox" id={id} checked={checked} onChange={onChange}/> <label htmlFor={id} className={outerLabel}> <label htmlFor={id} className={innerLabel}> <svg className={toggleActive} viewBox="0 0 41 32"> <path d="M0.169 17.815c0.169 1.098 0.76 2.111 1.689 2.871l14.269 10.385c1.942 1.435 4.644 1.013 6.079-0.844l18.069-23.303c1.435-1.858 1.098-4.559-0.844-5.995s-4.644-1.098-6.164 0.844l-15.367 19.842-10.723-7.852c-1.942-1.435-4.644-1.013-6.164 0.844-0.76 0.929-1.013 2.111-0.844 3.208z"/> </svg> <svg className={toggleInactive} viewBox="0 0 143 32"> <path d="M0 0h142.545v32h-142.545v-32z"/> </svg> </label> </label> </div> ); } } ToggleSwitch.displayName = 'ToggleSwitch'; ToggleSwitch.propTypes = { checked: PropTypes.bool.isRequired, /** Callback function when user changes the value of the component */ onChange: PropTypes.func.isRequired, disabled: PropTypes.bool, /** Specifies toggle size */ size: PropTypes.oneOf(['x-small', 'small', 'large']) }; ToggleSwitch.defaultProps = { checked: false, onChange: () => {}, disabled: false, size: 'large' }; export default ToggleSwitch;
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProfiles = require('../INeatContextProfiles'); class NeatContextProfiles extends INeatContextProfiles { preInit() { /** * @type {object} */ this.data = {}; /** * @type {NeatClient} */ this.neat = 'neat'; super.preInit(...arguments); } init() { super.init(); this.neat = Jii.app.get(this.neat); } /** * * @param {string} profileName * @param {string} collectionName * @param {object} [params] * @returns {Promise.<T>} */ getCollection(profileName, collectionName, params) { params = params || {}; /** @typedef {NeatComet.bindings.BindingServer} bingind */ /*var binding = this.neat.engine.profilesDefinition[profileName] && this.neat.engine.profilesDefinition[profileName][name] || null; if (!binding) { throw new InvalidConfigException('Not found collection for profile id `' + name + '`'); }*/ return Promise.resolve().then(() => { // @todo Temporary code var opened = this.neat.engine._openedProfilesByProfileId; var profile = opened && opened[profileName] && opened[profileName][0] || this.neat.openProfile(profileName, params); var collection = profile.getCollection(collectionName); if (this.data[collectionName]) { collection.set(this.data[collectionName]); this.data[collectionName] = null; // Mark as exists record (not isNew) collection.each(model => { model.setOldAttributes(_clone(model.getAttributes())); }); /*return new Collection(this.data[collectionName], { modelClass: binding.serverModel || binding.clientModel })*/ } return collection; }); } } module.exports = NeatContextProfiles;
it("update for, init with empty data", function (done) { // [inject] init var lis = wrap.getElementsByTagName('li'); expect(lis.length).toBe(2); myComponent.data.push('persons', {name: 'otakustay', email: 'otakustay@gmail.com'} ); san.nextTick(function () { var lis = wrap.getElementsByTagName('li'); expect(lis.length).toBe(3); expect(lis[1].getAttribute('title')).toBe('otakustay'); expect(lis[1].innerHTML.indexOf('otakustay - otakustay@gmail.com')).toBe(0); myComponent.dispose(); document.body.removeChild(wrap); done(); }); });
var data = require("../data.json"); exports.view = function(req, res){ console.log("---------- Inside of previous contribution -------- "); res.render('previouscontribution', { answers: data.user.contributions, questions: data.user.personalquestions }); };
// DOM Ready $(function() { // SVG fallback // toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update if (!Modernizr.svg) { var imgs = document.getElementsByTagName('img'); var dotSVG = /.*\.svg$/; for (var i = 0; i != imgs.length; ++i) { if(imgs[i].src.match(dotSVG)) { imgs[i].src = imgs[i].src.slice(0, -3) + "png"; } } } // Check if an object or array is empty function is_empty(obj) { if (obj === null) return true; if (obj.length && obj.length > 0) return false; if (obj.length === 0) return true; for (var key in obj) { if (hasOwnProperty.call(obj, key)) return false; } return true; } // Remove some attribution $(".leaflet-control-attribution").css('display', 'none'); /** * This loops al the listitems and ul's in the filtering nav from the elm plugin and adds images to all of them if there * exists an iimage/icon with a name that is {slug}.png of each list item (layer) */ $(".easy-layer-map-navigation-list-item").each(function() { var layer_slug = this.getAttribute('data-slug'); // that = the anchor tag var that = $(this).children(':first'); url = theme_url + '/img/icons/' + layer_slug + '.png'; url_transparent = theme_url + '/img/icons/transparent.png'; var checkbox = '<img class=\'arkipelag-sthlm-layer-checkbox checked\' src=\'' + theme_url +'/img/icons/cb_checked.png\' />'; $.ajax({ url: url, async: false, success: function() { $(that).prepend('<img class=\'arkipelag-sthlm-layer-icon\' src=\'' + url + '\' />'); $(that).append(checkbox); }, error: function() { $(that).prepend('<img class=\'arkipelag-sthlm-layer-icon\' src=\'' + url_transparent + '\' />'); $(that).append(checkbox); } }); }); // Add the site logo to the top of the navigation var url = theme_url + '/img/logo.png'; $("#easy-layer-map-navigation-container").prepend('<div class=""><img class="arkipelag-sthlm-nav-logo" src="' + url + '" /></div>'); // Add hide/show functionality for the navigationmenu $('.easy-layer-map-navigation-header-link').click(function(e) { e.preventDefault(); $(this).next('ul').children('li').slideToggle(); }); // check of uncheck the checkboxes in the navigation/filtering $(".easy-layer-map-navigation-link").click(function() { var checked_url = theme_url +'/img/icons/cb_checked.png'; var unchecked_url = theme_url +'/img/icons/cb_unchecked.png'; var element = $(this).children('.arkipelag-sthlm-layer-checkbox.checked'); if(element.length > 0) { $(element).attr('src', unchecked_url).removeClass('checked'); } else { element = $(this).children('.arkipelag-sthlm-layer-checkbox'); $(element).attr('src', checked_url).addClass('checked'); } }); // Add the searchfieldfunctionality var first_search = true; $('.elm-search-field').on('focus', function() { if(first_search === true) { $(this).val(''); first_search = false; } }).on('change', function() { $('.elm-result-body').html(''); // If the searchfield isnt empty we search the spots and adds them to the searchresult div if($(this).val() !== '') { var pattern = new RegExp($(this).val().toLowerCase(), 'i'); search_results = []; for(var i in elm_spots_list) { console.log(elm_spots_list); var added = false; var title = elm_spots_list[i].title.toLowerCase(); var layers = elm_spots_list[i].layers; var plats = elm_spots_list[i].plats.toLowerCase(); var omrade = elm_spots_list[i].omrade.toLowerCase(); if(pattern.test(title) || pattern.test(plats) || pattern.test(omrade)) { search_results.push(elm_spots_list[i]); added = true; } if(!added) { for(var p in layers) { if(pattern.test(layers[p].title)) { search_results.push(elm_spots_list[i]); break; } } } } } function sortResult(result, index) { return array.sort((function(index){ return function(a, b){ return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1)); }; })(index)); } var result_array = []; for(var o in search_results) { result_array[o] = []; result_array[o]['url'] = search_results[o].url; result_array[o]['id'] = search_results[o].spotid; result_array[o]['title'] = search_results[o].title; result_array[o]['omrade'] = search_results[o].omrade; result_array[o]['plats'] = search_results[o].plats; result_array[o]['layers'] = ''; for(var t in search_results[o].layers) { if(t > 0) { result_array[o]['layers'] += ", " + search_results[o]['layers'][t].title; } else { result_array[o]['layers'] += search_results[o]['layers'][t].title; } } } function render(spots) { var html = ''; for(var i in spots) { console.log(spots); html += "<tr class='elm-result-row' id='" + spots[i].url + "'>"; html += "<td class='elm-result-cell'>" + spots[i].title + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].layers + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].omrade + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].plats + "</td>"; html += "</tr>"; } $('.elm-result-body').append(html); $('.elm-result-row').click(function() { console.log(this.id); }); } if(!is_empty(search_results)) { render(result_array); search_results = []; } else { } }).on('empty', function() { $('.elm-result-body').html(''); }); });
//= require ./sweetalert2.all.min
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { throw new Error("No notification message set"); } const notification = Ember.Object.create({ message: options.message, type: options.type || 'info', // info, success, warning, error autoClear: (Ember.isEmpty(options.autoClear) ? this.get('defaultAutoClear') : options.autoClear), clearDuration: options.clearDuration || this.get('defaultClearDuration'), onClick: options.onClick, htmlContent: options.htmlContent || false }); this.pushObject(notification); if (notification.autoClear) { notification.set('remaining', notification.get('clearDuration')); this.setupAutoClear(notification); } return notification; }, // Helper methods for each type of notification error(message, options) { this.addNotification(assign({ message: message, type: 'error' }, options)); }, success(message, options) { this.addNotification(assign({ message: message, type: 'success' }, options)); }, info(message, options) { this.addNotification(assign({ message: message, type: 'info' }, options)); }, warning(message, options) { this.addNotification(assign({ message: message, type: 'warning' }, options)); }, removeNotification(notification) { if (!notification) { return; } notification.set('dismiss', true); // Delay removal from DOM for dismissal animation Ember.run.later(this, () => { this.removeObject(notification); }, 500); }, setupAutoClear(notification) { notification.set('startTime', Date.now()); const timer = Ember.run.later(this, () => { // Hasn't been closed manually if (this.indexOf(notification) >= 0) { this.removeNotification(notification); } }, notification.get('remaining')); notification.set('timer', timer); }, pauseAutoClear(notification) { Ember.run.cancel(notification.get('timer')); const elapsed = Date.now() - notification.get('startTime'); const remaining = notification.get('clearDuration') - elapsed; notification.set('remaining', remaining); }, clearAll() { this.set('content', Ember.A()); }, setDefaultAutoClear(autoClear) { if (Ember.typeOf(autoClear) !== 'boolean') { throw new Error('Default auto clear preference must be a boolean'); } this.set('defaultAutoClear', autoClear); }, setDefaultClearNotification(clearDuration) { if (Ember.typeOf(clearDuration) !== 'number') { throw new Error('Clear duration must be a number'); } this.set('defaultClearDuration', clearDuration); } });
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, } from 'react-native'; const propTypes = { bottom: PropTypes.number.isRequired, displayText: PropTypes.string, color: PropTypes.string, opacity: PropTypes.number, width: PropTypes.number.isRequired }; const defaultProps = { color: 'gray', opacity: .7 }; class HorizontalLine extends React.Component { render() { const { color, opacity, bottom, displayText, width } = this.props; return ( <View style={{ opacity: opacity, backgroundColor: 'transparent', width: width, borderStyle: 'dashed', borderColor: color, borderWidth: .5, height: 1, bottom: bottom, position: 'absolute' }} > <Text style={{ position: 'absolute', bottom: 0, fontSize: 8 }} > {displayText} </Text> </View> ); } } HorizontalLine.propTypes = propTypes; HorizontalLine.defaultProps = defaultProps; export default HorizontalLine;
const RouteRecognizer = require('route-recognizer'); const glob = require('glob'); const router = new RouteRecognizer(); class Router { constructor(paths = []) { this.multiAdd(paths); } add(paths) { paths = Array.isArray(paths) ? paths : [ paths ]; router.add(paths); } multiAdd(paths) { paths = Array.isArray(paths) ? paths : [ paths ]; paths.forEach(path => router.add([ path ])); } async install(ctx, next) { const assemblyLine = router.recognize(ctx.path) || []; for (let i = 0; i < assemblyLine.length; i++) { const { handler, params } = assemblyLine[i]; delete params['']; Object.assign(ctx.request.query, params); await handler.apply(ctx, [ ctx ]); } await next(); } } const pages = glob.sync('./server/pages/*'); const paths = pages.reduce((paths, each) => { const path = each.replace(/^\.\/server\/pages|\.js$/g, ''); const handler = require(each.replace(/^\.\/server/, '..')); paths.push({ path, handler }); if (path === '/auto') { paths.push({ path: '/auto/', handler }); } return paths; }, [ { path: '/', handler: require('../pages/index.js') }, { path: '/static/*', handler: require('../pages/static.js') }, { path: '/demos/*', handler: require('../pages/demos.js') }, { path: '/manifest.json', handler: require('../pages/demos.js') }, { path: '/auto/manifest.json', handler: require('../pages/demos.js') }, { path: '/auto/*', handler: require('../pages/auto.js') }, { path: '/sw.js', handler: require('../pages/sw.js') }, { path: '/googleb2d01223dfd5850d.html', handler: require('../pages/googleb2d01223dfd5850d.js') }, { path: '/whoareyou.json', handler: require('../pages/whoareyou.js') }, ]); module.exports = new Router(paths);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactNative = require('react-native'); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); var _checkIndexBounds = require('./utils/checkIndexBounds'); var _checkIndexBounds2 = _interopRequireDefault(_checkIndexBounds); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // weak /** * This is an alternative version that use `ScrollView` and `ViewPagerAndroid`. * I'm not sure what version give the best UX experience. * I'm keeping the two versions here until we figured out. */ var _Dimensions$get = _reactNative.Dimensions.get('window'); var windowWidth = _Dimensions$get.width; var styles = _reactNative.StyleSheet.create({ root: { flex: 1, overflow: 'hidden' }, container: { flex: 1 }, slide: { flex: 1 } }); var SwipeableViews = function (_Component) { (0, _inherits3.default)(SwipeableViews, _Component); function SwipeableViews() { var _ref; var _temp, _this, _ret; (0, _classCallCheck3.default)(this, SwipeableViews); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SwipeableViews.__proto__ || (0, _getPrototypeOf2.default)(SwipeableViews)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this.handleScroll = function (event) { if (_this.props.onSwitching) { _this.props.onSwitching(event.nativeEvent.contentOffset.x / _this.state.viewWidth, 'move'); } }, _this.handleMomentumScrollEnd = function (event) { var offset = event.nativeEvent.contentOffset; var indexNew = offset.x / _this.state.viewWidth; var indexLatest = _this.state.indexLatest; _this.setState({ indexLatest: indexNew, offset: offset }, function () { if (_this.props.onSwitching) { _this.props.onSwitching(indexNew, 'end'); } if (_this.props.onChangeIndex && indexNew !== indexLatest) { _this.props.onChangeIndex(indexNew, indexLatest); } }); }, _this.handlePageSelected = function (event) { var indexLatest = _this.state.indexLatest; var indexNew = event.nativeEvent.position; _this.setState({ indexLatest: indexNew }, function () { if (_this.props.onSwitching) { _this.props.onSwitching(indexNew, 'end'); } if (_this.props.onChangeIndex && indexNew !== indexLatest) { _this.props.onChangeIndex(indexNew, indexLatest); } }); }, _this.handlePageScroll = function (event) { if (_this.props.onSwitching) { _this.props.onSwitching(event.nativeEvent.offset + event.nativeEvent.position, 'move'); } }, _this.handleLayout = function (event) { var width = event.nativeEvent.layout.width; if (width) { _this.setState({ viewWidth: width, offset: { x: _this.state.indexLatest * width } }); } }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret); } (0, _createClass3.default)(SwipeableViews, [{ key: 'componentWillMount', value: function componentWillMount() { if (process.env.NODE_ENV !== 'production') { (0, _checkIndexBounds2.default)(this.props); } var initState = { indexLatest: this.props.index, viewWidth: windowWidth, offset: {} }; // android not use offset if (_reactNative.Platform.OS === 'ios') { initState.offset = { x: initState.viewWidth * initState.indexLatest }; } this.setState(initState); process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.animateHeight, 'react-swipeable-view: The animateHeight property is not implement yet.') : void 0; process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!this.props.axis, 'react-swipeable-view: The axis property is not implement yet.') : void 0; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var _this2 = this; var index = nextProps.index; if (typeof index === 'number' && index !== this.props.index) { (0, _checkIndexBounds2.default)(nextProps); this.setState({ indexLatest: index, offset: { x: this.state.viewWidth * index } }, function () { if (_reactNative.Platform.OS === 'android') { if (_this2.props.animateTransitions) { _this2.refs.scrollView.setPage(index); } else { _this2.refs.scrollView.setPageWithoutAnimation(index); } } }); } } }, { key: 'render', value: function render() { var _props = this.props; var resistance = _props.resistance; var children = _props.children; var slideStyle = _props.slideStyle; var style = _props.style; var containerStyle = _props.containerStyle; var disabled = _props.disabled; var other = (0, _objectWithoutProperties3.default)(_props, ['resistance', 'children', 'slideStyle', 'style', 'containerStyle', 'disabled']); var _state = this.state; var viewWidth = _state.viewWidth; var indexLatest = _state.indexLatest; var offset = _state.offset; var slideStyleObj = [styles.slide, { width: viewWidth }, slideStyle]; var childrenToRender = _react.Children.map(children, function (element, index) { if (disabled && indexLatest !== index) { return null; } return _react2.default.createElement( _reactNative.View, { style: slideStyleObj }, element ); }); return _react2.default.createElement( _reactNative.View, { onLayout: this.handleLayout, style: [styles.root, style] }, _reactNative.Platform.OS === 'ios' ? _react2.default.createElement( _reactNative.ScrollView, (0, _extends3.default)({}, other, { ref: 'scrollView', style: [styles.container, containerStyle], horizontal: true, pagingEnabled: true, scrollsToTop: false, bounces: resistance, onScroll: this.handleScroll, scrollEventThrottle: 200, showsHorizontalScrollIndicator: false, contentOffset: offset, onMomentumScrollEnd: this.handleMomentumScrollEnd }), childrenToRender ) : _react2.default.createElement( _reactNative.ViewPagerAndroid, (0, _extends3.default)({}, other, { ref: 'scrollView', style: [styles.container, containerStyle], initialPage: indexLatest, onPageSelected: this.handlePageSelected, onPageScroll: this.handlePageScroll }), childrenToRender ) ); } }]); return SwipeableViews; }(_react.Component); SwipeableViews.defaultProps = { animateTransitions: true, disabled: false, index: 0, resistance: false }; process.env.NODE_ENV !== "production" ? SwipeableViews.propTypes = { /** * If `true`, the height of the container will be animated to match the current slide height. * Animating another style property has a negative impact regarding performance. */ animateHeight: _react.PropTypes.bool, /** * If `false`, changes to the index prop will not cause an animated transition. */ animateTransitions: _react.PropTypes.bool, /** * The axis on which the slides will slide. */ axis: _react.PropTypes.oneOf(['x', 'x-reverse', 'y', 'y-reverse']), /** * Use this property to provide your slides. */ children: _react.PropTypes.node, /** * This is the inlined style that will be applied * to each slide container. */ containerStyle: _reactNative.ScrollView.propTypes.style, /** * If `true`, it will disable touch events. * This is useful when you want to prohibit the user from changing slides. */ disabled: _react.PropTypes.bool, /** * This is the index of the slide to show. * This is useful when you want to change the default slide shown. * Or when you have tabs linked to each slide. */ index: _react.PropTypes.number, /** * This is callback prop. It's call by the * component when the shown slide change after a swipe made by the user. * This is useful when you have tabs linked to each slide. * * @param {integer} index This is the current index of the slide. * @param {integer} fromIndex This is the oldest index of the slide. */ onChangeIndex: _react.PropTypes.func, /** * This is callback prop. It's called by the * component when the slide switching. * This is useful when you want to implement something corresponding to the current slide position. * * @param {integer} index This is the current index of the slide. * @param {string} type Can be either `move` or `end`. */ onSwitching: _react.PropTypes.func, /** * If `true`, it will add bounds effect on the edges. */ resistance: _react.PropTypes.bool, /** * This is the inlined style that will be applied * on the slide component. */ slideStyle: _reactNative.View.propTypes.style, /** * This is the inlined style that will be applied * on the root component. */ style: _reactNative.View.propTypes.style } : void 0; exports.default = SwipeableViews;
(function(module) { var contactController = {}; contactController.index = function() { $('.containing-landing').hide(); $('#contact').show().siblings().hide(); }; module.contactController = contactController; })(window);
import React, { Component } from 'react'; import Sticky from '../components/Sticky'; import MovieNav from '../components/MovieNav'; import MovieCards from '../components/MovieCards'; import PropTypes from 'prop-types'; import Loader from '../components/Loader'; const propTypes = { sticky: PropTypes.bool.isRequired, navigation: PropTypes.object.isRequired, loadingMovies: PropTypes.bool.isRequired }; class MovieContent extends Component { componentWillMount() {} paginationOnChange = (page) => { this.props.setPage(page); } render() { const { dispatch, height, sticky, movies, navigation, loadingMovies } = this.props; return ( <div className={`movies ${(sticky ? 'sticky' : '')}`}> <MovieNav {...this.props} /> { (loadingMovies) ? <Loader /> : <MovieCards {...this.props} data={movies.data} /> } {/* { this.props.loading ? <Loader /> : null } */} </div> ); } } MovieContent.propTypes = propTypes; export default Sticky(MovieContent, 50);
describe( 'Event object', function () { var source, Klass, pkgDef, proxy, pkgInst, tank; beforeEach(function () { source = {a:{b:1,c:4},d:{f:1,g:{h:3,k:9}}}; Klass = Panzer.create(); pkgDef = Klass.pkg('a'); proxy = new Klass(source); pkgInst = pkgDef(proxy); tank = pkgInst.tank; }); describe( '.id', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.id).to.be.a('number'); e.id.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should increase across events of all Panzer class instances', function () { var lastId = 0, Klass2 = Panzer.create(), pkgDef2 = Klass2.pkg('foo'), events = ['init', 'begin', 'move', 'idle', 'end', 'traverse', 'scope'], spy = sinon.spy(function (e) { e.id.should.be.above(lastId); lastId = e.id; }) ; pkgDef.on(events, spy); pkgDef2.on(events, spy); pkgDef2(new Klass2()).tank.go(1); tank.go(1); spy.should.have.been.called; }); }); describe( '.order', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.order).to.be.a('number'); e.order.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should start with 1, for the "init" event', function () { var spy = sinon.spy(function (e) { e.order.should.equal(1); }); pkgDef.on('init', spy); proxy = new Klass(); spy.should.have.been.called; }); it( 'should increase per event of an instance', function () { var lastOrder = 0; pkgDef.on(['begin', 'move', 'idle', 'end'], function (e) { e.order.should.be.above(lastOrder); lastOrder = e.order; }); tank.go(); expect(lastOrder).to.be.above(0); }); }); describe( '.tid', function () { it( 'should be a string property', function () { var spy = sinon.spy(function (e) { expect(e.tid).to.be.a('string'); e.tid.length.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should reflect the corresponding tank id', function () { var spy = sinon.spy(function (e) { e.tid.should.equal(this.tank.id); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); }); describe( '.trip', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.trip).to.be.a('number'); e.trip.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should increment after each completed navigation', function () { var lastTripCount, spy = sinon.spy(function (e) { e.trip.should.equal(lastTripCount + 1); }) ; pkgDef.on('begin', function first(e) { lastTripCount = e.trip; }); tank.go(); pkgDef .off('begin') .on('begin', spy) ; tank.go(); spy.should.have.been.called; }); it( 'should be the same across events', function () { var events = ['begin', 'end', 'move', 'idle', 'engage', 'release', 'switch', 'traverse'], expectedTripCount = 1 ; pkgDef.on(events, function (e) { var eIdx = events.indexOf(e.type); if (~eIdx) { events.splice(eIdx, 1); } e.trip.should.equal(expectedTripCount); }); tank.go(2); events.should.have.lengthOf(0); }); it( 'should be the same across events of stopped trips', function () { var firstCallCount, spy = sinon.spy(function (e) { e.trip.should.equal(1); }) ; pkgDef.on( ['begin', 'end', 'move', 'idle', 'engage', 'release', 'switch', 'traverse'], spy ); pkgDef.on('move', function tmp() { pkgDef.off('move', tmp); tank.stop(); }); tank.go(4); firstCallCount = spy.callCount; firstCallCount.should.equal(4); tank.go(); spy.callCount.should.be.above(firstCallCount * 2); }); it( 'should be the same across events of blocked trips', function () { var spy = sinon.spy(function (e) { e.trip.should.equal(1); }), firstCallCount, promise ; pkgDef.on( ['begin', 'end', 'move', 'idle', 'engage', 'release', 'switch', 'traverse'], spy ); pkgDef.on('move', function tmp() { pkgDef.off('move', tmp); return Promise.resolve(); }); promise = tank.go(4); firstCallCount = spy.callCount; // this will fire after unblocked pkgDef.on('end', function () { spy.callCount.should.be.above(firstCallCount); }); return promise.then(function () { spy.should.have.been.called; }); }); it( 'should be the same across events of queued trips', function () { var firstCallCount, spy = sinon.spy(function (e) { e.trip.should.equal(1); }), pkgDef2 = Klass.pkg('asdf'), tankB = pkgDef2(new Klass()).tank ; pkgDef.on( ['begin', 'end', 'move', 'idle', 'engage', 'release', 'switch', 'traverse'], spy ); pkgDef.on('move', function tmp() { pkgDef.off('move', tmp); tank.queue(tankB); }); tank.go(4); firstCallCount = spy.callCount; firstCallCount.should.equal(4); tankB.go(); spy.callCount.should.be.above(firstCallCount * 2); }); }); describe( '.leg', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.leg).to.be.a('number'); e.leg.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should be the same across events', function () { var events = ['begin', 'end', 'move', 'idle', 'engage', 'release', 'switch', 'traverse'], expectedTripCount = 1 ; pkgDef.on(events, function (e) { var eIdx = events.indexOf(e.type); if (~eIdx) { events.splice(eIdx, 1); } e.leg.should.equal(expectedTripCount); }); tank.go(2); events.should.have.lengthOf(0); }); it( 'should increment across events between stopped trips', function () { var lastLegCount, spy = sinon.spy(function (e) { e.leg.should.be.equal(lastLegCount + 1); }) ; pkgDef.on('begin', function (e) { lastLegCount = e.leg; tank.stop(); pkgDef.off('begin'); }); tank.go(2); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.called; }); it( 'should increment across events between blocked trips', function () { var promise, firstLegCount, secondLegCount ; pkgDef.on('move', function (e) { firstLegCount = e.leg; pkgDef.off('move'); return Promise.resolve(); }); promise = tank.go(2); pkgDef.on('move', function (e) { secondLegCount = e.leg; }); return promise.then(function () { secondLegCount.should.equal(firstLegCount + 1); }); }); it( 'should increment across events between queued trips', function () { var pkgDef2 = Klass.pkg('asdf'), tankB = pkgDef2(new Klass()).tank, spy = sinon.spy(function (e) { if (e.tid === tank.id) { e.leg.should.be.equal(lastLegCount + 1); } }), lastLegCount ; pkgDef.on('begin', function (e) { pkgDef.off('begin'); lastLegCount = e.leg; tank.queue(tankB); }); tank.go(2); pkgDef.on('begin', spy); tankB.go(); spy.should.have.been.called; }); }); describe( '.command', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.command).to.be.a('number'); e.command.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should start as 1', function () { var spy = sinon.spy(function (e) { e.command.should.equal(1); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should reflect the number of calls to `tank.go`', function () { var lastCommand; pkgDef.on('begin', function (e) { lastCommand = e.command; }); tank.go(); expect(lastCommand).to.be.a('number'); lastCommand.should.equal(1); tank.go(); tank.go(); expect(lastCommand).to.equal(3); }); it( 'should be the same between events', function () { var beginValue, endValue; pkgDef.on(['begin', 'end'], function (e) { if (e.type === 'begin') { beginValue = e.command; } else { endValue = e.command; } }); tank.go(1); tank.go(2); expect(beginValue).to.exist; expect(endValue).to.exist; beginValue.should.equal(endValue); }); it( 'should increment even if no navigation events fire', function () { var spy = sinon.spy(), lastCommand ; pkgDef.on('begin', function (e) { lastCommand = e.command; pkgDef.off(); return Promise.resolve(); }); tank.go(1); pkgDef.off(); lastCommand.should.equal(1); pkgDef.on('begin', spy); tank.go(); spy.should.not.have.been.called; pkgDef.off(); pkgDef.on('intercept', function (e) { lastCommand = e.command; }); tank.go(); lastCommand.should.equal(3); }); }); describe( '.type', function () { it( 'should be a string property', function () { var spy = sinon.spy(function (e) { expect(e.type).to.be.a('string'); e.type.length.should.be.above(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should reflect the subscribed event name', function () { var eventName = 'begin', spy = sinon.spy(function (e) { e.type.should.equal(eventName); }) ; pkgDef.on(eventName, spy); tank.go(); spy.should.have.been.called; }); }); describe( '.index', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.index).to.be.a('number'); }); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.called; }); it( 'should reflect the current tank node index', function () { var spy = sinon.spy(function (e) { e.index.should.equal(tank.index); }); pkgDef.on('traverse', spy); tank.go(1); spy.callCount.should.be.above(1); }); }); describe( '.path', function () { it( 'should be a string property', function () { var spy = sinon.spy(function (e) { expect(e.path).to.be.a('string'); }); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.called; }); it( 'should reflect the current tank node path', function () { var spy = sinon.spy(function (e) { e.path.should.equal(tank.path); }); pkgDef.on('traverse', spy); tank.go(1); spy.callCount.should.be.above(1); }); }); describe( '.depth', function () { it( 'should be a numeric property', function () { var spy = sinon.spy(function (e) { expect(e.depth).to.be.a('number'); }); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.called; }); it( 'should reflect the current tank node depth', function () { var spy = sinon.spy(function (e) { e.depth.should.equal(tank.depth); }); pkgDef.on('traverse', spy); tank.go(3); spy.callCount.should.be.above(1); }); }); describe( '.stack', function () { it( 'should be an array property', function () { var spy = sinon.spy(function (e) { expect(e.stack).to.be.an('array'); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should be empty when event has no parent event (e.g., is outside another loop)', function () { var spy = sinon.spy(function (e) { e.stack.should.be.empty; }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should host event ancestry of nested loops', function () { var grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), ancestry, lastStack ; pkgDef .on('begin', function (e) { switch(this) { case grandInst: parentInst.tank.go(); break; case parentInst: pkgInst.tank.go(); break; case pkgInst: ancestry = e.stack; break; // no default } }) .on('end', function (e) { switch(this) { case grandInst: lastStack = e.stack; break; case parentInst: e.stack.should.have.lengthOf(1); break; case pkgInst: e.stack.should.have.lengthOf(2); break; // no default } }) ; grandInst.tank.go(); expect(ancestry).to.be.an('array'); ancestry.should.have.lengthOf(2); parentInst.proxy.should.equal(ancestry[0].proxy); grandInst.proxy.should.equal(ancestry[1].proxy); expect(lastStack).to.be.an('array'); lastStack.should.have.lengthOf(0); }); describe( 'when stopped', function () { it( 'should preserve ancestry', function () { var spy = sinon.spy(function (e) { var stack = e.stack; stack.should.have.lengthOf(2); stack[0].proxy.should.equal(parentInst.proxy); stack[0].type.should.equal(e.type); stack[1].proxy.should.equal(grandInst.proxy); stack[1].type.should.equal(e.type); }), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); childInst.tank.go(1); break; case childInst: e.stack.should.have.lengthOf(2); childInst.tank.stop(); break; // no default } }); grandInst.tank.go(1); grandInst.tank.index.should.equal(1); parentInst.tank.index.should.equal(1); childInst.tank.index.should.equal(0); grandInst.tank.stopped.should.be.false; parentInst.tank.stopped.should.be.false; childInst.tank.stopped.should.be.true; pkgDef .off() .on('begin', spy) ; childInst.tank.go(); childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; spy.should.have.been.calledOnce; }); it( 'should clear ancestry afterwards', function () { var spy = sinon.spy(function (e) { e.stack.should.have.lengthOf(0); }), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); childInst.tank.go(1); break; case childInst: pkgDef.off(); e.stack.should.have.lengthOf(2); childInst.tank.stop(); break; // no default } }); grandInst.tank.go(1); childInst.tank.stopped.should.be.true; childInst.tank.go(); childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; pkgDef.on('begin', spy); childInst.tank.go(0); spy.should.have.been.calledOnce; }); }); describe( 'when blocked by a returned Promise', function () { it( 'should preserve ancestry', function () { var spy = sinon.spy(), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst, promise ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); promise = childInst.tank.go(1); break; case childInst: pkgDef.off('begin'); e.stack.should.have.lengthOf(2); return Promise.resolve(); // no default } }); grandInst.tank.go(1); grandInst.tank.index.should.equal(1); parentInst.tank.index.should.equal(1); childInst.tank.index.should.equal(0); grandInst.tank.stopped.should.be.false; parentInst.tank.stopped.should.be.false; childInst.tank.stopped.should.be.false; childInst.tank.blocked.should.be.true; pkgDef .on('intercept', spy) .on('end', function (e) { var stack = e.stack; stack.should.have.lengthOf(2); stack[0].proxy.should.equal(parentInst.proxy); stack[0].type.should.equal('begin'); stack[1].proxy.should.equal(grandInst.proxy); stack[1].type.should.equal('begin'); }) ; // ensures we're blocked childInst.tank.go(); spy.should.have.been.calledOnce; return promise.then(function () { childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; spy.should.have.been.calledOnce; }); }); it( 'should clear ancestry afterwards ', function () { var interceptSpy = sinon.spy(), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst, promise ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); promise = childInst.tank.go(1); break; case childInst: pkgDef.off(); e.stack.should.have.lengthOf(2); return Promise.resolve(); // no default } }); grandInst.tank.go(1); childInst.tank.stopped.should.be.false; childInst.tank.blocked.should.be.true; pkgDef.on('intercept', interceptSpy); // prove we're blocked childInst.tank.go(); interceptSpy.should.have.been.calledOnce; pkgDef.off(); return promise.then(function () { var beginSpy = sinon.spy(function (e) { e.stack.should.have.lengthOf(0); }); pkgDef.on('begin', beginSpy); return childInst.tank.go(0); }); }); }); describe( 'when blocked with `#block()`', function () { it( 'should preserve ancestry', function () { var spy = sinon.spy(), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst, promise ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); promise = childInst.tank.go(1); break; case childInst: pkgDef.off('begin'); e.stack.should.have.lengthOf(2); childInst.tank.block(Promise.resolve(), true); break; // no default } }); grandInst.tank.go(1); grandInst.tank.index.should.equal(1); parentInst.tank.index.should.equal(1); childInst.tank.index.should.equal(0); grandInst.tank.stopped.should.be.false; parentInst.tank.stopped.should.be.false; childInst.tank.stopped.should.be.false; childInst.tank.blocked.should.be.true; pkgDef .on('intercept', spy) .on('end', function (e) { var stack = e.stack; stack.should.have.lengthOf(2); stack[0].proxy.should.equal(parentInst.proxy); stack[0].type.should.equal('begin'); stack[1].proxy.should.equal(grandInst.proxy); stack[1].type.should.equal('begin'); }) ; // ensures we're blocked childInst.tank.go(); spy.should.have.been.calledOnce; return promise.then(function () { childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; spy.should.have.been.calledOnce; }); }); it( 'should clear ancestry afterwards ', function () { var interceptSpy = sinon.spy(), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst, promise ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); promise = childInst.tank.go(1); break; case childInst: pkgDef.off(); e.stack.should.have.lengthOf(2); return Promise.resolve(); // no default } }); grandInst.tank.go(1); childInst.tank.stopped.should.be.false; childInst.tank.blocked.should.be.true; pkgDef.on('intercept', interceptSpy); // prove we're blocked childInst.tank.go(); interceptSpy.should.have.been.calledOnce; pkgDef.off(); return promise.then(function () { var beginSpy = sinon.spy(function (e) { e.stack.should.have.lengthOf(0); }); pkgDef.on('begin', beginSpy); return childInst.tank.go(0); }); }); }); describe( 'when queued', function () { it( 'should preserve ancestry', function () { var spy = sinon.spy(function (e) { var stack = e.stack; stack.should.have.lengthOf(2); stack[0].proxy.should.equal(parentInst.proxy); stack[0].type.should.equal(e.type); stack[1].proxy.should.equal(grandInst.proxy); stack[1].type.should.equal(e.type); }), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); childInst.tank.go(1); break; case childInst: e.stack.should.have.lengthOf(2); childInst.tank.queue(new Klass()); break; // no default } }); grandInst.tank.go(1); grandInst.tank.index.should.equal(1); parentInst.tank.index.should.equal(1); childInst.tank.index.should.equal(0); grandInst.tank.stopped.should.be.false; parentInst.tank.stopped.should.be.false; childInst.tank.stopped.should.be.false; childInst.tank.queued.should.be.true; pkgDef .off() .on('begin', spy) ; childInst.tank.go(); childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; spy.should.have.been.calledOnce; }); it( 'should clear ancestry afterwards', function () { var spy = sinon.spy(function (e) { e.stack.should.have.lengthOf(0); }), grandInst = pkgDef(new Klass()), parentInst = pkgDef(new Klass()), childInst = pkgInst ; pkgDef.on('begin', function (e) { switch(this) { case grandInst: e.stack.should.have.lengthOf(0); parentInst.tank.go(1); break; case parentInst: e.stack.should.have.lengthOf(1); childInst.tank.go(1); break; case childInst: pkgDef.off(); e.stack.should.have.lengthOf(2); childInst.tank.queue(new Klass()); break; // no default } }); grandInst.tank.go(1); childInst.tank.stopped.should.be.false; childInst.tank.queued.should.be.true; childInst.tank.go(); childInst.tank.index.should.equal(1); childInst.tank.stopped.should.be.false; childInst.tank.queued.should.be.false; pkgDef.on('begin', spy); childInst.tank.go(0); spy.should.have.been.calledOnce; }); }); }); describe( '.trail', function () { it( 'should be an array', function () { var spy = sinon.spy(function (e) { expect(e.trail).to.be.an('array'); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should be empty on first event of tank', function () { var spy = sinon.spy(function (e) { e.trail.should.have.lengthOf(0); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should contain all events fired during navigation', function () { var trail; pkgDef.on('end', function (e) { trail = e.trail; e.type.should.equal('end'); }); tank.go(1); expect(trail).to.be.an('array'); trail.map(function(crumb) { return crumb.type; }).should.eql([ 'idle', 'release', 'traverse', 'traverse', 'scope', 'engage', 'switch', 'move', 'begin' ]); }); it( 'should order events from most recent to oldest', function () { var spy = sinon.spy(function (e) { e.trail[0].type.should.equal('end'); e.trail[e.trail.length - 1].type.should.equal('begin'); }); pkgDef.on('begin', function () { tank.stop(); }); tank.go(1); pkgDef.off().on('begin', spy); tank.go(); spy.should.have.been.called; }); describe( 'when stopped', function () { it( 'should preserve history', function () { var spy = sinon.spy(function (e) { e.trail.length.should.be.above(0); }); pkgDef .on('begin', function (e) { e.trail.should.have.lengthOf(0); tank.stop(); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; tank.go(1); tank.stopped.should.be.true; pkgDef .off() .on('begin', spy) ; tank.go(); spy.should.have.been.calledOnce; }); it( 'should clear history afterwards', function () { var spy = sinon.spy(function (e) { e.trail.length.should.equal(0); }); pkgDef.on('begin', function () { tank.stop(); }); tank.go(1); tank.stopped.should.be.true; pkgDef.off(); tank.go(); tank.stopped.should.be.false; tank.target.should.equal(-1); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.calledOnce; }); }); describe( 'when blocked by a returned Promise', function () { it( 'should preserve history', function () { var spy = sinon.spy(function (e) { e.trail.length.should.be.above(0); }), promise ; pkgDef .on('begin', function (e) { pkgDef.off(); e.trail.should.have.lengthOf(0); return Promise.resolve(); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; promise = tank.go(1); tank.blocked.should.be.true; pkgDef.on('begin', spy); return promise.then(function () { spy.should.have.been.calledOnce; }); }); it( 'should clear history afterwards', function () { pkgDef .on('begin', function (e) { pkgDef.off(); e.trail.should.have.lengthOf(0); return Promise.resolve(); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; return tank.go(1).then(function () { var spy = sinon.spy(function (e) { e.trail.should.have.lengthOf(0); }); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.calledOnce; }); }); }); describe( 'when blocked with `#block()`', function () { it( 'should preserve history', function () { var spy = sinon.spy(function (e) { e.trail.length.should.be.above(0); }), promise ; pkgDef .on('begin', function (e) { pkgDef.off(); e.trail.should.have.lengthOf(0); tank.block(Promise.resolve(), true); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; promise = tank.go(1); tank.blocked.should.be.true; pkgDef.on('begin', spy); return promise.then(function () { spy.should.have.been.calledOnce; }); }); it( 'should clear history afterwards', function () { pkgDef .on('begin', function (e) { pkgDef.off(); e.trail.should.have.lengthOf(0); tank.block(Promise.resolve(), true); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; return tank.go(1).then(function () { var spy = sinon.spy(function (e) { e.trail.should.have.lengthOf(0); }); pkgDef.on('begin', spy); tank.go(1); spy.should.have.been.calledOnce; }); }); }); describe( 'when queued', function () { it( 'should preserve history', function () { var spy = sinon.spy(function (e) { e.trail.length.should.be.above(0); }); pkgDef .on('begin', function (e) { e.trail.should.have.lengthOf(0); tank.queue(new Klass()); }) .on('end', function (e) { e.trail.length.should.be.above(0); }) ; tank.go(1); tank.stopped.should.be.false; tank.queued.should.be.true; pkgDef .off() .on('begin', spy) ; tank.go(); spy.should.have.been.calledOnce; }); it( 'should clear history afterwards', function () { var spy = sinon.spy(function (e) { e.trail.length.should.equal(0); }); pkgDef.on('begin', function () { tank.queue(new Klass()); }); tank.go(1); tank.stopped.should.be.false; tank.queued.should.be.true; pkgDef.off(); tank.go(); tank.stopped.should.be.false; tank.queued.should.be.false; tank.target.should.equal(-1); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.calledOnce; }); }); }); describe( '.proxy', function () { it( 'should be an object property', function () { var spy = sinon.spy(function (e) { expect(e.proxy).to.be.an('object'); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should reference the corresponding proxy object', function () { var spy = sinon.spy(function (e) { e.proxy.should.equal(proxy); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); }); describe( '.tally', function () { it( 'should be an object property', function () { var spy = sinon.spy(function (e) { expect(e.tally).to.be.an('object'); }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); it( 'should have members with numeric values', function () { var spy = sinon.spy(function (e) { Object.keys(e.tally).every(function (member) { return typeof e.tally[member] === 'number'; }).should.be.ok; }); pkgDef.on('begin', spy); tank.go(); spy.should.have.been.called; }); describe( '.proxy', function () { it( 'should reflect count of events on the public instance', function () { var lastInstanceEventCount = 0, spy = sinon.spy(function (e) { e.tally.proxy.should.be.above(lastInstanceEventCount); lastInstanceEventCount = e.tally.proxy; }) ; pkgDef.on('begin',spy); tank.go(); tank.go(); tank.go(); tank.go(); spy.should.have.been.called; }); it( 'should start with 1', function () { var instCount = 0; pkgDef.on('traverse', function (e) { instCount = e.tally.proxy; pkgDef.off(); }); tank.go(1); instCount.should.equal(1); }); it( 'should increment across trips', function () { var lastInstance = 0; pkgDef.on('traverse', function (e) { e.tally.proxy.should.equal(lastInstance + 1); lastInstance = e.tally.proxy; }); tank.go(1); tank.go(3); tank.go(0); lastInstance.should.be.above(0); }); }); describe( '.node', function () { it( 'should reflect count of events on a given node', function () { var watchIndex = 1, lastNodeEventCount = 0, nodeTallyTests = 0 ; pkgDef.on('traverse', function (e) { if (e.index === watchIndex) { e.tally.node.should.be.above(lastNodeEventCount); lastNodeEventCount = e.tally.node; nodeTallyTests++; } }); tank.go(2); tank.go(0); tank.go(2); tank.go(0); nodeTallyTests.should.be.above(3); }); it( 'should start with 1', function () { var nodeCount = 0; pkgDef.on('traverse', function (e) { nodeCount = e.tally.node; pkgDef.off(); }); tank.go(1); nodeCount.should.equal(1); }); }); describe( '.trip', function () { it( 'should reflect count of events during navigation', function () { var tripCount = 0; pkgDef.on('traverse', function (e) { tripCount = e.tally.trip; }); tank.go(1); tripCount.should.equal(2); }); it( 'should start with 1', function () { var tripCount = 0; pkgDef.on('traverse', function (e) { tripCount = e.tally.trip; pkgDef.off(); }); tank.go(1); tripCount.should.equal(1); }); it( 'should be preserved between legs of an interupted navigation', function () { var lastTripCount = 0; pkgDef.on('traverse', function (e) { lastTripCount = e.tally.trip; }); pkgDef.on('release', function () { tank.stop(); }); tank.go(2); lastTripCount.should.be.above(0); tank.index.should.not.equal(2, 'trip was not interupted'); pkgDef.off(); pkgDef.on('traverse', function (e) { e.tally.trip.should.equal(lastTripCount + 1); pkgDef.off(); }); tank.go(); tank.index.should.equal(2); }); it( 'should reset when navigation completes', function () { var lastTripCount = 0; pkgDef.on('traverse', function (e) { lastTripCount = e.tally.trip; }); tank.go(1); pkgDef.off(); lastTripCount.should.be.above(1); tank.index.should.equal(1, 'trip did not complete'); // start at top of tree again tank.go(0); pkgDef.on('traverse', function (e) { e.tally.trip.should.not.equal(lastTripCount + 1); e.tally.trip.should.equal(1); pkgDef.off(); }); tank.go(1); tank.index.should.equal(1); }); }); describe( '.leg', function () { it( 'should reflect count of events during navigation', function () { var legCount = 0; pkgDef.on('traverse', function (e) { legCount = e.tally.leg; }); tank.go(1); legCount.should.equal(2); }); it( 'should start with 1', function () { var legCount = 0; pkgDef.on('traverse', function (e) { legCount = e.tally.leg; pkgDef.off(); }); tank.go(1); legCount.should.equal(1); }); it( 'should reset when the trip is interupted', function () { var spy = sinon.spy(function (e) { e.tally.leg.should.equal(1); pkgDef.off(); }), lastLegCount = 0 ; pkgDef.on('traverse', function (e) { lastLegCount = e.tally.leg; }); pkgDef.on('release', function () { tank.stop(); }); tank.go(2); lastLegCount.should.be.above(0); tank.index.should.not.equal(2, 'trip was not interupted'); pkgDef.off(); pkgDef.on('traverse', spy); tank.go(); tank.index.should.equal(2); spy.should.have.been.called; }); }); }); });
(function() { 'use strict'; angular .module('core') .run(run); run.$inject = ['$rootScope']; /* @ngInject */ function run($rootScope) { var _ = $rootScope, methods = {}; methods.chunk = function(array, n) { return _.transform(array, function(result, el, i, arr) { return i % n === 0 ? result.push(arr.slice(i, i + n)) : null; }); }; methods.stripBase64 = function(str) { return str.replace(/^data:image\/png;base64,/, ''); }; //methods.recursive = function(obj, opt, iterator) { // function recurse(obj, property) { // iterator(obj, property); // _.each(_.keys(obj), function(prop) { // recurse(obj[prop]); // }); // //_.each(obj[opt], recurse); // } // recurse(obj); //}; _.each(methods, function(method, methodName) { _[methodName] = _.bind(method, _); }); } })();
this.manifest = { "name": "Visual Site Alert", "icon": "icon.png", "settings": [ { "tab": "Site List", "group": "Add New Alert", "name": "myDescription", "type": "description", "text": "Site URL specifies the URL you want to match. You can use <strong>*</strong> as a wild card. \ For example, <strong>http*://*.ca</strong> will match all sites in .ca domain. \ Alert text specifies the text that will appear atop of the bar.\ Similarly, use a regular expression in the Page Content field, to show the notification bar only \ when certain content is present." }, { "tab": "Site List", "group": "Add New Alert", "name": "site_url", "type": "text", "label": "Site URL", "text": "Example: http://google.*" }, { "tab": "Site List", "group": "Add New Alert", "name": "site_contents", "type": "text", "label": "Page Contents" }, { "tab": "Site List", "group": "Add New Alert", "name": "site_alert", "type": "text", "label": "Alert Text", "text": "Example: Warning! You are now on google!" }, { "tab": "Site List", "group": "Add New Alert", "name": "addAlert", "type": "button", "text": "Add Alert" }, { "tab": "Site List", "group": "Existing Alerts", "name": "existingAlerts", "type": "description", "text": "Existing alerts." } ], "alignment": [ [ "site_url", "site_alert", "site_contents" ] ] };
/* * purge.js * * CVS/SVN Keywords *------------------------------ * $Author: cnobile $ * $Date: 2011-11-10 20:29:49 -0500 (Thu, 10 Nov 2011) $ * $Revision: 54 $ *------------------------------ */ var Purge = function() { this._setupSubmit(); this._CONFIRM_REQUEST = null; this._DELETE_REQUEST = null; }; Purge.prototype = { _CONTACT_SERVER_TXT: "Wait while contacting the server...", _setupSubmit: function() { this._CONFIRM_REQUEST = this._confirmationRequest.bind(this); this._DELETE_REQUEST = this._deleteRequest.bind(this); $('form#form').submit(this._CONFIRM_REQUEST); $('input#search').click(function() { window.location = "/maintenance/purge/"; }); $('input#reset').click(function () { this._setMessage(""); }.bind(this)); }, _confirmationRequest: function() { this._setMessage(this._CONTACT_SERVER_TXT); this._callAjax("post", this._assembleURI("/maintenance/confirm/"), this._createJSON(), this._confirmationCB); }, _confirmationCB: function(json, status) { this._setMessage(json['message']); if(json['valid']) { $('form#form').unbind('submit', this._CONFIRM_REQUEST); $('form#form').bind('submit', this._DELETE_REQUEST); } }, _deleteRequest: function() { this._callAjax("post", this._assembleURI("/maintenance/delete/"), this._createJSON(), this._deleteCB); }, _deleteCB: function(json, status) { this._setMessage(json["message"]); if(json['valid']) { $('td input[type=checkbox]').each(function() { if(this.checked) { $(this).parent().parent().remove(); } }); } $('form#form').unbind('submit', this._DELETE_REQUEST); $('form#form').bind('submit', this._CONFIRM_REQUEST); this._setMessage(true); }, _createJSON: function() { var checkboxes = $('td > input[type=checkbox]'); var pks = []; for(var i = 0; i < checkboxes.length; i++) { var box = checkboxes[i]; if(box.checked) { var node = $(box).parent().parent().find("td > input[type=hidden]"); pks[i] = node[0].value; } } var json = {pks: pks}; return json; } }; $(document).ready(function() { extend(Purge, AjaxBase); new Purge(); });
/* The MIT License (MIT) Copyright (c) 2014 Charles Bryan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ !function(t){t.fn.activeScroll=function(n){var o=t.extend({animation:200,"class":"active",nav:"nav",navItem:"li",navLink:"a",sections:"section",sectionIdAttr:"id",threshold:-10},n),i=o.nav+" "+o.navItem,s=i+" "+o.navLink,a=!1,e=t(this).find(o.sections).filter(function(){var n=t(this),i=n.attr(o.sectionIdAttr);if(!i)return!1;var e="#"+i,r=t(s+"[href='"+e+"']");return r?(r.click(function(i){if(i.preventDefault(),window.history.pushState){var s=window.location.hash.replace(window.location.hash,e);a?window.history.replaceState({},"",s):window.history.pushState({},"",s),a=!0}t("html, body").animate({scrollTop:n.offset().top+(o.threshold+1)})}),t(this).prop("$link",r),!0):!1});t(window).scroll(function(){var n=t(window).scrollTop();e.each(function(){t(this).offset().top<=n-o.threshold&&(t(i+"."+o.class).removeClass(o.class),t(this).prop("$link").closest(i).addClass(o.class))})}).scroll()}}(jQuery);
(function(testacular, requirejs, require) { // monkey patch requirejs, to use append timestamps to sources // to take advantage of testacular's heavy caching // it would work even without this hack, but with reloading all the files all the time var normalizePath = function(path) { var normalized = []; var parts = path.split('/'); for (var i = 0; i < parts.length; i++) { if (parts[i] === '.') { continue; } if (parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..') { normalized.pop(); continue; } normalized.push(parts[i]); } return normalized.join('/'); }; var createPatchedLoad = function(files, originalLoadFn) { return function (context, moduleName, url) { url = normalizePath(url); if (files.hasOwnProperty(url)) { url = url + '?' + files[url]; } else { console.error('There is no timestamp for ' + url + '!'); } return originalLoadFn.call(this, context, moduleName, url); }; }; // config base path require.config({ baseUrl: '/base' }); // make it async testacular.loaded = function() {}; // patch require.js requirejs.load = createPatchedLoad(testacular.files, requirejs.load); })(window.__testacular__, window.requirejs, window.require);
import SVG from './SVG'; import Radium from 'radium'; import { layout, svg } from 'd3'; import { Spring } from 'react-motion'; import { Component, PropTypes } from 'react'; export default class PieChart extends Component { static defaultProps = { data: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, outerRadius: PropTypes.number.isRequired, innerRadius: PropTypes.number.isRequired } state = { ...[...Array(this.props.data.length)].map(() => false) } onMouseOver = (i) => () => this.setState({ [i]: true }) onMouseOut = (i) => () => this.setState({ [i]: false }) render() { const { innerRadius, outerRadius, width, height } = this.props; const pie = layout.pie().padAngle(.02); const arc = svg.arc().padRadius(outerRadius).innerRadius(innerRadius); return ( <SVG width={width} height={height}> <g transform={`translate(${width / 2}, ${height / 2})`}> { pie(this.props.data).map( (dataPoint, i) => <Spring key={i} endValue={{ val: this.state[i] ? outerRadius : outerRadius - 20 }}> { ({ val }) => <Path d={arc({ ...dataPoint, outerRadius: val })} onMouseOver={this.onMouseOver(i)} onMouseOut={this.onMouseOut(i)} /> } </Spring>) } </g> </SVG> ); } } @Radium class Path extends Component { render() { return ( <path style={{ fill: '#CCCCCC', stroke: '#333333', strokeWidth: 1.5, transition: 'fill 250ms linear', cursor: 'pointer', ':hover': { fill: '#999999', stroke: '#000000' } }} d={this.props.d} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} /> ); } }
/*jslint node:true, vars:true, bitwise:true, unparam:true */ /*jshint unused:true */ /*global */ var ledController = require("./ledController.js"); ledController.clear(); ledController.smile(); var motorController = require("./motorController.js") motorController.go(); motorController.stop(); //motorController.demo(); var headControler = require("./headcontroller.js"); headControler.lookMiddle(); var theThingsAPI = require('thethingsio-api'); var motionKEY = 'motion'; //create Client var client = theThingsAPI.createClient(); var lastAction = "@@@"; function readMotions() { //read latest write var req1 = client.thingReadLatest(motionKEY); //event fired when the response arrives req1.on('response',function(res){ if (res.statusCode == 200 && res.payload !== undefined) { var payload = JSON.parse(res.payload); var newAction = payload.data[0].value; if (newAction !== lastAction) { lastAction = newAction; motorController.doAction(newAction); } } }); req1.end(); } readMotions(); motorController.stop(); var loopCounter = 0; setInterval(function() { readMotions(); }, 200);
module.exports = { accepted: ':attribute må være akseptert.', alpha: ':attribute feltet kan kun inneholde alfabetiske tegn.', alpha_dash: ':attribute feltet kan kun inneholde alfanumeriske tegn, i tillegg til bindestreker og understreker.', alpha_num: ':attribute feltet må være alfanumerisk.', between: ':attribute feltet må være mellom :min og :max.', confirmed: ':attribute feltet stemmer ikke overens med bekreftelsen.', email: ':attribute formatet er ugyldig.', date: ':attribute er et ugyldig datoformat.', def: ':attribute attributtet har feil.', digits: ':attribute må være på :digits siffer.', different: ':attribute og :different må være forskjellige.', 'in': 'Den oppgitte verdien for :attribute er ugyldig.', integer: ':attribute må være et heltall.', hex: 'The :attribute should have hexadecimal format', min: { numeric: ':attribute må minst være :min.', string: ':attribute må være på minst :min tegn.' }, max: { numeric: ':attribute kan ikke være større enn :max.', string: ':attribute kan maks ha :max tegn.' }, 'not_in': 'Den oppgitte verdien for :attribute er ugyldig.', numeric: ':attribute må være et tall.', present: 'The :attribute field must be present (but can be empty).', required: ':attribute feltet er påkrevd.', required_if: ':attribute er påkrevd når :other er :value.', same: ':attribute og :same må være like.', size: { numeric: ':attribute må ha størrelsen :size.', string: ':attribute må ha :size tegn.' }, string: ':attribute må være tekst.', url: ':attribute formatet er ugyldig.', regex: ':attribute formatet er ugyldig.', attributes: {} };
/* eslint-disable */ // @ts-nocheck /* Copyright (c) 2013 Gildas Lormeau. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc. * JZlib is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ (function(global) { "use strict"; // Global var MAX_BITS = 15; var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; var inflate_mask = [ 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff ]; var MANY = 1440; // JZlib version : "1.0.2" var Z_NO_FLUSH = 0; var Z_FINISH = 4; // InfTree var fixed_bl = 9; var fixed_bd = 5; var fixed_tl = [ 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255 ]; var fixed_td = [ 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 ]; // Tables for deflate from PKZIP's appnote.txt. var cplens = [ // Copy lengths for literal codes 257..285 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; // see note #13 above about 258 var cplext = [ // Extra bits for literal codes 257..285 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid ]; var cpdist = [ // Copy offsets for distance codes 0..29 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ]; var cpdext = [ // Extra bits for distance codes 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ]; // If BMAX needs to be larger than 16, then h and x[] should be uLong. var BMAX = 15; // maximum bit length of any code function InfTree() { var that = this; var hn; // hufts used in space var v; // work area for huft_build var c; // bit length count table var r; // table entry for structure assignment var u; // table stack var x; // bit offsets, then code stack function huft_build(b, // code lengths in bits (all assumed <= // BMAX) bindex, n, // number of codes (assumed <= 288) s, // number of simple-valued codes (0..s-1) d, // list of base values for non-simple codes e, // list of extra bits for non-simple codes t, // result: starting table m, // maximum lookup bits, returns actual hp,// space for trees hn,// hufts used in space v // working area: values in order of bit length ) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, // Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in // this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set // of // lengths), or Z_MEM_ERROR if not enough memory. var a; // counter for codes of length k var f; // i repeats in table every f entries var g; // maximum code length var h; // table level var i; // counter, current code var j; // counter var k; // number of bits in current code var l; // bits per table (returned in m) var mask; // (1 << w) - 1, to avoid cc -O bug on HP var p; // pointer into c[], b[], or v[] var q; // points to current table var w; // bits before this table == (l * h) var xp; // pointer into x var y; // number of dummy codes added var z; // number of entries in current table // Generate counts for each bit length p = 0; i = n; do { c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX } while (i !== 0); if (c[0] == n) { // null input--all zero length codes t[0] = -1; m[0] = 0; return Z_OK; } // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) if (c[j] !== 0) break; k = j; // minimum code length if (l < j) { l = j; } for (i = BMAX; i !== 0; i--) { if (c[i] !== 0) break; } g = i; // maximum code length if (l > i) { l = i; } m[0] = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) { if ((y -= c[j]) < 0) { return Z_DATA_ERROR; } } if ((y -= c[i]) < 0) { return Z_DATA_ERROR; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = 1; xp = 2; while (--i !== 0) { // note that i == g from above x[xp] = (j += c[p]); xp++; p++; } // Make a table of values in order of bit lengths i = 0; p = 0; do { if ((j = b[bindex + p]) !== 0) { v[x[j]++] = i; } p++; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) u[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { a = c[k]; while (a-- !== 0) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l) { h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = (z > l) ? l : z; // table size upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for // k-w bit table f -= a + 1; // deduct codes from patterns left xp = k; if (j < z) { while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) break; // enough codes to use up j bits f -= c[xp]; // else deduct codes from patterns } } } z = 1 << j; // table entries for j-bit table // allocate new table if (hn[0] + z > MANY) { // (note: doesn't matter for fixed) return Z_DATA_ERROR; // overflow of MANY } u[h] = q = /* hp+ */hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if (h !== 0) { x[h] = i; // save pattern for backing up r[0] = /* (byte) */j; // bits in this table r[1] = /* (byte) */l; // bits to dump before this table j = i >>> (w - l); r[2] = /* (int) */(q - u[h - 1] - j); // offset to this table hp.set(r, (u[h - 1] + j) * 3); // to // last // table } else { t[0] = q; // first table is returned result } } // set up table entry in r r[1] = /* (byte) */(k - w); if (p >= n) { r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { r[0] = /* (byte) */(v[p] < 256 ? 0 : 32 + 64); // 256 is // end-of-block r[2] = v[p++]; // simple code is just the value } else { r[0] = /* (byte) */(e[v[p] - s] + 16 + 64); // non-simple--look // up in lists r[2] = d[v[p++] - s]; } // fill code-like entries with r f = 1 << (k - w); for (j = i >>> w; j < z; j += f) { hp.set(r, (q + j) * 3); } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) !== 0; j >>>= 1) { i ^= j; } i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]) { h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } function initWorkArea(vsize) { var i; if (!hn) { hn = []; // []; //new Array(1); v = []; // new Array(vsize); c = new Int32Array(BMAX + 1); // new Array(BMAX + 1); r = []; // new Array(3); u = new Int32Array(BMAX); // new Array(BMAX); x = new Int32Array(BMAX + 1); // new Array(BMAX + 1); } if (v.length < vsize) { v = []; // new Array(vsize); } for (i = 0; i < vsize; i++) { v[i] = 0; } for (i = 0; i < BMAX + 1; i++) { c[i] = 0; } for (i = 0; i < 3; i++) { r[i] = 0; } // for(int i=0; i<BMAX; i++){u[i]=0;} u.set(c.subarray(0, BMAX), 0); // for(int i=0; i<BMAX+1; i++){x[i]=0;} x.set(c.subarray(0, BMAX + 1), 0); } that.inflate_trees_bits = function(c, // 19 code lengths bb, // bits tree desired/actual depth tb, // bits tree result hp, // space for trees z // for messages ) { var result; initWorkArea(19); hn[0] = 0; result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); if (result == Z_DATA_ERROR) { z.msg = "oversubscribed dynamic bit lengths tree"; } else if (result == Z_BUF_ERROR || bb[0] === 0) { z.msg = "incomplete dynamic bit lengths tree"; result = Z_DATA_ERROR; } return result; }; that.inflate_trees_dynamic = function(nl, // number of literal/length codes nd, // number of distance codes c, // that many (total) code lengths bl, // literal desired/actual bit depth bd, // distance desired/actual bit depth tl, // literal/length tree result td, // distance tree result hp, // space for trees z // for messages ) { var result; // build literal/length tree initWorkArea(288); hn[0] = 0; result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); if (result != Z_OK || bl[0] === 0) { if (result == Z_DATA_ERROR) { z.msg = "oversubscribed literal/length tree"; } else if (result != Z_MEM_ERROR) { z.msg = "incomplete literal/length tree"; result = Z_DATA_ERROR; } return result; } // build distance tree initWorkArea(288); result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); if (result != Z_OK || (bd[0] === 0 && nl > 257)) { if (result == Z_DATA_ERROR) { z.msg = "oversubscribed distance tree"; } else if (result == Z_BUF_ERROR) { z.msg = "incomplete distance tree"; result = Z_DATA_ERROR; } else if (result != Z_MEM_ERROR) { z.msg = "empty distance tree with lengths"; result = Z_DATA_ERROR; } return result; } return Z_OK; }; } InfTree.inflate_trees_fixed = function(bl, // literal desired/actual bit depth bd, // distance desired/actual bit depth tl,// literal/length tree result td// distance tree result ) { bl[0] = fixed_bl; bd[0] = fixed_bd; tl[0] = fixed_tl; td[0] = fixed_td; return Z_OK; }; // InfCodes // waiting for "i:"=input, // "o:"=output, // "x:"=nothing var START = 0; // x: set up for LEN var LEN = 1; // i: get length/literal/eob next var LENEXT = 2; // i: getting length extra (have base) var DIST = 3; // i: get distance next var DISTEXT = 4;// i: getting distance extra var COPY = 5; // o: copying bytes in window, waiting // for space var LIT = 6; // o: got literal, waiting for output // space var WASH = 7; // o: got eob, possibly still output // waiting var END = 8; // x: got eob and all data flushed var BADCODE = 9;// x: got error function InfCodes() { var that = this; var mode; // current inflate_codes mode // mode dependent information var len = 0; var tree; // pointer into tree var tree_index = 0; var need = 0; // bits needed var lit = 0; // if EXT or COPY, where and how much var get = 0; // bits to get for extra var dist = 0; // distance back to copy from var lbits = 0; // ltree bits decoded per branch var dbits = 0; // dtree bits decoder per branch var ltree; // literal/length/eob tree var ltree_index = 0; // literal/length/eob tree var dtree; // distance tree var dtree_index = 0; // distance tree // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) { var t; // temporary pointer var tp; // temporary pointer var tp_index; // temporary pointer var e; // extra bits or operation var b; // bit buffer var k; // bits in bit buffer var p; // input data pointer var n; // bytes available there var q; // output window write pointer var m; // bytes to end of window or read pointer var ml; // mask for literal/length tree var md; // mask for distance tree var c; // bytes to copy var d; // distance back to copy from var r; // copy source pointer var tp_index_t_3; // (tp_index+t)*3 // load input, output, bit values p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; // initialize masks ml = inflate_mask[bl]; md = inflate_mask[bd]; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while (k < (20)) { // max bits for literal/length code n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } t = b & ml; tp = tl; tp_index = tl_index; tp_index_t_3 = (tp_index + t) * 3; if ((e = tp[tp_index_t_3]) === 0) { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); s.window[q++] = /* (byte) */tp[tp_index_t_3 + 2]; m--; continue; } do { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); if ((e & 16) !== 0) { e &= 15; c = tp[tp_index_t_3 + 2] + (/* (int) */b & inflate_mask[e]); b >>= e; k -= e; // decode distance base of block to copy while (k < (15)) { // max bits for distance code n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } t = b & md; tp = td; tp_index = td_index; tp_index_t_3 = (tp_index + t) * 3; e = tp[tp_index_t_3]; do { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); if ((e & 16) !== 0) { // get extra bits to add to distance base e &= 15; while (k < (e)) { // get extra bits (up to 13) n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]); b >>= (e); k -= (e); // do the copy m -= c; if (q >= d) { // offset before dest // just copy r = q - d; if (q - r > 0 && 2 > (q - r)) { s.window[q++] = s.window[r++]; // minimum // count is // three, s.window[q++] = s.window[r++]; // so unroll // loop a // little c -= 2; } else { s.window.set(s.window.subarray(r, r + 2), q); q += 2; r += 2; c -= 2; } } else { // else offset after destination r = q - d; do { r += s.end; // force pointer in window } while (r < 0); // covers invalid distances e = s.end - r; if (c > e) { // if source crosses, c -= e; // wrapped copy if (q - r > 0 && e > (q - r)) { do { s.window[q++] = s.window[r++]; } while (--e !== 0); } else { s.window.set(s.window.subarray(r, r + e), q); q += e; r += e; e = 0; } r = 0; // copy rest from start of window } } // copy all or what's left if (q - r > 0 && c > (q - r)) { do { s.window[q++] = s.window[r++]; } while (--c !== 0); } else { s.window.set(s.window.subarray(r, r + c), q); q += c; r += c; c = 0; } break; } else if ((e & 64) === 0) { t += tp[tp_index_t_3 + 2]; t += (b & inflate_mask[e]); tp_index_t_3 = (tp_index + t) * 3; e = tp[tp_index_t_3]; } else { z.msg = "invalid distance code"; c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_DATA_ERROR; } } while (true); break; } if ((e & 64) === 0) { t += tp[tp_index_t_3 + 2]; t += (b & inflate_mask[e]); tp_index_t_3 = (tp_index + t) * 3; if ((e = tp[tp_index_t_3]) === 0) { b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); s.window[q++] = /* (byte) */tp[tp_index_t_3 + 2]; m--; break; } } else if ((e & 32) !== 0) { c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_STREAM_END; } else { z.msg = "invalid literal/length code"; c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_DATA_ERROR; } } while (true); } while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_OK; } that.init = function(bl, bd, tl, tl_index, td, td_index) { mode = START; lbits = /* (byte) */bl; dbits = /* (byte) */bd; ltree = tl; ltree_index = tl_index; dtree = td; dtree_index = td_index; tree = null; }; that.proc = function(s, z, r) { var j; // temporary storage var tindex; // temporary pointer var e; // extra bits or operation var b = 0; // bit buffer var k = 0; // bits in bit buffer var p = 0; // input data pointer var n; // bytes available there var q; // output window write pointer var m; // bytes to end of window or read pointer var f; // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; // process input and output based on current state while (true) { switch (mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z); p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; if (r != Z_OK) { mode = r == Z_STREAM_END ? WASH : BADCODE; break; } } need = lbits; tree = ltree; tree_index = ltree_index; mode = LEN; /* falls through */ case LEN: // i: get length/literal/eob next j = need; while (k < (j)) { if (n !== 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b >>>= (tree[tindex + 1]); k -= (tree[tindex + 1]); e = tree[tindex]; if (e === 0) { // literal lit = tree[tindex + 2]; mode = LIT; break; } if ((e & 16) !== 0) { // length get = e & 15; len = tree[tindex + 2]; mode = LENEXT; break; } if ((e & 64) === 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } if ((e & 32) !== 0) { // end of block mode = WASH; break; } mode = BADCODE; // invalid code z.msg = "invalid literal/length code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case LENEXT: // i: getting length extra (have base) j = get; while (k < (j)) { if (n !== 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } len += (b & inflate_mask[j]); b >>= j; k -= j; need = dbits; tree = dtree; tree_index = dtree_index; mode = DIST; /* falls through */ case DIST: // i: get distance next j = need; while (k < (j)) { if (n !== 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; e = (tree[tindex]); if ((e & 16) !== 0) { // distance get = e & 15; dist = tree[tindex + 2]; mode = DISTEXT; break; } if ((e & 64) === 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } mode = BADCODE; // invalid code z.msg = "invalid distance code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case DISTEXT: // i: getting distance extra j = get; while (k < (j)) { if (n !== 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } dist += (b & inflate_mask[j]); b >>= j; k -= j; mode = COPY; /* falls through */ case COPY: // o: copying bytes in window, waiting for space f = q - dist; while (f < 0) { // modulo window size-"while" instead f += s.end; // of "if" handles invalid distances } while (len !== 0) { if (m === 0) { if (q == s.end && s.read !== 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; } if (m === 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; if (q == s.end && s.read !== 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; } if (m === 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } } s.window[q++] = s.window[f++]; m--; if (f == s.end) f = 0; len--; } mode = START; break; case LIT: // o: got literal, waiting for output space if (m === 0) { if (q == s.end && s.read !== 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; } if (m === 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; if (q == s.end && s.read !== 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; } if (m === 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } } r = Z_OK; s.window[q++] = /* (byte) */lit; m--; mode = START; break; case WASH: // o: got eob, possibly more output if (k > 7) { // return unused byte, if any k -= 8; n++; p--; // can always return one } s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; if (s.read != s.write) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } mode = END; /* falls through */ case END: r = Z_STREAM_END; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case BADCODE: // x: got error r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); default: r = Z_STREAM_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } }; that.free = function() { // ZFREE(z, c); }; } // InfBlocks // Table for deflate from PKZIP's appnote.txt. var border = [ // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; var TYPE = 0; // get type bits (3, including end bit) var LENS = 1; // get lengths for stored var STORED = 2;// processing stored block var TABLE = 3; // get table lengths var BTREE = 4; // get bit lengths tree for a dynamic // block var DTREE = 5; // get length, distance trees for a // dynamic block var CODES = 6; // processing fixed or dynamic block var DRY = 7; // output remaining window bytes var DONELOCKS = 8; // finished last block, done var BADBLOCKS = 9; // ot a data error--stuck here function InfBlocks(z, w) { var that = this; var mode = TYPE; // current inflate_block mode var left = 0; // if STORED, bytes left to copy var table = 0; // table lengths (14 bits) var index = 0; // index into blens (or border) var blens; // bit lengths of codes var bb = [ 0 ]; // bit length tree depth var tb = [ 0 ]; // bit length decoding tree var codes = new InfCodes(); // if CODES, current state var last = 0; // true if this block is the last block var hufts = new Int32Array(MANY * 3); // single malloc for tree space var check = 0; // check on output var inftree = new InfTree(); that.bitk = 0; // bits in bit buffer that.bitb = 0; // bit buffer that.window = new Uint8Array(w); // sliding window that.end = w; // one byte after sliding window that.read = 0; // window read pointer that.write = 0; // window write pointer that.reset = function(z, c) { if (c) c[0] = check; // if (mode == BTREE || mode == DTREE) { // } if (mode == CODES) { codes.free(z); } mode = TYPE; that.bitk = 0; that.bitb = 0; that.read = that.write = 0; }; that.reset(z, null); // copy as much as possible from the sliding window to the output area that.inflate_flush = function(z, r) { var n; var p; var q; // local copies of source and destination pointers p = z.next_out_index; q = that.read; // compute number of bytes to copy as far as end of window n = /* (int) */((q <= that.write ? that.write : that.end) - q); if (n > z.avail_out) n = z.avail_out; if (n !== 0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // copy as far as end of window z.next_out.set(that.window.subarray(q, q + n), p); p += n; q += n; // see if more to copy at beginning of window if (q == that.end) { // wrap pointers q = 0; if (that.write == that.end) that.write = 0; // compute bytes to copy n = that.write - q; if (n > z.avail_out) n = z.avail_out; if (n !== 0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // copy z.next_out.set(that.window.subarray(q, q + n), p); p += n; q += n; } // update pointers z.next_out_index = p; that.read = q; // done return r; }; that.proc = function(z, r) { var t; // temporary storage var b; // bit buffer var k; // bits in bit buffer var p; // input data pointer var n; // bytes available there var q; // output window write pointer var m; // bytes to end of window or read pointer var i; // copy input/output information to locals (UPDATE macro restores) // { p = z.next_in_index; n = z.avail_in; b = that.bitb; k = that.bitk; // } // { q = that.write; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); // } // process input based on current state // DEBUG dtree while (true) { switch (mode) { case TYPE: while (k < (3)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } t = /* (int) */(b & 7); last = t & 1; switch (t >>> 1) { case 0: // stored // { b >>>= (3); k -= (3); // } t = k & 7; // go to byte boundary // { b >>>= (t); k -= (t); // } mode = LENS; // get length of stored block break; case 1: // fixed // { var bl = []; // new Array(1); var bd = []; // new Array(1); var tl = [ [] ]; // new Array(1); var td = [ [] ]; // new Array(1); InfTree.inflate_trees_fixed(bl, bd, tl, td); codes.init(bl[0], bd[0], tl[0], 0, td[0], 0); // } // { b >>>= (3); k -= (3); // } mode = CODES; break; case 2: // dynamic // { b >>>= (3); k -= (3); // } mode = TABLE; break; case 3: // illegal // { b >>>= (3); k -= (3); // } mode = BADBLOCKS; z.msg = "invalid block type"; r = Z_DATA_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } break; case LENS: while (k < (32)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) { mode = BADBLOCKS; z.msg = "invalid stored block lengths"; r = Z_DATA_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } left = (b & 0xffff); b = k = 0; // dump bits mode = left !== 0 ? STORED : (last !== 0 ? DRY : TYPE); break; case STORED: if (n === 0) { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } if (m === 0) { if (q == that.end && that.read !== 0) { q = 0; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); } if (m === 0) { that.write = q; r = that.inflate_flush(z, r); q = that.write; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); if (q == that.end && that.read !== 0) { q = 0; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); } if (m === 0) { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } } } r = Z_OK; t = left; if (t > n) t = n; if (t > m) t = m; that.window.set(z.read_buf(p, t), q); p += t; n -= t; q += t; m -= t; if ((left -= t) !== 0) break; mode = last !== 0 ? DRY : TYPE; break; case TABLE: while (k < (14)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } table = t = (b & 0x3fff); if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { mode = BADBLOCKS; z.msg = "too many length or distance symbols"; r = Z_DATA_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if (!blens || blens.length < t) { blens = []; // new Array(t); } else { for (i = 0; i < t; i++) { blens[i] = 0; } } // { b >>>= (14); k -= (14); // } index = 0; mode = BTREE; /* falls through */ case BTREE: while (index < 4 + (table >>> 10)) { while (k < (3)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } blens[border[index++]] = b & 7; // { b >>>= (3); k -= (3); // } } while (index < 19) { blens[border[index++]] = 0; } bb[0] = 7; t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z); if (t != Z_OK) { r = t; if (r == Z_DATA_ERROR) { blens = null; mode = BADBLOCKS; } that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } index = 0; mode = DTREE; /* falls through */ case DTREE: while (true) { t = table; if (index >= 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) { break; } var j, c; t = bb[0]; while (k < (t)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } // if (tb[0] == -1) { // System.err.println("null..."); // } t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1]; c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2]; if (c < 16) { b >>>= (t); k -= (t); blens[index++] = c; } else { // c == 16..18 i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; while (k < (t + i)) { if (n !== 0) { r = Z_OK; } else { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } n--; b |= (z.read_byte(p++) & 0xff) << k; k += 8; } b >>>= (t); k -= (t); j += (b & inflate_mask[i]); b >>>= (i); k -= (i); i = index; t = table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { blens = null; mode = BADBLOCKS; z.msg = "invalid bit length repeat"; r = Z_DATA_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } c = c == 16 ? blens[i - 1] : 0; do { blens[i++] = c; } while (--j !== 0); index = i; } } tb[0] = -1; // { var bl_ = []; // new Array(1); var bd_ = []; // new Array(1); var tl_ = []; // new Array(1); var td_ = []; // new Array(1); bl_[0] = 9; // must be <= 9 for lookahead assumptions bd_[0] = 6; // must be <= 9 for lookahead assumptions t = table; t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl_, bd_, tl_, td_, hufts, z); if (t != Z_OK) { if (t == Z_DATA_ERROR) { blens = null; mode = BADBLOCKS; } r = t; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]); // } mode = CODES; /* falls through */ case CODES: that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; if ((r = codes.proc(that, z, r)) != Z_STREAM_END) { return that.inflate_flush(z, r); } r = Z_OK; codes.free(z); p = z.next_in_index; n = z.avail_in; b = that.bitb; k = that.bitk; q = that.write; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); if (last === 0) { mode = TYPE; break; } mode = DRY; /* falls through */ case DRY: that.write = q; r = that.inflate_flush(z, r); q = that.write; m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); if (that.read != that.write) { that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } mode = DONELOCKS; /* falls through */ case DONELOCKS: r = Z_STREAM_END; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); case BADBLOCKS: r = Z_DATA_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); default: r = Z_STREAM_ERROR; that.bitb = b; that.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; that.write = q; return that.inflate_flush(z, r); } } }; that.free = function(z) { that.reset(z, null); that.window = null; hufts = null; // ZFREE(z, s); }; that.set_dictionary = function(d, start, n) { that.window.set(d.subarray(start, start + n), 0); that.read = that.write = n; }; // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. that.sync_point = function() { return mode == LENS ? 1 : 0; }; } // Inflate // preset dictionary flag in zlib header var PRESET_DICT = 0x20; var Z_DEFLATED = 8; var METHOD = 0; // waiting for method byte var FLAG = 1; // waiting for flag byte var DICT4 = 2; // four dictionary check bytes to go var DICT3 = 3; // three dictionary check bytes to go var DICT2 = 4; // two dictionary check bytes to go var DICT1 = 5; // one dictionary check byte to go var DICT0 = 6; // waiting for inflateSetDictionary var BLOCKS = 7; // decompressing blocks var DONE = 12; // finished check, done var BAD = 13; // got an error--stay here var mark = [ 0, 0, 0xff, 0xff ]; function Inflate() { var that = this; that.mode = 0; // current inflate mode // mode dependent information that.method = 0; // if FLAGS, method byte // if CHECK, check values to compare that.was = [ 0 ]; // new Array(1); // computed check value that.need = 0; // stream check value // if BAD, inflateSync's marker bytes count that.marker = 0; // mode independent information that.wbits = 0; // log2(window size) (8..15, defaults to 15) // this.blocks; // current inflate_blocks state function inflateReset(z) { if (!z || !z.istate) return Z_STREAM_ERROR; z.total_in = z.total_out = 0; z.msg = null; z.istate.mode = BLOCKS; z.istate.blocks.reset(z, null); return Z_OK; } that.inflateEnd = function(z) { if (that.blocks) that.blocks.free(z); that.blocks = null; // ZFREE(z, z->state); return Z_OK; }; that.inflateInit = function(z, w) { z.msg = null; that.blocks = null; // set window size if (w < 8 || w > 15) { that.inflateEnd(z); return Z_STREAM_ERROR; } that.wbits = w; z.istate.blocks = new InfBlocks(z, 1 << w); // reset state inflateReset(z); return Z_OK; }; that.inflate = function(z, f) { var r; var b; if (!z || !z.istate || !z.next_in) return Z_STREAM_ERROR; f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; r = Z_BUF_ERROR; while (true) { // System.out.println("mode: "+z.istate.mode); switch (z.istate.mode) { case METHOD: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; if (((z.istate.method = z.read_byte(z.next_in_index++)) & 0xf) != Z_DEFLATED) { z.istate.mode = BAD; z.msg = "unknown compression method"; z.istate.marker = 5; // can't try inflateSync break; } if ((z.istate.method >> 4) + 8 > z.istate.wbits) { z.istate.mode = BAD; z.msg = "invalid window size"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.mode = FLAG; /* falls through */ case FLAG: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; b = (z.read_byte(z.next_in_index++)) & 0xff; if ((((z.istate.method << 8) + b) % 31) !== 0) { z.istate.mode = BAD; z.msg = "incorrect header check"; z.istate.marker = 5; // can't try inflateSync break; } if ((b & PRESET_DICT) === 0) { z.istate.mode = BLOCKS; break; } z.istate.mode = DICT4; /* falls through */ case DICT4: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need = ((z.read_byte(z.next_in_index++) & 0xff) << 24) & 0xff000000; z.istate.mode = DICT3; /* falls through */ case DICT3: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 16) & 0xff0000; z.istate.mode = DICT2; /* falls through */ case DICT2: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 8) & 0xff00; z.istate.mode = DICT1; /* falls through */ case DICT1: if (z.avail_in === 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (z.read_byte(z.next_in_index++) & 0xff); z.istate.mode = DICT0; return Z_NEED_DICT; case DICT0: z.istate.mode = BAD; z.msg = "need dictionary"; z.istate.marker = 0; // can try inflateSync return Z_STREAM_ERROR; case BLOCKS: r = z.istate.blocks.proc(z, r); if (r == Z_DATA_ERROR) { z.istate.mode = BAD; z.istate.marker = 0; // can try inflateSync break; } if (r == Z_OK) { r = f; } if (r != Z_STREAM_END) { return r; } r = f; z.istate.blocks.reset(z, z.istate.was); z.istate.mode = DONE; /* falls through */ case DONE: return Z_STREAM_END; case BAD: return Z_DATA_ERROR; default: return Z_STREAM_ERROR; } } }; that.inflateSetDictionary = function(z, dictionary, dictLength) { var index = 0; var length = dictLength; if (!z || !z.istate || z.istate.mode != DICT0) return Z_STREAM_ERROR; if (length >= (1 << z.istate.wbits)) { length = (1 << z.istate.wbits) - 1; index = dictLength - length; } z.istate.blocks.set_dictionary(dictionary, index, length); z.istate.mode = BLOCKS; return Z_OK; }; that.inflateSync = function(z) { var n; // number of bytes to look at var p; // pointer to bytes var m; // number of marker bytes found in a row var r, w; // temporaries to save total_in and total_out // set up if (!z || !z.istate) return Z_STREAM_ERROR; if (z.istate.mode != BAD) { z.istate.mode = BAD; z.istate.marker = 0; } if ((n = z.avail_in) === 0) return Z_BUF_ERROR; p = z.next_in_index; m = z.istate.marker; // search while (n !== 0 && m < 4) { if (z.read_byte(p) == mark[m]) { m++; } else if (z.read_byte(p) !== 0) { m = 0; } else { m = 4 - m; } p++; n--; } // restore z.total_in += p - z.next_in_index; z.next_in_index = p; z.avail_in = n; z.istate.marker = m; // return no joy or set up to restart on a new block if (m != 4) { return Z_DATA_ERROR; } r = z.total_in; w = z.total_out; inflateReset(z); z.total_in = r; z.total_out = w; z.istate.mode = BLOCKS; return Z_OK; }; // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP // implementation to provide an additional safety check. PPP uses // Z_SYNC_FLUSH // but removes the length bytes of the resulting empty stored block. When // decompressing, PPP checks that at the end of input packet, inflate is // waiting for these length bytes. that.inflateSyncPoint = function(z) { if (!z || !z.istate || !z.istate.blocks) return Z_STREAM_ERROR; return z.istate.blocks.sync_point(); }; } // ZStream function ZStream() { } ZStream.prototype = { inflateInit : function(bits) { var that = this; that.istate = new Inflate(); if (!bits) bits = MAX_BITS; return that.istate.inflateInit(that, bits); }, inflate : function(f) { var that = this; if (!that.istate) return Z_STREAM_ERROR; return that.istate.inflate(that, f); }, inflateEnd : function() { var that = this; if (!that.istate) return Z_STREAM_ERROR; var ret = that.istate.inflateEnd(that); that.istate = null; return ret; }, inflateSync : function() { var that = this; if (!that.istate) return Z_STREAM_ERROR; return that.istate.inflateSync(that); }, inflateSetDictionary : function(dictionary, dictLength) { var that = this; if (!that.istate) return Z_STREAM_ERROR; return that.istate.inflateSetDictionary(that, dictionary, dictLength); }, read_byte : function(start) { var that = this; return that.next_in.subarray(start, start + 1)[0]; }, read_buf : function(start, size) { var that = this; return that.next_in.subarray(start, start + size); } }; // Inflater function Inflater() { var that = this; var z = new ZStream(); var bufsize = 512; var flush = Z_NO_FLUSH; var buf = new Uint8Array(bufsize); var nomoreinput = false; z.inflateInit(); z.next_out = buf; that.append = function(data, onprogress) { var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array; if (data.length === 0) return; z.next_in_index = 0; z.next_in = data; z.avail_in = data.length; do { z.next_out_index = 0; z.avail_out = bufsize; if ((z.avail_in === 0) && (!nomoreinput)) { // if buffer is empty and more input is available, refill it z.next_in_index = 0; nomoreinput = true; } err = z.inflate(flush); if (nomoreinput && (err === Z_BUF_ERROR)) { if (z.avail_in !== 0) throw new Error("inflating: bad input"); } else if (err !== Z_OK && err !== Z_STREAM_END) throw new Error("inflating: " + z.msg); if ((nomoreinput || err === Z_STREAM_END) && (z.avail_in === data.length)) throw new Error("inflating: bad input"); if (z.next_out_index) if (z.next_out_index === bufsize) buffers.push(new Uint8Array(buf)); else buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index))); bufferSize += z.next_out_index; if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) { onprogress(z.next_in_index); lastIndex = z.next_in_index; } } while (z.avail_in > 0 || z.avail_out === 0); array = new Uint8Array(bufferSize); buffers.forEach(function(chunk) { array.set(chunk, bufferIndex); bufferIndex += chunk.length; }); return array; }; that.flush = function() { z.inflateEnd(); }; } // 'zip' may not be defined in z-worker and some tests var env = global.zip || global; env.Inflater = env._jzlib_Inflater = Inflater; })(this);
$(function(){ var from = MUDSLIDE.from, to = MUDSLIDE.to, label = MUDSLIDE.label, cloneAppend = MUDSLIDE.cloneAppend, copyProperties = MUDSLIDE.copyProperties, deepClone = MUDSLIDE.deepClone, tokenize = MUDSLIDE.tokenize, tokenizeChars = MUDSLIDE.tokenizeChars, mediaPlay = MUDSLIDE.mediaPlay, mediaVolume = MUDSLIDE.mediaVolume, mediaStop = MUDSLIDE.mediaStop, killTweens = MUDSLIDE.killTweens, record = MUDSLIDE.record, revert = MUDSLIDE.revert, delay = MUDSLIDE.delay, pause = MUDSLIDE.pause, wrapInner = MUDSLIDE.wrapInner; /** These are the tween generation rules, with an order which can be used to determine their priority within * a scene. Keys are selectors, and values are either... * - SchedulerFactories * - objects (further selector keys in the heirarchy) * - arrays (further sequences of factories and objects) * */ var gantZoomGs0 = {position:"absolute",fontSize:"12pt",top:"0%",left:"0%",width:"100%",height:"33%",zIndex:2,autoAlpha:1,repeat:1,yoyo:true}; var gantZoomGs1 = copyProperties({top:"33.6%"},deepClone(gantZoomGs0)); var gantZoomGs2 = copyProperties({top:"66.6%"},deepClone(gantZoomGs0)); var gantZoomMs = {duration:1,outerOffset:"-=2"}; var gantLiZoomGs = {display:"none",position:"relative",left:"500px",repeat:1,yoyo:true}; var gantLiZoomMs = {duration:1,innerOffset:"-=2"}; var rules = [ {".scene":[ //reveals in order of preferred appearance {".scene":from({},{duration:1.0,outerOffset:"-=0.9"})}, {".scene .gantt":pause()}, {".gantt td":record()}, //records position of all divs without disturbing layout {".gantt td":revert()}, //applies recorded positions to all, recreating layout in absolute terms? //animate transcription tasks {".gantt .method li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .method .transcription.phase0": to(gantZoomGs0,gantZoomMs)}, {".gantt .method .transcription.phase1":to(gantZoomGs1,gantZoomMs)}, {".gantt .method .transcription.phase2":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, //animate workshop tasks {".gantt .workshop li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .phase0 .workshop": to(gantZoomGs0,gantZoomMs)}, {".gantt .phase1 .workshop":to(gantZoomGs1,gantZoomMs)}, {".gantt .phase2 .workshop":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, //animate publication tasks {".gantt .publication li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .phase0 .publication": to(gantZoomGs0,gantZoomMs)}, {".gantt .phase1 .publication":to(gantZoomGs1,gantZoomMs)}, {".gantt .phase2 .publication":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, {".scene.console li.tokenize":[ cloneAppend("<audio class='typing' preload='auto' ><source src='audio/teletype_beep.wav' /> </audio>"), //creates an audio sample cloneAppend("<span class='cursor'>_</span>"), //copies a cursor in place at build time {">span.cursor":from({repeat:-1,yoyo:true},{duration:0.25,parallel:true})}, {"li.tokenize:not(.auto)":pause()}, {"audio.typing":[from({duration:0.05},{}), mediaVolume(0.15), mediaPlay()]}, //plays the audio sample tokenizeChars( from({display:"none",delay:0.05},{duration:0}) ), {">span.cursor":to({},{parallel:true})}, {"audio.typing":mediaStop()}, //stops the audio sample ]}, {".grow":from({width:0},{})}, {"h2":from({},{duration:2,innerOffset:"-=1.5"})}, {"blockquote":from({},{duration:2,innerOffset:"-=1.5"})}, {".left,.wide": from({position:"relative",top:"25px",left:"-25px",ease:Power1.easeIn},{})}, {".right": from({position:"relative",top:"25px",left:"25px",ease:Power1.easeIn},{outerOffset:"-=" + MUDSLIDE.configuration.defaultMsProps.from.duration})}, label("scene"), {".scene:not(.intro)":pause()}, //{".scene:not(.intro)":delay(2)}, //conceals in order of preferred appearance {".right": to({position:"relative",top:"25px",left:"25px"})}, {".left,.wide": to({position:"relative",top:"25px",left:"-25px"})}, {"blockquote":to({},{innerOffset:"-=" + (MUDSLIDE.configuration.defaultMsProps.to.duration * 0.75)})}, {"h2":to({},{innerOffset:"-=" + (MUDSLIDE.configuration.defaultMsProps.to.duration * 0.75)})}, {".grow":to({width:0})}, {".scene:not(.intro)":to({delay:0.1}, {duration:1.0})}, {".scene.intro":to({}, {autoDelay:0.075})}, ]} ]; //CH TODO - figure out how to activate this on a per-slide basis - triggering only when shown to save CPU var translateMax = 50; var scaleMax = 1.2; var translateX = Math.round(-translateMax + (Math.random() * translateMax * 2)); var translateY = Math.round(-translateMax + (Math.random() * translateMax * 2)); TweenMax.to(".background", 60, { transform:"translateX(" + translateX + "px) translateY(" + translateY + "px) scaleX(" + scaleMax + ") scaleY(" + scaleMax + ")", ease:Linear.easeNone, repeat:-1, yoyo:true }); //CH TODO - find a neat representation for this within the macro language var washTl = new TimelineMax({repeat:-1,yoyo:true}); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(0,50%,50%)"})); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(120,50%,50%)"})); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(240,50%,50%)"})); washTl.play(); MUDSLIDE.initDeck(rules); MUDSLIDE.timeline.pause(); /* var matchMaker = function(string){ return function(item){ return item.name.indexOf(string) != -1; }; }; TweenLite.fromTo(MUDSLIDE.timeline, 120, {time:0}, {time:300}); MUDSLIDE.timeline.tweenTo(MUDSLIDE.getPauseLabel(3), {onComplete:function(){MUDSLIDE.timeline.timeScale=1;}}); */ /* //switch this for a media tween factory ASAP var audio = $.media("#theme"); $("#theme").bind("canplaythrough", function () { //audio.seek(38); audio.play(); }); */ });
import assert from 'assert'; import sinon from 'sinon'; import githubSearch from '../../lib/resolver/github-search.js'; describe('github-search', () => { const sandbox = sinon.sandbox.create(); const fetchStub = sinon.stub(window, 'fetch'); const path = '/octo/foo.txt'; const target = 'bar.txt'; afterEach(() => { fetchStub.reset(); sandbox.reset(); }); after(() => { sandbox.restore(); }); it('returns a function', () => { assert.deepEqual( typeof githubSearch({ path, target }), 'function', ); }); it('calls the github search api', () => { githubSearch({ path, target })(); assert.deepEqual( fetchStub.args[0][0], 'https://api.github.com/search/code?q=bar.txt+in:path+filename:bar.txt+repo:octo/foo.txt+extension:.txt', ); }); it('does not append query param "extension" when target does not have a file extension', () => { githubSearch({ path, target: 'bar' })(); assert.deepEqual( fetchStub.args[0][0], 'https://api.github.com/search/code?q=bar+in:path+filename:bar+repo:octo/foo.txt', ); }); });
module.exports = { name: "part", ns: "irc", description: "Part Message", phrases: { active: "Client parting" }, ports: { input: { bot: { title: "IRC Client", type: "Client", required: true } }, output: { channel: { title: "Channel", type: "string" }, who: { title: "Who", type: "string" }, reason: { title: "Reason", type: "string" } } }, fn: function part(input, $, output, state, done, cb, on) { var r = function() { $.bot.part('part', function partCallback(channel, who, reason) { cb({ channel: channel, who: who, reason: reason }); }); }.call(this); return { output: output, state: state, on: on, return: r }; } }
import React from 'react'; import userEvent from '@testing-library/user-event'; import { render, screen } from '@testing-library/react'; import TextInput from './TextInput'; let clearErrorsCallback, setDataCallback; beforeEach(() => { clearErrorsCallback = jest.fn(); setDataCallback = jest.fn(); }); describe('TextInput component', () => { /** @test */ test('renders a text input element', () => { render( <TextInput clearErrors={clearErrorsCallback} id="text_input_test" setData={setDataCallback} value="sample text" />, ); const textInputElement = screen.getByTestId('text-input-element'); expect(textInputElement).toHaveAttribute('type', 'text'); }); /** @test */ test('will trigger clearErrors and setData methods on input change event', () => { render( <TextInput clearErrors={clearErrorsCallback} id="text_input_test" setData={setDataCallback} value="" />, ); const textInputElement = screen.getByTestId('text-input-element'); userEvent.type(textInputElement, 'hi'); const calls = setDataCallback.mock.calls; expect(clearErrorsCallback).toHaveBeenCalledTimes(2); expect(setDataCallback).toHaveBeenCalledTimes(2); expect(calls[0]).toEqual(['text_input_test', 'h']); expect(calls[1]).toEqual(['text_input_test', 'i']); }); });
var app = angular.module("ethics-app"); // Document revise controller app.controller("documentReviseController", function($scope, $rootScope, $filter, $translate, $location, config, $window, $q, $authenticationService, $documentService, $descriptionService, $concernService, upload) { /************************************************* FUNCTIONS *************************************************/ /** * [redirect description] * @param {[type]} path [description] * @return {[type]} [description] */ $scope.redirect = function(path){ $location.url(path); }; /** * [] */ $scope.resetFile = function(){ $scope.uploadstatus = "fail"; $scope.latest_revision.concerns.q14_filename = null; }; /** * [upload file] * @return {[type]} [file] */ $scope.doUpload = function (files) { $scope.uploadstatus = "uploading"; upload({ url: config.getUploadEndpoint() + $scope.latest_revision.concerns.concern_id, method: 'POST', headers: { 'Authorization': 'Bearer ' + $authenticationService.getToken(), 'X-DocumentId' : $documentService.getId() }, data: { filename: files[0], // a jqLite type="file" element, upload() will extract all the files from the input and put them into the FormData object before sending. } }).then( function (response) { $scope.uploadstatus = "success"; $scope.latest_revision.concerns.q14_file = true; $scope.latest_revision.concerns.q14_filename = files[0].name; $scope.latest_revision.concerns.q14_filepath = response.data; }, function (response) { $scope.uploadstatus = "fail"; $window.alert($filter('translate')('ALERT_UPLOAD_FILE_FAILED')); } ); }; /** * [toggleConcernHistory description] * @param {[type]} language [description] * @return {[type]} [description] */ $scope.toggle = function(category, property, language){ switch (category) { case 'general': { switch (property){ case 'display': { $scope.status.general.display = !$scope.status.general.display; break; } case 'history': { $scope.status.general.history = !$scope.status.general.history; if($scope.status.general.history){ $scope.status.general.limit = $scope.document.revisions.length; } else { $scope.status.general.limit = 1; } break; } } break; } case 'descriptions': { switch (property) { case 'language': { switch (language) { case 'en': { $scope.status.descriptions.language.en = !$scope.status.descriptions.language.en; break; } case 'de': { $scope.status.descriptions.language.de = !$scope.status.descriptions.language.de; break; } case 'pt': { $scope.status.descriptions.language.pt = !$scope.status.descriptions.language.pt; break; } } break; } case 'history': { switch (language) { case 'en': { $scope.status.descriptions.history.en.display = !$scope.status.descriptions.history.en.display; if($scope.status.descriptions.history.en.display){ $scope.status.descriptions.history.en.limit = $scope.document.revisions.length; } else { $scope.status.descriptions.history.en.limit = 1; } break; } case 'de': { $scope.status.descriptions.history.de.display = !$scope.status.descriptions.history.de.display; if($scope.status.descriptions.history.de.display){ $scope.status.descriptions.history.de.limit = $scope.document.revisions.length; } else { $scope.status.descriptions.history.de.limit = 1; } break; } case 'pt': { $scope.status.descriptions.history.pt.display = !$scope.status.descriptions.history.pt.display; if($scope.status.descriptions.history.pt.display){ $scope.status.descriptions.history.pt.limit = $scope.document.revisions.length; } else { $scope.status.descriptions.history.pt.limit = 1; } break; } } break; } case 'comments': { switch (language) { case 'en': { $scope.status.descriptions.comments.en = !$scope.status.descriptions.comments.en; break; } case 'de': { $scope.status.descriptions.comments.de = !$scope.status.descriptions.comments.de; break; } case 'pt': { $scope.status.descriptions.comments.pt = !$scope.status.descriptions.comments.pt; break; } } } } break; } case 'concerns': { switch (property) { case 'display': { $scope.status.concerns.display = !$scope.status.concerns.display; break; } case 'history': { $scope.status.concerns.history = !$scope.status.concerns.history; if($scope.status.concerns.history){ $scope.status.concerns.limit = $scope.document.revisions.length; } else { $scope.status.concerns.limit = 1; } break; } case 'comments': { $scope.status.concerns.comments = !$scope.status.concerns.comments; break; } } break; } } }; /** * [saveDocument description] * @return {[type]} [description] */ $scope.saveDocument = function(tab){ $scope.$parent.loading = { status: true, message: $filter('translate')('AUTO_SAVING') }; var save_descriptions = $q.defer(); var save_concerns = $q.defer(); // Save description $descriptionService.save($scope.latest_revision.descriptions.description_id, $scope.latest_revision.descriptions) .then(function onSuccess(response) { save_descriptions.resolve(); }) .catch(function onError(response) { $window.alert(response.data); }); // Save concern $concernService.save($scope.latest_revision.concerns.concern_id, $scope.latest_revision.concerns) .then(function onSuccess(response) { save_concerns.resolve(); }) .catch(function onError(response) { $window.alert(response.data); }); // Promises save_descriptions.promise.then(function(){ return; }); save_concerns.promise.then(function() { return; }); // Start parallel requests $q.all([ save_descriptions.promise, save_concerns.promise ]).then(function(){ $scope.$parent.loading = { status: false, message: ""}; // Redirect if(tab !== null){; $scope.tab = tab; } else { $scope.redirect("/documents/" + $documentService.getId() + "/status/" + $documentService.getStatus()); } }); }; /** * [submit description] * @return {[type]} [description] */ $scope.submit = function() { // Validate input if($scope.editDocumentForm.$invalid || ($scope.latest_revision.concerns.q14_filename == null && $scope.editDocumentForm.q14_value.$modelValue)) { // Update UI // Descriptions (en) $scope.editDocumentForm.en_title.$pristine = false; $scope.editDocumentForm.en_researcher.$pristine = false; $scope.editDocumentForm.en_study_time.$pristine = false; $scope.editDocumentForm.en_purpose.$pristine = false; $scope.editDocumentForm.en_procedure.$pristine = false; $scope.editDocumentForm.en_duration.$pristine = false; $scope.editDocumentForm.en_risks.$pristine = false; $scope.editDocumentForm.en_benefits.$pristine = false; // Descriptions (de) $scope.editDocumentForm.de_title.$pristine = false; $scope.editDocumentForm.de_researcher.$pristine = false; $scope.editDocumentForm.de_study_time.$pristine = false; $scope.editDocumentForm.de_purpose.$pristine = false; $scope.editDocumentForm.de_procedure.$pristine = false; $scope.editDocumentForm.de_duration.$pristine = false; $scope.editDocumentForm.de_risks.$pristine = false; $scope.editDocumentForm.de_benefits.$pristine = false; // Descriptions (pt) $scope.editDocumentForm.pt_title.$pristine = false; $scope.editDocumentForm.pt_researcher.$pristine = false; $scope.editDocumentForm.pt_study_time.$pristine = false; $scope.editDocumentForm.pt_purpose.$pristine = false; $scope.editDocumentForm.pt_procedure.$pristine = false; $scope.editDocumentForm.pt_duration.$pristine = false; $scope.editDocumentForm.pt_risks.$pristine = false; $scope.editDocumentForm.pt_benefits.$pristine = false; // Conerns (values) $scope.editDocumentForm.q01_value.$pristine = false; $scope.editDocumentForm.q02_value.$pristine = false; $scope.editDocumentForm.q03_value.$pristine = false; $scope.editDocumentForm.q04_value.$pristine = false; $scope.editDocumentForm.q05_value.$pristine = false; $scope.editDocumentForm.q06_value.$pristine = false; $scope.editDocumentForm.q07_value.$pristine = false; $scope.editDocumentForm.q08_value.$pristine = false; $scope.editDocumentForm.q09_value.$pristine = false; $scope.editDocumentForm.q10_value.$pristine = false; $scope.editDocumentForm.q11_1_value.$pristine = false; $scope.editDocumentForm.q11_2_value.$pristine = false; $scope.editDocumentForm.q12_value.$pristine = false; $scope.editDocumentForm.q13_value.$pristine = false; $scope.editDocumentForm.q14_value.$pristine = false; // Conerns (explanations) if($scope.editDocumentForm.q01_explanation){ $scope.editDocumentForm.q01_explanation.$pristine = false; } if($scope.editDocumentForm.q02_explanation){ $scope.editDocumentForm.q02_explanation.$pristine = false; } if($scope.editDocumentForm.q03_explanation){ $scope.editDocumentForm.q03_explanation.$pristine = false; } if($scope.editDocumentForm.q04_explanation){ $scope.editDocumentForm.q04_explanation.$pristine = false; } if($scope.editDocumentForm.q05_explanation){ $scope.editDocumentForm.q05_explanation.$pristine = false; } if($scope.editDocumentForm.q06_explanation){ $scope.editDocumentForm.q06_explanation.$pristine = false; } if($scope.editDocumentForm.q07_explanation){ $scope.editDocumentForm.q07_explanation.$pristine = false; } if($scope.editDocumentForm.q08_explanation){ $scope.editDocumentForm.q08_explanation.$pristine = false; } if($scope.editDocumentForm.q09_explanation){ $scope.editDocumentForm.q09_explanation.$pristine = false; } if($scope.editDocumentForm.q10_explanation){ $scope.editDocumentForm.q10_explanation.$pristine = false; } if($scope.editDocumentForm.q11_1_explanation){ $scope.editDocumentForm.q11_1_explanation.$pristine = false; } if($scope.editDocumentForm.q11_2_explanation){ $scope.editDocumentForm.q11_2_explanation.$pristine = false; } if($scope.editDocumentForm.q12_explanation){ $scope.editDocumentForm.q12_explanation.$pristine = false; } if($scope.editDocumentForm.q13_explanation){ $scope.editDocumentForm.q13_explanation.$pristine = false; } if($scope.editDocumentForm.q14_explanation){ $scope.editDocumentForm.q14_explanation.$pristine = false; } $window.alert($filter('translate')('ALERT_SUBMIT_DOCUMENT_FAILED')); } else { $scope.$parent.loading = { status: true, message: $filter('translate')('SUBMITTING_DOCUMENT') }; // Submit document $documentService.submit($documentService.getId()) .then(function onSuccess(response) { $scope.redirect("/documents/" + $documentService.getId()); }) .catch(function onError(response) { $window.alert(response.data); }); } }; /************************************************* INIT *************************************************/ $scope.$parent.loading = { status: true, message: $scope.$parent.loading.message }; $scope.document = $documentService.get(); $scope.latest_revision = $documentService.getLatestRevision(); $scope.tab = 0; // Check status if($documentService.getStatus()>1 && $documentService.getStatus()!=5){ // Redirect $scope.redirect("/documents/" + $documentService.getId() + "/status/" + $documentService.getStatus()); } // Show/hide comments and history $scope.status = { general: { display: true, history: false, limit: 1 }, descriptions: { language: { en: true, de: false, pt: false }, history: { en: { display: false, limit: 1 }, de: { display: false, limit: 1 }, pt: { display: false, limit: 1 } }, comments: { en: true, de: true, pt: true } }, concerns: { display: true, history: false, limit: 1, comments: true } }; // Show all comments and history $scope.toggle('general', 'history'); $scope.toggle('descriptions', 'history', 'en'); if($scope.latest_revision.descriptions.de_used){ $scope.toggle('descriptions', 'history', 'de'); } else { $scope.toggle('descriptions', 'language', 'de'); } if($scope.latest_revision.descriptions.pt_used){ $scope.toggle('descriptions', 'history', 'pt'); } else { $scope.toggle('descriptions', 'language', 'de'); } $scope.toggle('concerns', 'history'); if ($scope.latest_revision.concerns.q14_filename !== null) { $scope.uploadstatus= 'success'; } $scope.$parent.loading = { status: false, message: "" }; });
var controllersModule = angular.module('controllers', ['services']);//create a module with name 'controllers' and 'services' as dependency to it //create controller under this module 'controllers' and inject 'searchService' to it. controllersModule.controller('searchController', ['$scope', 'searchService', function($scope, searchService) { $scope.welcomeMsg = 'Search PB Site'; $scope.search = function() { //use the injected searchService to make actual search searchService.search($scope.searchTerm).then(function(result) { $scope.result = result.data;//response from searchService is set in $scope.result to render it in UI. }); } } ]);
/** * 缓存图片 * * @author liuwencheng * @date 2012-12-20 * * @update by liuwencheng 2013-6-2 重新处理已加载的图片缓存 * @update by z 2013-6-15 添加参数处理图片附加数据 * @update by liuwencheng 2013-8-28 包装成Class以实现多个实例加载, 增加loaded */ define(function(require,exports){ var $ = require('jquery') , objs = require('zz/utils/objs') , Class = require('zz/core/Class') var defaultOpts = { imgs: [], infos: [], done: null, sync: false, loaded: null } var ImgsLoader = Class() .init(function (opts) { this._opts = objs.extend({},defaultOpts, opts) //配置 this._leftNum = this._opts.imgs.length //剩余加载的数量 this._start() }) .method({ /** * 开始加载图片 */ _start: function () { var len = this._opts.imgs.length //异步加载 if (! this._opts.sync) { while (len--) { this.loadImg(len) } } //同步加载 else { this.loadImg(0) //加载第一张 } }, /** * 加载单个图片 * @param index {Number} img在数组中的位置 */ loadImg: function (index) { var img = new Image , that = this , _opts = this._opts , info //超出数组大小 if(index >= _opts.imgs.length) return //获取信息 info = _opts.infos && _opts.infos[index] //加载成功 img.onload = function(){ _opts.done && _opts.done(img,index,info) //数量-1 that._leftNum = that._leftNum - 1 //全部加载完 if (that._leftNum === 0) { _opts.loaded && _opts.loaded() that.destroy() //销毁 return } // 顺序加载时加载下一个图片 _opts.sync && that.loadImg(index+1) } //加载失败 img.onerror = function(){ _opts.sync && that.loadImg(index+1) } img.src = _opts.imgs[index] } }) /* * opts = { * imgs: {Array} * infos:{Array} 图片附加信息,和图片对应 * done: {Function} ( {Object} ImgObj 图片对象, {Number} index, {*} info )回调函数,加载完图片后执行 * loaded {Function} 图片全部加载完成的回调 * sync: {Boolean} 顺序加载图片, 默认false * } */ return function(opts){ return new ImgsLoader(opts) } });
var express = require('express'); var router = express.Router(); var cb_handler = require('../handlers/cb_handler.js'); var db_handler = require('../handlers/db_handler.js'); //Listar categorias router.get('/', function(req, res) { var my_cb_handler = cb_handler(req, res, null, db_handler.getCategories); db_handler.atenderQuery(req,res,my_cb_handler); }); //Agregar nueva categoria router.post('/', function (req, res) { var my_cb_handler = cb_handler(req,res,null, db_handler.addCategory); db_handler.atenderQuery(req,res,my_cb_handler); }); module.exports = router;
/* --- Day 11: Corporate Policy --- Santa's previous password expired, and he needs help choosing a new one. To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly eight lowercase letters (for security reasons), so he finds his new password by incrementing his old password string repeatedly until it is valid. Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on. Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. Unfortunately for Santa, a new Security-Elf recently started, and he has imposed some additional password requirements: Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz. For example: hijklmmn meets the first requirement (because it contains the straight hij) but fails the second requirement requirement (because it contains i and l). abbceffg meets the third requirement (because it repeats bb and ff) but fails the first requirement. abbcegjk fails the third requirement, because it only has one double letter (bb). The next password after abcdefgh is abcdffaa. The next password after ghijklmn is ghjaabcc, because you eventually skip all the passwords that start with ghi..., since i is not allowed. Given Santa's current password (your puzzle input), what should his next password be? --- Part Two --- Santa's password expired again. What's the next one? */ var corporatePolicy = require('./app/corporate_policy'); console.log(corporatePolicy.day11()); console.log(corporatePolicy.part2());
var app = require('http').createServer(handler) , fs = require('fs') , path = require('path') , url = require('url') ,mime=require('mime') app.listen(80); function handler (req, res) { var uri = url.parse(req.url).pathname; if(uri=='/'){ uri='/index.html' } uri=uri.replace(/%20/g,' ') console.log(uri) var filename = path.join(process.cwd(), uri); fs.readFile(filename, function (err, data) { if (err) { res.writeHead(404); return res.end('Error loading file...'); } res.setHeader('Content-type',mime.lookup(uri)); res.writeHead(200); res.end(data); }) }
/** * * @providesModule ReactNativeHeading * @flow */ 'use strict'; var React = require('react-native'); var ReactNativeHeading = React.NativeModules.ReactNativeHeading; module.exports = ReactNativeHeading;
export default class AttributeLocalization { /** * AttributeLocalization constructor. * * @param {string} formLabel */ constructor(formLabel) { this.formLabel = formLabel; } }
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; moduloUsuario.controller('UsuarioNewController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService', function ($scope, $routeParams, $location, serverService, sharedSpaceService) { $scope.id = $routeParams.id; $scope.ob = 'usuario'; $scope.result = null; $scope.title = "Crear un nuevo usuario"; $scope.icon = "fa-user"; if (sharedSpaceService.getFase() == 0) { $scope.obj = { id: 0, login: "", password: "", id_estado: 0, obj_estado: { id: 0 }, id_tipousuario: 0, obj_tipousuario: { id: 0 }, ciudad: "", firma: "", skin: "" }; } else { $scope.obj = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } $scope.chooseOne = function (foreignObjectName) { sharedSpaceService.setObject($scope.obj); sharedSpaceService.setReturnLink('/' + $scope.ob + '/new'); sharedSpaceService.setFase(1); $location.path('/' + foreignObjectName + '/selection/1/10'); } $scope.save = function () { console.log("save"); console.log({json: JSON.stringify(serverService.array_identificarArray($scope.obj))}); //strValues = serverService.array_identificarArray(thisObject.form_getFormValues(strClass)); serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) { $scope.result = data; }); }; $scope.$watch('obj.obj_estado.id', function () { serverService.getDataFromPromise(serverService.promise_getOne('estado', $scope.obj.obj_estado.id)).then(function (data2) { $scope.obj.obj_estado = data2.message; }); }); $scope.$watch('obj.obj_tipousuario.id', function () { serverService.getDataFromPromise(serverService.promise_getOne('usuario', $scope.obj.obj_tipousuario.id)).then(function (data2) { $scope.obj.obj_tipousuario = data2.message; }); }); $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/usuario/plist'); }; $("#alta_group").datetimepicker({format: "DD/MM/YYYY", locale: "es"}); $("#cambio_group").datetimepicker({format: "DD/MM/YYYY", locale: "es"}); }]);
/*globals describe, it, beforeEach, afterEach */ var assert = require("assert"), fs = require('fs'), _ = require('underscore'), path = require("path"), Html = require("../lib/html.js"), describeReporting = require("../../../test/helpers.js").describeReporting; describeReporting(path.join(__dirname, "../../"), ["html"], function(reporter) { describe('html', function() { beforeEach(function() { this.html = new Html(reporter); }); it('should be rendered', function(done) { var request = { options: { type: "html", timeout: 5000 }, reporter: reporter, template: { content: "Hey" }, data: null }; var response = { headers: {}}; _.findWhere(reporter.extensionsManager.recipes, { name: "html" }).execute(request, response).then(function () { assert.equal("Hey", response.result); done(); }); }); }); });
'use babel'; const {CompositeDisposable} = require('atom'); const validUrl = require('valid-url'); const addMarker = (editor, marker) => { // abort early if (!editor.replaceSelectedText) { return ''; } return editor.replaceSelectedText(null, text => { return (text === '') ? '' : `${marker}$selection${marker}`.replace('$selection', text); }); }; class mdwrap { constructor() { this.subscriptions = new CompositeDisposable(); this.subscriptions.add( atom.commands.add('atom-workspace', { 'atom-markdown-wrapper:paste': this.paste, 'atom-markdown-wrapper:image': this.image, 'atom-markdown-wrapper:bold': this.bold, 'atom-markdown-wrapper:italic': this.italic, 'atom-markdown-wrapper:strikethrough': this.strikethrough }) ); } destroy() { this.subscriptions.dispose(); } paste(editor, selection, clipboard) { // abort early if (!editor.insertText || !clipboard) { return; } let insert; if (editor && selection && clipboard) { insert = '[$selection]($href)' .replace('$selection', selection) .replace('$href', clipboard); } if (!validUrl.isWebUri(clipboard) && !clipboard.match(/^#/)) { throw new Error('Not a valid URL or #anchor'); } editor.insertText(insert); return insert; } image(editor, selection, clipboard) { // abort early if (!editor.insertText || !clipboard) { return; } let insert; if (editor && clipboard) { insert = '![$selection]($href)' .replace('$selection', selection || '') .replace('$href', clipboard); } if (!validUrl.isWebUri(clipboard)) { throw new Error('Not a valid image URL'); } editor.insertText(insert); return insert; } bold(editor) { return addMarker(editor, '**'); } italic(editor) { return addMarker(editor, '_'); } strikethrough(editor) { return addMarker(editor, '~~'); } } module.exports = mdwrap;
define("ghost/routes/mobile-index-route", ["ghost/utils/mobile","exports"], function(__dependency1__, __exports__) { "use strict"; var mobileQuery = __dependency1__["default"]; // Routes that extend MobileIndexRoute need to implement // desktopTransition, a function which is called when // the user resizes to desktop levels. var MobileIndexRoute = Ember.Route.extend({ desktopTransition: Ember.K, activate: function attachDesktopTransition() { this._super(); mobileQuery.addListener(this.desktopTransitionMQ); }, deactivate: function removeDesktopTransition() { this._super(); mobileQuery.removeListener(this.desktopTransitionMQ); }, setDesktopTransitionMQ: function () { var self = this; this.set('desktopTransitionMQ', function desktopTransitionMQ() { if (!mobileQuery.matches) { self.desktopTransition(); } }); }.on('init') }); __exports__["default"] = MobileIndexRoute; });
import { Map, List, fromJS } from 'immutable'; import * as _ from 'lodash'; import appPackage from '../package.json'; import { getPromotions, filterPromotions } from '../utils/marketingUtils'; const productPropertiesMap = Map({ prod_id: ['code'], prod_name: ['name'], prod_brand: ['brand', 'name'], prod_category: ['mainCategoryName'], prod_univers: ['mainCategoryRooms', '0'], prod_price: ['price', 'selling', 'gross'], prod_avail_online: ['vendible'], prod_avail_store: ['isClickCollectProduct'], prod_gamma: ['gamma'], prod_sconto: ['price', 'selling', 'discount'] }); const layerMap = Map({ filter_name: List(), filter_value: List() }); const LABEL = { PROD_SCONTO: 'prod_sconto', PROD_AVAIL_ONLINE: 'prod_avail_online', PROD_AVAIL_STORE: 'prod_avail_store', PROD_VARIANT: 'prod_variant', PROD_PUNTI_OMAGGIO: 'prod_puntiomaggio', PROD_IDEAPIU: 'prod_idepiu', PROD_BUNDLE: 'prod_bundle', FILTER_NAME: 'filter_name', FILTER_VALUE: 'filter_value', FILTER_RESULT: 'filter_result', PROD_POSITION: 'prod_position', PROD_LIST: 'prod_list', PROD_GAMMA: 'prod_gamma', PROD_NEW: 'prod_new', PROD_PRICE: 'prod_price' }; const relatedProductsSize = 12; const buildCommonLayer = (product) => { const commonPropertiesLayer = productPropertiesMap.reduce((acc, property, key) => { const productProperty = product.hasIn(property) ? product.getIn(property) : ''; return acc.set(key, List().push(productProperty)); }, Map({})); const normalizedCommonPropertiesLayer = normalizeProperties( commonPropertiesLayer ); return normalizedCommonPropertiesLayer; }; const normalizeProperties = (layer) => layer .set(LABEL.PROD_SCONTO, normalizeSconto(layer.get(LABEL.PROD_SCONTO))) .set(LABEL.PROD_AVAIL_ONLINE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_ONLINE))) .set(LABEL.PROD_AVAIL_STORE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_STORE))) .set(LABEL.PROD_PRICE, normalizePrice(layer.get(LABEL.PROD_PRICE))); const normalizeSconto = (value = Map({})) => { const sconto = value.get(0); return List().push(sconto !== '' ? Math.round(sconto * 10).toString() : sconto); }; const normalizePrice = (value = Map({})) => { const price = value.get(0); return List().push(price !== '' ? price.toFixed(2) : ''); }; const normalizeAvail = (field = List()) => List().push(field.get(0) ? '1' : '0'); const isProductNew = product => { const marketingAttributes = product.get('marketingAttributes'); const loyaltyProgram = product.get('loyaltyProgram'); if (marketingAttributes && loyaltyProgram) { const promotions = getPromotions(marketingAttributes, loyaltyProgram); const filteredPromotions = filterPromotions(promotions); const isNew = filteredPromotions.reduce( (acc, promotion) => promotion.get('code') === 'NOVITA', false ); const prodNew = isNew ? '1' : '0'; return Map({ prod_new: List().push(prodNew) }); } }; const getVariant = product => { const masterProductCode = product.get('masterProductCode'); const value = masterProductCode ? `${product.get('code')}_${masterProductCode}` : 'master'; return Map({ [LABEL.PROD_VARIANT]: List().push(value) }); }; const getGiftPoints = product => { const giftPoints = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (giftPoints && giftPoints === 'ADDITIONAL_POINTS') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_PUNTI_OMAGGIO, points); } return layer; }; const getIdeapiuPoints = product => { const ideapiuPointsType = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (ideapiuPointsType && ideapiuPointsType === 'DISCOUNT') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_IDEAPIU, points); } return layer; }; const getBundle = product => { const isBundle = product.getIn(['bundleInformation', 'isBundle']); const list = List(); let layer = Map({ prod_bundle: list.push('0') }); if (isBundle) { layer = layer.set(LABEL.PROD_BUNDLE, list.push('1')); } return layer; }; const getProdList = (product, path) => { const mainCategory = product.get('mainCategory'); const mainCategoryName = product.get('mainCategoryName'); const pageContext = getPageContext(path[0]); return `${pageContext} > ${mainCategoryName}/${mainCategory}`; }; const customizer = (objValue, srcValue) => { if (_.isArray(objValue)) { return objValue.concat(srcValue); } }; const buildNavigationStore = (navigationStore = Map()) => { let storeName = ''; if (navigationStore.size > 0) { const storeN = navigationStore.get('name'); const storeCode = navigationStore.get('code'); storeName = `${storeCode} - ${storeN}`; } return Map({ navigation_store: storeName }); }; const buildAppliedFilters = (filterGroup, appliedFilters) => { const dataLayer = filterGroup.reduce((acc, group) => { const groupName = group.get('group'); let accumulator = acc; const activeFilters = group .get('filters') .filter(filter => appliedFilters.includes(filter.get('code'))); if (activeFilters.size) { const newLayer = buildLayer(activeFilters, groupName); accumulator = accumulator .updateIn([LABEL.FILTER_NAME], arr => arr.concat(newLayer.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(newLayer.get(LABEL.FILTER_VALUE)) ); } return accumulator; }, layerMap); return dataLayer; }; const buildLayer = (activeFilters = List(), groupName = '') => activeFilters.reduce( (acc, activeFilter) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.push(groupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(activeFilter.get('name')) ), layerMap ); const buildSellingAid = (sellingAids, currentAid) => { const aidGroupName = sellingAids.get('userText'); const { name } = sellingAids .get('aids') .filter(aid => aid.get('code') === currentAid) .get(0) .toJS(); return layerMap .updateIn([LABEL.FILTER_NAME], arr => arr.push(aidGroupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(name)); }; const buildFiltersDataLayer = (layerDataList = []) => layerDataList.reduce( (acc, data) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.concat(data.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(data.get(LABEL.FILTER_VALUE)) ), layerMap ); const addResultToLayer = (productsNumber = 0, dataLayer = Map({})) => dataLayer.set( LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString() ); const getPageContext = (value) => { const map = Map({ catalogue: 'gallery-prodotto', product: 'scheda-prodotto' }); return map.get(value); }; const resetOldLevels = (list, start, end) => list.slice(start, end); // --------------------- EXPORTED FUNCTIONS -------------------> const buildPageName = (type, data, pageName = List()) => { const { worldName = '', pathArray = [], categoryCode = '', categoryName = '', prodName = '', prodCode = '' } = data; const isSessionStarting = pageName.size === 0 && type && type === 'session'; const isCatalogStarting = pageName.size > 1 && type && type === 'catalogue'; const isProductStarting = pageName.size > 1 && type && type === 'product'; let levels = pageName; if (isSessionStarting) { levels = levels.push(worldName).push('homepage'); } if (isCatalogStarting) { levels = resetOldLevels(levels, 0, 1); levels = levels .push('prodotti') .push(getPageContext(pathArray[0])) .push(categoryName) .push(categoryCode); } if (isProductStarting) { levels = resetOldLevels(levels, 0, 5); levels = levels .push(prodName) .push(prodCode) .set(2, getPageContext(pathArray[0])); } return levels; }; const buildProductLayer = (product = {}, action = 'detail') => { let productLayer = Map({}); if (!_.isEmpty(product)) { const commonProperties = buildCommonLayer(product); const newProductProperty = isProductNew(product); const variantProperty = getVariant(product); const giftPoints = getGiftPoints(product); const ideapiuPoints = getIdeapiuPoints(product); const isBundle = getBundle(product); const prodAction = Map({ prod_action: action }); productLayer = productLayer.merge( commonProperties, newProductProperty, variantProperty, giftPoints, ideapiuPoints, isBundle, prodAction ); return productLayer; } }; const buildRelatedProductsLayer = ({ products = List(), pathArray = [] }) => { const productList = products.size > relatedProductsSize ? List(products).setSize(relatedProductsSize) : products; let prodPositionCount = 0; if (products.size) { const listOfProductsLayer = productList.map(product => { const prodPosition = List().push((prodPositionCount += 1)); const prodListList = List().push(getProdList(product, pathArray)); let productLayer = buildCommonLayer(product); // add additional properties to productLayer productLayer = productLayer.set(LABEL.PROD_POSITION, prodPosition); productLayer = productLayer.set(LABEL.PROD_LIST, prodListList); return productLayer .set(LABEL.PROD_POSITION, prodPosition) .set(LABEL.PROD_LIST, prodListList) .delete(LABEL.PROD_GAMMA); }); const mergedlistOfProductsLayer = listOfProductsLayer.reduce( (acc, productLayer) => { const mergedValues = _.mergeWith( acc.toJS(), productLayer.toJS(), customizer ); return Map(mergedValues); } ); const normalizeFinalLayer = mergedlistOfProductsLayer.mapKeys(key => _.replace(key, 'prod', 'imp') ); return normalizeFinalLayer; } }; const buildActiveFilters = (filtersData = {}) => { const { sellingAids = Map({}), filterGroup = List(), productsNumber = 0, activeFilters = Map({}), } = filtersData; const aid = activeFilters.get('aid'); const filters = activeFilters.get('filters'); const availability = activeFilters.get('availability'); let appliedFilters = layerMap; let aidFilters = appliedFilters; let availabilityFilters = appliedFilters; if (aid !== '') { aidFilters = buildSellingAid(sellingAids, aid); } if (!_.isEmpty(filters)) { appliedFilters = buildAppliedFilters(filterGroup, filters); } if (availability) { availabilityFilters = fromJS({ filter_name: ['disponibilità in negozio'], filter_value: ['true'] }); } const dataLayer = buildFiltersDataLayer([ aidFilters, appliedFilters, availabilityFilters ]); const dataLayerWithResult = addResultToLayer(productsNumber, dataLayer); return dataLayerWithResult; }; const clearFilters = (dataLayer = Map({}), productsNumber = 0) => dataLayer .set(LABEL.FILTER_VALUE, List()) .set(LABEL.FILTER_NAME, List()) .set(LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString()); const buildReleaseVersion = (worldName = '') => `${_.snakeCase(worldName)}_${appPackage.version}`; const normalizeProductClickLayer = (productLayer, index, product, pathArray) => productLayer .delete(LABEL.PROD_BUNDLE) .delete(LABEL.PROD_GAMMA) .delete(LABEL.PROD_NEW) .delete(LABEL.PROD_VARIANT) .set(LABEL.PROD_POSITION, List().push(index)) .set(LABEL.PROD_LIST, List().push(getProdList(product, pathArray))); const getProductProperty = (product = Map({})) => { const jsonProduct = product.toJS(); let prodCode = 0; let prodCategory = ''; Object.keys(jsonProduct).forEach(key => { Object.keys(jsonProduct[key]).forEach(productProperty => { if (productProperty === 'code') { prodCode = jsonProduct[key][productProperty]; } if (productProperty === 'mainCategoryName') { prodCategory = jsonProduct[key][productProperty]; } }); }); return { prodCode, prodCategory }; }; export { buildPageName, buildProductLayer, buildRelatedProductsLayer, buildActiveFilters, clearFilters, buildNavigationStore, buildReleaseVersion, normalizeProductClickLayer, getProductProperty };
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Callback // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function tellMeWhenItIsDone(Callback) { setTimeout(function() { Callback(); }, (3*1000)); } tellMeWhenItIsDone( function() { console.log('google Foobar'); })
import { createStore, applyMiddleware, compose } from 'redux'; import reduxLogger from 'redux-logger'; import thunk from 'redux-thunk'; import reducers from 'reducers'; const logger = reduxLogger({ predicate: () => process.env.NODE_ENV === 'development', collapsed: true, duration: true, }); const middlewares = []; middlewares.push(applyMiddleware(...[thunk, logger])); export default createStore(reducers, {}, compose(...middlewares));
/** * @class Oskari.mapframework.service.base.Bundle * */ Oskari.clazz.define("Oskari.mapframework.service.base.Bundle", /** * @constructor * * Bundle's constructor is called when bundle is created. At * this stage bundle sources have been loaded, if bundle is * loaded dynamically. * */ function() { /* * Any bundle specific classes may be declared within * constructor to enable stealth mode * * When running within map application framework - Bundle * may refer classes declared with Oskari.clazz.define() - * Bundle may refer classes declared with Ext.define - * Bundle may refer classes declared within OpenLayers * libary * * */ }, { /* * @method create * * called when a bundle instance will be created * */ "create" : function() { return null; }, /** * @method update * * Called by Bundle Manager to provide state information to * bundle * */ "update" : function(manager, bundle, bi, info) { } }, /** * metadata */ { "protocol" : ["Oskari.bundle.Bundle"], "source" : { "scripts" : [{ "type" : "text/javascript", "src" : "../../../../sources/framework/service/service.js" } /*, { "type" : "text/javascript", "src" : "../../../../sources/framework/service/language-service.js" }*/], "resources" : [] }, "bundle" : { "manifest" : { "Bundle-Identifier" : "service-base", "Bundle-Name" : "mapframework.service.base.Bundle", "Bundle-Tag" : { "mapframework" : true }, "Bundle-Author" : [{ "Name" : "jjk", "Organisation" : "nls.fi", "Temporal" : { "Start" : "2009", "End" : "2011" }, "Copyleft" : { "License" : { "License-Name" : "EUPL", "License-Online-Resource" : "http://www.paikkatietoikkuna.fi/license" } } }], "Bundle-Name-Locale" : { "fi" : { "Name" : " mapframework.service.Bundle", "Title" : " mapframework.service.Bundle" }, "en" : {} }, "Bundle-Version" : "1.0.0", "Import-Namespace" : ["Oskari"], "Import-Bundle" : {} } } }); /** * Install this bundle by instantating the Bundle Class * */ Oskari.bundle_manager.installBundleClass("service-base", "Oskari.mapframework.service.base.Bundle");
// // Set up a collection to contain player information. On the server, // // it is backed by a MongoDB collection named "players". // Players = new Meteor.Collection("players"); // if (Meteor.isClient) { // Template.leaderboard.players = function () { // return Players.find({}, {sort: {score: -1, name: 1}}); // }; // Template.leaderboard.selected_name = function () { // var player = Players.findOne(Session.get("selected_player")); // return player && player.name; // }; // Template.player.selected = function () { // return Session.equals("selected_player", this._id) ? "selected" : ''; // }; // Template.leaderboard.events({ // 'click input.inc': function () { // Players.update(Session.get("selected_player"), {$inc: {score: 5}}); // } // }); // Template.player.events({ // 'click': function () { // Session.set("selected_player", this._id); // } // }); // } // // On server startup, create some players if the database is empty. // if (Meteor.isServer) { // Meteor.startup(function () { // if (Players.find().count() === 0) { // var names = ["Ada Lovelace", // "Grace Hopper", // "Marie Curie", // "Carl Friedrich Gauss", // "Nikola Tesla", // "Claude Shannon"]; // for (var i = 0; i < names.length; i++) // Players.insert({name: names[i], score: Math.floor(Math.random()*10)*5}); // } // }); // }
define(['antispammail'], function(antiSpamMail) { /** * Crypt given mail * * @method encrypt * @param {String} emailToEncrypt email address to encrypt * @returns {String} encrypted email address */ antiSpamMail.encrypt = function(emailToEncrypt) { return this.encryptDecrypt('mailto:' + emailToEncrypt, 1); }; /** * Initiate the form to encrypt * * @method encryptForm * @param {String} formName the name of the form * @param {String} fieldName name of email field * @returns void */ antiSpamMail.encryptForm = function(formName, fieldName) { var cryptform, email, emailHtml, encryptedMail, fieldShowEncryptedHtml, fieldShowEncryptedMail, i, radioObj, radioValue; formName = formName || 'antiSpamMail'; fieldName = fieldName || 'cryptmail_email'; fieldShowEncryptedMail = 'cryptmail_cryptedmail'; fieldShowEncryptedHtml = 'cryptmail_html'; cryptform = document.forms[formName]; email = cryptform[fieldName].value; if (cryptform.cryptmail_email.value.length < 4) { return false; } radioObj = cryptform.cryptmail_radio; if (radioObj.length > 0) { i = 0; while (i < radioObj.length) { radioValue = parseInt(radioObj[i].checked ? radioObj[i].value : void 0, 10); i++; } } else { radioValue = 0; } if (radioValue === 1) { emailHtml = email.replace(/\./g, '<span class="crypt" aria-hidden="true">.</span>.<span class="crypt" aria-hidden="true">.</span>'); emailHtml = emailHtml.replace(/@/, '<span class="crypt" aria-hidden="true">.</span>@<span class="crypt" aria-hidden="true">.</span>'); } else { emailHtml = email.replace(/\./g, ' [dot] '); emailHtml = emailHtml.replace(/@/, ' [at] '); } encryptedMail = this.encrypt(email); cryptform[fieldShowEncryptedMail].value = encryptedMail; cryptform[fieldShowEncryptedHtml].value = '<a href="javascript:' + this.encryptFn + '(\'' + encryptedMail + '\');">' + emailHtml + '</a>'; }; });
var Settings = Brumobile.Model.define( "SETTINGS", { name: "string", value: "string" } ); Settings.get = function(name, callback) { Settings.findOne({name:name}, function(setting) { if(setting) callback(setting.value); else callback(null); }); } Settings.save = function(name, value) { Settings.findOne({name:name}, function(setting) { if(setting) { setting.value = value; setting.save(); } else { var setting = new Settings({name:name, value:value}); setting.save(); } }); } Settings.remove = function(name) { Settings.findOne({name:name}, function(setting) { if(setting) { setting.destroy(); } }); }
// Regular expression that matches all symbols in the Miscellaneous Mathematical Symbols-A block as per Unicode v5.1.0: /[\u27C0-\u27EF]/;
version https://git-lfs.github.com/spec/v1 oid sha256:3bcf67b7cec3082efb04ef523044585dc1497641c27abaeaebb18be49aaeddaf size 85842
const addWater = () => image => image.addBandsReplace(water(image)) const water = image => image .selfExpression('i.water or (!i.snow and (i.blue/i.swir1 > 4.0 or i.ndwi > 0.15))') .rename('water') module.exports = addWater
Lawnchair.adapter('webkit-sqlite', (function () { // private methods var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) } , now = function () { return new Date() } // FIXME need to use better date fn // not entirely sure if this is needed... if (!Function.prototype.bind) { Function.prototype.bind = function( obj ) { var slice = [].slice , args = slice.call(arguments, 1) , self = this , nop = function () {} , bound = function () { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))) } nop.prototype = self.prototype bound.prototype = new nop() return bound } } // public methods return { valid: function() { return !!(window.openDatabase) }, init: function (options, callback) { var that = this , cb = that.fn(that.name, callback) , create = "CREATE TABLE IF NOT EXISTS " + this.record + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)" , win = function(){ return cb.call(that, that); } // open a connection and create the db if it doesn't exist this.db = openDatabase(this.name, '1.0.0', this.name, 65536) this.db.transaction(function (t) { t.executeSql(create, [], win, fail) }) }, keys: function (callback) { var cb = this.lambda(callback) , that = this , keys = "SELECT id FROM " + this.record + " ORDER BY timestamp DESC" this.db.transaction(function(t) { var win = function (xxx, results) { if (results.rows.length == 0 ) { cb.call(that, []) } else { var r = []; for (var i = 0, l = results.rows.length; i < l; i++) { r.push(results.rows.item(i).id); } cb.call(that, r) } } t.executeSql(keys, [], win, fail) }) return this }, // you think thats air you're breathing now? save: function (obj, callback) { var that = this , id = obj.key || that.uuid() , ins = "INSERT INTO " + this.record + " (value, timestamp, id) VALUES (?,?,?)" , up = "UPDATE " + this.record + " SET value=?, timestamp=? WHERE id=?" , win = function () { if (callback) { obj.key = id; that.lambda(callback).call(that, obj) }} , val = [now(), id] // existential that.exists(obj.key, function(exists) { // transactions are like condoms that.db.transaction(function(t) { // TODO move timestamp to a plugin var insert = function (obj) { val.unshift(JSON.stringify(obj)) t.executeSql(ins, val, win, fail) } // TODO move timestamp to a plugin var update = function (obj) { delete(obj.key) val.unshift(JSON.stringify(obj)) t.executeSql(up, val, win, fail) } // pretty exists ? update(obj) : insert(obj) }) }); return this }, // FIXME this should be a batch insert (but we'd need to preserve the order of the results) batch: function (objs, callback) { var results = [] , done = objs.length , self = this var putOne = function(i) { self.save(objs[i], function(obj) { // make sure we preserve order results[i] = obj; if ((--done) > 0) { return; } if (callback) { self.lambda(callback).call(self, results); } }); }; for (var i = 0, l = objs.length; i < l; i++) putOne(i); return this }, get: function (keyOrArray, cb) { var that = this , sql = '' , args = this.isArray(keyOrArray) ? keyOrArray : [keyOrArray]; // batch selects support sql = 'SELECT id, value FROM ' + this.record + " WHERE id IN (" + args.map(function(){return '?'}).join(",") + ")" // FIXME // will always loop the results but cleans it up if not a batch return at the end.. // in other words, this could be faster var win = function (xxx, results) { var o , r , lookup = {} // map from results to keys for (var i = 0, l = results.rows.length; i < l; i++) { o = JSON.parse(results.rows.item(i).value) o.key = results.rows.item(i).id lookup[o.key] = o; } r = args.map(function(key) { return lookup[key]; }); if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null if (cb) that.lambda(cb).call(that, r) } this.db.transaction(function(t){ t.executeSql(sql, args, win, fail) }) return this }, exists: function (key, cb) { var is = "SELECT * FROM " + this.record + " WHERE id = ?" , that = this , win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) } this.db.transaction(function(t){ t.executeSql(is, [key], win, fail) }) return this }, all: function (callback) { var that = this , all = "SELECT * FROM " + this.record , r = [] , cb = this.fn(this.name, callback) || undefined , win = function (xxx, results) { if (results.rows.length != 0) { for (var i = 0, l = results.rows.length; i < l; i++) { var obj = JSON.parse(results.rows.item(i).value) obj.key = results.rows.item(i).id r.push(obj) } } if (cb) cb.call(that, r) } this.db.transaction(function (t) { t.executeSql(all, [], win, fail) }) return this }, remove: function (keyOrArray, cb) { var that = this , args , sql = "DELETE FROM " + this.record + " WHERE id " , win = function () { if (cb) that.lambda(cb).call(that) } if (!this.isArray(keyOrArray)) { sql += '= ?'; args = [keyOrArray]; } else { args = keyOrArray; sql += "IN (" + args.map(function(){return '?'}).join(',') + ")"; } args = args.map(function(obj) { return obj.key ? obj.key : obj; }); this.db.transaction( function (t) { t.executeSql(sql, args, win, fail); }); return this; }, nuke: function (cb) { var nuke = "DELETE FROM " + this.record , that = this , win = cb ? function() { that.lambda(cb).call(that) } : function(){} this.db.transaction(function (t) { t.executeSql(nuke, [], win, fail) }) return this } ////// }})())
var gplay = require('google-play-scraper'); var fs = require('fs'); var appSet = new Set(); var lineReader = require('readline').createInterface({ input: fs.createReadStream('teste') }); var wStream = fs.createWriteStream("handledApps.csv", { flags : 'w' }); lineReader.on('line', function (line){ if(line.indexOf("value") > -1){ var vals = line.split(":"); var pattern = /[\"\\\[\]]/g; var apps = vals[1].replace(pattern, "").split(","); console.log("********************"); console.log(vals[1]); console.log(vals[1].replace(pattern, "")); console.log(apps); apps.forEach(function(collectedApp){ appSet.add(collectedApp); }); } }); lineReader.on('close', function(){ console.log("Total of apps: " + appSet.size); appSet.forEach(function(collectedApp){ gplay.app({appId: collectedApp}) .then(function(app){ wStream.write(collectedApp + " " + app.genreId + "\n"); //console.log(collectedApp + " " + app.genreId); }) .catch(function(e){ console.log(collectedApp + ' = There was an error fetching the application!'); }); }); });
import chromedriver from'chromedriver'; export function testStart(webdriver) { chromedriver.start(); const driver = new webdriver.Builder() .forBrowser('chrome') .build(); return driver; } export function testStop(driver, done) { driver.quit().then(() => { chromedriver.stop(); done(); }); }
import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import * as reducers from './reducers'; import middleware from './middleware'; const reducer = combineReducers(reducers); // create a store that has redux-thunk middleware enabled const finalCreateStore = compose.apply(this, middleware.map(md => applyMiddleware(md)).concat([createStore])); export const store = finalCreateStore(reducer);
// For now we introduce the API but use the full underscore and backbone libs module.exports = require('./src/BevRealLibs.js');
import { GET_NEW_MUSIC_LIST_ID } from '../actions/index.js'; import { RESET_GAME } from '../actions/index.js'; export default function(state = null, action) { switch(action.type) { case GET_NEW_MUSIC_LIST_ID: return action.payload; case RESET_GAME: return null; } return state; }
'use strict'; angular.module('main') .service('Dialog', function ($cordovaDialogs, $q) { return { alert: function (message, title) { var defer = $q.defer(); if (window.cordova) { $cordovaDialogs.alert(message, title) .then(function () { defer.resolve(); }); } else { defer.reject('Unsupported platform'); } return defer.promise; }, confirm: function (message, title, buttonsText) { var defer = $q.defer(); if (window.cordova) { $cordovaDialogs.confirm(message, title, buttonsText) .then(function (result) { if (result === 2) { defer.resolve(true); } defer.reject(false); }); } else { defer.reject('Unsupported platform'); } return defer.promise; } }; });
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included with Laravel will automatically verify the header's value. */ //Vue.http.interceptors.push((request, next) => { // request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken); // // next(); //}); /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
/* Smoothly scroll element to the given target (element.scrollTop) for the given duration Returns a promise that's fulfilled when done, or rejected if interrupted Taken from https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery */ var smoothScrollTo = function(element, target, duration) { target = Math.round(target); duration = Math.round(duration); if (duration < 0) { return Promise.reject("bad duration"); } if (duration === 0) { element.scrollTop = target; return Promise.resolve(); } var start_time = Date.now(); var end_time = start_time + duration; var start_top = element.scrollTop; var distance = target - start_top; // based on http://en.wikipedia.org/wiki/Smoothstep var smooth_step = function(start, end, point) { if(point <= start) { return 0; } if(point >= end) { return 1; } var x = (point - start) / (end - start); // interpolation return x*x*(3 - 2*x); } return new Promise(function(resolve, reject) { // This is to keep track of where the element's scrollTop is // supposed to be, based on what we're doing var previous_top = element.scrollTop; // This is like a think function from a game loop var scroll_frame = function() { if(element.scrollTop != previous_top) { reject("interrupted"); return; } // set the scrollTop for this frame var now = Date.now(); var point = smooth_step(start_time, end_time, now); var frameTop = Math.round(start_top + (distance * point)); element.scrollTop = frameTop; // check if we're done! if(now >= end_time) { resolve(); return; } // If we were supposed to scroll but didn't, then we // probably hit the limit, so consider it done; not // interrupted. if(element.scrollTop === previous_top && element.scrollTop !== frameTop) { resolve(); return; } previous_top = element.scrollTop; // schedule next frame for execution setTimeout(scroll_frame, 0); } // boostrap the animation process setTimeout(scroll_frame, 0); }); }
import React from 'react'; import { createDevTools } from 'redux-devtools'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' defaultPosition='bottom' defaultSize={0.15} > <SliderMonitor keyboardEnabled /> </DockMonitor> );
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Sonar( opts ) { if ( !(this instanceof Sonar) ) { return new Sonar( opts ); } var last, samples, median; last = null; samples = []; opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.ANALOG; this.pin = opts.pin || 0; // Sonar instance properties this.freq = opts.freq || 100; this.voltage = null; // Set the pin to ANALOG mode this.firmata.pinMode( this.pin, this.mode ); this.firmata.analogRead( this.pin, function( data ) { this.voltage = data; samples.push( data ); }.bind(this)); // Throttle setInterval(function() { var err; err = null; median = samples.sort()[ Math.floor( samples.length / 2 ) ]; // Emit throttled event this.emit( "read", err, median ); // If the median value for this interval is not the same as the // median value in the last interval, fire a "change" event. if ( median !== last ) { this.emit( "change", err, median ); } // Store this media value for comparison // in next interval last = median; // Reset samples; samples.length = 0; }.bind(this), this.freq ); Object.defineProperties( this, { // Based on the voltage, // Calculate the distance in inches and centimeters inches: { get: function() { return ( 254 / 1024 ) * 2 * median; } }, cm: { get: function() { return ( median / 2 ) * 2.54; } } }); } util.inherits( Sonar, events.EventEmitter ); module.exports = Sonar; // Reference // // http://www.maxbotix.com/tutorials.htm#Code_example_for_the_BasicX_BX24p // http://www.electrojoystick.com/tutorial/?page_id=285 // Tutorials // // http://www.sensorpedia.com/blog/how-to-interface-an-ultrasonic-rangefinder-with-sensorpedia-via-twitter-guide-2/
define([ "dojo/_base/array", // array.indexOf, array.map "dojo/_base/declare", // declare "dojo/dom-geometry", // domGeometry.setMarginBox "dojo/has", "dojo/query", // query "./_FormValueWidget", "dojo/touch" // not used directly, but allows me to set dojoClick flag on node and get responsive click handling ], function(array, declare, domGeometry, has, query, _FormValueWidget){ // module: // dijit/form/MultiSelect var MultiSelect = declare("dijit.form.MultiSelect" + (has("dojo-bidi") ? "_NoBidi" : ""), _FormValueWidget, { // summary: // Widget version of a `<select multiple=true>` element, // for selecting multiple options. // size: Number // Number of elements to display on a page // NOTE: may be removed in version 2.0, since elements may have variable height; // set the size via style="..." or CSS class names instead. size: 7, baseClass: "dijitMultiSelect", templateString: "<select multiple='true' ${!nameAttrSetting} data-dojo-attach-point='containerNode,focusNode' data-dojo-attach-event='onchange: _onChange'></select>", buildRendering: function(){ this.inherited(arguments); // get responsive click handling, see dojo/touch this.domNode.dojoClick = true; }, addSelected: function(/*dijit/form/MultiSelect*/ select){ // summary: // Move the selected nodes of a passed Select widget // instance to this Select widget. // // example: // | // move all the selected values from "bar" to "foo" // | dijit.byId("foo").addSelected(dijit.byId("bar")); select.getSelected().forEach(function(n){ this.containerNode.appendChild(n); // scroll to bottom to see item // cannot use scrollIntoView since <option> tags don't support all attributes // does not work on IE due to a bug where <select> always shows scrollTop = 0 this.domNode.scrollTop = this.domNode.offsetHeight; // overshoot will be ignored // scrolling the source select is trickier esp. on safari who forgets to change the scrollbar size var oldscroll = select.domNode.scrollTop; select.domNode.scrollTop = 0; select.domNode.scrollTop = oldscroll; }, this); this._set('value', this.get('value')); }, getSelected: function(){ // summary: // Access the NodeList of the selected options directly return query("option", this.containerNode).filter(function(n){ return n.selected; // Boolean }); // dojo/NodeList }, _getValueAttr: function(){ // summary: // Hook so get('value') works. // description: // Returns an array of the selected options' values. // Don't call getSelect.map() because it doesn't return a real array, // and that messes up dojo.toJson() calls like in the Form.html test return array.map(this.getSelected(), function(n){ return n.value; }); }, multiple: true, // for Form _setValueAttr: function(/*Array*/ values, /*Boolean?*/ priorityChange){ // summary: // Hook so set('value', values) works. // description: // Set the value(s) of this Select based on passed values query("option", this.containerNode).forEach(function(n){ n.selected = (array.indexOf(values, n.value) != -1); }); this.inherited(arguments); }, invertSelection: function(/*Boolean?*/ onChange){ // summary: // Invert the selection // onChange: Boolean // If false, onChange is not fired. var val = []; query("option", this.containerNode).forEach(function(n){ if(!n.selected){ val.push(n.value); } }); this._setValueAttr(val, !(onChange === false || onChange == null)); }, _onChange: function(/*Event*/){ this._handleOnChange(this.get('value'), true); }, // for layout widgets: resize: function(/*Object*/ size){ if(size){ domGeometry.setMarginBox(this.domNode, size); } }, postCreate: function(){ this._set('value', this.get('value')); this.inherited(arguments); } }); if(has("dojo-bidi")){ MultiSelect = declare("dijit.form.MultiSelect", MultiSelect, { addSelected: function(/*dijit/form/MultiSelect*/ select){ select.getSelected().forEach(function(n){ n.text = this.enforceTextDirWithUcc(this.restoreOriginalText(n), n.text); }, this); this.inherited(arguments); }, _setTextDirAttr: function(textDir){ // to insure the code executed only when _BidiSupport loaded, and only // when there was a change in textDir if((this.textDir != textDir || !this._created) && this.enforceTextDirWithUcc){ this._set("textDir", textDir); query("option", this.containerNode).forEach(function(option){ // If the value wasn't defined explicitly, it the same object as // option.text. Since the option.text will be modified (by wrapping of UCC) // we want to save the original option.value for form submission. if(!this._created && option.value === option.text){ option.value = option.text; } // apply the bidi support option.text = this.enforceTextDirWithUcc(option, option.originalText || option.text); }, this); } } }); } return MultiSelect; });
import { put, takeLatest, call, select } from 'redux-saga/effects'; import { push } from 'react-router-redux'; import { LOGIN, RESOLVE_APP_STAGE, GET_PROFILE, SIGN_OUT } from '../../constants/user'; import { ROUTES } from '../../constants/routes'; import { setUser, destroyUser, setProfile } from '../../actions/user'; import { setAuthToken, removeAuthToken } from '../../utils/auth'; import { convertProfileResponse } from '../../utils/converters/api/response'; import routes from '../../utils/network/api'; export function* resolveAppStageSaga({ payload: { user } }) { if (user.token && user.profile) { if (!user.profile.registered) { yield put(push(ROUTES.USER.REGISTRATION)); } else { yield put(push(ROUTES.APP.HOME)); } } } export function* loginUserSaga({ payload: { user } }) { const { token } = user; setAuthToken(token); yield put(setUser(user)); } export function* signOutSaga() { removeAuthToken(); yield put(destroyUser()); yield put(push(ROUTES.USER.LOGIN)); } export function* getUserProfile() { const response = yield call(routes.user.profile); let profile = null; if (!response.err) { profile = response.data; } return profile; } export function* updateUserProfile() { const profile = yield getUserProfile(); if (profile) { yield put(setProfile(convertProfileResponse(profile))); } } export function* getUser() { let user = yield select((state) => state.get('user')); if (!user.toJS().profile) { const profile = yield getUserProfile(); if (profile) { yield put(setProfile(convertProfileResponse(profile))); const stateUser = yield select((state) => state.get('user')); user = stateUser.toJS(); } else { user = null; } } else { user = user.toJS(); } return user; } function* userFlow() { yield takeLatest(LOGIN, loginUserSaga); yield takeLatest(RESOLVE_APP_STAGE, resolveAppStageSaga); yield takeLatest(GET_PROFILE, getUserProfile); yield takeLatest(SIGN_OUT, signOutSaga); } export default [ userFlow, ];
var express = require('express'); var glob = require('glob'); var config = require('./config'); var dir = config.MEDIA_DIRECTORY + '/**/*.+(' + config.MEDIA_FILE_TYPES.join('|') + ')'; var data = []; var hashData = {}; glob(dir, {}, function(err,files) { for(var i = 0; i < files.length; i++) { var video = {name:files[i], id:i}; data.push(video); hashData[i] = video; } }); exports.getFromDirectory = function() { return data; } exports.getHashedVideos = function() { return hashData; }
/* * jquery.widgrid * by Alexandre Piel * email: alexandre (dot) piel (at) gmail (dot) com * */ (function ($) { var Widgrid = function (target, options) { var defaults = { widgets: [], columns: 6, rows: 4, dropClass: 'widgrid-drop', validClass: 'widgrid-valid-drop', hoverClass: 'widgrid-drop-hover', usedClass: 'widgrid-used-drop', resizeClass: 'widgrid-resize-over', opacity: .75, removeWidget: function(widget) { return widget; }, addWidget: function(widget) { return widget; }, }; this.target = $(target); this.options = $.extend(defaults, options); this.init(); }; Widgrid.prototype = { dropTimer: null, dropWidth: 0, dropHeight: 0, dropElmts: [], dropElmtsGrid: [], init: function () { var me = this; this.addDropArea(); this.calcDropSize(); this.setDroppable(); this.initWidgets(); this.target.on('click', 'a[href=#removeWidget]', function() { me.removeWidget($(this).parent()); return false; }); }, initWidgets: function() { var me = this; $.each(me.options.widgets, function() { var widget = me.addWidget(this.widget); for(var r = this.position.row; r<this.position.row+this.dimension.rows; r++) { for(var c = this.position.col; c<this.position.col+this.dimension.cols; c++) { var drop = me.dropElmtsGrid[r][c]; //me.target.find('div[row='+r+'][column='+c+']'); // this is not fine, we need a tree this.dropElmts drop.addClass(me.options.validClass); me.validDrop(widget, drop); } } }); }, addDropArea: function() { for (var r = 0; r < this.options.rows; r++) { this.dropElmtsGrid[r] = []; for (var c = 0; c < this.options.columns; c++) { var drop = $(this.getDropElement(r, c)); drop.addClass(this.options.dropClass) .css('float', 'left') .data('position', {row: r, col: c}) .appendTo(this.target); this.dropElmtsGrid[r][c] = drop; } } this.dropElmts = this.target.find("." + this.options.dropClass); }, getDropElement: function(row, col) { return '<div row="'+row+'" column="'+col+'"></div>'; }, calcDropSize: function() { this.dropWidth = Math.floor((this.target.innerWidth()-(this.dropElmts.outerWidth(true)*this.options.columns))/this.options.columns); this.dropElmts.width(this.dropWidth); this.dropHeight = Math.floor((this.target.innerHeight()-(this.dropElmts.outerHeight(true)*this.options.rows))/this.options.rows); this.dropElmts.height(this.dropHeight); }, setDroppable: function() { var me = this; this.dropElmts.droppable({ hoverClass: me.options.hoverClass, tolerance: "touch", drop: function(event, ui) { if ($(this).hasClass(me.options.validClass)) { var widget = me.addWidget($(ui.draggable)); me.validDrop(widget, this); } }, over: function( event, ui ) { clearTimeout(me.dropTimer); me.dropTimer = setTimeout(function() { me.dropOver($(ui.draggable), '.' + me.options.hoverClass); }, 10); }, out: function( event, ui ) { clearTimeout(me.dropTimer); me.dropTimer = setTimeout(function() { me.dropOver($(ui.draggable), '.' + me.options.hoverClass); }, 10); } }); }, validDrop: function(widget, dropElmt) { var posParent = $(dropElmt).parent().offset(); var pos = $(dropElmt).offset(); var top = pos.top - posParent.top; var left = pos.left - posParent.left; if (!widget.data('leftopset')) { widget.parent().css({ marginTop: top, marginLeft: left }); widget.css({ top: 0, left: 0 }); widget.data('leftopset', {top: top, left: left}); widget.data('droppables', []); widget.data('position', $(dropElmt).data('position')); } widget.css({ height: top - widget.data('leftopset').top + $(dropElmt).innerHeight() }); widget.css({ width: left - widget.data('leftopset').left + $(dropElmt).innerWidth() }); //$(dropElmt).droppable( "disable" ); $(dropElmt).addClass(this.options.usedClass); widget.data('droppables').push(dropElmt); $(dropElmt).removeClass(this.options.validClass); }, dropOver: function(widget, identifier) { var free = [], cntRow = 0, cntCol = 0; this.dropElmts.removeClass(this.options.validClass); this.target.find(identifier).not('.' + this.options.usedClass).each(function() { var row = $(this).attr('row'); if (typeof free[row] == 'undefined') free[row] = []; free[row][$(this).attr('column')] = this; }); var first = 0; for(first in free) break; for(var col in free[first]) { col = parseInt(col); cntCol++; if (typeof free[first][col+1] == 'undefined') { free[first].splice(col+1); break; } } for(var col in free[first]) { for(var row in free) { if (row !== first && typeof free[row][col] == 'undefined') { free.splice(row); } } } for(var row in free) { cntRow++; for(var col in free[row]) { if (typeof free[first][col] == 'undefined') delete free[row][col]; else $(free[row][col]).addClass(this.options.validClass); } } widget.data('dimension', {'rows': cntRow, 'cols': cntCol}); }, removeWidget: function(widget) { widget = this.options.removeWidget(widget); this.resetDrop(widget); widget.parent().remove(); }, getCloseElement: function() { return '<a class="close" href="#removeWidget">&times;</a>'; }, addWidget: function(widget) { widget = this.options.addWidget(widget); if (widget.parent().parent().get(0) !== this.target.get(0)) { this.setWidgetResizable(widget); this.setWidgetDraggable(widget); widget.prepend(this.getCloseElement()); $('<div></div>').append(widget).css('position', 'absolute') // Add a div element because of bug with draggable and margin .appendTo(this.target); } return widget; }, setWidgetDraggable: function(widget) { var me = this; widget.draggable(); // For cloned widget widget.draggable("destroy"); widget.draggable({ revert: true, zIndex: 100, opacity: me.options.opacity, start: function( event, ui ) { widget.data('leftopset', null); me.resetDrop(widget); }, }); }, setWidgetResizable: function(widget) { var me = this; widget.resizable({ minWidth: this.dropWidth, minHeight: this.dropHeight, start: function( event, ui ) { widget.css('opacity', me.options.opacity); widget.css('zIndex', 200); me.resetDrop(widget); }, resize: function( event, ui ) { $('.' + me.options.resizeClass).removeClass(me.options.resizeClass); me.dropElmts.not('.ui-droppable-disabled').each(function() { if (me.overlaps(widget, this)) { $(this).addClass(me.options.resizeClass); } }); me.dropOver(widget, '.' + me.options.resizeClass); }, stop: function( event, ui ) { widget.css('opacity', 1); widget.css('zIndex', 0); me.target.find("." + me.options.validClass).each(function () { me.validDrop(widget, this); }); $('.' + me.options.resizeClass).removeClass(me.options.resizeClass); } }); }, resetDrop: function(widget) { var me = this; $.each(widget.data('droppables'), function(k, droppable) { //$(droppable).droppable( "enable" ); $(droppable).removeClass(me.options.usedClass); }); widget.data('droppables', []); }, overlaps: (function () { function getPositions( elem ) { var pos, width, height; pos = $( elem ).offset(); width = $( elem ).width(); height = $( elem ).height(); return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ]; } function comparePositions( p1, p2 ) { var r1, r2; r1 = p1[0] < p2[0] ? p1 : p2; r2 = p1[0] < p2[0] ? p2 : p1; return r1[1] > r2[0] || r1[0] === r2[0]; } return function ( a, b ) { var pos1 = getPositions( a ), pos2 = getPositions( b ); return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] ); }; })(), }; $.fn.Widgrid = function (options) { new Widgrid(this, options); }; }(jQuery));
/*! * Bootstrap v3.3.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if("undefined" == typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery"); +function(a) { var b = a.fn.jquery.split(" ")[0].split("."); if(b[0] < 2 && b[1] < 9 || 1 == b[0] && 9 == b[1] && b[2] < 1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher") }(jQuery), +function(a) { "use strict"; function b() { var a = document.createElement("bootstrap"), b = { WebkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd otransitionend", transition: "transitionend" }; for(var c in b)if(void 0 !== a.style[c])return {end: b[c]}; return !1 } a.fn.emulateTransitionEnd = function(b) { var c = !1, d = this; a(this).one("bsTransitionEnd", function() { c = !0 }); var e = function() { c || a(d).trigger(a.support.transition.end) }; return setTimeout(e, b), this }, a(function() { a.support.transition = b(), a.support.transition && (a.event.special.bsTransitionEnd = { bindType: a.support.transition.end, delegateType: a.support.transition.end, handle: function(b) { return a(b.target).is(this) ? b.handleObj.handler.apply(this, arguments) : void 0 } }) }) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var c = a(this), e = c.data("bs.alert"); e || c.data("bs.alert", e = new d(this)), "string" == typeof b && e[b].call(c) }) } var c = '[data-dismiss="alert"]', d = function(b) { a(b).on("click", c, this.close) }; d.VERSION = "3.3.1", d.TRANSITION_DURATION = 150, d.prototype.close = function(b) { function c() { g.detach().trigger("closed.bs.alert").remove() } var e = a(this), f = e.attr("data-target"); f || (f = e.attr("href"), f = f && f.replace(/.*(?=#[^\s]*$)/, "")); var g = a(f); b && b.preventDefault(), g.length || (g = e.closest(".alert")), g.trigger(b = a.Event("close.bs.alert")), b.isDefaultPrevented() || (g.removeClass("in"), a.support.transition && g.hasClass("fade") ? g.one("bsTransitionEnd", c).emulateTransitionEnd(d.TRANSITION_DURATION) : c()) }; var e = a.fn.alert; a.fn.alert = b, a.fn.alert.Constructor = d, a.fn.alert.noConflict = function() { return a.fn.alert = e, this }, a(document).on("click.bs.alert.data-api", c, d.prototype.close) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.button"), f = "object" == typeof b && b; e || d.data("bs.button", e = new c(this, f)), "toggle" == b ? e.toggle() : b && e.setState(b) }) } var c = function(b, d) { this.$element = a(b), this.options = a.extend({}, c.DEFAULTS, d), this.isLoading = !1 }; c.VERSION = "3.3.1", c.DEFAULTS = {loadingText: "loading..."}, c.prototype.setState = function(b) { var c = "disabled", d = this.$element, e = d.is("input") ? "val" : "html", f = d.data(); b += "Text", null == f.resetText && d.data("resetText", d[e]()), setTimeout(a.proxy(function() { d[e](null == f[b] ? this.options[b] : f[b]), "loadingText" == b ? (this.isLoading = !0, d.addClass(c).attr(c, c)) : this.isLoading && (this.isLoading = !1, d.removeClass(c).removeAttr(c)) }, this), 0) }, c.prototype.toggle = function() { var a = !0, b = this.$element.closest('[data-toggle="buttons"]'); if(b.length) { var c = this.$element.find("input"); "radio" == c.prop("type") && (c.prop("checked") && this.$element.hasClass("active") ? a = !1 : b.find(".active").removeClass("active")), a && c.prop("checked", !this.$element.hasClass("active")).trigger("change") } else this.$element.attr("aria-pressed", !this.$element.hasClass("active")); a && this.$element.toggleClass("active") }; var d = a.fn.button; a.fn.button = b, a.fn.button.Constructor = c, a.fn.button.noConflict = function() { return a.fn.button = d, this }, a(document).on("click.bs.button.data-api", '[data-toggle^="button"]', function(c) { var d = a(c.target); d.hasClass("btn") || (d = d.closest(".btn")), b.call(d, "toggle"), c.preventDefault() }).on("focus.bs.button.data-api blur.bs.button.data-api", '[data-toggle^="button"]', function(b) { a(b.target).closest(".btn").toggleClass("focus", /^focus(in)?$/.test(b.type)) }) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.carousel"), f = a.extend({}, c.DEFAULTS, d.data(), "object" == typeof b && b), g = "string" == typeof b ? b : f.slide; e || d.data("bs.carousel", e = new c(this, f)), "number" == typeof b ? e.to(b) : g ? e[g]() : f.interval && e.pause().cycle() }) } var c = function(b, c) { this.$element = a(b), this.$indicators = this.$element.find(".carousel-indicators"), this.options = c, this.paused = this.sliding = this.interval = this.$active = this.$items = null, this.options.keyboard && this.$element.on("keydown.bs.carousel", a.proxy(this.keydown, this)), "hover" == this.options.pause && !("ontouchstart"in document.documentElement) && this.$element.on("mouseenter.bs.carousel", a.proxy(this.pause, this)).on("mouseleave.bs.carousel", a.proxy(this.cycle, this)) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 600, c.DEFAULTS = { interval: 5e3, pause: "hover", wrap: !0, keyboard: !0 }, c.prototype.keydown = function(a) { if(!/input|textarea/i.test(a.target.tagName)) { switch(a.which) { case 37: this.prev(); break; case 39: this.next(); break; default: return } a.preventDefault() } }, c.prototype.cycle = function(b) { return b || (this.paused = !1), this.interval && clearInterval(this.interval), this.options.interval && !this.paused && (this.interval = setInterval(a.proxy(this.next, this), this.options.interval)), this }, c.prototype.getItemIndex = function(a) { return this.$items = a.parent().children(".item"), this.$items.index(a || this.$active) }, c.prototype.getItemForDirection = function(a, b) { var c = "prev" == a ? -1 : 1, d = this.getItemIndex(b), e = (d + c) % this.$items.length; return this.$items.eq(e) }, c.prototype.to = function(a) { var b = this, c = this.getItemIndex(this.$active = this.$element.find(".item.active")); return a > this.$items.length - 1 || 0 > a ? void 0 : this.sliding ? this.$element.one("slid.bs.carousel", function() { b.to(a) }) : c == a ? this.pause().cycle() : this.slide(a > c ? "next" : "prev", this.$items.eq(a)) }, c.prototype.pause = function(b) { return b || (this.paused = !0), this.$element.find(".next, .prev").length && a.support.transition && (this.$element.trigger(a.support.transition.end), this.cycle(!0)), this.interval = clearInterval(this.interval), this }, c.prototype.next = function() { return this.sliding ? void 0 : this.slide("next") }, c.prototype.prev = function() { return this.sliding ? void 0 : this.slide("prev") }, c.prototype.slide = function(b, d) { var e = this.$element.find(".item.active"), f = d || this.getItemForDirection(b, e), g = this.interval, h = "next" == b ? "left" : "right", i = "next" == b ? "first" : "last", j = this; if(!f.length) { if(!this.options.wrap)return; f = this.$element.find(".item")[i]() } if(f.hasClass("active"))return this.sliding = !1; var k = f[0], l = a.Event("slide.bs.carousel", {relatedTarget: k, direction: h}); if(this.$element.trigger(l), !l.isDefaultPrevented()) { if(this.sliding = !0, g && this.pause(), this.$indicators.length) { this.$indicators.find(".active").removeClass("active"); var m = a(this.$indicators.children()[this.getItemIndex(f)]); m && m.addClass("active") } var n = a.Event("slid.bs.carousel", {relatedTarget: k, direction: h}); return a.support.transition && this.$element.hasClass("slide") ? (f.addClass(b), f[0].offsetWidth, e.addClass(h), f.addClass(h), e.one("bsTransitionEnd", function() { f.removeClass([b, h].join(" ")).addClass("active"), e.removeClass(["active", h].join(" ")), j.sliding = !1, setTimeout(function() { j.$element.trigger(n) }, 0) }).emulateTransitionEnd(c.TRANSITION_DURATION)) : (e.removeClass("active"), f.addClass("active"), this.sliding = !1, this.$element.trigger(n)), g && this.cycle(), this } }; var d = a.fn.carousel; a.fn.carousel = b, a.fn.carousel.Constructor = c, a.fn.carousel.noConflict = function() { return a.fn.carousel = d, this }; var e = function(c) { var d, e = a(this), f = a(e.attr("data-target") || (d = e.attr("href")) && d.replace(/.*(?=#[^\s]+$)/, "")); if(f.hasClass("carousel")) { var g = a.extend({}, f.data(), e.data()), h = e.attr("data-slide-to"); h && (g.interval = !1), b.call(f, g), h && f.data("bs.carousel").to(h), c.preventDefault() } }; a(document).on("click.bs.carousel.data-api", "[data-slide]", e).on("click.bs.carousel.data-api", "[data-slide-to]", e), a(window).on("load", function() { a('[data-ride="carousel"]').each(function() { var c = a(this); b.call(c, c.data()) }) }) }(jQuery), +function(a) { "use strict"; function b(b) { var c, d = b.attr("data-target") || (c = b.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, ""); return a(d) } function c(b) { return this.each(function() { var c = a(this), e = c.data("bs.collapse"), f = a.extend({}, d.DEFAULTS, c.data(), "object" == typeof b && b); !e && f.toggle && "show" == b && (f.toggle = !1), e || c.data("bs.collapse", e = new d(this, f)), "string" == typeof b && e[b]() }) } var d = function(b, c) { this.$element = a(b), this.options = a.extend({}, d.DEFAULTS, c), this.$trigger = a(this.options.trigger).filter('[href="#' + b.id + '"], [data-target="#' + b.id + '"]'), this.transitioning = null, this.options.parent ? this.$parent = this.getParent() : this.addAriaAndCollapsedClass(this.$element, this.$trigger), this.options.toggle && this.toggle() }; d.VERSION = "3.3.1", d.TRANSITION_DURATION = 350, d.DEFAULTS = { toggle: !0, trigger: '[data-toggle="collapse"]' }, d.prototype.dimension = function() { var a = this.$element.hasClass("width"); return a ? "width" : "height" }, d.prototype.show = function() { if(!this.transitioning && !this.$element.hasClass("in")) { var b, e = this.$parent && this.$parent.find("> .panel").children(".in, .collapsing"); if(!(e && e.length && (b = e.data("bs.collapse"), b && b.transitioning))) { var f = a.Event("show.bs.collapse"); if(this.$element.trigger(f), !f.isDefaultPrevented()) { e && e.length && (c.call(e, "hide"), b || e.data("bs.collapse", null)); var g = this.dimension(); this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded", !0), this.$trigger.removeClass("collapsed").attr("aria-expanded", !0), this.transitioning = 1; var h = function() { this.$element.removeClass("collapsing").addClass("collapse in")[g](""), this.transitioning = 0, this.$element.trigger("shown.bs.collapse") }; if(!a.support.transition)return h.call(this); var i = a.camelCase(["scroll", g].join("-")); this.$element.one("bsTransitionEnd", a.proxy(h, this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i]) } } } }, d.prototype.hide = function() { if(!this.transitioning && this.$element.hasClass("in")) { var b = a.Event("hide.bs.collapse"); if(this.$element.trigger(b), !b.isDefaultPrevented()) { var c = this.dimension(); this.$element[c](this.$element[c]())[0].offsetHeight, this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded", !1), this.$trigger.addClass("collapsed").attr("aria-expanded", !1), this.transitioning = 1; var e = function() { this.transitioning = 0, this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse") }; return a.support.transition ? void this.$element[c](0).one("bsTransitionEnd", a.proxy(e, this)).emulateTransitionEnd(d.TRANSITION_DURATION) : e.call(this) } } }, d.prototype.toggle = function() { this[this.$element.hasClass("in") ? "hide" : "show"]() }, d.prototype.getParent = function() { return a(this.options.parent).find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]').each(a.proxy(function(c, d) { var e = a(d); this.addAriaAndCollapsedClass(b(e), e) }, this)).end() }, d.prototype.addAriaAndCollapsedClass = function(a, b) { var c = a.hasClass("in"); a.attr("aria-expanded", c), b.toggleClass("collapsed", !c).attr("aria-expanded", c) }; var e = a.fn.collapse; a.fn.collapse = c, a.fn.collapse.Constructor = d, a.fn.collapse.noConflict = function() { return a.fn.collapse = e, this }, a(document).on("click.bs.collapse.data-api", '[data-toggle="collapse"]', function(d) { var e = a(this); e.attr("data-target") || d.preventDefault(); var f = b(e), g = f.data("bs.collapse"), h = g ? "toggle" : a.extend({}, e.data(), {trigger: this}); c.call(f, h) }) }(jQuery), +function(a) { "use strict"; function b(b) { b && 3 === b.which || (a(e).remove(), a(f).each(function() { var d = a(this), e = c(d), f = {relatedTarget: this}; e.hasClass("open") && (e.trigger(b = a.Event("hide.bs.dropdown", f)), b.isDefaultPrevented() || (d.attr("aria-expanded", "false"), e.removeClass("open").trigger("hidden.bs.dropdown", f))) })) } function c(b) { var c = b.attr("data-target"); c || (c = b.attr("href"), c = c && /#[A-Za-z]/.test(c) && c.replace(/.*(?=#[^\s]*$)/, "")); var d = c && a(c); return d && d.length ? d : b.parent() } function d(b) { return this.each(function() { var c = a(this), d = c.data("bs.dropdown"); d || c.data("bs.dropdown", d = new g(this)), "string" == typeof b && d[b].call(c) }) } var e = ".dropdown-backdrop", f = '[data-toggle="dropdown"]', g = function(b) { a(b).on("click.bs.dropdown", this.toggle) }; g.VERSION = "3.3.1", g.prototype.toggle = function(d) { var e = a(this); if(!e.is(".disabled, :disabled")) { var f = c(e), g = f.hasClass("open"); if(b(), !g) { "ontouchstart"in document.documentElement && !f.closest(".navbar-nav").length && a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click", b); var h = {relatedTarget: this}; if(f.trigger(d = a.Event("show.bs.dropdown", h)), d.isDefaultPrevented())return; e.trigger("focus").attr("aria-expanded", "true"), f.toggleClass("open").trigger("shown.bs.dropdown", h) } return !1 } }, g.prototype.keydown = function(b) { if(/(38|40|27|32)/.test(b.which) && !/input|textarea/i.test(b.target.tagName)) { var d = a(this); if(b.preventDefault(), b.stopPropagation(), !d.is(".disabled, :disabled")) { var e = c(d), g = e.hasClass("open"); if(!g && 27 != b.which || g && 27 == b.which)return 27 == b.which && e.find(f).trigger("focus"), d.trigger("click"); var h = " li:not(.divider):visible a", i = e.find('[role="menu"]' + h + ', [role="listbox"]' + h); if(i.length) { var j = i.index(b.target); 38 == b.which && j > 0 && j--, 40 == b.which && j < i.length - 1 && j++, ~j || (j = 0), i.eq(j).trigger("focus") } } } }; var h = a.fn.dropdown; a.fn.dropdown = d, a.fn.dropdown.Constructor = g, a.fn.dropdown.noConflict = function() { return a.fn.dropdown = h, this }, a(document).on("click.bs.dropdown.data-api", b).on("click.bs.dropdown.data-api", ".dropdown form", function(a) { a.stopPropagation() }).on("click.bs.dropdown.data-api", f, g.prototype.toggle).on("keydown.bs.dropdown.data-api", f, g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="menu"]', g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="listbox"]', g.prototype.keydown) }(jQuery), +function(a) { "use strict"; function b(b, d) { return this.each(function() { var e = a(this), f = e.data("bs.modal"), g = a.extend({}, c.DEFAULTS, e.data(), "object" == typeof b && b); f || e.data("bs.modal", f = new c(this, g)), "string" == typeof b ? f[b](d) : g.show && f.show(d) }) } var c = function(b, c) { this.options = c, this.$body = a(document.body), this.$element = a(b), this.$backdrop = this.isShown = null, this.scrollbarWidth = 0, this.options.remote && this.$element.find(".modal-content").load(this.options.remote, a.proxy(function() { this.$element.trigger("loaded.bs.modal") }, this)) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 300, c.BACKDROP_TRANSITION_DURATION = 150, c.DEFAULTS = { backdrop: !0, keyboard: !0, show: !0 }, c.prototype.toggle = function(a) { return this.isShown ? this.hide() : this.show(a) }, c.prototype.show = function(b) { var d = this, e = a.Event("show.bs.modal", {relatedTarget: b}); this.$element.trigger(e), this.isShown || e.isDefaultPrevented() || (this.isShown = !0, this.checkScrollbar(), this.setScrollbar(), this.$body.addClass("modal-open"), this.escape(), this.resize(), this.$element.on("click.dismiss.bs.modal", '[data-dismiss="modal"]', a.proxy(this.hide, this)), this.backdrop(function() { var e = a.support.transition && d.$element.hasClass("fade"); d.$element.parent().length || d.$element.appendTo(d.$body), d.$element.show().scrollTop(0), d.options.backdrop && d.adjustBackdrop(), d.adjustDialog(), e && d.$element[0].offsetWidth, d.$element.addClass("in").attr("aria-hidden", !1), d.enforceFocus(); var f = a.Event("shown.bs.modal", {relatedTarget: b}); e ? d.$element.find(".modal-dialog").one("bsTransitionEnd", function() { d.$element.trigger("focus").trigger(f) }).emulateTransitionEnd(c.TRANSITION_DURATION) : d.$element.trigger("focus").trigger(f) })) }, c.prototype.hide = function(b) { b && b.preventDefault(), b = a.Event("hide.bs.modal"), this.$element.trigger(b), this.isShown && !b.isDefaultPrevented() && (this.isShown = !1, this.escape(), this.resize(), a(document).off("focusin.bs.modal"), this.$element.removeClass("in").attr("aria-hidden", !0).off("click.dismiss.bs.modal"), a.support.transition && this.$element.hasClass("fade") ? this.$element.one("bsTransitionEnd", a.proxy(this.hideModal, this)).emulateTransitionEnd(c.TRANSITION_DURATION) : this.hideModal()) }, c.prototype.enforceFocus = function() { a(document).off("focusin.bs.modal").on("focusin.bs.modal", a.proxy(function(a) { this.$element[0] === a.target || this.$element.has(a.target).length || this.$element.trigger("focus") }, this)) }, c.prototype.escape = function() { this.isShown && this.options.keyboard ? this.$element.on("keydown.dismiss.bs.modal", a.proxy(function(a) { 27 == a.which && this.hide() }, this)) : this.isShown || this.$element.off("keydown.dismiss.bs.modal") }, c.prototype.resize = function() { this.isShown ? a(window).on("resize.bs.modal", a.proxy(this.handleUpdate, this)) : a(window).off("resize.bs.modal") }, c.prototype.hideModal = function() { var a = this; this.$element.hide(), this.backdrop(function() { a.$body.removeClass("modal-open"), a.resetAdjustments(), a.resetScrollbar(), a.$element.trigger("hidden.bs.modal") }) }, c.prototype.removeBackdrop = function() { this.$backdrop && this.$backdrop.remove(), this.$backdrop = null }, c.prototype.backdrop = function(b) { var d = this, e = this.$element.hasClass("fade") ? "fade" : ""; if(this.isShown && this.options.backdrop) { var f = a.support.transition && e; if(this.$backdrop = a('<div class="modal-backdrop ' + e + '" />').prependTo(this.$element).on("click.dismiss.bs.modal", a.proxy(function(a) { a.target === a.currentTarget && ("static" == this.options.backdrop ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this)) }, this)), f && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), !b)return; f ? this.$backdrop.one("bsTransitionEnd", b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : b() } else if(!this.isShown && this.$backdrop) { this.$backdrop.removeClass("in"); var g = function() { d.removeBackdrop(), b && b() }; a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one("bsTransitionEnd", g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : g() } else b && b() }, c.prototype.handleUpdate = function() { this.options.backdrop && this.adjustBackdrop(), this.adjustDialog() }, c.prototype.adjustBackdrop = function() { this.$backdrop.css("height", 0).css("height", this.$element[0].scrollHeight) }, c.prototype.adjustDialog = function() { var a = this.$element[0].scrollHeight > document.documentElement.clientHeight; this.$element.css({ paddingLeft: !this.bodyIsOverflowing && a ? this.scrollbarWidth : "", paddingRight: this.bodyIsOverflowing && !a ? this.scrollbarWidth : "" }) }, c.prototype.resetAdjustments = function() { this.$element.css({paddingLeft: "", paddingRight: ""}) }, c.prototype.checkScrollbar = function() { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight, this.scrollbarWidth = this.measureScrollbar() }, c.prototype.setScrollbar = function() { var a = parseInt(this.$body.css("padding-right") || 0, 10); this.bodyIsOverflowing && this.$body.css("padding-right", a + this.scrollbarWidth) }, c.prototype.resetScrollbar = function() { this.$body.css("padding-right", "") }, c.prototype.measureScrollbar = function() { var a = document.createElement("div"); a.className = "modal-scrollbar-measure", this.$body.append(a); var b = a.offsetWidth - a.clientWidth; return this.$body[0].removeChild(a), b }; var d = a.fn.modal; a.fn.modal = b, a.fn.modal.Constructor = c, a.fn.modal.noConflict = function() { return a.fn.modal = d, this }, a(document).on("click.bs.modal.data-api", '[data-toggle="modal"]', function(c) { var d = a(this), e = d.attr("href"), f = a(d.attr("data-target") || e && e.replace(/.*(?=#[^\s]+$)/, "")), g = f.data("bs.modal") ? "toggle" : a.extend({remote: !/#/.test(e) && e}, f.data(), d.data()); d.is("a") && c.preventDefault(), f.one("show.bs.modal", function(a) { a.isDefaultPrevented() || f.one("hidden.bs.modal", function() { d.is(":visible") && d.trigger("focus") }) }), b.call(f, g, this) }) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.tooltip"), f = "object" == typeof b && b, g = f && f.selector; (e || "destroy" != b) && (g ? (e || d.data("bs.tooltip", e = {}), e[g] || (e[g] = new c(this, f))) : e || d.data("bs.tooltip", e = new c(this, f)), "string" == typeof b && e[b]()) }) } var c = function(a, b) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null, this.init("tooltip", a, b) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 150, c.DEFAULTS = { animation: !0, placement: "top", selector: !1, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: "hover focus", title: "", delay: 0, html: !1, container: !1, viewport: {selector: "body", padding: 0} }, c.prototype.init = function(b, c, d) { this.enabled = !0, this.type = b, this.$element = a(c), this.options = this.getOptions(d), this.$viewport = this.options.viewport && a(this.options.viewport.selector || this.options.viewport); for(var e = this.options.trigger.split(" "), f = e.length; f--;) { var g = e[f]; if("click" == g)this.$element.on("click." + this.type, this.options.selector, a.proxy(this.toggle, this)); else if("manual" != g) { var h = "hover" == g ? "mouseenter" : "focusin", i = "hover" == g ? "mouseleave" : "focusout"; this.$element.on(h + "." + this.type, this.options.selector, a.proxy(this.enter, this)), this.$element.on(i + "." + this.type, this.options.selector, a.proxy(this.leave, this)) } } this.options.selector ? this._options = a.extend({}, this.options, { trigger: "manual", selector: "" }) : this.fixTitle() }, c.prototype.getDefaults = function() { return c.DEFAULTS }, c.prototype.getOptions = function(b) { return b = a.extend({}, this.getDefaults(), this.$element.data(), b), b.delay && "number" == typeof b.delay && (b.delay = { show: b.delay, hide: b.delay }), b }, c.prototype.getDelegateOptions = function() { var b = {}, c = this.getDefaults(); return this._options && a.each(this._options, function(a, d) { c[a] != d && (b[a] = d) }), b }, c.prototype.enter = function(b) { var c = b instanceof this.constructor ? b : a(b.currentTarget).data("bs." + this.type); return c && c.$tip && c.$tip.is(":visible") ? void(c.hoverState = "in") : (c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)), clearTimeout(c.timeout), c.hoverState = "in", c.options.delay && c.options.delay.show ? void(c.timeout = setTimeout(function() { "in" == c.hoverState && c.show() }, c.options.delay.show)) : c.show()) }, c.prototype.leave = function(b) { var c = b instanceof this.constructor ? b : a(b.currentTarget).data("bs." + this.type); return c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)), clearTimeout(c.timeout), c.hoverState = "out", c.options.delay && c.options.delay.hide ? void(c.timeout = setTimeout(function() { "out" == c.hoverState && c.hide() }, c.options.delay.hide)) : c.hide() }, c.prototype.show = function() { var b = a.Event("show.bs." + this.type); if(this.hasContent() && this.enabled) { this.$element.trigger(b); var d = a.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]); if(b.isDefaultPrevented() || !d)return; var e = this, f = this.tip(), g = this.getUID(this.type); this.setContent(), f.attr("id", g), this.$element.attr("aria-describedby", g), this.options.animation && f.addClass("fade"); var h = "function" == typeof this.options.placement ? this.options.placement.call(this, f[0], this.$element[0]) : this.options.placement, i = /\s?auto?\s?/i, j = i.test(h); j && (h = h.replace(i, "") || "top"), f.detach().css({ top: 0, left: 0, display: "block" }).addClass(h).data("bs." + this.type, this), this.options.container ? f.appendTo(this.options.container) : f.insertAfter(this.$element); var k = this.getPosition(), l = f[0].offsetWidth, m = f[0].offsetHeight; if(j) { var n = h, o = this.options.container ? a(this.options.container) : this.$element.parent(), p = this.getPosition(o); h = "bottom" == h && k.bottom + m > p.bottom ? "top" : "top" == h && k.top - m < p.top ? "bottom" : "right" == h && k.right + l > p.width ? "left" : "left" == h && k.left - l < p.left ? "right" : h, f.removeClass(n).addClass(h) } var q = this.getCalculatedOffset(h, k, l, m); this.applyPlacement(q, h); var r = function() { var a = e.hoverState; e.$element.trigger("shown.bs." + e.type), e.hoverState = null, "out" == a && e.leave(e) }; a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", r).emulateTransitionEnd(c.TRANSITION_DURATION) : r() } }, c.prototype.applyPlacement = function(b, c) { var d = this.tip(), e = d[0].offsetWidth, f = d[0].offsetHeight, g = parseInt(d.css("margin-top"), 10), h = parseInt(d.css("margin-left"), 10); isNaN(g) && (g = 0), isNaN(h) && (h = 0), b.top = b.top + g, b.left = b.left + h, a.offset.setOffset(d[0], a.extend({ using: function(a) { d.css({top: Math.round(a.top), left: Math.round(a.left)}) } }, b), 0), d.addClass("in"); var i = d[0].offsetWidth, j = d[0].offsetHeight; "top" == c && j != f && (b.top = b.top + f - j); var k = this.getViewportAdjustedDelta(c, b, i, j); k.left ? b.left += k.left : b.top += k.top; var l = /top|bottom/.test(c), m = l ? 2 * k.left - e + i : 2 * k.top - f + j, n = l ? "offsetWidth" : "offsetHeight"; d.offset(b), this.replaceArrow(m, d[0][n], l) }, c.prototype.replaceArrow = function(a, b, c) { this.arrow().css(c ? "left" : "top", 50 * (1 - a / b) + "%").css(c ? "top" : "left", "") }, c.prototype.setContent = function() { var a = this.tip(), b = this.getTitle(); a.find(".tooltip-inner")[this.options.html ? "html" : "text"](b), a.removeClass("fade in top bottom left right") }, c.prototype.hide = function(b) { function d() { "in" != e.hoverState && f.detach(), e.$element.removeAttr("aria-describedby").trigger("hidden.bs." + e.type), b && b() } var e = this, f = this.tip(), g = a.Event("hide.bs." + this.type); return this.$element.trigger(g), g.isDefaultPrevented() ? void 0 : (f.removeClass("in"), a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", d).emulateTransitionEnd(c.TRANSITION_DURATION) : d(), this.hoverState = null, this) }, c.prototype.fixTitle = function() { var a = this.$element; (a.attr("title") || "string" != typeof a.attr("data-original-title")) && a.attr("data-original-title", a.attr("title") || "").attr("title", "") }, c.prototype.hasContent = function() { return this.getTitle() }, c.prototype.getPosition = function(b) { b = b || this.$element; var c = b[0], d = "BODY" == c.tagName, e = c.getBoundingClientRect(); null == e.width && (e = a.extend({}, e, {width: e.right - e.left, height: e.bottom - e.top})); var f = d ? { top: 0, left: 0 } : b.offset(), g = {scroll: d ? document.documentElement.scrollTop || document.body.scrollTop : b.scrollTop()}, h = d ? { width: a(window).width(), height: a(window).height() } : null; return a.extend({}, e, g, h, f) }, c.prototype.getCalculatedOffset = function(a, b, c, d) { return "bottom" == a ? { top: b.top + b.height, left: b.left + b.width / 2 - c / 2 } : "top" == a ? { top: b.top - d, left: b.left + b.width / 2 - c / 2 } : "left" == a ? {top: b.top + b.height / 2 - d / 2, left: b.left - c} : { top: b.top + b.height / 2 - d / 2, left: b.left + b.width } }, c.prototype.getViewportAdjustedDelta = function(a, b, c, d) { var e = {top: 0, left: 0}; if(!this.$viewport)return e; var f = this.options.viewport && this.options.viewport.padding || 0, g = this.getPosition(this.$viewport); if(/right|left/.test(a)) { var h = b.top - f - g.scroll, i = b.top + f - g.scroll + d; h < g.top ? e.top = g.top - h : i > g.top + g.height && (e.top = g.top + g.height - i) } else { var j = b.left - f, k = b.left + f + c; j < g.left ? e.left = g.left - j : k > g.width && (e.left = g.left + g.width - k) } return e }, c.prototype.getTitle = function() { var a, b = this.$element, c = this.options; return a = b.attr("data-original-title") || ("function" == typeof c.title ? c.title.call(b[0]) : c.title) }, c.prototype.getUID = function(a) { do a += ~~(1e6 * Math.random()); while(document.getElementById(a)); return a }, c.prototype.tip = function() { return this.$tip = this.$tip || a(this.options.template) }, c.prototype.arrow = function() { return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") }, c.prototype.enable = function() { this.enabled = !0 }, c.prototype.disable = function() { this.enabled = !1 }, c.prototype.toggleEnabled = function() { this.enabled = !this.enabled }, c.prototype.toggle = function(b) { var c = this; b && (c = a(b.currentTarget).data("bs." + this.type), c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c))), c.tip().hasClass("in") ? c.leave(c) : c.enter(c) }, c.prototype.destroy = function() { var a = this; clearTimeout(this.timeout), this.hide(function() { a.$element.off("." + a.type).removeData("bs." + a.type) }) }; var d = a.fn.tooltip; a.fn.tooltip = b, a.fn.tooltip.Constructor = c, a.fn.tooltip.noConflict = function() { return a.fn.tooltip = d, this } }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.popover"), f = "object" == typeof b && b, g = f && f.selector; (e || "destroy" != b) && (g ? (e || d.data("bs.popover", e = {}), e[g] || (e[g] = new c(this, f))) : e || d.data("bs.popover", e = new c(this, f)), "string" == typeof b && e[b]()) }) } var c = function(a, b) { this.init("popover", a, b) }; if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js"); c.VERSION = "3.3.1", c.DEFAULTS = a.extend({}, a.fn.tooltip.Constructor.DEFAULTS, { placement: "right", trigger: "click", content: "", template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }), c.prototype = a.extend({}, a.fn.tooltip.Constructor.prototype), c.prototype.constructor = c, c.prototype.getDefaults = function() { return c.DEFAULTS }, c.prototype.setContent = function() { var a = this.tip(), b = this.getTitle(), c = this.getContent(); a.find(".popover-title")[this.options.html ? "html" : "text"](b), a.find(".popover-content").children().detach().end()[this.options.html ? "string" == typeof c ? "html" : "append" : "text"](c), a.removeClass("fade top bottom left right in"), a.find(".popover-title").html() || a.find(".popover-title").hide() }, c.prototype.hasContent = function() { return this.getTitle() || this.getContent() }, c.prototype.getContent = function() { var a = this.$element, b = this.options; return a.attr("data-content") || ("function" == typeof b.content ? b.content.call(a[0]) : b.content) }, c.prototype.arrow = function() { return this.$arrow = this.$arrow || this.tip().find(".arrow") }, c.prototype.tip = function() { return this.$tip || (this.$tip = a(this.options.template)), this.$tip }; var d = a.fn.popover; a.fn.popover = b, a.fn.popover.Constructor = c, a.fn.popover.noConflict = function() { return a.fn.popover = d, this } }(jQuery), +function(a) { "use strict"; function b(c, d) { var e = a.proxy(this.process, this); this.$body = a("body"), this.$scrollElement = a(a(c).is("body") ? window : c), this.options = a.extend({}, b.DEFAULTS, d), this.selector = (this.options.target || "") + " .nav li > a", this.offsets = [], this.targets = [], this.activeTarget = null, this.scrollHeight = 0, this.$scrollElement.on("scroll.bs.scrollspy", e), this.refresh(), this.process() } function c(c) { return this.each(function() { var d = a(this), e = d.data("bs.scrollspy"), f = "object" == typeof c && c; e || d.data("bs.scrollspy", e = new b(this, f)), "string" == typeof c && e[c]() }) } b.VERSION = "3.3.1", b.DEFAULTS = {offset: 10}, b.prototype.getScrollHeight = function() { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) }, b.prototype.refresh = function() { var b = "offset", c = 0; a.isWindow(this.$scrollElement[0]) || (b = "position", c = this.$scrollElement.scrollTop()), this.offsets = [], this.targets = [], this.scrollHeight = this.getScrollHeight(); var d = this; this.$body.find(this.selector).map(function() { var d = a(this), e = d.data("target") || d.attr("href"), f = /^#./.test(e) && a(e); return f && f.length && f.is(":visible") && [[f[b]().top + c, e]] || null }).sort(function(a, b) { return a[0] - b[0] }).each(function() { d.offsets.push(this[0]), d.targets.push(this[1]) }) }, b.prototype.process = function() { var a, b = this.$scrollElement.scrollTop() + this.options.offset, c = this.getScrollHeight(), d = this.options.offset + c - this.$scrollElement.height(), e = this.offsets, f = this.targets, g = this.activeTarget; if(this.scrollHeight != c && this.refresh(), b >= d)return g != (a = f[f.length - 1]) && this.activate(a); if(g && b < e[0])return this.activeTarget = null, this.clear(); for(a = e.length; a--;)g != f[a] && b >= e[a] && (!e[a + 1] || b <= e[a + 1]) && this.activate(f[a]) }, b.prototype.activate = function(b) { this.activeTarget = b, this.clear(); var c = this.selector + '[data-target="' + b + '"],' + this.selector + '[href="' + b + '"]', d = a(c).parents("li").addClass("active"); d.parent(".dropdown-menu").length && (d = d.closest("li.dropdown").addClass("active")), d.trigger("activate.bs.scrollspy") }, b.prototype.clear = function() { a(this.selector).parentsUntil(this.options.target, ".active").removeClass("active") }; var d = a.fn.scrollspy; a.fn.scrollspy = c, a.fn.scrollspy.Constructor = b, a.fn.scrollspy.noConflict = function() { return a.fn.scrollspy = d, this }, a(window).on("load.bs.scrollspy.data-api", function() { a('[data-spy="scroll"]').each(function() { var b = a(this); c.call(b, b.data()) }) }) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.tab"); e || d.data("bs.tab", e = new c(this)), "string" == typeof b && e[b]() }) } var c = function(b) { this.element = a(b) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 150, c.prototype.show = function() { var b = this.element, c = b.closest("ul:not(.dropdown-menu)"), d = b.data("target"); if(d || (d = b.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")), !b.parent("li").hasClass("active")) { var e = c.find(".active:last a"), f = a.Event("hide.bs.tab", {relatedTarget: b[0]}), g = a.Event("show.bs.tab", {relatedTarget: e[0]}); if(e.trigger(f), b.trigger(g), !g.isDefaultPrevented() && !f.isDefaultPrevented()) { var h = a(d); this.activate(b.closest("li"), c), this.activate(h, h.parent(), function() { e.trigger({type: "hidden.bs.tab", relatedTarget: b[0]}), b.trigger({ type: "shown.bs.tab", relatedTarget: e[0] }) }) } } }, c.prototype.activate = function(b, d, e) { function f() { g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !1), b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded", !0), h ? (b[0].offsetWidth, b.addClass("in")) : b.removeClass("fade"), b.parent(".dropdown-menu") && b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !0), e && e() } var g = d.find("> .active"), h = e && a.support.transition && (g.length && g.hasClass("fade") || !!d.find("> .fade").length); g.length && h ? g.one("bsTransitionEnd", f).emulateTransitionEnd(c.TRANSITION_DURATION) : f(), g.removeClass("in") }; var d = a.fn.tab; a.fn.tab = b, a.fn.tab.Constructor = c, a.fn.tab.noConflict = function() { return a.fn.tab = d, this }; var e = function(c) { c.preventDefault(), b.call(a(this), "show") }; a(document).on("click.bs.tab.data-api", '[data-toggle="tab"]', e).on("click.bs.tab.data-api", '[data-toggle="pill"]', e) }(jQuery), +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.affix"), f = "object" == typeof b && b; e || d.data("bs.affix", e = new c(this, f)), "string" == typeof b && e[b]() }) } var c = function(b, d) { this.options = a.extend({}, c.DEFAULTS, d), this.$target = a(this.options.target).on("scroll.bs.affix.data-api", a.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", a.proxy(this.checkPositionWithEventLoop, this)), this.$element = a(b), this.affixed = this.unpin = this.pinnedOffset = null, this.checkPosition() }; c.VERSION = "3.3.1", c.RESET = "affix affix-top affix-bottom", c.DEFAULTS = { offset: 0, target: window }, c.prototype.getState = function(a, b, c, d) { var e = this.$target.scrollTop(), f = this.$element.offset(), g = this.$target.height(); if(null != c && "top" == this.affixed)return c > e ? "top" : !1; if("bottom" == this.affixed)return null != c ? e + this.unpin <= f.top ? !1 : "bottom" : a - d >= e + g ? !1 : "bottom"; var h = null == this.affixed, i = h ? e : f.top, j = h ? g : b; return null != c && c >= i ? "top" : null != d && i + j >= a - d ? "bottom" : !1 }, c.prototype.getPinnedOffset = function() { if(this.pinnedOffset)return this.pinnedOffset; this.$element.removeClass(c.RESET).addClass("affix"); var a = this.$target.scrollTop(), b = this.$element.offset(); return this.pinnedOffset = b.top - a }, c.prototype.checkPositionWithEventLoop = function() { setTimeout(a.proxy(this.checkPosition, this), 1) }, c.prototype.checkPosition = function() { if(this.$element.is(":visible")) { var b = this.$element.height(), d = this.options.offset, e = d.top, f = d.bottom, g = a("body").height(); "object" != typeof d && (f = e = d), "function" == typeof e && (e = d.top(this.$element)), "function" == typeof f && (f = d.bottom(this.$element)); var h = this.getState(g, b, e, f); if(this.affixed != h) { null != this.unpin && this.$element.css("top", ""); var i = "affix" + (h ? "-" + h : ""), j = a.Event(i + ".bs.affix"); if(this.$element.trigger(j), j.isDefaultPrevented())return; this.affixed = h, this.unpin = "bottom" == h ? this.getPinnedOffset() : null, this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix", "affixed") + ".bs.affix") } "bottom" == h && this.$element.offset({top: g - b - f}) } }; var d = a.fn.affix; a.fn.affix = b, a.fn.affix.Constructor = c, a.fn.affix.noConflict = function() { return a.fn.affix = d, this }, a(window).on("load", function() { a('[data-spy="affix"]').each(function() { var c = a(this), d = c.data(); d.offset = d.offset || {}, null != d.offsetBottom && (d.offset.bottom = d.offsetBottom), null != d.offsetTop && (d.offset.top = d.offsetTop), b.call(c, d) }) }) }(jQuery);
var config = require('../dist/config/config'); var DynamoDb = require('./DynamoDb'); var fs = require('fs'); var data = JSON.parse(fs.readFileSync(__dirname + '/data.json', 'utf8')); var type = "init"; // create, delete, sample, reset, init var table = "all"; // all, Message, User if(typeof process.argv[4] !== "undefined") { type = process.argv[4]; } if(typeof process.argv[3] !== "undefined") { table = process.argv[3]; } if(table !== "all") { data.forEach((t,i) => { if(t.name !== table) { delete data[i]; } }); } var db = new DynamoDb(); data.forEach((t) => { if(type == "init") { // create table db.create(t, function (err, data) { if(err == null) { // db.addItems(t, function (err, data) { // }); } }); } else if(type == "reset") { // create table db.delete(t.name, function (err, data) { // create table db.create(t, function (err, data) { db.addItems(t, function (err, data) { }); }); }); } else if(type == "create") { db.create(t, function (err, data) { }); } else if(type == "delete") { db.delete(t.name, function (err, data) { }); } else if(type == "sample") { db.addItems(t, function (err, data) { }); } });
'use strict'; const passport = require('passport'); //capitalize constructors as convention const LocalStrategy = require('passport-local').Strategy; const User = require('./user.model'); const SUCCESSFUL_LOGIN_MSG = 'Success!'; const INCORRECT_USERNAME_MSG = 'Incorrect Username or password'; const INCORRECT_PASSWORD_MSG = 'Incorrect Username or password'; passport.serializeUser((user, done) => { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, done); }); passport.use(new LocalStrategy ({ usernameField: 'email' }, (email, password, done) => { User.findOne({ email: email }, (err, user) => { if (err) throw err; if (user) { user.authenticate(password, (err, valid) => { if (err) throw err; if (valid) { done(null, user); } else { done(); } }); } else { done(); } }); }) );
/** * @author v.lugovksy * created on 16.12.2015 */ (function () { 'use strict'; angular.module('GasNinjasAdmin.pages.dashboard') .directive('trafficChart', trafficChart); /** @ngInject */ function trafficChart() { return { restrict: 'E', controller: 'TrafficChartCtrl', templateUrl: 'app/pages/dashboard/trafficChart/trafficChart.html' }; } })();
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE dd MMMM y", "longDate": "dd MMMM y", "medium": "dd MMM,y h:mm:ss a", "mediumDate": "dd MMM,y", "mediumTime": "h:mm:ss a", "short": "d/M/yyyy h:mm a", "shortDate": "d/M/yyyy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(\u00a4", "negSuf": ")", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-zw", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
$(document).ready(function(){ Mobify.Capture.init(function(capture){ var capturedDoc = capture.capturedDoc; var images = capturedDoc.querySelectorAll('img, picture'); Mobify.ResizeImages.resize(images, capturedDoc) capture.renderCapturedDoc(); }); });
'use strict' var auth = require('./lib/authenticate') var repos = require('./lib/repos') var events = require('./lib/events') var eventsReport = require('./lib/events-report') var pullRequests = require('./lib/pull-requests') module.exports = function githubStatusReport(user, callback) { var options = { github: auth(), user: user, per_page: 100 } var data = {} repos(options, function(err, repos) { data.repos = repos pullRequests(repos, options, function(err, pullRequests) { data.pullRequests = pullRequests events(options, function(err, events) { data.events = events.all data.eventsReport = eventsReport(events.all) callback(err, data) }) }) }) }
var rework = require('rework'), path = require('path'), validator = require('validator'); module.exports = function rebaseUrls(args) { args = args || {}; args.contentsBuffer; args.filepath; args.destpath; var css = args.contentsBuffer.toString(); var foldersToGoUp = args.destpath.split(path.sep).length - 1; var myArray = []; for (var i = 0; i < foldersToGoUp; i++) { myArray.push('..'); } var prefix = myArray.join(path.sep); return rework(css) .use(rework.url(function (url) { if (validator.isURL(url)) { return url; } if (/^(data:.*;.*,)/.test(url)) { return url; } if (/^(\/)/.test(url)) { //url is absolute return url; } var p = path.join(prefix, path.dirname(args.filepath), url); // console.log('before:', url); // console.log('after:', p); if (process.platform === 'win32') { p = p.replace(/\\/g, '/'); } return p; })) .toString(); };