code
stringlengths
2
1.05M
'use strict'; var User = require('./user.model.js'); var config = require('../config'); var request = require('request'); var jwt = require('jwt-simple'); var authUtils = require('./authUtils'); exports.authenticate = function (req, res) { var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token'; var peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'; var params = { code: req.body.code, client_id: req.body.clientId, client_secret: config.GOOGLE_SECRET, redirect_uri: req.body.redirectUri, grant_type: 'authorization_code' }; // Step 1. Exchange authorization code for access token. request.post(accessTokenUrl, { json: true, form: params }, function(err, response, token) { var accessToken = token.access_token; var headers = { Authorization: 'Bearer ' + accessToken }; // Step 2. Retrieve profile information about the current user. request.get({ url: peopleApiUrl, headers: headers, json: true }, function(err, response, profile) { // Step 3a. Link user accounts. if (req.headers.authorization) { User.findOne({ google: profile.sub }, function(err, existingUser) { if (existingUser) { return res.status(409).send({ message: 'There is already a Google account that belongs to you' }); } var token = req.headers.authorization.split(' ')[1]; var payload = jwt.decode(token, config.TOKEN_SECRET); User.findById(payload.sub, function(err, user) { if (!user) { return res.status(400).send({ message: 'User not found' }); } user.google = profile.sub; user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200'); user.displayName = user.displayName || profile.name; user.save(function() { var token = authUtils.createJWT(user); res.send({ token: token }); }); }); }); } else { // Step 3b. Create a new user account or return an existing one. User.findOne({ google: profile.sub }, function(err, existingUser) { if (existingUser) { return res.send({ token: authUtils.createJWT(existingUser) }); } var user = new User(); user.google = profile.sub; user.picture = profile.picture.replace('sz=50', 'sz=200'); user.displayName = profile.name; user.save(function(err) { var token = authUtils.createJWT(user); res.send({ token: token }); }); }); } }); }); }
"use strict"; function IndicatorComparisonViewModel (data) { var self = this; self.type = "IndicatorComparisonViewModel"; self.rootvm = data.rootvm; self.map = undefined; self.added_map_layers = []; self.markers = []; self.geojson = undefined; self.mapInfo = undefined; self.mapInfo_div = undefined; self.map_divisions = undefined; self.map_legend = undefined; self.map_legend_div = undefined; self.map_selected_year = ko.observable(); self.locations = ko.observableArray([]); self.location_types = ko.observableArray([]); /* We might have a selected location from the parameter line */ self.indicator_uuid = ko.observable(); self.location_uuid = ko.observable(); self.selected_indicator = ko.observable(new Indicator({rootvm:data.rootvm})); self.indicator_locations = ko.observableArray([]); self.observable_timestamps = ko.observableArray([]); self.observable_timestamp_options = ko.computed(function(){ // Matt just sidestepping doing it the right way. // return [{value: 2010, text: "2006-2010"}, {value: 2015, text:"2011-2015"}]; // This is a bit of a hack since we don't exactly handle ranges // the best... var options = []; if(self.rootvm.startpagevm.educationvm.indicator_titles.indexOf( self.selected_indicator().title()) >= 0){ for(var i = 0; i < self.observable_timestamps().length; i++){ options.push({'value':self.observable_timestamps()[i].year(), 'label':(parseInt(self.observable_timestamps()[i].year()) - 1) + '-' + self.observable_timestamps()[i].year() }) } } else if(self.observable_timestamps().length > 2){ for(var i = 0; i < self.observable_timestamps().length; i++){ options.push({'value':self.observable_timestamps()[i].year(), 'label':self.observable_timestamps()[i].year()}) } } else if(self.selected_indicator().title() && self.selected_indicator().title().indexOf('burden') >= 0){ options = ko.utils.arrayMap(self.observable_timestamps(), function(item){ return {value: item.year(), label:item.year() - 4 + ' - ' + item.year()}; }); } else if(self.selected_indicator().title() && self.selected_indicator().title().indexOf('ebl') >= 0 ){ options = ko.utils.arrayMap(self.observable_timestamps(), function(item){ return {value: item.year(), label:item.year() - 4 + ' - ' + item.year()}; }); } else if(self.selected_indicator().title() && self.selected_indicator().title().indexOf('mort') >= 0 ){ options = ko.utils.arrayMap(self.observable_timestamps(), function(item){ return {value: item.year(), label:item.year() - 4 + ' - ' + item.year()}; }); } else if(self.observable_timestamps().length == 2){ // Then our second set of values is really a range /* options.push({'value':self.observable_timestamps()[0].year(), 'label':'2006-'+self.observable_timestamps()[0].year()}) options.push({'value':self.observable_timestamps()[1].year(), 'label':'2011-' + self.observable_timestamps()[1].year()}) */ options = ko.utils.arrayMap(self.observable_timestamps(), function(item){ return {value: item.year(), label:item.year() - 4 + ' - ' + item.year()}; }); } else if(self.observable_timestamps().length == 1){ options = ko.utils.arrayMap(self.observable_timestamps(), function(item){ return {value: item.year(), label:'Avg. ' + (item.year() - 4) + ' - ' + item.year()}; }); // Then our second set of values is really a range //options.push({'value':self.observable_timestamps()[0].year(), // 'label':'Avg. 2009 - ' + self.observable_timestamps()[0].year()}) } return options; }); self.selector_location = ko.observable(); self.asc = ko.observable(true); self.sort_column = ko.observable(); self.selected_location_type = ko.observable(); self.location_search = ko.observable(); self.initialize = function(){ //We gotta refresh the map if(self.map){ self.map.invalidateSize(); } self.selected_indicator().indicator_uuid(self.indicator_uuid()); self.selected_indicator().look_up_details(); self.get_all_location_types().then(self.get_all_locations); self.get_all_indicator_values(); // Reset Sort self.asc(true); self.sort_column(undefined); // When we hit the page again, clear out the map if(self.map != undefined){ self.clear_map(); } }; self.csv_link = ko.computed(function(){ var base_url= "/api/indicator-values-by-indicator-csv"; base_url += '?indicator_uuid=' + self.selected_indicator().indicator_uuid(); return base_url; }); self.location_type_filtered = ko.computed(function(){ if(self.selected_location_type() != undefined){ return ko.utils.arrayFilter(self.indicator_locations(), function(item){ return item.location_type() == self.selected_location_type(); }); } else{ return self.indicator_locations(); } }); self.location_search_filtered = ko.computed(function(){ if(self.location_search()){ return ko.utils.arrayFilter(self.location_type_filtered(), function(item){ return item.title().indexOf(self.location_search()) >= 0; }); } else{ return self.location_type_filtered(); } }); self.location_click_sort = function(){ self.sort_column('location'); // now we need to do the actual sort by year here // of indicator_locations self.indicator_locations.sort(function(left, right){ var sort_mult = self.asc() ? -1 : 1; // need to get in to indicator values and year return left.title() > right.title() ? 1 * sort_mult : -1 * sort_mult; }); self.asc(!self.asc()); } self.year_click_sort = function(observable_timestamp_option){ var year = observable_timestamp_option.value; self.sort_column(year); // now we need to do the actual sort by year here // of indicator_locations self.indicator_locations.sort(function(left, right){ var sort_mult = self.asc() ? -1 : 1; // need to get in to indicator values and year // var left_value = left.indicator_value_by_year(year); var right_value = right.indicator_value_by_year(year); if (typeof(left_value) == 'function' && typeof(right_value) == 'function') { return left_value() > right_value() ? 1 * sort_mult : -1 * sort_mult; } return typeof(left_value) != 'function' && typeof(right_value) != 'function' ? 0 : typeof(right_value) != 'function' ? 1 * sort_mult : -1 * sort_mult; }); self.asc(!self.asc()); }; self.get_all_indicator_values = function(){ self.rootvm.is_busy(true); return $.ajax({ url: "/api/indicator-values-by-indicator", type: "GET", dataType: "json", processData: true, data: {'indicator_uuid':self.selected_indicator().indicator_uuid(), 'order_by_area':true }, complete: function () { self.rootvm.is_busy(false); }, success: function (data) { if (data.success) { self.observable_timestamps(ko.utils.arrayMap( data.distinct_observable_timestamps || [], function(x){ return new moment(x.observation_timestamp); } )); self.indicator_locations(ko.utils.arrayMap( data.indicatorvalues || [], function (x) { x.location.rootvm = self.rootvm; var l = new Location(x.location); l.indicator_values(ko.utils.arrayMap( x.indicator_location_values|| [], function (x) { x.rootvm = self.rootvm; x.indicator = self.selected_indicator(); x.indicator_value_format= self.selected_indicator().indicator_value_format(); return new IndicatorValue(x); } )); return l; })); } else { toastr.error(data.message); } } }); }; self.get_all_location_types = function(){ /* Look up the different location_types */ return $.ajax({ url: "/api/location-types", type: "GET", dataType: "json", complete: function () { }, success: function (data) { if (data.success) { self.location_types(data.location_types); } else { toastr.error(data.message); } } }); } self.get_all_locations = function(){ return $.ajax({ url: "/api/all-locations-with-shape-data", type: "GET", dataType: "json", complete: function () { }, success: function (data) { if (data.success) { self.locations( ko.utils.arrayMap( data.locations || [], function (x) { x.rootvm = self.rootvm; return new Location(x); })); } else { toastr.error(data.message); } } }); }; /* We need to do this after the source is loaded and part of the DOM * so that we can instantiate the map here */ self.sourceLoaded = function(){ self.map = L.map("comparisonMap").setView([41.49, -81.69], 11); L.esri.basemapLayer("Streets").addTo(self.map); self.mapInfo = L.control(); self.legend = L.control({position: 'bottomleft'}); self.legend.onAdd = self.create_legend; }; self.clear_map = function(){ self.map.removeLayer(self.geojson); for ( var index in self.markers){ self.map.removeLayer(self.markers[index]) } self.markers = []; if(self.legend._map != null){ self.map.removeControl(self.legend); } if(self.mapInfo._map != null){ self.map.removeControl(self.mapInfo); } }; self.update_map_button_disable = ko.computed(function(){ if(self.selected_location_type() != undefined && self.map_selected_year() != undefined){ return false; } else{ return true; } }); self.update_map = function(){ // First clear map if it's got stuff on it if(self.geojson != undefined){ self.clear_map(); } var geoToAdd = []; var geoValues = []; ko.utils.arrayForEach(self.location_search_filtered(), function(loc){ var leaf_feature = loc.leaflet_feature(self.map_selected_year().value); // only add if we have a value if(typeof(leaf_feature.properties.indicator_value) == 'function' && leaf_feature.geometry){ geoToAdd.push(leaf_feature); geoValues.push(leaf_feature.properties.indicator_value); } }); // Sort geo to add by value asc geoValues.sort(function(a, b){ return a()-b(); }); //Make divisions self.map_divisions = [] if (geoValues.length >= 5) { self.map_divisions = [geoValues[0], geoValues[Math.floor(geoValues.length / 4)], geoValues[Math.floor(geoValues.length / 2)], geoValues[Math.floor(geoValues.length * .75)], geoValues[geoValues.length - 1]]; } else{ self.map_divisions[geoValues[0], geoValues[geoValues.length-1]] } // This adds the actual layers to the map var featureCollection = {"type": "FeatureCollection", "features":geoToAdd}; console.debug(featureCollection); self.geojson = L.geoJson(featureCollection,{ style: self.makeStyle, onEachFeature:self.makeOnEachFeature}).addTo(self.map); self.mapInfo.onAdd = function (map) { if(self.mapInfo_div == undefined){ // create a div with a class "info" self.mapInfo_div = L.DomUtil.create('div', 'info'); this._div = self.mapInfo_div; this.update(); return this._div; } else{ return self.mapInfo_div; } }; // method that we will use to update the control based on feature properties passed self.mapInfo.update = function (props) { this._div.innerHTML = '<h4>' + self.selected_indicator().pretty_label() + (props ? ' - ' + self.map_selected_year().text + '</h4>' + '<b>' + props.name + '</b><br />' + '<i style="background:' + self.get_location_color(props.indicator_value()) + '"></i>' + props.indicator_value.formatted() :'</h4>' + 'Hover over a location or click on a marker'); }; self.mapInfo.addTo(self.map); self.legend.addTo(self.map); }; /* Makes an outline of an area on the map*/ self.create_feature_layer = function(new_location){ var layer_coordinates = new_location.location_shape_json(); var geoToAdd = [L.geoJson(layer_coordinates, {style: {color:"#444", opacity:.4, fillColor:"#72B5F2", weight:1, fillOpacity:0.6}})]; var fg = L.featureGroup(geoToAdd) fg.addTo(self.map); self.added_map_layers.push(fg); } /* These are mapping things */ self.create_legend = function(map){ var div; var labels = []; if(self.map_legend_div == undefined){ // create a div with a class "info" var div = L.DomUtil.create('div', 'info legend'); self.map_legend_div = div; } else{ div = self.map_legend_div; } // If we redraw map, clear out the div $(div).empty(); // loop through our density intervals and // generate a label with a colored square for each interval for (var i = 0; i < self.map_divisions.length - 1; i++) { div.innerHTML += '<i style="background:' + self.get_location_color(self.map_divisions[i]() + 1) + '"></i> ' + self.map_divisions[i].formatted() + (self.map_divisions[i + 1].formatted() ? '&ndash;' + self.map_divisions[i + 1].formatted() + '<br>' : '+'); } return div; }; self.makeStyle = function (feature) { return { fillColor: self.get_location_color(feature.properties.indicator_value()), weight: 2, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7 }; } self.layers_highlighted = []; self.highlightFeature = function (e, args) { if(self.layers_highlighted.length > 0){ self.resetAllHighlights(); } var layer = (e.layer == undefined ? e.target.layer : e.target) layer.setStyle({ weight: 5, color: '#666', dashArray: '', fillOpacity: 0.7 }); self.mapInfo.update(layer.feature.properties); if (!L.Browser.ie && !L.Browser.opera) { layer.bringToFront(); } // Add to all layers that we've highlighted self.layers_highlighted.push(layer); } self.resetAllHighlights = function(){ // clear out all highlighted layers while(self.layers_highlighted.length > 0){ self.resetHighlight(self.layers_highlighted.pop()); } } self.resetHighlight = function (e) { // Gonna reeset all highlights var layer = (e.target != undefined ? e.target : e); self.geojson.resetStyle(layer); self.mapInfo.update(); } self.makeOnEachFeature = function(feature, layer) { layer.on({ mouseover: self.highlightFeature, mouseout: self.resetHighlight, }); // Do not draw markers for neighborhoods. if (feature.properties.location_type != "neighborhood") { var bounds = layer.getBounds(); // Get center of bounds var center = bounds.getCenter(); // Use center to put marker on map var marker = L.marker(center) marker.layer = layer layer.marker = marker self.markers.push(marker); marker.on('click', self.highlightFeature).addTo(self.map); } } self.get_location_color = function(value){ if(self.map_divisions.length == 5){ return value > self.map_divisions[4]() ? '#00441b' : value > self.map_divisions[3]() ? '#006d2c' : value > self.map_divisions[2]() ? '#238b45' : value > self.map_divisions[1]() ? '#41ab5d' : '#74c476'; } else{ return '#238b45'; } } };
import ExtendableError from 'es6-error'; import Client from '../../api/client.js'; export class CoverArtArchiveError extends ExtendableError { constructor(message, response) { super(message); this.response = response; } } export default class CoverArtArchiveClient extends Client { constructor({ baseURL = process.env.COVER_ART_ARCHIVE_BASE_URL || 'http://coverartarchive.org/', limit = 10, period = 1000, ...options } = {}) { super({ baseURL, limit, period, ...options }); } /** * Sinfully attempt to parse HTML responses for the error message. */ parseErrorMessage(err) { if (err.name === 'HTTPError') { const { body } = err.response; if (typeof body === 'string' && body.startsWith('<!')) { const heading = /<h1>([^<]+)<\/h1>/i.exec(body); const message = /<p>([^<]+)<\/p>/i.exec(body); return new CoverArtArchiveError( `${heading ? heading[1] + ': ' : ''}${message ? message[1] : ''}`, err.response ); } } return super.parseErrorMessage(err); } images(entityType, mbid) { return this.get(`${entityType}/${mbid}`, { resolveBodyOnly: true }); } async imageURL(entityType, mbid, typeOrID = 'front', size) { let url = `${entityType}/${mbid}/${typeOrID}`; if (size != null) { url += `-${size}`; } const response = await this.get(url, { method: 'HEAD', followRedirect: false, }); return response.headers.location; } }
export const listComponent = new Component({ element: "#list", render: (data) => html` <li> <h3>${ data }</h3> </li>` })
import React, {Component, PropTypes} from 'react'; import {Tree, Menu, Icon} from 'antd'; const TreeNode = Tree.TreeNode; import Animate from 'rc-animate'; import './OrganizationTreeComponent.scss'; export default class OrganizationTreeComponent extends Component { static PropTypes = { checkable: PropTypes.bool, orgs: PropTypes.array, checkedKeys: PropTypes.array, setCheckedKeys: PropTypes.func, setParentId: PropTypes.func, } static defaultProps = { checkedKeys: [] }; constructor(props) { super(props); } onCheck = (checkedKeys, info) => { const setCheckedKeys = this.props.setCheckedKeys; if(setCheckedKeys) { setCheckedKeys(checkedKeys); } } onSelect = (selectedKeys, info) => { const setParentId = this.props.setParentId; if(setParentId) { const parentId = selectedKeys[0]; setParentId(parentId); } } genTreeNodes(orgs) { return orgs.map((org) => { if(org.children && org.children.length) { return( <TreeNode key={org.id} title={org.organizationName}> { this.genTreeNodes(org.children) } </TreeNode> ); } else { return( <TreeNode key={org.id} title={org.organizationName} /> ); } }); } render() { const orgs = this.props.orgs; const checkedKeys = this.props.checkedKeys; return( <Tree className='orgTree' showLine defaultExpandAll defaultCheckedKeys={checkedKeys} checkable={this.props.checkable} onSelect={this.onSelect} onCheck={this.onCheck}> { orgs ? this.genTreeNodes(orgs) : ''} </Tree> ); } }
/** * Created by liumengjun on 2016-04-11. * 注: 不用于微信端, 微信端自行处理 */ function showLoading(msg) { var $loadingDialog = $('#mLoadingDialog'); var $loadingText = $("#mLoadingText"); $loadingText.html(msg ? msg : ""); $loadingDialog.show(); } function hideLoading() { $('#mLoadingDialog').hide(); } var DEFAULT_ERR_MSG = '请求失败, 请稍后重试, 或联系管理员!'; function _malaAjax0(method, url, data, success, dataType, error, loadingMsg) { if ($.isFunction(data)) { loadingMsg = error; error = dataType; dataType = success; success = data; data = undefined; } if ($.isFunction(dataType)) { loadingMsg = error; error = dataType; dataType = undefined; } showLoading(loadingMsg); return $.ajax({ url: url, type: method, dataType: dataType, data: data, success: function (result, textStatus, jqXHR) { if (typeof(success) === 'function') { success(result, textStatus, jqXHR); } hideLoading(); }, error: function (jqXHR, errorType, errorDesc) { if (typeof(error) === 'function') { error(jqXHR, errorType, errorDesc); } hideLoading(); } }); } function malaAjaxPost(url, data, success, dataType, error, loadingMsg) { return _malaAjax0('post', url, data, success, dataType, error, loadingMsg); } function malaAjaxGet(url, data, success, dataType, error, loadingMsg) { return _malaAjax0('get', url, data, success, dataType, error, loadingMsg); }
/** * `grunt-protractor-webdriver` * * Grunt task to start the `Selenium Webdriver` which comes bundled with * `Protractor`, the E2E test framework for Angular applications. * * Copyright (c) 2014 Steffen Eckardt * Licensed under the MIT license. * * @see https://github.com/seckardt/grunt-protractor-webdriver * @see https://github.com/angular/protractor * @see https://code.google.com/p/selenium/wiki/WebDriverJs * @see http://angularjs.org */ module.exports = function (grunt) { 'use strict'; var spawn = require('child_process').spawn, http = require('http'), rl = require('readline'), noop = function () {}, REGEXP_REMOTE = /RemoteWebDriver instances should connect to: (.*)/, REGEXP_START_READY = /Started org\.openqa\.jetty\.jetty\.Server/, REGEXP_START_RUNNING = /Selenium is already running/, REGEXP_START_FAILURE = /Failed to start/, REGEXP_START_NOTPRESENT = /Selenium Standalone is not present/i, REGEXP_SESSION_DELETE = /Executing: \[delete session: (.*)\]/, REGEXP_SESSION_NEW = /Executing: \[new session: (.*)\]/, REGEXP_CAPABILITIES = /Capabilities \[\{(.*)\}\]/, REGEXP_EXIT_EXCEPTION = /Exception thrown(.*)/m, REGEXP_EXIT_FATAL = /Fatal error/, REGEXP_SHUTDOWN_OK = /OKOK/i, DEFAULT_PATH = 'node_modules/protractor/bin/', DEFAULT_CMD = 'webdriver-manager start', DEFAULT_INSTANCE = 'http://localhost:4444'; function exec(command) { var opts = { cwd: process.cwd(), stdio: [process.stdin] }; if (process.platform === 'win32') { opts.windowsVerbatimArguments = true; var child = spawn('cmd.exe', ['/s', '/c', command.replace(/\//g, '\\')], opts); rl.createInterface({ input: process.stdin, output: process.stdout }).on('SIGINT', function () { process.emit('SIGINT'); }); return child; } else { return spawn('/bin/sh', ['-c', command], opts); } } function extract(regexp, value, idx) { var result; if (regexp.test(value) && (result = regexp.exec(value)) && typeof result[idx] === 'string') { return result[idx].trim(); } return ''; } function Webdriver(context, options, restarted) { var done = context.async(), restartedPrefix = (restarted === true ? 'Res' : 'S'), selenium, destroy, failureTimeout, stackTrace, server = DEFAULT_INSTANCE, sessions = 0, // Running sessions status = [false, false, false],// [0 = Stopping, 1 = Stopped, 2 = Exited] stopCallbacks = []; function start() { grunt.log.writeln((restartedPrefix + 'tarting').cyan + ' Selenium server'); selenium = exec('node ' + options.path + options.command); selenium.on('error', exit) .on('uncaughtException', exit) .on('exit', exit) .on('close', exit) .on('SIGINT', exit); selenium.stdout.setEncoding('utf8'); selenium.stderr.setEncoding('utf8'); selenium.stdout.on('data', data); selenium.stderr.on('data', data); destroy = exit(selenium); } function started(callback) { status[1] = false; grunt.log.writeln((restartedPrefix + 'tarted').cyan + ' Selenium server: ' + server.green); if (callback) { callback(); } } function stop(callback) { if (status[2]) { callback(true); return; } else if (status[0] || status[1]) { stopCallbacks.push(callback); return; } status[0] = true; grunt.log.writeln('Shutting down'.cyan + ' Selenium server: ' + server); var response = ''; http.get(server + '/selenium-server/driver/?cmd=shutDownSeleniumServer', function (res) { res.on('data',function (data) { response += data; }).on('end', function () { status[0] = false; if (callback) { var success = status[1] = REGEXP_SHUTDOWN_OK.test(response), callbacks = stopCallbacks.slice(); stopCallbacks = []; callbacks.push(callback); grunt.log.writeln('Shut down'.cyan + ' Selenium server: ' + server + ' (' + (success ? response.green : response.red) + ')'); callbacks.forEach(function (cb) { cb(success); }); } }); }); } function exit(proc) { return function (callback) { var cb = function () { status[2] = true; proc.kill(); if (typeof callback === 'function') { callback(); } else { grunt.fatal(stackTrace || 'Selenium terminated unexpectedly'); } }; if (status[2]) { cb(); return; } stop(cb); }; } function data(out) { grunt.verbose.writeln('>> '.red + out); var lines; if (REGEXP_REMOTE.test(out)) { server = extract(REGEXP_REMOTE, out, 1).replace(/\/wd\/hub/, '') || server; } else if (REGEXP_START_READY.test(out)) { // Success started(done); } else if (REGEXP_START_RUNNING.test(out)) { if (failureTimeout) { clearTimeout(failureTimeout); } // Webdriver instance is already running -> Trying to shutdown stop(function (success) { if (success) { // Shutdown succeeded -> Retry new Webdriver(context, options, true); } else { // Shutdown failed -> Exit destroy(); } }); } else if (REGEXP_START_FAILURE.test(out)) { // Failure -> Exit after timeout. The timeout is needed to // enable further console sniffing as the output needed to // match `REGEXP_RUNNING` is coming behind the failure message. failureTimeout = setTimeout(destroy, 500); } else if (REGEXP_START_NOTPRESENT.test(out)) { // Failure -> Selenium server not present grunt.warn(out); } else if (REGEXP_EXIT_EXCEPTION.test(out)) { // Failure -> Exit var msg = 'Exception thrown: '.red; if (options.keepAlive) { grunt.log.writeln(msg + 'Keeping the Selenium server alive'); stackTrace = out; grunt.warn(out); } else { grunt.log.writeln(msg + 'Going to shut down the Selenium server'); stackTrace = out; destroy(); } } else if (REGEXP_EXIT_FATAL.test(out)) { // Failure -> Exit destroy(); } else if (REGEXP_SESSION_NEW.test(out)) { // As there might be race-conditions with multiple logs for // `REGEXP_SESSION_NEW` in one log statement, we have to parse // the data lines = out.split(/[\n\r]/); lines.forEach(function (line) { if (REGEXP_SESSION_NEW.test(line)) { sessions++; var caps = extract(REGEXP_CAPABILITIES, line, 1); grunt.log.writeln('Session created: '.cyan + caps); } }); } else if (REGEXP_SESSION_DELETE.test(out)) { // As there might be race-conditions with multiple logs for // `REGEXP_SESSION_DELETE` in one log statement, we have to // parse the data lines = out.split(/[\n\r]/); lines.forEach(function (line) { if (REGEXP_SESSION_DELETE.test(line)) { sessions--; var msg = 'Session deleted: '.cyan; if (sessions <= 0) { // Done -> Exit if (options.keepAlive) { grunt.log.writeln(msg + 'Keeping the Selenium server alive'); } else { grunt.log.writeln(msg + 'Going to shut down the Selenium server'); destroy(noop); } } else { grunt.log.writeln(msg + sessions + ' session(s) left'); } } }); } } process.on('removeListener', function (event, fn) { // Grunt uses node-exit [0], which eats process 'exit' event handlers. // Instead, listen for an implementation detail: When Grunt shuts down, it // removes some 'uncaughtException' event handlers that contain the string // 'TASK_FAILURE'. Super hacky, but it works. // [0]: https://github.com/cowboy/node-exit if (event === 'uncaughtException' && fn.toString().match(/TASK_FAILURE/)) { stop(noop); } }); start(); } grunt.registerMultiTask('protractor_webdriver', 'grunt plugin for starting Protractor\'s bundled Selenium Webdriver', function () { new Webdriver(this, this.options({ path: DEFAULT_PATH, command: DEFAULT_CMD, keepAlive: false })); }); };
exports.init = function (app) { var data = [{ name: 'C', desc: 'old program language', history: getFakeHistory() }, { name: 'Java', desc: 'large language!', history: getFakeHistory() }, { name: 'C#', desc: 'Microsoft create it', history: getFakeHistory() }, { name: 'JavaScript', desc: 'the web language', history: getFakeHistory() }] app.get('/itemList', function(req, res) { res.send(JSON.stringify(data)) }) app.get('/item/:name', function (req, res) { var item = data.find(item => item.name === req.params.name) if (item) { res.type('json') res.send(JSON.stringify(item)) } else { res.status(404).end() } }) app.post('/item/:name', function(req, res) { var item = data.find(item => item.name === req.params.name) if (item) { saveItem(item, JSON.parse(res.body)) } }) app.put('/item/:name', function(req, res) { var item = findItem(data, req.params.name) if (item) { res.status(403).end() } else { try { item = JSON.parse(req.body) } catch(e) { console.log('parse req body fail: ' + req.body) item = { name: req.params.name } } item.history = getFakeHistory() data.push(item) res.send(JSON.stringify(item)) } }) app.delete('/item/:name', function(req, res) { var i = data.findIndex(item => item.name === req.params.name) if (i > -1) { var item = data.splice(i, 1) res.send(JSON.stringify(item)) } else { res.status(404).end() } }) } function findItem(items, name) { return items && items.find(item => item.name === name) } function saveItem(item, data) { for (let k of data) { item[k] = data[k] } } function getFakeHistory() { var nodes = [] if (dice()) nodes.push({name: '1990', desc: 'aaa'}) if (dice()) nodes.push({name: '1991', desc: 'bbb'}) if (dice()) nodes.push({name: '1992', desc: 'ccc'}) if (dice()) nodes.push({name: '1993', desc: 'ddd'}) if (dice()) nodes.push({name: '1994', desc: 'eee'}) if (dice()) nodes.push({name: '1995', desc: 'fff'}) if (dice()) nodes.push({name: '1996', desc: 'ggg'}) if (dice()) nodes.push({name: '1997', desc: 'hhh'}) if (dice()) nodes.push({name: '1998', desc: 'jjj'}) if (dice()) nodes.push({name: '1999', desc: 'kkk'}) if (dice()) nodes.push({name: '2000', desc: 'lll'}) return nodes } function dice() { return Math.random() > 0.5 }
var _logFunction = new $NavCogLogFunction(); $(document).ready(function() { document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile); }); function $NavCogLogFunction() { var logLocations = []; function loadFile(e) { logLocations = []; var file = this.files[0]; if (file) { var fr = new FileReader(); fr.addEventListener("load", function(e) { parseLogData(fr.result); }); fr.readAsText(file); } } function parseLogData(text) { text.split("\n").forEach(function(line, i) { if (line) { var params = line.match(/(.*?) (.*?) (.*?) (.*)/); if (params && params.length == 5) { var msgs = params[4].split(","); var obj; switch (msgs[0]) { case "FoundCurrentLocation": obj = { "edge" : msgs[3], "x" : msgs[4], "y" : msgs[5], "knndist" : msgs[6] }; break; case "CurrentPosition": obj = { "dist" : msgs[1], "edge" : msgs[3], "x" : msgs[4], "y" : msgs[5], "knndist" : msgs[6] }; break; } if (obj) { obj.event = msgs[0]; obj.timestamp = params[1] + " " + params[2]; // console.log(JSON.stringify(obj)); logLocations.push(obj); } } } }); } function renderLayer(layer) { for ( var edgeID in layer.edges) { drawMarkers(layer.edges[edgeID]); } } function drawMarkers(edge) { for (var i = 0; i < logLocations.length; i++) { var log = logLocations[i]; if (log.edge == edge.id) { var marker = logLocations[i].marker; if (!marker) { var node1 = _currentLayer.nodes[edge.node1], node2 = _currentLayer.nodes[edge.node2]; var info1 = node1.infoFromEdges[edge.id], info2 = node2.infoFromEdges[edge.id] // console.log(log); // console.log(edge); // console.log(node1); // console.log(node1.lat + "," + node1.lng); // console.log(node2.lat + "," + node2.lng); // console.log(info1.x + "," + info1.y); // console.log(info2.x + "," + info2.y); var ratio = (log.y - info1.y) / (info2.y - info1.y); var lat = node1.lat + (node2.lat - node1.lat) * ratio; var lng = node1.lng + (node2.lng - node1.lng) * ratio; // console.log(ratio + "," + lat + "," + lng); var title = log.timestamp.substr(17, 2); // i + 1; var hover = (log.event == "CurrentPosition" ? "Navigation position" : "Current location"); hover += "\n" + log.timestamp; if (!isNaN(log.dist)) { hover += "\ndistance: " + log.dist; } hover += "\n"; hover += "\npos.x: " + log.x + "\npos.y: " + log.y + "\npos.knndist: " + log.knndist; hover += "\nnormalized dist: " + ((log.knndist - edge.minKnnDist) / (edge.maxKnnDist - edge.minKnnDist)); hover += "\n"; hover += "\nedge.id: " + edge.id; hover += "\nedge.minKnnDist: " + edge.minKnnDist; hover += "\nedge.maxKnnDist: " + edge.maxKnnDist; hover += "\n"; hover += "\nnode1.id: " + node1.id; hover += "\nnode1.knnDistThres: " + node1.knnDistThres; hover += "\nnode1.posDistThres: " + node1.posDistThres; hover += "\n"; hover += "\nnode2.id: " + node2.id; hover += "\nnode2.knnDistThres: " + node2.knnDistThres; hover += "\nnode2.posDistThres: " + node2.posDistThres; console.log("\n-------- " + hover) var options = { position : new google.maps.LatLng(lat, lng), draggable : false, raiseOnDrag : false, labelContent : title, labelClass : "labels", title : hover, labelAnchor : new google.maps.Point(10.5, 35) }; if (log.event == "CurrentPosition") { options.icon = { size : new google.maps.Size(25, 25), anchor : new google.maps.Point(12.5, 12.5), url : "./img/round-blue.png" }; options.shape = { coords : [ 12.5, 12.5, 25 ], type : "circle", }; options.labelAnchor = new google.maps.Point(10.5, 6.25); } logLocations[i].marker = marker = new MarkerWithLabel(options); } marker.setMap(_map); } } } $editor.on("derender", function(e, layer) { for (var i = 0; i < logLocations.length; i++) { var marker = logLocations[i].marker; if (marker) { marker.setMap(null); } } }); return { "loadFile" : loadFile, "renderLayer" : renderLayer }; }
{ unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset); }
goog.provide('ol.format.Polyline'); goog.require('ol'); goog.require('ol.asserts'); goog.require('ol.Feature'); goog.require('ol.format.Feature'); goog.require('ol.format.TextFeature'); goog.require('ol.geom.GeometryLayout'); goog.require('ol.geom.LineString'); goog.require('ol.geom.SimpleGeometry'); goog.require('ol.geom.flat.flip'); goog.require('ol.geom.flat.inflate'); goog.require('ol.proj'); /** * @classdesc * Feature format for reading and writing data in the Encoded * Polyline Algorithm Format. * * @constructor * @extends {ol.format.TextFeature} * @param {olx.format.PolylineOptions=} opt_options * Optional configuration object. * @api stable */ ol.format.Polyline = function(opt_options) { var options = opt_options ? opt_options : {}; ol.format.TextFeature.call(this); /** * @inheritDoc */ this.defaultDataProjection = ol.proj.get('EPSG:4326'); /** * @private * @type {number} */ this.factor_ = options.factor ? options.factor : 1e5; /** * @private * @type {ol.geom.GeometryLayout} */ this.geometryLayout_ = options.geometryLayout ? options.geometryLayout : ol.geom.GeometryLayout.XY; }; ol.inherits(ol.format.Polyline, ol.format.TextFeature); /** * Encode a list of n-dimensional points and return an encoded string * * Attention: This function will modify the passed array! * * @param {Array.<number>} numbers A list of n-dimensional points. * @param {number} stride The number of dimension of the points in the list. * @param {number=} opt_factor The factor by which the numbers will be * multiplied. The remaining decimal places will get rounded away. * Default is `1e5`. * @return {string} The encoded string. * @api */ ol.format.Polyline.encodeDeltas = function(numbers, stride, opt_factor) { var factor = opt_factor ? opt_factor : 1e5; var d; var lastNumbers = new Array(stride); for (d = 0; d < stride; ++d) { lastNumbers[d] = 0; } var i, ii; for (i = 0, ii = numbers.length; i < ii;) { for (d = 0; d < stride; ++d, ++i) { var num = numbers[i]; var delta = num - lastNumbers[d]; lastNumbers[d] = num; numbers[i] = delta; } } return ol.format.Polyline.encodeFloats(numbers, factor); }; /** * Decode a list of n-dimensional points from an encoded string * * @param {string} encoded An encoded string. * @param {number} stride The number of dimension of the points in the * encoded string. * @param {number=} opt_factor The factor by which the resulting numbers will * be divided. Default is `1e5`. * @return {Array.<number>} A list of n-dimensional points. * @api */ ol.format.Polyline.decodeDeltas = function(encoded, stride, opt_factor) { var factor = opt_factor ? opt_factor : 1e5; var d; /** @type {Array.<number>} */ var lastNumbers = new Array(stride); for (d = 0; d < stride; ++d) { lastNumbers[d] = 0; } var numbers = ol.format.Polyline.decodeFloats(encoded, factor); var i, ii; for (i = 0, ii = numbers.length; i < ii;) { for (d = 0; d < stride; ++d, ++i) { lastNumbers[d] += numbers[i]; numbers[i] = lastNumbers[d]; } } return numbers; }; /** * Encode a list of floating point numbers and return an encoded string * * Attention: This function will modify the passed array! * * @param {Array.<number>} numbers A list of floating point numbers. * @param {number=} opt_factor The factor by which the numbers will be * multiplied. The remaining decimal places will get rounded away. * Default is `1e5`. * @return {string} The encoded string. * @api */ ol.format.Polyline.encodeFloats = function(numbers, opt_factor) { var factor = opt_factor ? opt_factor : 1e5; var i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { numbers[i] = Math.round(numbers[i] * factor); } return ol.format.Polyline.encodeSignedIntegers(numbers); }; /** * Decode a list of floating point numbers from an encoded string * * @param {string} encoded An encoded string. * @param {number=} opt_factor The factor by which the result will be divided. * Default is `1e5`. * @return {Array.<number>} A list of floating point numbers. * @api */ ol.format.Polyline.decodeFloats = function(encoded, opt_factor) { var factor = opt_factor ? opt_factor : 1e5; var numbers = ol.format.Polyline.decodeSignedIntegers(encoded); var i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { numbers[i] /= factor; } return numbers; }; /** * Encode a list of signed integers and return an encoded string * * Attention: This function will modify the passed array! * * @param {Array.<number>} numbers A list of signed integers. * @return {string} The encoded string. */ ol.format.Polyline.encodeSignedIntegers = function(numbers) { var i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { var num = numbers[i]; numbers[i] = (num < 0) ? ~(num << 1) : (num << 1); } return ol.format.Polyline.encodeUnsignedIntegers(numbers); }; /** * Decode a list of signed integers from an encoded string * * @param {string} encoded An encoded string. * @return {Array.<number>} A list of signed integers. */ ol.format.Polyline.decodeSignedIntegers = function(encoded) { var numbers = ol.format.Polyline.decodeUnsignedIntegers(encoded); var i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { var num = numbers[i]; numbers[i] = (num & 1) ? ~(num >> 1) : (num >> 1); } return numbers; }; /** * Encode a list of unsigned integers and return an encoded string * * @param {Array.<number>} numbers A list of unsigned integers. * @return {string} The encoded string. */ ol.format.Polyline.encodeUnsignedIntegers = function(numbers) { var encoded = ''; var i, ii; for (i = 0, ii = numbers.length; i < ii; ++i) { encoded += ol.format.Polyline.encodeUnsignedInteger(numbers[i]); } return encoded; }; /** * Decode a list of unsigned integers from an encoded string * * @param {string} encoded An encoded string. * @return {Array.<number>} A list of unsigned integers. */ ol.format.Polyline.decodeUnsignedIntegers = function(encoded) { var numbers = []; var current = 0; var shift = 0; var i, ii; for (i = 0, ii = encoded.length; i < ii; ++i) { var b = encoded.charCodeAt(i) - 63; current |= (b & 0x1f) << shift; if (b < 0x20) { numbers.push(current); current = 0; shift = 0; } else { shift += 5; } } return numbers; }; /** * Encode one single unsigned integer and return an encoded string * * @param {number} num Unsigned integer that should be encoded. * @return {string} The encoded string. */ ol.format.Polyline.encodeUnsignedInteger = function(num) { var value, encoded = ''; while (num >= 0x20) { value = (0x20 | (num & 0x1f)) + 63; encoded += String.fromCharCode(value); num >>= 5; } value = num + 63; encoded += String.fromCharCode(value); return encoded; }; /** * Read the feature from the Polyline source. The coordinates are assumed to be * in two dimensions and in latitude, longitude order. * * @function * @param {Document|Node|Object|string} source Source. * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.Feature} Feature. * @api stable */ ol.format.Polyline.prototype.readFeature; /** * @inheritDoc */ ol.format.Polyline.prototype.readFeatureFromText = function(text, opt_options) { var geometry = this.readGeometryFromText(text, opt_options); return new ol.Feature(geometry); }; /** * Read the feature from the source. As Polyline sources contain a single * feature, this will return the feature in an array. * * @function * @param {Document|Node|Object|string} source Source. * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.<ol.Feature>} Features. * @api stable */ ol.format.Polyline.prototype.readFeatures; /** * @inheritDoc */ ol.format.Polyline.prototype.readFeaturesFromText = function(text, opt_options) { var feature = this.readFeatureFromText(text, opt_options); return [feature]; }; /** * Read the geometry from the source. * * @function * @param {Document|Node|Object|string} source Source. * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.geom.Geometry} Geometry. * @api stable */ ol.format.Polyline.prototype.readGeometry; /** * @inheritDoc */ ol.format.Polyline.prototype.readGeometryFromText = function(text, opt_options) { var stride = ol.geom.SimpleGeometry.getStrideForLayout(this.geometryLayout_); var flatCoordinates = ol.format.Polyline.decodeDeltas( text, stride, this.factor_); ol.geom.flat.flip.flipXY( flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); var coordinates = ol.geom.flat.inflate.coordinates( flatCoordinates, 0, flatCoordinates.length, stride); return /** @type {ol.geom.Geometry} */ ( ol.format.Feature.transformWithOptions( new ol.geom.LineString(coordinates, this.geometryLayout_), false, this.adaptOptions(opt_options))); }; /** * Read the projection from a Polyline source. * * @function * @param {Document|Node|Object|string} source Source. * @return {ol.proj.Projection} Projection. * @api stable */ ol.format.Polyline.prototype.readProjection; /** * @inheritDoc */ ol.format.Polyline.prototype.writeFeatureText = function(feature, opt_options) { var geometry = feature.getGeometry(); if (geometry) { return this.writeGeometryText(geometry, opt_options); } else { ol.asserts.assert(false, 40); // Expected `feature` to have a geometry return ''; } }; /** * @inheritDoc */ ol.format.Polyline.prototype.writeFeaturesText = function(features, opt_options) { goog.DEBUG && console.assert(features.length == 1, 'features array should have 1 item'); return this.writeFeatureText(features[0], opt_options); }; /** * Write a single geometry in Polyline format. * * @function * @param {ol.geom.Geometry} geometry Geometry. * @param {olx.format.WriteOptions=} opt_options Write options. * @return {string} Geometry. * @api stable */ ol.format.Polyline.prototype.writeGeometry; /** * @inheritDoc */ ol.format.Polyline.prototype.writeGeometryText = function(geometry, opt_options) { geometry = /** @type {ol.geom.LineString} */ (ol.format.Feature.transformWithOptions( geometry, true, this.adaptOptions(opt_options))); var flatCoordinates = geometry.getFlatCoordinates(); var stride = geometry.getStride(); ol.geom.flat.flip.flipXY( flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates); return ol.format.Polyline.encodeDeltas(flatCoordinates, stride, this.factor_); };
'use strict'; var Backbone = require('backbone'); var User = require('./User'); var AdminView = require('./AdminView'); window.app.on('start', function () { var self = this; var Users = Backbone.Collection.extend({ model: User, url: window.URL_PREFIX + '/admin/users' }); var users = self.users = new Users(); self.showAdmin = function () { users.fetch().then(function () { self.rootView.main.show(new AdminView({ collection: users })); }); }; });
var App = function() { if(!App.supportsWebGL) { document.body.className = 'app--broken'; return; } THREE.ImageUtils.crossOrigin = 'Anonymous'; this.camera = this.getCamera(); this.gravitationPoints = this.getGravitationPoints(); this.isInside = true; this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.scene = new THREE.Scene(); this.skybox = this.getSkybox(); this.scene.add(this.skybox); this.timer = new Timer(); this.timer.multiplier = 1 / 16; this.resize(); this.render(); this.addEventHandlers(); document.body.appendChild(this.renderer.domElement); }; App.prototype.addEventHandlers = function() { document.getElementById('btn-fullscreen').onclick = this.fullscreen.bind(this); document.getElementById('btn-start-low').onclick = (function() { this.start(0); }).bind(this); document.getElementById('btn-start-medium').onclick = (function() { this.start(1); }).bind(this); document.getElementById('btn-start-high').onclick = (function() { this.start(2); }).bind(this); document.getElementById('btn-start-ultra').onclick = (function() { this.start(3); }).bind(this); window.onkeydown = this.keydownHandler.bind(this); window.onresize = this.resize.bind(this); }; App.prototype.start = function(quality) { this.controls = new THREE.OrbitControls(this.camera.outside); this.controls.noPan = true; this.controls.noKeys = true; this.particles = this.getParticles(quality); this.scene.add(this.particles); document.body.className = 'app--simulation'; }; /******************************** * GETTERS ********************************/ App.prototype.getCamera = function() { var camera = { inside: new THREE.PerspectiveCamera(30, 1, 0.1, 10000), outside: new THREE.PerspectiveCamera(35, 1, 0.1, 10000) }; camera.outside.position.set(0, 0, 50); return camera; }; App.prototype.getGravitationPoints = function() { // Turns out I only need one... oh well! return [ new GravitationPoint(50, new THREE.Vector3(0, 0, 0)) ]; }; App.prototype.getParticles = function(quality) { var pcount = { min: 1 << 12, max: 1 << 16 }; var psize = { min: 0.5, max: 2 }; var particles = Math.floor(pcount.min + (pcount.max - pcount.min) * (quality / 3)); var size = psize.max - (psize.max - psize.min) * (quality / 3); var map; if(quality > 0) { map = THREE.ImageUtils.loadTexture('assets/textures/particle.png'); } else { map = THREE.ImageUtils.loadTexture('assets/textures/particle-low.png'); size = 0.25; } var geo = new THREE.Geometry(); var mat = new THREE.ParticleSystemMaterial({ blending: THREE.AdditiveBlending, depthBuffer: false, depthTest: false, map: map, transparent: true, vertexColors: true, size: size }); var p; while(particles--) { p = new Particle(0.125 + Math.random() * 4); p.set( 20 + App.biRandom() * 10, App.biRandom(), 10 + App.biRandom() ); p.velocity = new THREE.Vector3( -10 + Math.random() * 0.5, 8 + Math.random() * 0.25, 0 ); geo.vertices.push(p); geo.colors.push(p.color); } return new THREE.ParticleSystem(geo, mat); }; App.prototype.getSkybox = function() { var prefix = 'assets/textures/skybox/space-'; var suffix = '.png'; // var dirs = []; var files = [ 'right', 'left', 'top', 'bottom', 'front', 'back' ]; var geo = new THREE.BoxGeometry(5000, 5000, 5000, 1, 1, 1); var mats = []; var i; for(i = 0; i < 6; i++) { mats.push(new THREE.MeshBasicMaterial({ blending: THREE.AdditiveBlending, map: THREE.ImageUtils.loadTexture(prefix + files[i] + suffix), side: THREE.BackSide })); } return new THREE.Mesh(geo, new THREE.MeshFaceMaterial(mats)); }; /******************************** * EVENTS ********************************/ App.prototype.resize = function() { var h = window.innerHeight; var w = window.innerWidth; this.camera.inside.aspect = w / h; this.camera.inside.updateProjectionMatrix(); this.camera.outside.aspect = w / h; this.camera.outside.updateProjectionMatrix(); this.renderer.setSize(w, h); }; App.prototype.keydownHandler = function(e) { if(e.keyCode === 86) this.isInside = !this.isInside; }; App.prototype.fullscreen = function() { var el = this.renderer.domElement; if(el.requestFullscreen) el.requestFullscreen(); else if(el.webkitRequestFullscreen) el.webkitRequestFullscreen(); else if(el.mozRequestFullScreen) el.mozRequestFullScreen(); else if(el.msRequestFullscreen) el.msRequestFullscreen(); this.resize(); }; /******************************** * RENDER LOOP ********************************/ App.prototype.update = function() { this.updateParticleSystem(this.particles); this.updateMovingGravitationPoint(this.gravitationPoints[0]); }; App.prototype.updateParticleSystem = function(ps) { var geo = ps.geometry; var i = geo.vertices.length; var j; // Fixed delta? Yes, I don't want my particles to lag out of orbit var t = 1000 / 60 / 1000 * this.timer.multiplier; while(i--) { j = this.gravitationPoints.length; while(j--) this.gravitationPoints[j].attract(geo.vertices[i], t); geo.vertices[i].add(geo.vertices[i].velocity.clone().multiplyScalar(t)); } geo.verticesNeedUpdate = true; }; App.prototype.updateMovingGravitationPoint = function(gp) { gp.position.x = Math.cos(this.timer.elapsed / 2) * 8; gp.position.y = Math.sin(this.timer.elapsed / 3.43) * 8; gp.position.z = Math.sin(this.timer.elapsed / 1.23) * 8; }; App.prototype.render = function() { requestAnimationFrame(this.render.bind(this)); this.timer.update(); var camera = (this.isInside && this.particles ? this.camera.inside : this.camera.outside); if(this.particles) { var pf = this.particles.geometry.vertices[0]; var pl = this.particles.geometry.vertices[this.particles.geometry.vertices.length - 1]; this.update(); this.camera.inside.position = pf; this.camera.inside.lookAt(pf.clone().addVectors( this.gravitationPoints[0].position, pf.velocity, pl )); } else { camera.rotation.y = -this.timer.elapsed * 0.25 - Math.PI; camera.rotation.x = Math.sin(camera.rotation.y) * Math.PI / 16; } this.skybox.position = camera.position; this.renderer.render(this.scene, camera); }; /******************************** * STATIC ********************************/ App.biRandom = function() { return (Math.random() * 2) - 1; }; App.supportsWebGL = (function() { var canvas; try { canvas = document.createElement('canvas'); return !!window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')); } catch(e) {} return false; })(); App.initialize = function() { new App(); }; window.onload = App.initialize;
var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"), width = canvas.width, height = canvas.height, radius = 20; var circles = d3.range(324).map(function(i) { return { x: (i % 25) * (radius + 1) * 2, y: Math.floor(i / 25) * (radius + 1) * 2 }; }); var simulation = d3.forceSimulation(circles) .force("collide", d3.forceCollide(radius + 1).iterations(4)) .on("tick", drawCircles); d3.select(canvas) .call(d3.drag() .container(canvas) .subject(dragsubject) .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); function drawCircles() { context.clearRect(0, 0, width, height); context.save(); context.beginPath(); circles.forEach(drawCircle); context.fill(); context.strokeStyle = "#fff"; context.stroke(); } function drawCircle(d) { context.moveTo(d.x + radius, d.y); context.arc(d.x, d.y, radius, 0, 2 * Math.PI); } function dragsubject() { return simulation.find(d3.event.x, d3.event.y, radius); } function dragstarted() { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d3.event.subject.fx = d3.event.subject.x; d3.event.subject.fy = d3.event.subject.y; } function dragged() { d3.event.subject.fx = d3.event.x; d3.event.subject.fy = d3.event.y; } function dragended() { if (!d3.event.active) simulation.alphaTarget(0); d3.event.subject.fx = null; d3.event.subject.fy = null; }
/* * simple sliding menu using jQuery and Interface - http://www.getintothis.com * * note: this library depends on jquery (http://www.jquery.com) and * interface (http://interface.eyecon.ro) * * Copyright (c) 2006 Ramin Bozorgzadeh * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LECENSE.txt) linceses. */ jQuery.fn.rb_menu = function(options) { var self = this; self.options = { // transitions: easein, easeout, easeboth, bouncein, bounceout, // bounceboth, elasticin, elasticout, elasticboth transition: 'bounceout', // trigger events: mouseover, mousedown, mouseup, click, dblclick triggerEvent: 'mouseover', // number of ms to delay before hiding menu (on page load) loadHideDelay : 1000, // number of ms to delay before hiding menu (on mouseout) blurHideDelay: 500, // number of ms for transition effect effectDuration: 1000, // hide the menu when the page loads hideOnLoad: true, // automatically hide menu when mouse leaves area autoHide: true } // make sure to check if options are given! if(options) { jQuery.extend(self.options, options); } return this.each(function() { var menu = jQuery(this).find('.rb_menu'); var toggle = jQuery(this).find('.rb_toggle span'); // add 'hover' class to trigger for css styling toggle.hover( function() { jQuery(this).addClass('hover'); }, function() { jQuery(this).removeClass('hover'); }); if(self.options.hideOnLoad) { if(self.options.loadHideDelay <= 0) { menu.hide(); self.closed = true; self.unbind(); } else { // let's hide the menu when the page is loading // after {loadHideDelay} milliseconds setTimeout( function() { menu.hideMenu(); }, self.options.loadHideDelay); } } // bind event defined by {triggerEvent} to the trigger // to open and close the menu toggle.bind(self.options.triggerEvent, function() { // if the trigger event is click or dblclick, we want // to close the menu if its open if((self.options.triggerEvent == 'click' || self.options.triggerEvent == 'dblclick') && !self.closed) { menu.hideMenu(); } else { menu.showMenu(); } }); menu.hideMenu = function() { if(this.css('display') == 'block' && !self.closed) { this.SlideOutLeft( self.options.effectDuration, function() { self.closed = true; self.unbind(); }, self.options.transition ); } } menu.showMenu = function() { if(this.css('display') == 'none' && self.closed) { this.SlideInLeft( self.options.effectDuration, function() { self.closed = false; if(self.options.autoHide) { self.hover(function() { clearTimeout(self.timeout); }, function() { self.timeout = setTimeout( function() { menu.hideMenu(); }, self.options.blurHideDelay); }); } }, self.options.transition ); } } }); };
import DS from 'ember-data'; import DomainResource from 'ember-fhir/models/domain-resource'; const { attr, belongsTo, hasMany } = DS; export default DomainResource.extend({ identifier: hasMany('identifier', { async: true }), basedOn: hasMany('reference', { async: true }), status: attr('string'), category: belongsTo('codeable-concept', { async: false }), code: belongsTo('codeable-concept', { async: false }), subject: belongsTo('reference', { async: false }), context: belongsTo('reference', { async: false }), effectiveDateTime: attr('date'), effectivePeriod: belongsTo('period', { async: false }), issued: attr('string'), performer: hasMany('diagnostic-report-performer', { async: true }), specimen: hasMany('reference', { async: true }), result: hasMany('reference', { async: true }), imagingStudy: hasMany('reference', { async: true }), image: hasMany('diagnostic-report-image', { async: true }), conclusion: attr('string'), codedDiagnosis: hasMany('codeable-concept', { async: true }), presentedForm: hasMany('attachment', { async: true }) });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.19-2-13 description: > Array.prototype.map - applied to the Array-like object when 'length' is inherited accessor property without a get function includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return val > 10; } var proto = {}; Object.defineProperty(proto, "length", { set: function () { }, configurable: true }); var Con = function () { }; Con.prototype = proto; var child = new Con(); child[0] = 11; child[1] = 12; var testResult = Array.prototype.map.call(child, callbackfn); return 0 === testResult.length; } runTestCase(testcase);
module.exports = { __esModule: true, default: { plugins: ['esm-object'] } }
$(document).ready(function() { var loading = $('#loading'); ['ceneo', 'allegro'].forEach(function(service) { $('#' + service + '-form').submit(function(e) { e.preventDefault(); var self = $(this); var resultsUl = $('#' + service + '-results'); resultsUl.empty().hide(); loading.show(); $.post('/' + service, self.serialize(), function(data){ loading.hide(); resultsUl.show(); console.log(data.result); data.result.forEach(function(row) { products = []; row.products.forEach(function(product) { products.push( '<a href="' + product.url + '">' + product.name + '</a> ' + product.price.toFixed(2) ); }); $('<li><b><a href="' + row.url + '">' + row.shop + '</a> ' + row.price.toFixed(2) + ' ' + row.products.length + ' prod.</b> (' + products.join(', ') + ')</li>').appendTo(resultsUl); }); }).fail(function(data){ loading.hide(); resultsUl.show(); $('<li class=\'error\'>Error occured!</li>').appendTo(resultsUl); }); }); }); });
// Generated by CoffeeScript 1.4.0-beerscript (function() { var CoffeeScript, cakefileDirectory, existsSync, fatalError, fs, helpers, missingTask, oparse, options, optparse, path, printTasks, switches, tasks; fs = require('fs'); path = require('path'); helpers = require('./helpers'); optparse = require('./optparse'); CoffeeScript = require('./coffee-script'); existsSync = fs.existsSync || path.existsSync; tasks = {}; options = {}; switches = []; oparse = null; helpers.extend(global, { task: function(name, description, action) { var _ref; if (!action) { _ref = [description, action], action = _ref[0], description = _ref[1]; } return tasks[name] = { name: name, description: description, action: action }; }, option: function(letter, flag, description) { return switches.push([letter, flag, description]); }, invoke: function(name) { if (!tasks[name]) { missingTask(name); } return tasks[name].action(options); } }); exports.run = function() { var arg, args, _i, _len, _ref, _results; global.__originalDirname = fs.realpathSync('.'); process.chdir(cakefileDirectory(__originalDirname)); args = process.argv.slice(2); CoffeeScript.run(fs.readFileSync('Cakefile').toString(), { filename: 'Cakefile' }); oparse = new optparse.OptionParser(switches); if (!args.length) { return printTasks(); } try { options = oparse.parse(args); } catch (e) { return fatalError("" + e); } _ref = options["arguments"]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { arg = _ref[_i]; _results.push(invoke(arg)); } return _results; }; printTasks = function() { var cakefilePath, desc, name, relative, spaces, task; relative = path.relative || path.resolve; cakefilePath = path.join(relative(__originalDirname, process.cwd()), 'Cakefile'); console.log("" + cakefilePath + " defines the following tasks:\n"); for (name in tasks) { task = tasks[name]; spaces = 20 - name.length; spaces = spaces > 0 ? Array(spaces + 1).join(' ') : ''; desc = task.description ? "# " + task.description : ''; console.log("cake " + name + spaces + " " + desc); } if (switches.length) { return console.log(oparse.help()); } }; fatalError = function(message) { console.error(message + '\n'); console.log('To see a list of all tasks/options, run "cake"'); return process.exit(1); }; missingTask = function(task) { return fatalError("No such task: " + task); }; cakefileDirectory = function(dir) { var parent; if (existsSync(path.join(dir, 'Cakefile'))) { return dir; } parent = path.normalize(path.join(dir, '..')); if (parent !== dir) { return cakefileDirectory(parent); } throw new Error("Cakefile not found in " + (process.cwd())); }; }).call(this);
import App from './container'; export default App;
const path = require('path'); const { CheckerPlugin } = require('awesome-typescript-loader'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const baseConfig = require('./webpack.base'); const baseDevConfig = { ...baseConfig, devtool: 'source-map', mode: 'development', devServer: { contentBase: baseConfig.output.path, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', }, compress: true, port: 3000, }, }; const viewerConfig = { ...baseDevConfig, entry: { index: path.join(__dirname, 'src', 'viewer', 'viewer.tsx'), }, plugins: [ new CheckerPlugin(), new HtmlWebpackPlugin({ title: 'CSpell Settings Viewer', hash: true, template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'), inject: 'body', }), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: '[name].css', chunkFilename: '[id].css', }), ], }; const testConfig = { ...baseDevConfig, entry: { test: path.join(__dirname, 'src', 'viewer', 'vsCodeTestWrapper.tsx'), }, plugins: [ new HtmlWebpackPlugin({ title: 'Tester CSpell Settings Viewer', hash: true, template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'), inject: 'body', filename: 'test.html', }), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: '[name].css', chunkFilename: '[id].css', }), ], }; module.exports = [viewerConfig, testConfig];
/*global describe: false, it: false, expect: false */ 'use strict'; var apiFactory = require('../controller/apiFactory.js'); describe('will this work', function () { var method = apiFactory.get('session'); it('Default test case', function apiFactory1() { expect(method.create).toBe(require('../controller/sessionManager.js').create); }); });
import { randomInt32 } from '@provably-fair/core'; /** * Shuffles an array based on the given seeds, using the given HMAC algorithm. * @param {[]} arr Array to be shuffled. * @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair. * @param {string|Buffer} secretSeed Secret seed used as HMAC key. * @param {string|Buffer} [publicSeed] Public seed used as HMAC data. To prove fairness of random * outputs, the hash of `secretSeed` shall be known before revealing `publicSeed`. * @param {function} [hmacBufferUIntParser] Function to be used for parsing a UInt from the * generated HMAC buffer. * @param {function} [fallbackProvider] Function to provide a fallback value in a given range * whether no appropriate number can be parsed from the generated HMAC buffer. * @returns {[]} A new array instance containing every element of the input. */ export const shuffle = ( arr, hmacAlgorithm, secretSeed, publicSeed, hmacBufferUIntParser, fallbackProvider, ) => { const result = [...arr]; for (let i = arr.length - 1; i > 0; i -= 1) { // Generate a random integer within [0, i] const j = randomInt32( hmacAlgorithm, secretSeed, `${publicSeed}-${i}`, 0, i + 1, hmacBufferUIntParser, fallbackProvider, ); // Exchange `result[i]` and `result[j]` [result[i], result[j]] = [result[j], result[i]]; } return result; }; export default shuffle;
'use strict'; const Flag = require('../src/Flag'); const expect = require('chai').expect; describe('flag.isShort', function () { it('(empty)', function () { const input = ''; const output = Flag.isShort(input); expect(output).to.be.false; }); it('-f', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.true; }); it('--', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.true; }); it('-F', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.true; }); it('---', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.false; }); it('aa', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.false; }); it('a', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.false; }); it('-1', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.false; }); it('-2', function () { const input = this.test.title; const output = Flag.isShort(input); expect(output).to.be.false; }); });
/** * Created by Jairo Martinez on 8/15/15. */ var five = require("johnny-five"); var board = {}; var lcd = {}; var rly1 = {}; var rly2 = {}; var btnBack = {}; var btnMenu = {}; var btnHome = {}; var btnEntr = {}; var btnNvUp = {}; var btnNvDn = {}; var btnNvLt = {}; var btnNvRt = {}; function _btnsSetup() { btnEntr = new five.Button({ pin: 2, isPullup: true }); btnHome = new five.Button({ pin: 3, isPullup: true }); btnBack = new five.Button({ pin: 8, isPullup: true }); btnMenu = new five.Button({ pin: 9, isPullup: true }); btnNvRt = new five.Button({ pin: 5, // isPullup: true }); btnNvDn = new five.Button({ pin: 4, // isPullup: true }); btnNvUp = new five.Button({ pin: 7, // isPullup: true }); btnNvLt = new five.Button({ pin: 6, isPullup: true }); } function _btns() { _btnsSetup(); btnMenu.on("down", function () { console.log("Btn Menu"); lcd.print("Menu"); }); btnHome.on("down", function () { console.log("Btn Home"); }); btnEntr.on("down", function () { console.log("Btn Enter"); }); btnBack.on("down", function () { console.log("Btn Back"); }); btnNvUp.on("down", function () { console.log("Btn Up"); }); btnNvDn.on("down", function () { console.log("Btn Down"); }); btnNvLt.on("down", function () { console.log("Btn Left"); }); btnNvRt.on("down", function () { console.log("Btn Right"); }); } function _lcd() { lcd = new five.LCD({ controller: "PCF8574", address: 0x20, rows: 4, cols: 20 }); lcd.clear(); lcd.home(); } /** * Setup Relays * @private */ function _relays() { rly1 = new five.Relay(10); rly2 = new five.Relay(11); setTimeout(function () { rly1.on(); rly2.on(); }, 1000); } /** * Initialize * @private */ function _init() { _btns(); _lcd(); _relays(); } /////////////////////////////////////////////////// // var j5 = function (){ }; /** * Initialize Module * @param opts * @param cb */ j5.prototype.init = function (opts, cb) { cb = (typeof cb === 'function') ? cb : function () {}; opts = opts || { port: "/dev/ttyAMA0" }; board = new five.Board(opts); try { board.on("ready", function () { _init(); this.repl.inject({ lcd: lcd }); cb(null); }); } catch(ex){ cb(ex,null); } }; /** * Send Message To The LCD * @param msg * @param row * @param col */ j5.prototype.message = function(msg,row,col){ row = row || 0; col = col || 0; lcd.cursor(row, col).print(msg); }; module.exports = new j5();
// Dependencies var Enny = require("enny") , Deffy = require("deffy") ; /** * lineType * Returns the line type for given input. * * @name lineType * @function * @param {Element|SubElement} source The source (sub)element. * @param {Element|SubElement} target The target (sub)element. * @param {} target * @return {String} The line type. */ module.exports = function (source, target) { if (!Deffy(source.id.parentId, {}, true).isServer && Deffy(target.id.parentId, {}, true).isServer) { return "link-in"; } // * -> error if (Enny.TYPES(target.type, Enny.TYPES.errorHandler)) { // "line-" // <path class="line-error-in"...> return "error-in"; } // error -> * if (Enny.TYPES(source.type, Enny.TYPES.errorHandler)) { return "error-out"; } // data -> * if (Enny.TYPES(source.type, Enny.TYPES.dataHandler)) { return "data-out"; } return "normal"; };
var decode = require('base64-decode'); var crypto = require('crypto'); var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z'; var SALT = 'af0ik392jrmt0nsfdghy0'; function parse(save) { if (save.indexOf(ANTI_CHEAT_CODE) > -1) { var result = save.split(ANTI_CHEAT_CODE); save = ''; for (var i = 0; i < result[0].length; i += 2) { save += result[0].charAt(i); } var md5 = crypto.createHash('md5'); md5.update(save + SALT, 'ascii'); if (md5.digest('hex') !== result[1]) { throw new Error('Bad hash'); } } else { throw new Error('Anti-cheat code not found'); } var data = JSON.parse(decode(save)); return data; } module.exports = parse;
import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; /// /// LOGIN WITHOUT PASSWORD /// // Method called by a user to request a password reset email. This is // the start of the reset process. Meteor.methods({ loginWithoutPassword: function ({ email, username = null }) { if (username !== null) { check(username, String); var user = Meteor.users.findOne({ $or: [{ "username": username, "emails.address": { $exists: 1 } }, { "emails.address": email }] }); if (!user) throw new Meteor.Error(403, "User not found"); email = user.emails[0].address; } else { check(email, String); var user = Meteor.users.findOne({ "emails.address": email }); if (!user) throw new Meteor.Error(403, "User not found"); } if (Accounts.ui._options.requireEmailVerification) { if (!user.emails[0].verified) { throw new Meteor.Error(403, "Email not verified"); } } Accounts.sendLoginEmail(user._id, email); }, }); /** * @summary Send an email with a link the user can use verify their email address. * @locus Server * @param {String} userId The id of the user to send email to. * @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first unverified email in the list. */ Accounts.sendLoginEmail = function (userId, address) { // XXX Also generate a link using which someone can delete this // account if they own said address but weren't those who created // this account. // Make sure the user exists, and address is one of their addresses. var user = Meteor.users.findOne(userId); if (!user) throw new Error("Can't find user"); // pick the first unverified address if we weren't passed an address. if (!address) { var email = (user.emails || []).find(({ verified }) => !verified); address = (email || {}).address; } // make sure we have a valid address if (!address || !(user.emails || []).map(({ address }) => address).includes(address)) throw new Error("No such email address for user."); var tokenRecord = { token: Random.secret(), address: address, when: new Date()}; Meteor.users.update( {_id: userId}, {$push: {'services.email.verificationTokens': tokenRecord}}); // before passing to template, update user object with new token Meteor._ensure(user, 'services', 'email'); if (!user.services.email.verificationTokens) { user.services.email.verificationTokens = []; } user.services.email.verificationTokens.push(tokenRecord); var loginUrl = Accounts.urls.verifyEmail(tokenRecord.token); var options = { to: address, from: Accounts.emailTemplates.loginNoPassword.from ? Accounts.emailTemplates.loginNoPassword.from(user) : Accounts.emailTemplates.from, subject: Accounts.emailTemplates.loginNoPassword.subject(user) }; if (typeof Accounts.emailTemplates.loginNoPassword.text === 'function') { options.text = Accounts.emailTemplates.loginNoPassword.text(user, loginUrl); } if (typeof Accounts.emailTemplates.loginNoPassword.html === 'function') options.html = Accounts.emailTemplates.loginNoPassword.html(user, loginUrl); if (typeof Accounts.emailTemplates.headers === 'object') { options.headers = Accounts.emailTemplates.headers; } Email.send(options); }; // Check for installed accounts-password dependency. if (Accounts.emailTemplates) { Accounts.emailTemplates.loginNoPassword = { subject: function(user) { return "Login on " + Accounts.emailTemplates.siteName; }, text: function(user, url) { var greeting = (user.profile && user.profile.name) ? ("Hello " + user.profile.name + ",") : "Hello,"; return `${greeting} To login, simply click the link below. ${url} Thanks. `; } }; }
//@flow import EventEmitter from 'eventemitter2' import { ApiManager } from '../api-manager' import NetworkerFabric from '../networker' import { PureStorage } from '../../store' import TL from '../../tl' import configValidator from './config-validation' import generateInvokeLayer from './invoke-layer-generator' import type { TLFabric } from '../../tl' import type { ApiConfig, ConfigType, StrictConfig, Emit, On, PublicKey } from './index.h' import type { ApiManagerInstance } from '../api-manager/index.h' const api57 = require('../../../schema/api-57.json') const mtproto57 = require('../../../schema/mtproto-57.json') const apiConfig: ApiConfig = { invokeWithLayer: 0xda9b0d0d, layer : 57, initConnection : 0x69796de9, api_id : 49631, device_model : 'Unknown UserAgent', system_version : 'Unknown Platform', app_version : '1.0.1', lang_code : 'en' } class MTProto { config: StrictConfig tls: TLFabric emitter = new EventEmitter({ wildcard: true }) api: ApiManagerInstance on: On = this.emitter.on.bind(this.emitter) emit: Emit = this.emitter.emit.bind(this.emitter) constructor(config: ConfigType) { this.config = configNormalization(config) this.tls = TL(this.config.schema, this.config.mtSchema) const netFabric = NetworkerFabric(this.config.api, this.tls, this.config.app.storage, this.emit) this.api = new ApiManager(this.config, this.tls, netFabric, { on: this.on, emit: this.emit }) } } export default MTProto const configNormalization = (config: ConfigType): StrictConfig => { const { server = {}, api = {}, app: { storage = PureStorage, publicKeys = publicKeysHex } = {}, schema = api57, mtSchema = mtproto57, } = config const apiNormalized = { ...apiConfig, ...api } const invokeLayer = generateInvokeLayer(apiNormalized.layer) apiNormalized.invokeWithLayer = invokeLayer const fullCfg = { server, api: apiNormalized, app: { storage, publicKeys }, schema, mtSchema } configValidator(fullCfg) return fullCfg } /** * Server public key, obtained from here: https://core.telegram.org/api/obtaining_api_id * * -----BEGIN RSA PUBLIC KEY----- * MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6 * lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS * an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw * Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+ * 8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n * Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB * -----END RSA PUBLIC KEY----- */ const publicKeysHex: PublicKey[] = [{ modulus: 'c150023e2f70db7985ded064759cfecf0af328e69a41daf4d6f01b538135a6f91f' + '8f8b2a0ec9ba9720ce352efcf6c5680ffc424bd634864902de0b4bd6d49f4e5802' + '30e3ae97d95c8b19442b3c0a10d8f5633fecedd6926a7f6dab0ddb7d457f9ea81b' + '8465fcd6fffeed114011df91c059caedaf97625f6c96ecc74725556934ef781d86' + '6b34f011fce4d835a090196e9a5f0e4449af7eb697ddb9076494ca5f81104a305b' + '6dd27665722c46b60e5df680fb16b210607ef217652e60236c255f6a28315f4083' + 'a96791d7214bf64c1df4fd0db1944fb26a2a57031b32eee64ad15a8ba68885cde7' + '4a5bfc920f6abf59ba5c75506373e7130f9042da922179251f', exponent: '010001' }]
var pieceJson = { type: 'pawn', color: Chess.Piece.Color.WHITE, 'displacementsNumber': 10 }; var getPieceObject = function() { var factory = new Chess.Piece.PieceFactory(); return factory.create('pawn', Chess.Piece.Color.WHITE, 10); }; test("importFromJson", function() { var jsonifier = new Chess.Piece.PieceJsonifier(); deepEqual(jsonifier.importFromJson(pieceJson), getPieceObject()); }); test("exportToJson", function() { var jsonifier = new Chess.Piece.PieceJsonifier(); deepEqual(jsonifier.exportToJson(getPieceObject()), pieceJson); });
import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; import 'styled-components-test-utils/lib/jest'; import getTheme from '../src/getTheme'; import Link from '../src/Link'; import * as utils from '../src/utils/'; const theme = getTheme({ font: { size: '16px', }, }); describe('Link', () => { test('should render a Link', () => { const component = ReactTestRenderer.create(<Link theme={theme} />); expect(component).toBeDefined(); expect(component.toJSON()).toMatchSnapshot(); }); test('should have an a tag', () => { const component = ReactTestRenderer.create(<Link theme={theme} />).toJSON(); expect(component.type).toEqual('a'); }); test('should have a color', () => { const spy = jest.spyOn(utils, 'getTextColor'); const component = ReactTestRenderer.create( <Link theme={theme} textColor="white" />, ); expect(component).toHaveStyleRule('color', 'white'); expect(spy).toHaveBeenCalled(); }); test('should have opacity', () => { const spy = jest.spyOn(utils, 'getOpacity'); const component = ReactTestRenderer.create( <Link theme={theme} opacity={0.75} />, ); expect(component).toHaveStyleRule('opacity', '0.75'); expect(spy).toHaveBeenCalled(); }); test('should have a color hover', () => { const spy = jest.spyOn(utils, 'getHover'); const component = ReactTestRenderer.create( <Link theme={theme} hoverColor="white" />, ); expect({ component, modifier: '&:hover', }).toHaveStyleRule('color', 'white'); expect(spy).toHaveBeenCalled(); }); test('should have the correct font size', () => { const component = ReactTestRenderer.create( <Link theme={theme} />, ); expect(component).toHaveStyleRule('font-size', '16px'); }); });
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var HotUpdateChunkTemplate = require("../HotUpdateChunkTemplate"); function NodeHotUpdateChunkTemplate(outputOptions) { HotUpdateChunkTemplate.call(this, outputOptions); } module.exports = NodeHotUpdateChunkTemplate; NodeHotUpdateChunkTemplate.prototype = Object.create(HotUpdateChunkTemplate.prototype); NodeHotUpdateChunkTemplate.prototype.renderHeader = function(id, modules, hash) { var buf = HotUpdateChunkTemplate.prototype.renderHeader.call(this, id, modules, hash); buf.unshift( "exports.id = " + JSON.stringify(id) + ";\n", "exports.modules = " ); return buf; }; NodeHotUpdateChunkTemplate.prototype.updateHash = function(hash) { HotUpdateChunkTemplate.prototype.updateHash.call(this, hash); hash.update("NodeHotUpdateChunkTemplate"); hash.update("3"); hash.update(this.outputOptions.hotUpdateFunction + ""); hash.update(this.outputOptions.library + ""); };
export default { "hljs-comment": { "color": "#969896" }, "hljs-quote": { "color": "#969896" }, "hljs-variable": { "color": "#d54e53" }, "hljs-template-variable": { "color": "#d54e53" }, "hljs-tag": { "color": "#d54e53" }, "hljs-name": { "color": "#d54e53" }, "hljs-selector-id": { "color": "#d54e53" }, "hljs-selector-class": { "color": "#d54e53" }, "hljs-regexp": { "color": "#d54e53" }, "hljs-deletion": { "color": "#d54e53" }, "hljs-number": { "color": "#e78c45" }, "hljs-built_in": { "color": "#e78c45" }, "hljs-builtin-name": { "color": "#e78c45" }, "hljs-literal": { "color": "#e78c45" }, "hljs-type": { "color": "#e78c45" }, "hljs-params": { "color": "#e78c45" }, "hljs-meta": { "color": "#e78c45" }, "hljs-link": { "color": "#e78c45" }, "hljs-attribute": { "color": "#e7c547" }, "hljs-string": { "color": "#b9ca4a" }, "hljs-symbol": { "color": "#b9ca4a" }, "hljs-bullet": { "color": "#b9ca4a" }, "hljs-addition": { "color": "#b9ca4a" }, "hljs-title": { "color": "#7aa6da" }, "hljs-section": { "color": "#7aa6da" }, "hljs-keyword": { "color": "#c397d8" }, "hljs-selector-tag": { "color": "#c397d8" }, "hljs": { "display": "block", "overflowX": "auto", "background": "black", "color": "#eaeaea", "padding": "0.5em" }, "hljs-emphasis": { "fontStyle": "italic" }, "hljs-strong": { "fontWeight": "bold" } }
(function() { "use strict"; // no longer used // just serves up one particular file // should always be running // nohup node server& var fs = require('fs'); var http = require('http'); var url = require('url'); http.createServer(function(req, res) { var request = url.parse(req.url, true); var action = request.pathname; if (action == '/functal.png') { var img = fs.readFileSync('./functal.png'); res.writeHead(200, { 'Content-Type': 'image/png' }); res.end(img, 'binary'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Functal\n'); } }).listen(8081); })();
import React from 'react'; import CalculatorInput from './CalculatorInput.js'; import CalculatoResult from './CalculatoResult.js'; import styles from './Calculator.scss'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Calculator { static propTypes = { }; render() { return ( <div className="Calculator" id="calculator"> <CalculatoResult /> <CalculatorInput /> </div> ); } } export default Calculator;
/** @preserve * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria * 2014 Diego Casorran, https://github.com/diegocr * 2014 Daniel Husar, https://github.com/danielhusar * 2014 Wolfgang Gassler, https://github.com/woolfg * 2014 Steven Spungin, https://github.com/flamenco * * 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 (jsPDFAPI) { var clone, DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson; clone = (function () { return function (obj) { Clone.prototype = obj; return new Clone() }; function Clone() {} })(); PurgeWhiteSpace = function (array) { var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace; i = 0; l = array.length; fragment = void 0; lTrimmed = false; rTrimmed = false; while (!lTrimmed && i !== l) { fragment = array[i] = array[i].trimLeft(); if (fragment) { lTrimmed = true; } i++; } i = l - 1; while (l && !rTrimmed && i !== -1) { fragment = array[i] = array[i].trimRight(); if (fragment) { rTrimmed = true; } i--; } r = /\s+$/g; trailingSpace = true; i = 0; while (i !== l) { // Leave the line breaks intact if (array[i] != "\u2028") { fragment = array[i].replace(/\s+/g, " "); if (trailingSpace) { fragment = fragment.trimLeft(); } if (fragment) { trailingSpace = r.test(fragment); } array[i] = fragment; } i++; } return array; }; Renderer = function (pdf, x, y, settings) { this.pdf = pdf; this.x = x; this.y = y; this.settings = settings; //list of functions which are called after each element-rendering process this.watchFunctions = []; this.init(); return this; }; ResolveFont = function (css_font_family_string) { var name, part, parts; name = void 0; parts = css_font_family_string.split(","); part = parts.shift(); while (!name && part) { name = FontNameDB[part.trim().toLowerCase()]; part = parts.shift(); } return name; }; ResolveUnitedNumber = function (css_line_height_string) { //IE8 issues css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string; if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) { css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px"; } if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) { css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px"; } var normal, undef, value; undef = void 0; normal = 16.00; value = UnitedNumberMap[css_line_height_string]; if (value) { return value; } value = { "xx-small" : 9, "x-small" : 11, small : 13, medium : 16, large : 19, "x-large" : 23, "xx-large" : 28, auto : 0 }[{ css_line_height_string : css_line_height_string }]; if (value !== undef) { return UnitedNumberMap[css_line_height_string] = value / normal; } if (value = parseFloat(css_line_height_string)) { return UnitedNumberMap[css_line_height_string] = value / normal; } value = css_line_height_string.match(/([\d\.]+)(px)/); if (value.length === 3) { return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal; } return UnitedNumberMap[css_line_height_string] = 1; }; GetCSS = function (element) { var css,tmp,computedCSSElement; computedCSSElement = (function (el) { var compCSS; compCSS = (function (el) { if (document.defaultView && document.defaultView.getComputedStyle) { return document.defaultView.getComputedStyle(el, null); } else if (el.currentStyle) { return el.currentStyle; } else { return el.style; } })(el); return function (prop) { prop = prop.replace(/-\D/g, function (match) { return match.charAt(1).toUpperCase(); }); return compCSS[prop]; }; })(element); css = {}; tmp = void 0; css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times"; css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal"; css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left"; tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal"; if (tmp === "bold") { if (css["font-style"] === "normal") { css["font-style"] = tmp; } else { css["font-style"] = tmp + css["font-style"]; } } css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1; css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1; css["display"] = (computedCSSElement("display") === "inline" ? "inline" : "block"); tmp = (css["display"] === "block"); css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0; css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0; css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0; css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0; css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0; css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0; css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0; css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0; css["page-break-before"] = computedCSSElement("page-break-before") || "auto"; //float and clearing of floats css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none"; css["clear"] = ClearMap[computedCSSElement("clear")] || "none"; css["color"] = computedCSSElement("color"); return css; }; elementHandledElsewhere = function (element, renderer, elementHandlers) { var handlers, i, isHandledElsewhere, l, t; isHandledElsewhere = false; i = void 0; l = void 0; t = void 0; handlers = elementHandlers["#" + element.id]; if (handlers) { if (typeof handlers === "function") { isHandledElsewhere = handlers(element, renderer); } else { i = 0; l = handlers.length; while (!isHandledElsewhere && i !== l) { isHandledElsewhere = handlers[i](element, renderer); i++; } } } handlers = elementHandlers[element.nodeName]; if (!isHandledElsewhere && handlers) { if (typeof handlers === "function") { isHandledElsewhere = handlers(element, renderer); } else { i = 0; l = handlers.length; while (!isHandledElsewhere && i !== l) { isHandledElsewhere = handlers[i](element, renderer); i++; } } } return isHandledElsewhere; }; tableToJson = function (table, renderer) { var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l; data = []; headers = []; i = 0; l = table.rows[0].cells.length; table_with = table.clientWidth; while (i < l) { cell = table.rows[0].cells[i]; headers[i] = { name : cell.textContent.toLowerCase().replace(/\s+/g, ''), prompt : cell.textContent.replace(/\r?\n/g, ''), width : (cell.clientWidth / table_with) * renderer.pdf.internal.pageSize.width }; i++; } i = 1; while (i < table.rows.length) { tableRow = table.rows[i]; rowData = {}; j = 0; while (j < tableRow.cells.length) { rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, ''); j++; } data.push(rowData); i++; } return table_obj = { rows : data, headers : headers }; }; var SkipNode = { SCRIPT : 1, STYLE : 1, NOSCRIPT : 1, OBJECT : 1, EMBED : 1, SELECT : 1 }; var listCount = 1; DrillForContent = function (element, renderer, elementHandlers) { var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb; cns = element.childNodes; cn = void 0; fragmentCSS = GetCSS(element); isBlock = fragmentCSS.display === "block"; if (isBlock) { renderer.setBlockBoundary(); renderer.setBlockStyle(fragmentCSS); } px2pt = 0.264583 * 72 / 25.4; i = 0; l = cns.length; while (i < l) { cn = cns[i]; if (typeof cn === "object") { //execute all watcher functions to e.g. reset floating renderer.executeWatchFunctions(cn); /*** HEADER rendering **/ if (cn.nodeType === 1 && cn.nodeName === 'HEADER') { var header = cn; //store old top margin var oldMarginTop = renderer.pdf.margins_doc.top; //subscribe for new page event and render header first on every page renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) { //set current y position to old margin renderer.y = oldMarginTop; //render all child nodes of the header element DrillForContent(header, renderer, elementHandlers); //set margin to old margin + rendered header + 10 space to prevent overlapping //important for other plugins (e.g. table) to start rendering at correct position after header renderer.pdf.margins_doc.top = renderer.y + 10; renderer.y += 10; }, false); } if (cn.nodeType === 8 && cn.nodeName === "#comment") { if (~cn.textContent.indexOf("ADD_PAGE")) { renderer.pdf.addPage(); renderer.y = renderer.pdf.margins_doc.top; } } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) { /*** IMAGE RENDERING ***/ var cached_image; if (cn.nodeName === "IMG") { var url = cn.getAttribute("src"); cached_image = images[renderer.pdf.sHashCode(url) || url]; } if (cached_image) { if ((renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height) && (renderer.y > renderer.pdf.margins_doc.top)) { renderer.pdf.addPage(); renderer.y = renderer.pdf.margins_doc.top; //check if we have to set back some values due to e.g. header rendering for new page renderer.executeWatchFunctions(cn); } var imagesCSS = GetCSS(cn); var imageX = renderer.x; var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor; //define additional paddings, margins which have to be taken into account for margin calculations var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"])*fontToUnitRatio; var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"])*fontToUnitRatio; var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"])*fontToUnitRatio; var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"])*fontToUnitRatio; //if float is set to right, move the image to the right border //add space if margin is set if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') { imageX += renderer.settings.width - cn.width - additionalSpaceRight; } else { imageX += additionalSpaceLeft; } renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height); cached_image = undefined; //if the float prop is specified we have to float the text around the image if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') { //add functiont to set back coordinates after image rendering renderer.watchFunctions.push((function(diffX , thresholdY, diffWidth, el) { //undo drawing box adaptions which were set by floating if (renderer.y >= thresholdY) { renderer.x += diffX; renderer.settings.width += diffWidth; return true; } else if(el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x+el.width > (renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width)) { renderer.x += diffX; renderer.y = thresholdY; renderer.settings.width += diffWidth; return true; } else { return false; } }).bind(this, (imagesCSS['float'] === 'left') ? -cn.width-additionalSpaceLeft-additionalSpaceRight : 0, renderer.y+cn.height+additionalSpaceTop+additionalSpaceBottom, cn.width)); //reset floating by clear:both divs //just set cursorY after the floating element renderer.watchFunctions.push((function(yPositionAfterFloating, pages, el) { if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) { if (el.nodeType === 1 && GetCSS(el).clear === 'both') { renderer.y = yPositionAfterFloating; return true; } else { return false; } } else { return true; } }).bind(this, renderer.y+cn.height, renderer.pdf.internal.getNumberOfPages())); //if floating is set we decrease the available width by the image width renderer.settings.width -= cn.width+additionalSpaceLeft+additionalSpaceRight; //if left just add the image width to the X coordinate if (imagesCSS['float'] === 'left') { renderer.x += cn.width+additionalSpaceLeft+additionalSpaceRight; } } else { //if no floating is set, move the rendering cursor after the image height renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom; } /*** TABLE RENDERING ***/ } else if (cn.nodeName === "TABLE") { table2json = tableToJson(cn, renderer); renderer.y += 10; renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, { autoSize : false, printHeaders: elementHandlers.printHeaders, margins: renderer.pdf.margins_doc, css: GetCSS(cn) }); renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20; } else if (cn.nodeName === "OL" || cn.nodeName === "UL") { listCount = 1; if (!elementHandledElsewhere(cn, renderer, elementHandlers)) { DrillForContent(cn, renderer, elementHandlers); } renderer.y += 10; } else if (cn.nodeName === "LI") { var temp = renderer.x; renderer.x += 20 / renderer.pdf.internal.scaleFactor; renderer.y += 3; if (!elementHandledElsewhere(cn, renderer, elementHandlers)) { DrillForContent(cn, renderer, elementHandlers); } renderer.x = temp; } else if (cn.nodeName === "BR") { renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor; renderer.addText("\u2028", clone(fragmentCSS)); } else { if (!elementHandledElsewhere(cn, renderer, elementHandlers)) { DrillForContent(cn, renderer, elementHandlers); } } } else if (cn.nodeType === 3) { var value = cn.nodeValue; if (cn.nodeValue && cn.parentNode.nodeName === "LI") { if (cn.parentNode.parentNode.nodeName === "OL") { value = listCount++ + '. ' + value; } else { var fontSize = fragmentCSS["font-size"]; var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor; var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor; var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor; cb = function (x, y) { this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD'); }; } } // Only add the text if the text node is in the body element // Add compatibility with IE11 if(!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)){ renderer.addText(value, fragmentCSS); } } else if (typeof cn === "string") { renderer.addText(cn, fragmentCSS); } } i++; } elementHandlers.outY = renderer.y; if (isBlock) { return renderer.setBlockBoundary(cb); } }; images = {}; loadImgs = function (element, renderer, elementHandlers, cb) { var imgs = element.getElementsByTagName('img'), l = imgs.length, found_images, x = 0; function done() { renderer.pdf.internal.events.publish('imagesLoaded'); cb(found_images); } function loadImage(url, width, height) { if (!url) return; var img = new Image(); found_images = ++x; img.crossOrigin = ''; img.onerror = img.onload = function () { if(img.complete) { //to support data urls in images, set width and height //as those values are not recognized automatically if (img.src.indexOf('data:image/') === 0) { img.width = width || img.width || 0; img.height = height || img.height || 0; } //if valid image add to known images array if (img.width + img.height) { var hash = renderer.pdf.sHashCode(url) || url; images[hash] = images[hash] || img; } } if(!--x) { done(); } }; img.src = url; } while (l--) loadImage(imgs[l].getAttribute("src"),imgs[l].width,imgs[l].height); return x || done(); }; checkForFooter = function (elem, renderer, elementHandlers) { //check if we can found a <footer> element var footer = elem.getElementsByTagName("footer"); if (footer.length > 0) { footer = footer[0]; //bad hack to get height of footer //creat dummy out and check new y after fake rendering var oldOut = renderer.pdf.internal.write; var oldY = renderer.y; renderer.pdf.internal.write = function () {}; DrillForContent(footer, renderer, elementHandlers); var footerHeight = Math.ceil(renderer.y - oldY) + 5; renderer.y = oldY; renderer.pdf.internal.write = oldOut; //add 20% to prevent overlapping renderer.pdf.margins_doc.bottom += footerHeight; //Create function render header on every page var renderFooter = function (pageInfo) { var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1; //set current y position to old margin var oldPosition = renderer.y; //render all child nodes of the header element renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom; renderer.pdf.margins_doc.bottom -= footerHeight; //check if we have to add page numbers var spans = footer.getElementsByTagName('span'); for (var i = 0; i < spans.length; ++i) { //if we find some span element with class pageCounter, set the page if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) { spans[i].innerHTML = pageNumber; } //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) { spans[i].innerHTML = '###jsPDFVarTotalPages###'; } } //render footer content DrillForContent(footer, renderer, elementHandlers); //set bottom margin to previous height including the footer height renderer.pdf.margins_doc.bottom += footerHeight; //important for other plugins (e.g. table) to start rendering at correct position after header renderer.y = oldPosition; }; //check if footer contains totalPages which should be replace at the disoposal of the document var spans = footer.getElementsByTagName('span'); for (var i = 0; i < spans.length; ++i) { if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) { renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true); } } //register event to render footer on every new page renderer.pdf.internal.events.subscribe('addPage', renderFooter, false); //render footer on first page renderFooter(); //prevent footer rendering SkipNode['FOOTER'] = 1; } }; process = function (pdf, element, x, y, settings, callback) { if (!element) return false; if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML; if (typeof element === "string") { element = (function (element) { var $frame, $hiddendiv, framename, visuallyhidden; framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0); visuallyhidden = "position: absolute !important;" + "clip: rect(1px 1px 1px 1px); /* IE6, IE7 */" + "clip: rect(1px, 1px, 1px, 1px);" + "padding:0 !important;" + "border:0 !important;" + "height: 1px !important;" + "width: 1px !important; " + "top:auto;" + "left:-100px;" + "overflow: hidden;"; $hiddendiv = document.createElement('div'); $hiddendiv.style.cssText = visuallyhidden; $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />"; document.body.appendChild($hiddendiv); $frame = window.frames[framename]; $frame.document.open(); $frame.document.writeln(element); $frame.document.close(); return $frame.document.body; })(element.replace(/<\/?script[^>]*?>/gi, '')); } var r = new Renderer(pdf, x, y, settings), out; // 1. load images // 2. prepare optional footer elements // 3. render content loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) { checkForFooter( element, r, settings.elementHandlers); DrillForContent(element, r, settings.elementHandlers); //send event dispose for final taks (e.g. footer totalpage replacement) r.pdf.internal.events.publish('htmlRenderingFinished'); out = r.dispose(); if (typeof callback === 'function') callback(out); else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!'); }); return out || {x: r.x, y:r.y}; }; Renderer.prototype.init = function () { this.paragraph = { text : [], style : [] }; return this.pdf.internal.write("q"); }; Renderer.prototype.dispose = function () { this.pdf.internal.write("Q"); return { x : this.x, y : this.y, ready:true }; }; //Checks if we have to execute some watcher functions //e.g. to end text floating around an image Renderer.prototype.executeWatchFunctions = function(el) { var ret = false; var narray = []; if (this.watchFunctions.length > 0) { for(var i=0; i< this.watchFunctions.length; ++i) { if (this.watchFunctions[i](el) === true) { ret = true; } else { narray.push(this.watchFunctions[i]); } } this.watchFunctions = narray; } return ret; }; Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) { var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style; defaultFontSize = 12; k = this.pdf.internal.scaleFactor; fontMetricsCache = {}; ff = void 0; fs = void 0; fontMetrics = void 0; fragment = void 0; style = void 0; fragmentSpecificMetrics = void 0; fragmentLength = void 0; fragmentChopped = void 0; line = []; lines = [line]; currentLineLength = 0; maxLineLength = this.settings.width; while (fragments.length) { fragment = fragments.shift(); style = styles.shift(); if (fragment) { ff = style["font-family"]; fs = style["font-style"]; fontMetrics = fontMetricsCache[ff + fs]; if (!fontMetrics) { fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode; fontMetricsCache[ff + fs] = fontMetrics; } fragmentSpecificMetrics = { widths : fontMetrics.widths, kerning : fontMetrics.kerning, fontSize : style["font-size"] * defaultFontSize, textIndent : currentLineLength }; fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k; if (fragment == "\u2028") { line = []; lines.push(line); } else if (currentLineLength + fragmentLength > maxLineLength) { fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics); line.push([fragmentChopped.shift(), style]); while (fragmentChopped.length) { line = [[fragmentChopped.shift(), style]]; lines.push(line); } currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k; } else { line.push([fragment, style]); currentLineLength += fragmentLength; } } } //if text alignment was set, set margin/indent of each line if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) { for (var i = 0; i < lines.length; ++i) { var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k; //if there is more than on line we have to clone the style object as all lines hold a reference on this object if (i > 0) { lines[i][0][1] = clone(lines[i][0][1]); } var space = (maxLineLength - length); if (style['text-align'] === 'right') { lines[i][0][1]['margin-left'] = space; //if alignment is not right, it has to be center so split the space to the left and the right } else if (style['text-align'] === 'center') { lines[i][0][1]['margin-left'] = space / 2; //if justify was set, calculate the word spacing and define in by using the css property } else if (style['text-align'] === 'justify') { var countSpaces = lines[i][0][0].split(' ').length - 1; lines[i][0][1]['word-spacing'] = space / countSpaces; //ignore the last line in justify mode if (i === (lines.length - 1)) { lines[i][0][1]['word-spacing'] = 0; } } } } return lines; }; Renderer.prototype.RenderTextFragment = function (text, style) { var defaultFontSize, font, maxLineHeight; maxLineHeight = 0; defaultFontSize = 12; if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) { this.pdf.internal.write("ET", "Q"); this.pdf.addPage(); this.y = this.pdf.margins_doc.top; this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td"); //move cursor by one line on new page maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]); this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td"); } font = this.pdf.internal.getFont(style["font-family"], style["font-style"]); // text color var pdfTextColor = this.getPdfColor(style["color"]); if (pdfTextColor !== this.lastTextColor) { this.pdf.internal.write(pdfTextColor); this.lastTextColor = pdfTextColor; } //set the word spacing for e.g. justify style if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) { this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw"); } this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj"); //set the word spacing back to neutral => 0 if (style['word-spacing'] !== undefined) { this.pdf.internal.write(0, "Tw"); } }; // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name Renderer.prototype.getPdfColor = function(style) { var textColor; var r,g,b; var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/; var m = rx.exec(style); if (m != null){ r = parseInt(m[1]); g = parseInt(m[2]); b = parseInt(m[3]); } else{ if (style.charAt(0) != '#') { style = CssColors.colorNameToHex(style); if (!style) { style = '#000000'; } } r = style.substring(1, 3); r = parseInt(r, 16); g = style.substring(3, 5); g = parseInt(g, 16); b = style.substring(5, 7); b = parseInt(b, 16); } if ((typeof r === 'string') && /^#[0-9A-Fa-f]{6}$/.test(r)) { var hex = parseInt(r.substr(1), 16); r = (hex >> 16) & 255; g = (hex >> 8) & 255; b = (hex & 255); } var f3 = this.f3; if ((r === 0 && g === 0 && b === 0) || (typeof g === 'undefined')) { textColor = f3(r / 255) + ' g'; } else { textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' '); } return textColor; }; Renderer.prototype.f3 = function(number) { return number.toFixed(3); // Ie, %.3f }, Renderer.prototype.renderParagraph = function (cb) { var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize; fragments = PurgeWhiteSpace(this.paragraph.text); styles = this.paragraph.style; blockstyle = this.paragraph.blockstyle; priorblockstyle = this.paragraph.priorblockstyle || {}; this.paragraph = { text : [], style : [], blockstyle : {}, priorblockstyle : blockstyle }; if (!fragments.join("").trim()) { return; } lines = this.splitFragmentsIntoLines(fragments, styles); line = void 0; maxLineHeight = void 0; defaultFontSize = 12; fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor; this.priorMarginBottom = this.priorMarginBottom || 0; paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio; paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio; this.priorMarginBottom = blockstyle["margin-bottom"] || 0; if (blockstyle['page-break-before'] === 'always'){ this.pdf.addPage(); this.y = 0; paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio; } out = this.pdf.internal.write; i = void 0; l = void 0; this.y += paragraphspacing_before; out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); //stores the current indent of cursor position var currentIndent = 0; while (lines.length) { line = lines.shift(); maxLineHeight = 0; i = 0; l = line.length; while (i !== l) { if (line[i][0].trim()) { maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]); fontSize = line[i][1]["font-size"] * 7; } i++; } //if we have to move the cursor to adapt the indent var indentMove = 0; var wantedIndent = 0; //if a margin was added (by e.g. a text-alignment), move the cursor if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) { wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]); indentMove = wantedIndent - currentIndent; currentIndent = wantedIndent; } var indentMore = (Math.max(blockstyle["margin-left"] || 0, 0)) * fontToUnitRatio; //move the cursor out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td"); i = 0; l = line.length; while (i !== l) { if (line[i][0]) { this.RenderTextFragment(line[i][0], line[i][1]); } i++; } this.y += maxLineHeight * fontToUnitRatio; //if some watcher function was executed successful, so e.g. margin and widths were changed, //reset line drawing and calculate position and lines again //e.g. to stop text floating around an image if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) { var localFragments = []; var localStyles = []; //create fragment array of lines.forEach(function(localLine) { var i = 0; var l = localLine.length; while (i !== l) { if (localLine[i][0]) { localFragments.push(localLine[i][0]+' '); localStyles.push(localLine[i][1]); } ++i; } }); //split lines again due to possible coordinate changes lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles); //reposition the current cursor out("ET", "Q"); out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); } } if (cb && typeof cb === "function") { cb.call(this, this.x - 9, this.y - fontSize / 2); } out("ET", "Q"); return this.y += paragraphspacing_after; }; Renderer.prototype.setBlockBoundary = function (cb) { return this.renderParagraph(cb); }; Renderer.prototype.setBlockStyle = function (css) { return this.paragraph.blockstyle = css; }; Renderer.prototype.addText = function (text, css) { this.paragraph.text.push(text); return this.paragraph.style.push(css); }; FontNameDB = { helvetica : "helvetica", "sans-serif" : "helvetica", "times new roman" : "times", serif : "times", times : "times", monospace : "courier", courier : "courier" }; FontWeightMap = { 100 : "normal", 200 : "normal", 300 : "normal", 400 : "normal", 500 : "bold", 600 : "bold", 700 : "bold", 800 : "bold", 900 : "bold", normal : "normal", bold : "bold", bolder : "bold", lighter : "normal" }; FontStyleMap = { normal : "normal", italic : "italic", oblique : "italic" }; TextAlignMap = { left : "left", right : "right", center : "center", justify : "justify" }; FloatMap = { none : 'none', right: 'right', left: 'left' }; ClearMap = { none : 'none', both : 'both' }; UnitedNumberMap = { normal : 1 }; /** * Converts HTML-formatted text into formatted PDF text. * * Notes: * 2012-07-18 * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed. * Plugin relies on jQuery for CSS extraction. * Targeting HTML output from Markdown templating, which is a very simple * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.) * Images, tables are NOT supported. * * @public * @function * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF. * @param x {Number} starting X coordinate in jsPDF instance's declared units. * @param y {Number} starting Y coordinate in jsPDF instance's declared units. * @param settings {Object} Additional / optional variables controlling parsing, rendering. * @returns {Object} jsPDF instance */ jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) { "use strict"; this.margins_doc = margins || { top : 0, bottom : 0 }; if (!settings) settings = {}; if (!settings.elementHandlers) settings.elementHandlers = {}; return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback); }; })(jsPDF.API);
// --------- Dependencies --------- let mongoose = require('mongoose'); /** * Saves the update for the user into the database or returns a general error * on failure. * @param {Object} user The user object * @param {Object} obj The object to return to the user * @param {string} message The message to display on an error * @param {Function} done The callback function to execute upon completion * @return {Function} Execute the callback function */ function saveUpdate(user, obj, message, done) { return user.save(function(err) { // An error occurred if (err) { return done(new Error(message)); } // Saved object to user return done(null, obj); }); } module.exports = function(UserSchema, messages) { ['Facebook', 'YouTube'].forEach(function(serviceName) { /** * Populate service identifiers and tokens. * @param {ObjectId} id The current user's id in MongoDB * @param {Object} service User-specific details for the service * @param {Function} done The callback function to execute upon * completion */ UserSchema.statics['add' + serviceName] = function(id, service, done) { mongoose.models.User.findById(id, function(err, user) { // Database Error if (err) { return done(new Error(messages.ERROR.GENERAL)); } // Unexpected Error: User not found if (!user) { return done(new Error(messages.ERROR.GENERAL)); } if (service.reauth) { return done(messages.STATUS[serviceName.toUpperCase()] .MISSING_PERMISSIONS); } else if (service.refreshAccessToken) { delete service.refreshAccessToken; user[serviceName.toLowerCase()] = service; user.save(function(err) { // Database Error if (err) { return done(new Error(messages.ERROR.GENERAL)); } // Success: Refreshed access token for service return done(messages.STATUS[serviceName.toUpperCase()].RENEWED); }); } else if (user['has' + serviceName]) { // Defined Error: Service already exists return done(new Error(messages.STATUS[serviceName.toUpperCase()] .ALREADY_CONNECTED)); } else { // Save service information (excluding other states) to account delete service.reauth; delete service.refreshAccessToken; user[serviceName.toLowerCase()] = service; return saveUpdate(user, user, messages.ERROR.GENERAL, done); } }); }; /** * Check if the user is connected to the service. * @return {Boolean} A status of whether the user has added this service */ UserSchema.virtual('has' + serviceName).get(function() { return Boolean(this[serviceName.toLowerCase()].profileId); }); /** * Enable or disable updates for a service. * @param {Function} done The callback function to execute upon completion */ UserSchema.methods['toggle' + serviceName] = function(done) { mongoose.models.User.findById(this._id, function(err, user) { // Database Error if (err) { return done(new Error(messages.ERROR.GENERAL)); } let message = messages.STATUS[serviceName.toUpperCase()].NOT_CONFIGURED; if (user['has' + serviceName]) { message = user[serviceName.toLowerCase()].acceptUpdates ? messages.STATUS[serviceName.toUpperCase()].UPDATES_DISABLED : messages.STATUS[serviceName.toUpperCase()].UPDATES_ENABLED; user[serviceName.toLowerCase()].acceptUpdates = !user[serviceName.toLowerCase()].acceptUpdates; } return saveUpdate(user, message, messages.ERROR.GENERAL, done); }); }; }); };
import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import App from './App'; import CurrentStatus from './CurrentStatus'; import History from './History'; import store from '../store'; const history = syncHistoryWithStore(browserHistory, store); class AppRouter extends React.Component { render() { return ( <div> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={CurrentStatus} /> <Route path="history" component={History} /> </Route> </Router> </div> ); } } export default AppRouter;
netjs.collections.CollectionBase = (function (netjs, ListEnumerator) { 'use strict'; var CollectionBase = function CollectionBase() { // use _isBase to determine if this constructor is being invoked via chain or new if(!CollectionBase._isBase){ throw new Error("Can't instantiate abstract classes"); } else { /** * Call the parent constructor */ var _args = Array.prototype.slice.call(arguments); CollectionBase._parent.constructor.apply(this, _args); this._list = new netjs.collections.ArrayList(); } if(!CollectionBase._isBase){ return netjs.Util.proxy(this); } else { return this; } }; CollectionBase.inheritsFrom(netjs.Class).isType('CollectionBase'); /** * Implementation of IEnumerable * 'enumerator' */ CollectionBase.prototype.enumerator = function (){ var self = this; return self._list.enumerator(); }; /** * Implementation of ICollection * 'copyTo', 'count' */ CollectionBase.prototype.copyTo = function (array, index) { var self = this; self._list.copyTo(array, index); }; CollectionBase.prototype.count = function () { var self = this; return self._list.count(); }; /** * Implementation of IList * 'add', 'clear', 'contains', 'get', 'indexOf', 'insert', 'remove', 'removeAt', 'set' */ CollectionBase.prototype.add = function (value) { var self = this, index = self.count(); self.insert(index, value); return index; }; CollectionBase.prototype.clear = function () { var self = this; self.onClear(); self._list.clear(); self.onClearComplete(); }; CollectionBase.prototype.contains = function (value) { var self = this; return self._list.contains(value); }; CollectionBase.prototype.getItem = function (index) { var self = this; return self._list.getItem(index); }; CollectionBase.prototype.indexOf = function (value) { var self = this; return self._list.indexOf(value); }; CollectionBase.prototype.insert = function (index, value) { var self = this; self.onValidate(value); self.onInsert(index, value); self._list.insert(index, value); self.onInsertComplete(index, value); }; CollectionBase.prototype.remove = function (value) { var self = this, index; index = self.indexOf(value); self.onValidate(value); self.onRemove(index, value); self._list.remove(value); self.onRemoveComplete(index, value); }; CollectionBase.prototype.removeAt = function (index) { var self = this, value; value = self.getItem(index); self.onValidate(value); self.onRemove(index, value); self._list.removeAt(index); self.onRemoveComplete(index, value); }; CollectionBase.prototype.setItem = function (index, value) { var self = this, oldValue; oldValue = self.getItem(index); self.onValidate(value); self.onSet(index, oldValue, value); self._list.setItem(index, value); self.onSetComplete(index, oldValue, value); }; CollectionBase.prototype.onClear = function () {}; CollectionBase.prototype.onClearComplete = function () {}; CollectionBase.prototype.onInsert = function (index, value) {}; CollectionBase.prototype.onInsertComplete = function (index, value) {}; CollectionBase.prototype.onRemove = function (index, value) {}; CollectionBase.prototype.onRemoveComplete = function (index, value) {}; CollectionBase.prototype.onSet = function (index, oldValue, newValue) {}; CollectionBase.prototype.onSetComplete = function (index, oldValue, newValue) {}; CollectionBase.prototype.onValidate = function (value) {}; CollectionBase.ensureImplements(netjs.collections.IList, netjs.collections.ICollection, netjs.collections.IEnumerable); return CollectionBase; } (netjs));
/* * CMS.js v1.0.0 * Copyright 2015 Chris Diana * www.cdmedia.github.io/cms.js * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ var CMS = { settings: { siteName: 'CMS.js', siteTagline: 'Your site tagline', siteEmail: 'your_email@example.com', siteAuthor: 'Your Name', siteUrl: '', siteNavItems: [ { name: 'Github', href: '#', newWindow: false}, { name: 'About' } ], pagination: 3, postsFolder: 'posts', postSnippetLength: 120, pagesFolder: 'pages', fadeSpeed: 300, mainContainer: $('.cms_main'), footerContainer: $('.cms_footer'), footerText: '&copy; ' + new Date().getFullYear() + ' All Rights Reserved.', parseSeperator: '---', loader: '<div class="loader">Loading...</div>', get siteAttributes() { return [ { attr: 'title', value: CMS.settings.siteName }, { attr: '.cms_sitename', value: CMS.settings.siteName}, { attr: '.cms_tagline', value: CMS.settings.siteTagline}, { attr: '.cms_footer_text', value: CMS.settings.footerText} ]; }, mode: 'Github', githubUserSettings: { username: 'yourusername', repo: 'yourrepo', }, githubSettings: { branch: 'gh-pages', host: 'https://api.github.com' } }, posts: [], pages: [], loaded: {}, // ---------------------------------------------------------------- extend: function (target, opts, callback) { var next; if (typeof opts === "undefined") { opts = target; target = CMS; } for (next in opts) { if (Object.prototype.hasOwnProperty.call(opts, next)) { target[next] = opts[next]; } } callback(); // check user config options return target; }, // ---------------------------------------------------------------- render: function (url) { CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed); CMS.settings.footerContainer.hide(); var type = url.split('/')[0]; var map = { // Main view '' : function () { CMS.renderPosts(); }, // Post view '#post' : function() { var id = url.split('#post/')[1].trim(); CMS.renderPost(id); }, // Post view '#page' : function() { var title = url.split('#page/')[1].trim(); CMS.renderPage(title); } }; if (map[type]) { map[type](); } else { var errorMsg = 'Error loading page.'; CMS.renderError(errorMsg); } }, // ---------------------------------------------------------------- renderPage: function(title) { CMS.pages.forEach(function(page){ if(page.title == title) { var tpl = $('#page-template').html(), $tpl = $(tpl); $tpl.find('.page-title').html(page.title); $tpl.find('.page-content').html(page.contentData); CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed); } }); CMS.renderFooter(); }, // ---------------------------------------------------------------- renderPost: function(id) { CMS.posts.forEach(function(post){ if(post.id == id) { var tpl = $('#post-template').html(), $tpl = $(tpl); $tpl.find('.post-title').html(post.title); $tpl.find('.post-date').html((post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' + post.date.getFullYear()); $tpl.find('.post-content').html(post.contentData); CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed); } }); CMS.renderFooter(); }, // ---------------------------------------------------------------- renderPosts: function() { CMS.posts.forEach(function(post){ var tpl = $('#post-template').html(), $tpl = $(tpl); var title = '<a href="#">' + post.title + '</a>', date = (post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' + post.date.getFullYear(), snippet = post.contentData.split('.')[0] + '.'; var postLink = $tpl.find('.post-title'), postDate = $tpl.find('.post-date'), postSnippet = $tpl.find('.post-content'); postLink.on('click', function (e) { e.preventDefault(); window.location.hash = 'post/' + post.id; }); postLink.html(title); postSnippet.html(snippet); postDate.html(date); CMS.settings.mainContainer.append($tpl).hide().fadeIn(CMS.settings.fadeSpeed); }); CMS.renderFooter(); }, // ---------------------------------------------------------------- renderFooter: function() { // Load footer later so things dont look weird loading ajax stuff setTimeout(function () { CMS.settings.footerContainer.fadeIn(CMS.settings.fadeSpeed); }, 800); }, // ---------------------------------------------------------------- renderError: function(msg) { var tpl = $('#error-template').html(), $tpl = $(tpl); $tpl.find('.error_text').html(msg); CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed, function(){ CMS.settings.mainContainer.html($tpl).fadeIn(CMS.settings.fadeSpeed); }); }, // ---------------------------------------------------------------- contentLoaded: function(type) { CMS.loaded[type] = true; if(CMS.loaded.page && CMS.loaded.post) { // Set navigation this.setNavigation(); // Manually trigger on initial load $(window).trigger('hashchange'); } }, // ---------------------------------------------------------------- parseContent: function(content, type, file, counter, numFiles) { var data = content.split(CMS.settings.parseSeperator), contentObj = {}, id = counter, date = file.date; contentObj.id = id; contentObj.date = date; // Get content info var infoData = data[1].split('\n'); $.each(infoData, function(k, v) { if(v.length) { v.replace(/^\s+|\s+$/g, '').trim(); var i = v.split(':'); var val = i[1]; k = i[0]; contentObj[k] = val.trim(); } }); // Drop stuff we dont need data.splice(0,2); // Put everything back together if broken var contentData = data.join(); contentObj.contentData = marked(contentData); if(type == 'post') { CMS.posts.push(contentObj); } else if (type == 'page') { CMS.pages.push(contentObj); } // Execute after all content is loaded if(counter === numFiles) { CMS.contentLoaded(type); } }, // ---------------------------------------------------------------- getContent: function(type, file, counter, numFiles) { var urlFolder = ''; switch(type) { case 'post': urlFolder = CMS.settings.postsFolder; break; case 'page': urlFolder = CMS.settings.pagesFolder; break; } if(CMS.settings.mode == 'Github') { url = file.link; } else { url = urlFolder + '/' + file.name; } $.ajax({ type: 'GET', url: url, dataType: 'html', success: function(content) { CMS.parseContent(content, type, file, counter, numFiles); }, error: function() { var errorMsg = 'Error loading ' + type + ' content'; CMS.renderError(errorMsg); } }); }, // ---------------------------------------------------------------- getFiles: function(type) { var folder = '', url = ''; switch(type) { case 'post': folder = CMS.settings.postsFolder; break; case 'page': folder = CMS.settings.pagesFolder; break; } if(CMS.settings.mode == 'Github') { var gus = CMS.settings.githubUserSettings, gs = CMS.settings.githubSettings; if (gus.repo === '') { url = gs.host + '/' + folder + '?ref=' + gs.branch; } else { url = gs.host + '/repos/' + gus.username + '/' + gus.repo + '/contents/' + folder + '?ref=' + gs.branch; } // msloth.github.io/repos/msloth//contents/posts?ref=gh-pages // msloth.github.io/posts?ref=gh-pages } else { url = folder; } $.ajax({ url: url, success: function(data) { var files = [], linkFiles; if(CMS.settings.mode == 'Github') { linkFiles = data; } else { linkFiles = $(data).find("a"); } $(linkFiles).each(function(k, f) { var filename, downloadLink; if(CMS.settings.mode == 'Github') { filename = f.name; downloadLink = f.download_url; } else { filename = $(f).attr("href"); } if(filename.endsWith('.md')) { var file = {}; file.date = new Date(filename.substring(0, 10)); file.name = filename; if(downloadLink) { file.link = downloadLink; } files.push(file); } }); var counter = 0, numFiles = files.length; if(files.length > 0) { $(files).each(function(k, file) { counter++; CMS.getContent(type, file, counter, numFiles); }); } else { var errorMsg = 'Error loading ' + type + 's in directory. Make sure ' + 'there are Markdown ' + type + 's in the ' + type + 's folder.'; CMS.renderError(errorMsg); } }, error: function() { var errorMsg; if(CMS.settings.mode == 'Github') { errorMsg = 'Error loading ' + type + 's directory. Make sure ' + 'your Github settings are correctly set in your config.js file.'; } else { errorMsg = 'Error loading ' + type + 's directory. Make sure ' + type + 's directory is set correctly in config and .htaccess is in ' + type + 's directory with Apache "Options Indexes" set on.'; } CMS.renderError(errorMsg); } }); }, // ---------------------------------------------------------------- setNavigation: function() { var nav = '<ul>'; CMS.settings.siteNavItems.forEach(function(navItem) { if(navItem.hasOwnProperty('href')) { nav += '<li><a href="' + navItem.href + '"'; if(navItem.hasOwnProperty('newWindow')) { if(navItem.newWindow) { nav += 'target="_blank"'; } } nav += '>' + navItem.name + '</a></li>'; } else { CMS.pages.forEach(function(page) { if(navItem.name == page.title) { nav += '<li><a href="#" class="cms_nav_link" id="' + navItem.name + '">' + navItem.name + '</a></li>'; } }); } }); nav += '</ul>'; $('.cms_nav').html(nav).hide().fadeIn(CMS.settings.fadeSpeed); // Set onclicks for nav links $.each($('.cms_nav_link'), function(k, link) { var title = $(this).attr("id"); $(this).on('click', function (e) { e.preventDefault(); window.location.hash = 'page/' + title; }); }); }, // ---------------------------------------------------------------- setSiteAttributes: function() { CMS.settings.siteAttributes.forEach(function(attribute) { var value; // Set brand if(attribute.attr == '.cms_sitename') { if (attribute.value.match(/\.(jpeg|jpg|gif|png)$/)) { value = '<img src="' + attribute.value + '" />'; } else { value = attribute.value; } } else { value = attribute.value; } $(attribute.attr).html(value).hide().fadeIn(CMS.settings.fadeSpeed); }); }, // ---------------------------------------------------------------- generateSite: function() { this.setSiteAttributes(); var types = ['post', 'page']; types.forEach(function(type){ CMS.getFiles(type); }); // Check for hash changes $(window).on('hashchange', function () { CMS.render(window.location.hash); }); }, // ---------------------------------------------------------------- init: function (options) { if ($.isPlainObject(options)) { return this.extend(this.settings, options, function () { CMS.generateSite(); }); } } };
var Adapter = require('../factory-girl').Adapter; var tests = require('./adapter-tests'); var should = require('should'); var context = describe; var TestModel = function(props) { this.props = props; }; var TestAdapter = function() { this.db = []; }; TestAdapter.prototype = new Adapter(); TestAdapter.prototype.save = function(doc, Model, cb) { this.db.push(doc); process.nextTick(function() { cb(null, doc); }); }; TestAdapter.prototype.destroy = function(doc, Model, cb) { var db = this.db; var i = db.indexOf(doc); if (i != -1) this.db = db.slice(0, i).concat(db.slice(i + 1)); process.nextTick(cb); }; describe('test adapter', function() { var adapter = new TestAdapter(); tests(adapter, TestModel, countModels); function countModels(cb) { process.nextTick(function() { cb(null, adapter.db.length); }); } });
/* AngularJS v1.2.19 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(T,V,s){'use strict';function v(b){return function(){var a=arguments[0],c,a="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.2.19/"+(b?b+"/":"")+a;for(c=1;c<arguments.length;c++)a=a+(1==c?"?":"&")+"p"+(c-1)+"="+encodeURIComponent("function"==typeof arguments[c]?arguments[c].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[c]?"undefined":"string"!=typeof arguments[c]?JSON.stringify(arguments[c]):arguments[c]);return Error(a)}}function db(b){if(null==b||Ea(b))return!1; var a=b.length;return 1===b.nodeType&&a?!0:y(b)||L(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function q(b,a,c){var d;if(b)if(O(b))for(d in b)"prototype"==d||("length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d))||a.call(c,b[d],d);else if(b.forEach&&b.forEach!==q)b.forEach(a,c);else if(db(b))for(d=0;d<b.length;d++)a.call(c,b[d],d);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d);return b}function Vb(b){var a=[],c;for(c in b)b.hasOwnProperty(c)&&a.push(c);return a.sort()}function Tc(b, a,c){for(var d=Vb(b),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function Wb(b){return function(a,c){b(c,a)}}function eb(){for(var b=ka.length,a;b;){b--;a=ka[b].charCodeAt(0);if(57==a)return ka[b]="A",ka.join("");if(90==a)ka[b]="0";else return ka[b]=String.fromCharCode(a+1),ka.join("")}ka.unshift("0");return ka.join("")}function Xb(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function E(b){var a=b.$$hashKey;q(arguments,function(a){a!==b&&q(a,function(a,c){b[c]=a})});Xb(b,a);return b}function Z(b){return parseInt(b, 10)}function Yb(b,a){return E(new (E(function(){},{prototype:b})),a)}function A(){}function Fa(b){return b}function $(b){return function(){return b}}function D(b){return"undefined"===typeof b}function B(b){return"undefined"!==typeof b}function U(b){return null!=b&&"object"===typeof b}function y(b){return"string"===typeof b}function xb(b){return"number"===typeof b}function Oa(b){return"[object Date]"===xa.call(b)}function O(b){return"function"===typeof b}function fb(b){return"[object RegExp]"===xa.call(b)} function Ea(b){return b&&b.document&&b.location&&b.alert&&b.setInterval}function Uc(b){return!(!b||!(b.nodeName||b.prop&&b.attr&&b.find))}function Vc(b,a,c){var d=[];q(b,function(b,g,f){d.push(a.call(c,b,g,f))});return d}function Pa(b,a){if(b.indexOf)return b.indexOf(a);for(var c=0;c<b.length;c++)if(a===b[c])return c;return-1}function Qa(b,a){var c=Pa(b,a);0<=c&&b.splice(c,1);return a}function Ga(b,a,c,d){if(Ea(b)||b&&b.$evalAsync&&b.$watch)throw Ra("cpws");if(a){if(b===a)throw Ra("cpi");c=c||[]; d=d||[];if(U(b)){var e=Pa(c,b);if(-1!==e)return d[e];c.push(b);d.push(a)}if(L(b))for(var g=a.length=0;g<b.length;g++)e=Ga(b[g],null,c,d),U(b[g])&&(c.push(b[g]),d.push(e)),a.push(e);else{var f=a.$$hashKey;q(a,function(b,c){delete a[c]});for(g in b)e=Ga(b[g],null,c,d),U(b[g])&&(c.push(b[g]),d.push(e)),a[g]=e;Xb(a,f)}}else(a=b)&&(L(b)?a=Ga(b,[],c,d):Oa(b)?a=new Date(b.getTime()):fb(b)?a=RegExp(b.source):U(b)&&(a=Ga(b,{},c,d)));return a}function la(b,a){if(L(b)){a=a||[];for(var c=0;c<b.length;c++)a[c]= b[c]}else if(U(b))for(c in a=a||{},b)!yb.call(b,c)||"$"===c.charAt(0)&&"$"===c.charAt(1)||(a[c]=b[c]);return a||b}function ya(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&"object"==c)if(L(b)){if(!L(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ya(b[d],a[d]))return!1;return!0}}else{if(Oa(b))return Oa(a)&&b.getTime()==a.getTime();if(fb(b)&&fb(a))return b.toString()==a.toString();if(b&&b.$evalAsync&&b.$watch||a&&a.$evalAsync&& a.$watch||Ea(b)||Ea(a)||L(a))return!1;c={};for(d in b)if("$"!==d.charAt(0)&&!O(b[d])){if(!ya(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&a[d]!==s&&!O(a[d]))return!1;return!0}return!1}function Zb(){return V.securityPolicy&&V.securityPolicy.isActive||V.querySelector&&!(!V.querySelector("[ng-csp]")&&!V.querySelector("[data-ng-csp]"))}function zb(b,a){var c=2<arguments.length?za.call(arguments,2):[];return!O(a)||a instanceof RegExp?a:c.length?function(){return arguments.length? a.apply(b,c.concat(za.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Wc(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)?c=s:Ea(a)?c="$WINDOW":a&&V===a?c="$DOCUMENT":a&&(a.$evalAsync&&a.$watch)&&(c="$SCOPE");return c}function sa(b,a){return"undefined"===typeof b?s:JSON.stringify(b,Wc,a?" ":null)}function $b(b){return y(b)?JSON.parse(b):b}function Sa(b){"function"===typeof b?b=!0:b&&0!==b.length?(b=I(""+b),b=!("f"==b||"0"==b||"false"== b||"no"==b||"n"==b||"[]"==b)):b=!1;return b}function ga(b){b=x(b).clone();try{b.empty()}catch(a){}var c=x("<div>").append(b).html();try{return 3===b[0].nodeType?I(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+I(b)})}catch(d){return I(c)}}function ac(b){try{return decodeURIComponent(b)}catch(a){}}function bc(b){var a={},c,d;q((b||"").split("&"),function(b){b&&(c=b.split("="),d=ac(c[0]),B(d)&&(b=B(c[1])?ac(c[1]):!0,a[d]?L(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a} function Ab(b){var a=[];q(b,function(b,d){L(b)?q(b,function(b){a.push(Aa(d,!0)+(!0===b?"":"="+Aa(b,!0)))}):a.push(Aa(d,!0)+(!0===b?"":"="+Aa(b,!0)))});return a.length?a.join("&"):""}function gb(b){return Aa(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function Aa(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,a?"%20":"+")}function Xc(b,a){function c(a){a&&d.push(a)}var d=[b],e,g,f=["ng:app", "ng-app","x-ng-app","data-ng-app"],k=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;q(f,function(a){f[a]=!0;c(V.getElementById(a));a=a.replace(":","\\:");b.querySelectorAll&&(q(b.querySelectorAll("."+a),c),q(b.querySelectorAll("."+a+"\\:"),c),q(b.querySelectorAll("["+a+"]"),c))});q(d,function(a){if(!e){var b=k.exec(" "+a.className+" ");b?(e=a,g=(b[2]||"").replace(/\s+/g,",")):q(a.attributes,function(b){!e&&f[b.name]&&(e=a,g=b.value)})}});e&&a(e,g?[g]:[])}function cc(b,a){var c=function(){b=x(b);if(b.injector()){var c= b[0]===V?"document":ga(b);throw Ra("btstrpd",c);}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);a.unshift("ng");c=dc(a);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animate",function(a,b,c,d,e){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;if(T&&!d.test(T.name))return c();T.name=T.name.replace(d,"");Ta.resumeBootstrap=function(b){q(b,function(b){a.push(b)});c()}}function hb(b,a){a=a||"_";return b.replace(Yc,function(b, d){return(d?a:"")+b.toLowerCase()})}function Bb(b,a,c){if(!b)throw Ra("areq",a||"?",c||"required");return b}function Ua(b,a,c){c&&L(b)&&(b=b[b.length-1]);Bb(O(b),a,"not a function, got "+(b&&"object"===typeof b?b.constructor.name||"Object":typeof b));return b}function Ba(b,a){if("hasOwnProperty"===b)throw Ra("badname",a);}function ec(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,g=a.length,f=0;f<g;f++)d=a[f],b&&(b=(e=b)[d]);return!c&&O(b)?zb(e,b):b}function Cb(b){var a=b[0];b=b[b.length-1];if(a=== b)return x(a);var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b);return x(c)}function Zc(b){var a=v("$injector"),c=v("ng");b=b.angular||(b.angular={});b.$$minErr=b.$$minErr||v;return b.module||(b.module=function(){var b={};return function(e,g,f){if("hasOwnProperty"===e)throw c("badname","module");g&&b.hasOwnProperty(e)&&(b[e]=null);return b[e]||(b[e]=function(){function b(a,d,e){return function(){c[e||"push"]([a,d,arguments]);return p}}if(!g)throw a("nomod",e);var c=[],d=[],l=b("$injector", "invoke"),p={_invokeQueue:c,_runBlocks:d,requires:g,name:e,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:b("$provide","value"),constant:b("$provide","constant","unshift"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider","register"),directive:b("$compileProvider","directive"),config:l,run:function(a){d.push(a);return this}};f&&l(f);return p}())}}())}function $c(b){E(b,{bootstrap:cc, copy:Ga,extend:E,equals:ya,element:x,forEach:q,injector:dc,noop:A,bind:zb,toJson:sa,fromJson:$b,identity:Fa,isUndefined:D,isDefined:B,isString:y,isFunction:O,isObject:U,isNumber:xb,isElement:Uc,isArray:L,version:ad,isDate:Oa,lowercase:I,uppercase:Ha,callbacks:{counter:0},$$minErr:v,$$csp:Zb});Va=Zc(T);try{Va("ngLocale")}catch(a){Va("ngLocale",[]).provider("$locale",bd)}Va("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:cd});a.provider("$compile",fc).directive({a:dd,input:gc,textarea:gc, form:ed,script:fd,select:gd,style:hd,option:id,ngBind:jd,ngBindHtml:kd,ngBindTemplate:ld,ngClass:md,ngClassEven:nd,ngClassOdd:od,ngCloak:pd,ngController:qd,ngForm:rd,ngHide:sd,ngIf:td,ngInclude:ud,ngInit:vd,ngNonBindable:wd,ngPluralize:xd,ngRepeat:yd,ngShow:zd,ngStyle:Ad,ngSwitch:Bd,ngSwitchWhen:Cd,ngSwitchDefault:Dd,ngOptions:Ed,ngTransclude:Fd,ngModel:Gd,ngList:Hd,ngChange:Id,required:hc,ngRequired:hc,ngValue:Jd}).directive({ngInclude:Kd}).directive(Db).directive(ic);a.provider({$anchorScroll:Ld, $animate:Md,$browser:Nd,$cacheFactory:Od,$controller:Pd,$document:Qd,$exceptionHandler:Rd,$filter:jc,$interpolate:Sd,$interval:Td,$http:Ud,$httpBackend:Vd,$location:Wd,$log:Xd,$parse:Yd,$rootScope:Zd,$q:$d,$sce:ae,$sceDelegate:be,$sniffer:ce,$templateCache:de,$timeout:ee,$window:fe,$$rAF:ge,$$asyncCallback:he})}])}function Wa(b){return b.replace(ie,function(a,b,d,e){return e?d.toUpperCase():d}).replace(je,"Moz$1")}function Eb(b,a,c,d){function e(b){var e=c&&b?[this.filter(b)]:[this],m=a,h,l,p,n,r, t;if(!d||null!=b)for(;e.length;)for(h=e.shift(),l=0,p=h.length;l<p;l++)for(n=x(h[l]),m?n.triggerHandler("$destroy"):m=!m,r=0,n=(t=n.children()).length;r<n;r++)e.push(Ca(t[r]));return g.apply(this,arguments)}var g=Ca.fn[b],g=g.$original||g;e.$original=g;Ca.fn[b]=e}function S(b){if(b instanceof S)return b;y(b)&&(b=aa(b));if(!(this instanceof S)){if(y(b)&&"<"!=b.charAt(0))throw Fb("nosel");return new S(b)}if(y(b)){var a=b;b=V;var c;if(c=ke.exec(a))b=[b.createElement(c[1])];else{var d=b,e;b=d.createDocumentFragment(); c=[];if(Gb.test(a)){d=b.appendChild(d.createElement("div"));e=(le.exec(a)||["",""])[1].toLowerCase();e=ea[e]||ea._default;d.innerHTML="<div>&#160;</div>"+e[1]+a.replace(me,"<$1></$2>")+e[2];d.removeChild(d.firstChild);for(a=e[0];a--;)d=d.lastChild;a=0;for(e=d.childNodes.length;a<e;++a)c.push(d.childNodes[a]);d=b.firstChild;d.textContent=""}else c.push(d.createTextNode(a));b.textContent="";b.innerHTML="";b=c}Hb(this,b);x(V.createDocumentFragment()).append(this)}else Hb(this,b)}function Ib(b){return b.cloneNode(!0)} function Ia(b){kc(b);var a=0;for(b=b.childNodes||[];a<b.length;a++)Ia(b[a])}function lc(b,a,c,d){if(B(d))throw Fb("offargs");var e=ma(b,"events");ma(b,"handle")&&(D(a)?q(e,function(a,c){Xa(b,c,a);delete e[c]}):q(a.split(" "),function(a){D(c)?(Xa(b,a,e[a]),delete e[a]):Qa(e[a]||[],c)}))}function kc(b,a){var c=b.ng339,d=Ya[c];d&&(a?delete Ya[c].data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),lc(b)),delete Ya[c],b.ng339=s))}function ma(b,a,c){var d=b.ng339,d=Ya[d||-1];if(B(c))d||(b.ng339= d=++ne,d=Ya[d]={}),d[a]=c;else return d&&d[a]}function mc(b,a,c){var d=ma(b,"data"),e=B(c),g=!e&&B(a),f=g&&!U(a);d||f||ma(b,"data",d={});if(e)d[a]=c;else if(g){if(f)return d&&d[a];E(d,a)}else return d}function Jb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function ib(b,a){a&&b.setAttribute&&q(a.split(" "),function(a){b.setAttribute("class",aa((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+aa(a)+" ", " ")))})}function jb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");q(a.split(" "),function(a){a=aa(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",aa(c))}}function Hb(b,a){if(a){a=a.nodeName||!B(a.length)||Ea(a)?[a]:a;for(var c=0;c<a.length;c++)b.push(a[c])}}function nc(b,a){return kb(b,"$"+(a||"ngController")+"Controller")}function kb(b,a,c){b=x(b);9==b[0].nodeType&&(b=b.find("html"));for(a=L(a)?a:[a];b.length;){for(var d=b[0],e= 0,g=a.length;e<g;e++)if((c=b.data(a[e]))!==s)return c;b=x(d.parentNode||11===d.nodeType&&d.host)}}function oc(b){for(var a=0,c=b.childNodes;a<c.length;a++)Ia(c[a]);for(;b.firstChild;)b.removeChild(b.firstChild)}function pc(b,a){var c=lb[a.toLowerCase()];return c&&qc[b.nodeName]&&c}function oe(b,a){var c=function(c,e){c.preventDefault||(c.preventDefault=function(){c.returnValue=!1});c.stopPropagation||(c.stopPropagation=function(){c.cancelBubble=!0});c.target||(c.target=c.srcElement||V);if(D(c.defaultPrevented)){var g= c.preventDefault;c.preventDefault=function(){c.defaultPrevented=!0;g.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=function(){return c.defaultPrevented||!1===c.returnValue};var f=la(a[e||c.type]||[]);q(f,function(a){a.call(b,c)});8>=P?(c.preventDefault=null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};c.elem=b;return c}function Ja(b,a){var c=typeof b,d;"function"==c||"object"==c&&null!==b?"function"==typeof(d= b.$$hashKey)?d=b.$$hashKey():d===s&&(d=b.$$hashKey=(a||eb)()):d=b;return c+":"+d}function Za(b,a){if(a){var c=0;this.nextUid=function(){return++c}}q(b,this.put,this)}function rc(b){var a,c;"function"===typeof b?(a=b.$inject)||(a=[],b.length&&(c=b.toString().replace(pe,""),c=c.match(qe),q(c[1].split(re),function(b){b.replace(se,function(b,c,d){a.push(d)})})),b.$inject=a):L(b)?(c=b.length-1,Ua(b[c],"fn"),a=b.slice(0,c)):Ua(b,"fn",!0);return a}function dc(b){function a(a){return function(b,c){if(U(b))q(b, Wb(a));else return a(b,c)}}function c(a,b){Ba(a,"service");if(O(b)||L(b))b=p.instantiate(b);if(!b.$get)throw $a("pget",a);return l[a+k]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[],c,d,g,k;q(a,function(a){if(!h.get(a)){h.put(a,!0);try{if(y(a))for(c=Va(a),b=b.concat(e(c.requires)).concat(c._runBlocks),d=c._invokeQueue,g=0,k=d.length;g<k;g++){var f=d[g],m=p.get(f[0]);m[f[1]].apply(m,f[2])}else O(a)?b.push(p.invoke(a)):L(a)?b.push(p.invoke(a)):Ua(a,"module")}catch(l){throw L(a)&&(a= a[a.length-1]),l.message&&(l.stack&&-1==l.stack.indexOf(l.message))&&(l=l.message+"\n"+l.stack),$a("modulerr",a,l.stack||l.message||l);}}});return b}function g(a,b){function c(d){if(a.hasOwnProperty(d)){if(a[d]===f)throw $a("cdep",d+" <- "+m.join(" <- "));return a[d]}try{return m.unshift(d),a[d]=f,a[d]=b(d)}catch(e){throw a[d]===f&&delete a[d],e;}finally{m.shift()}}function d(a,b,e){var g=[],k=rc(a),f,m,h;m=0;for(f=k.length;m<f;m++){h=k[m];if("string"!==typeof h)throw $a("itkn",h);g.push(e&&e.hasOwnProperty(h)? e[h]:c(h))}L(a)&&(a=a[f]);return a.apply(b,g)}return{invoke:d,instantiate:function(a,b){var c=function(){},e;c.prototype=(L(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return U(e)||O(e)?e:c},get:c,annotate:rc,has:function(b){return l.hasOwnProperty(b+k)||a.hasOwnProperty(b)}}}var f={},k="Provider",m=[],h=new Za([],!0),l={$provide:{provider:a(c),factory:a(d),service:a(function(a,b){return d(a,["$injector",function(a){return a.instantiate(b)}])}),value:a(function(a,b){return d(a,$(b))}),constant:a(function(a, b){Ba(a,"constant");l[a]=b;n[a]=b}),decorator:function(a,b){var c=p.get(a+k),d=c.$get;c.$get=function(){var a=r.invoke(d,c);return r.invoke(b,null,{$delegate:a})}}}},p=l.$injector=g(l,function(){throw $a("unpr",m.join(" <- "));}),n={},r=n.$injector=g(n,function(a){a=p.get(a+k);return r.invoke(a.$get,a)});q(e(b),function(a){r.invoke(a||A)});return r}function Ld(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null; q(a,function(a){b||"a"!==I(a.nodeName)||(b=a)});return b}function g(){var b=c.hash(),d;b?(d=f.getElementById(b))?d.scrollIntoView():(d=e(f.getElementsByName(b)))?d.scrollIntoView():"top"===b&&a.scrollTo(0,0):a.scrollTo(0,0)}var f=a.document;b&&d.$watch(function(){return c.hash()},function(){d.$evalAsync(g)});return g}]}function he(){this.$get=["$$rAF","$timeout",function(b,a){return b.supported?function(a){return b(a)}:function(b){return a(b,0,!1)}}]}function te(b,a,c,d){function e(a){try{a.apply(null, za.call(arguments,1))}finally{if(t--,0===t)for(;J.length;)try{J.pop()()}catch(b){c.error(b)}}}function g(a,b){(function ba(){q(w,function(a){a()});u=b(ba,a)})()}function f(){z=null;K!=k.url()&&(K=k.url(),q(ha,function(a){a(k.url())}))}var k=this,m=a[0],h=b.location,l=b.history,p=b.setTimeout,n=b.clearTimeout,r={};k.isMock=!1;var t=0,J=[];k.$$completeOutstandingRequest=e;k.$$incOutstandingRequestCount=function(){t++};k.notifyWhenNoOutstandingRequests=function(a){q(w,function(a){a()});0===t?a():J.push(a)}; var w=[],u;k.addPollFn=function(a){D(u)&&g(100,p);w.push(a);return a};var K=h.href,Q=a.find("base"),z=null;k.url=function(a,c){h!==b.location&&(h=b.location);l!==b.history&&(l=b.history);if(a){if(K!=a)return K=a,d.history?c?l.replaceState(null,"",a):(l.pushState(null,"",a),Q.attr("href",Q.attr("href"))):(z=a,c?h.replace(a):h.href=a),k}else return z||h.href.replace(/%27/g,"'")};var ha=[],N=!1;k.onUrlChange=function(a){if(!N){if(d.history)x(b).on("popstate",f);if(d.hashchange)x(b).on("hashchange",f); else k.addPollFn(f);N=!0}ha.push(a);return a};k.baseHref=function(){var a=Q.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};var M={},ca="",C=k.baseHref();k.cookies=function(a,b){var d,e,g,k;if(a)b===s?m.cookie=escape(a)+"=;path="+C+";expires=Thu, 01 Jan 1970 00:00:00 GMT":y(b)&&(d=(m.cookie=escape(a)+"="+escape(b)+";path="+C).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(m.cookie!==ca)for(ca=m.cookie, d=ca.split("; "),M={},g=0;g<d.length;g++)e=d[g],k=e.indexOf("="),0<k&&(a=unescape(e.substring(0,k)),M[a]===s&&(M[a]=unescape(e.substring(k+1))));return M}};k.defer=function(a,b){var c;t++;c=p(function(){delete r[c];e(a)},b||0);r[c]=!0;return c};k.defer.cancel=function(a){return r[a]?(delete r[a],n(a),e(A),!0):!1}}function Nd(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new te(b,d,a,c)}]}function Od(){this.$get=function(){function b(b,d){function e(a){a!=p&&(n?n==a&& (n=a.n):n=a,g(a.n,a.p),g(a,p),p=a,p.n=null)}function g(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw v("$cacheFactory")("iid",b);var f=0,k=E({},d,{id:b}),m={},h=d&&d.capacity||Number.MAX_VALUE,l={},p=null,n=null;return a[b]={put:function(a,b){if(h<Number.MAX_VALUE){var c=l[a]||(l[a]={key:a});e(c)}if(!D(b))return a in m||f++,m[a]=b,f>h&&this.remove(n.key),b},get:function(a){if(h<Number.MAX_VALUE){var b=l[a];if(!b)return;e(b)}return m[a]},remove:function(a){if(h<Number.MAX_VALUE){var b=l[a];if(!b)return; b==p&&(p=b.p);b==n&&(n=b.n);g(b.n,b.p);delete l[a]}delete m[a];f--},removeAll:function(){m={};f=0;l={};p=n=null},destroy:function(){l=k=m=null;delete a[b]},info:function(){return E({},k,{size:f})}}}var a={};b.info=function(){var b={};q(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function de(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function fc(b,a){var c={},d="Directive",e=/^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,g=/(([\d\w_\-]+)(?:\:([^;]+))?;?)/, f=/^(on[a-z]+|formaction)$/;this.directive=function m(a,e){Ba(a,"directive");y(a)?(Bb(e,"directiveFactory"),c.hasOwnProperty(a)||(c[a]=[],b.factory(a+d,["$injector","$exceptionHandler",function(b,d){var e=[];q(c[a],function(c,g){try{var f=b.invoke(c);O(f)?f={compile:$(f)}:!f.compile&&f.link&&(f.compile=$(f.link));f.priority=f.priority||0;f.index=g;f.name=f.name||a;f.require=f.require||f.controller&&f.name;f.restrict=f.restrict||"A";e.push(f)}catch(m){d(m)}});return e}])),c[a].push(e)):q(a,Wb(m)); return this};this.aHrefSanitizationWhitelist=function(b){return B(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(b){return B(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};this.$get=["$injector","$interpolate","$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,l,p,n,r,t,J,w,u,K,Q){function z(a,b,c,d,e){a instanceof x||(a=x(a));q(a,function(b,c){3==b.nodeType&&b.nodeValue.match(/\S+/)&&(a[c]=x(b).wrap("<span></span>").parent()[0])});var g=N(a,b,a,c,d,e);ha(a,"ng-scope");return function(b,c,d,e){Bb(b,"scope");var f=c?Ka.clone.call(a):a;q(d,function(a,b){f.data("$"+b+"Controller",a)});d=0;for(var m=f.length;d<m;d++){var h=f[d].nodeType;1!==h&&9!==h||f.eq(d).data("$scope",b)}c&&c(f,b);g&&g(b,f,f,e);return f}}function ha(a,b){try{a.addClass(b)}catch(c){}}function N(a,b,c,d,e,g){function f(a,c,d,e){var g,h,l,r,p, n,t;g=c.length;var w=Array(g);for(p=0;p<g;p++)w[p]=c[p];t=p=0;for(n=m.length;p<n;t++)h=w[t],c=m[p++],g=m[p++],l=x(h),c?(c.scope?(r=a.$new(),l.data("$scope",r)):r=a,l=c.transcludeOnThisElement?M(a,c.transclude,e):!c.templateOnThisElement&&e?e:!e&&b?M(a,b):null,c(g,r,h,d,l)):g&&g(a,h.childNodes,s,e)}for(var m=[],h,l,r,p,n=0;n<a.length;n++)h=new Kb,l=ca(a[n],[],h,0===n?d:s,e),(g=l.length?H(l,a[n],h,b,c,null,[],[],g):null)&&g.scope&&ha(x(a[n]),"ng-scope"),h=g&&g.terminal||!(r=a[n].childNodes)||!r.length? null:N(r,g?(g.transcludeOnThisElement||!g.templateOnThisElement)&&g.transclude:b),m.push(g,h),p=p||g||h,g=null;return p?f:null}function M(a,b,c){return function(d,e,g){var f=!1;d||(d=a.$new(),f=d.$$transcluded=!0);e=b(d,e,g,c);if(f)e.on("$destroy",function(){d.$destroy()});return e}}function ca(a,b,c,d,f){var h=c.$attr,m;switch(a.nodeType){case 1:ba(b,na(La(a).toLowerCase()),"E",d,f);for(var l,r,p,n=a.attributes,t=0,w=n&&n.length;t<w;t++){var J=!1,K=!1;l=n[t];if(!P||8<=P||l.specified){m=l.name;r= aa(l.value);l=na(m);if(p=W.test(l))m=hb(l.substr(6),"-");var u=l.replace(/(Start|End)$/,"");l===u+"Start"&&(J=m,K=m.substr(0,m.length-5)+"end",m=m.substr(0,m.length-6));l=na(m.toLowerCase());h[l]=m;if(p||!c.hasOwnProperty(l))c[l]=r,pc(a,l)&&(c[l]=!0);S(a,b,r,l);ba(b,l,"A",d,f,J,K)}}a=a.className;if(y(a)&&""!==a)for(;m=g.exec(a);)l=na(m[2]),ba(b,l,"C",d,f)&&(c[l]=aa(m[3])),a=a.substr(m.index+m[0].length);break;case 3:v(b,a.nodeValue);break;case 8:try{if(m=e.exec(a.nodeValue))l=na(m[1]),ba(b,l,"M", d,f)&&(c[l]=aa(m[2]))}catch(z){}}b.sort(D);return b}function C(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ia("uterdir",b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return x(d)}function G(a,b,c){return function(d,e,g,f,m){e=C(e[0],b,c);return a(d,e,g,f,m)}}function H(a,c,d,e,g,f,m,p,n){function w(a,b,c,d){if(a){c&&(a=G(a,c,d));a.require=F.require;a.directiveName=oa;if(M===F||F.$$isolateScope)a= tc(a,{isolateScope:!0});m.push(a)}if(b){c&&(b=G(b,c,d));b.require=F.require;b.directiveName=oa;if(M===F||F.$$isolateScope)b=tc(b,{isolateScope:!0});p.push(b)}}function J(a,b,c,d){var e,g="data",f=!1;if(y(b)){for(;"^"==(e=b.charAt(0))||"?"==e;)b=b.substr(1),"^"==e&&(g="inheritedData"),f=f||"?"==e;e=null;d&&"data"===g&&(e=d[b]);e=e||c[g]("$"+b+"Controller");if(!e&&!f)throw ia("ctreq",b,a);}else L(b)&&(e=[],q(b,function(b){e.push(J(a,b,c,d))}));return e}function K(a,e,g,f,n){function w(a,b){var c;2> arguments.length&&(b=a,a=s);Da&&(c=ca);return n(a,b,c)}var u,R,z,Q,G,C,ca={},mb;u=c===g?d:la(d,new Kb(x(g),d.$attr));R=u.$$element;if(M){var ba=/^\s*([@=&])(\??)\s*(\w*)\s*$/;f=x(g);C=e.$new(!0);!H||H!==M&&H!==M.$$originalDirective?f.data("$isolateScopeNoTemplate",C):f.data("$isolateScope",C);ha(f,"ng-isolate-scope");q(M.scope,function(a,c){var d=a.match(ba)||[],g=d[3]||c,f="?"==d[2],d=d[1],m,l,p,n;C.$$isolateBindings[c]=d+g;switch(d){case "@":u.$observe(g,function(a){C[c]=a});u.$$observers[g].$$scope= e;u[g]&&(C[c]=b(u[g])(e));break;case "=":if(f&&!u[g])break;l=r(u[g]);n=l.literal?ya:function(a,b){return a===b};p=l.assign||function(){m=C[c]=l(e);throw ia("nonassign",u[g],M.name);};m=C[c]=l(e);C.$watch(function(){var a=l(e);n(a,C[c])||(n(a,m)?p(e,a=C[c]):C[c]=a);return m=a},null,l.literal);break;case "&":l=r(u[g]);C[c]=function(a){return l(e,a)};break;default:throw ia("iscp",M.name,c,a);}})}mb=n&&w;N&&q(N,function(a){var b={$scope:a===M||a.$$isolateScope?C:e,$element:R,$attrs:u,$transclude:mb}, c;G=a.controller;"@"==G&&(G=u[a.name]);c=t(G,b);ca[a.name]=c;Da||R.data("$"+a.name+"Controller",c);a.controllerAs&&(b.$scope[a.controllerAs]=c)});f=0;for(z=m.length;f<z;f++)try{Q=m[f],Q(Q.isolateScope?C:e,R,u,Q.require&&J(Q.directiveName,Q.require,R,ca),mb)}catch(F){l(F,ga(R))}f=e;M&&(M.template||null===M.templateUrl)&&(f=C);a&&a(f,g.childNodes,s,n);for(f=p.length-1;0<=f;f--)try{Q=p[f],Q(Q.isolateScope?C:e,R,u,Q.require&&J(Q.directiveName,Q.require,R,ca),mb)}catch(B){l(B,ga(R))}}n=n||{};for(var u= -Number.MAX_VALUE,Q,N=n.controllerDirectives,M=n.newIsolateScopeDirective,H=n.templateDirective,ba=n.nonTlbTranscludeDirective,D=!1,E=!1,Da=n.hasElementTranscludeDirective,v=d.$$element=x(c),F,oa,X,T=e,S,P=0,pa=a.length;P<pa;P++){F=a[P];var W=F.$$start,Y=F.$$end;W&&(v=C(c,W,Y));X=s;if(u>F.priority)break;if(X=F.scope)Q=Q||F,F.templateUrl||(I("new/isolated scope",M,F,v),U(X)&&(M=F));oa=F.name;!F.templateUrl&&F.controller&&(X=F.controller,N=N||{},I("'"+oa+"' controller",N[oa],F,v),N[oa]=F);if(X=F.transclude)D= !0,F.$$tlb||(I("transclusion",ba,F,v),ba=F),"element"==X?(Da=!0,u=F.priority,X=C(c,W,Y),v=d.$$element=x(V.createComment(" "+oa+": "+d[oa]+" ")),c=v[0],nb(g,x(za.call(X,0)),c),T=z(X,e,u,f&&f.name,{nonTlbTranscludeDirective:ba})):(X=x(Ib(c)).contents(),v.empty(),T=z(X,e));if(F.template)if(E=!0,I("template",H,F,v),H=F,X=O(F.template)?F.template(v,d):F.template,X=Z(X),F.replace){f=F;X=Gb.test(X)?x(aa(X)):[];c=X[0];if(1!=X.length||1!==c.nodeType)throw ia("tplrt",oa,"");nb(g,v,c);pa={$attr:{}};X=ca(c,[], pa);var ue=a.splice(P+1,a.length-(P+1));M&&sc(X);a=a.concat(X).concat(ue);B(d,pa);pa=a.length}else v.html(X);if(F.templateUrl)E=!0,I("template",H,F,v),H=F,F.replace&&(f=F),K=A(a.splice(P,a.length-P),v,d,g,D&&T,m,p,{controllerDirectives:N,newIsolateScopeDirective:M,templateDirective:H,nonTlbTranscludeDirective:ba}),pa=a.length;else if(F.compile)try{S=F.compile(v,d,T),O(S)?w(null,S,W,Y):S&&w(S.pre,S.post,W,Y)}catch($){l($,ga(v))}F.terminal&&(K.terminal=!0,u=Math.max(u,F.priority))}K.scope=Q&&!0===Q.scope; K.transcludeOnThisElement=D;K.templateOnThisElement=E;K.transclude=T;n.hasElementTranscludeDirective=Da;return K}function sc(a){for(var b=0,c=a.length;b<c;b++)a[b]=Yb(a[b],{$$isolateScope:!0})}function ba(b,e,g,f,h,r,p){if(e===h)return null;h=null;if(c.hasOwnProperty(e)){var n;e=a.get(e+d);for(var t=0,w=e.length;t<w;t++)try{n=e[t],(f===s||f>n.priority)&&-1!=n.restrict.indexOf(g)&&(r&&(n=Yb(n,{$$start:r,$$end:p})),b.push(n),h=n)}catch(J){l(J)}}return h}function B(a,b){var c=b.$attr,d=a.$attr,e=a.$$element; q(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});q(b,function(b,g){"class"==g?(ha(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==g?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==g.charAt(0)||a.hasOwnProperty(g)||(a[g]=b,d[g]=c[g])})}function A(a,b,c,d,e,g,f,m){var h=[],l,r,t=b[0],w=a.shift(),J=E({},w,{templateUrl:null,transclude:null,replace:null,$$originalDirective:w}),K=O(w.templateUrl)?w.templateUrl(b, c):w.templateUrl;b.empty();p.get(u.getTrustedResourceUrl(K),{cache:n}).success(function(p){var n,u;p=Z(p);if(w.replace){p=Gb.test(p)?x(aa(p)):[];n=p[0];if(1!=p.length||1!==n.nodeType)throw ia("tplrt",w.name,K);p={$attr:{}};nb(d,b,n);var z=ca(n,[],p);U(w.scope)&&sc(z);a=z.concat(a);B(c,p)}else n=t,b.html(p);a.unshift(J);l=H(a,n,c,e,b,w,g,f,m);q(d,function(a,c){a==n&&(d[c]=b[0])});for(r=N(b[0].childNodes,e);h.length;){p=h.shift();u=h.shift();var Q=h.shift(),G=h.shift(),z=b[0];if(u!==t){var C=u.className; m.hasElementTranscludeDirective&&w.replace||(z=Ib(n));nb(Q,x(u),z);ha(x(z),C)}u=l.transcludeOnThisElement?M(p,l.transclude,G):G;l(r,p,z,d,u)}h=null}).error(function(a,b,c,d){throw ia("tpload",d.url);});return function(a,b,c,d,e){a=e;h?(h.push(b),h.push(c),h.push(d),h.push(a)):(l.transcludeOnThisElement&&(a=M(b,l.transclude,e)),l(r,b,c,d,a))}}function D(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function I(a,b,c,d){if(b)throw ia("multidir",b.name, c.name,a,ga(d));}function v(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){var b=a.parent().length;b&&ha(a.parent(),"ng-binding");return function(a,c){var e=c.parent(),g=e.data("$binding")||[];g.push(d);e.data("$binding",g);b||ha(e,"ng-binding");a.$watch(d,function(a){c[0].nodeValue=a})}}})}function T(a,b){if("srcdoc"==b)return u.HTML;var c=La(a);if("xlinkHref"==b||"FORM"==c&&"action"==b||"IMG"!=c&&("src"==b||"ngSrc"==b))return u.RESOURCE_URL}function S(a,c,d,e){var g=b(d,!0);if(g){if("multiple"=== e&&"SELECT"===La(a))throw ia("selmulti",ga(a));c.push({priority:100,compile:function(){return{pre:function(c,d,m){d=m.$$observers||(m.$$observers={});if(f.test(e))throw ia("nodomevents");if(g=b(m[e],!0,T(a,e)))m[e]=g(c),(d[e]||(d[e]=[])).$$inter=!0,(m.$$observers&&m.$$observers[e].$$scope||c).$watch(g,function(a,b){"class"===e&&a!=b?m.$updateClass(a,b):m.$set(e,a)})}}}})}}function nb(a,b,c){var d=b[0],e=b.length,g=d.parentNode,f,m;if(a)for(f=0,m=a.length;f<m;f++)if(a[f]==d){a[f++]=c;m=f+e-1;for(var h= a.length;f<h;f++,m++)m<h?a[f]=a[m]:delete a[f];a.length-=e-1;break}g&&g.replaceChild(c,d);a=V.createDocumentFragment();a.appendChild(d);c[x.expando]=d[x.expando];d=1;for(e=b.length;d<e;d++)g=b[d],x(g).remove(),a.appendChild(g),delete b[d];b[0]=c;b.length=1}function tc(a,b){return E(function(){return a.apply(null,arguments)},a,b)}var Kb=function(a,b){this.$$element=a;this.$attr=b||{}};Kb.prototype={$normalize:na,$addClass:function(a){a&&0<a.length&&K.addClass(this.$$element,a)},$removeClass:function(a){a&& 0<a.length&&K.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=uc(a,b),d=uc(b,a);0===c.length?K.removeClass(this.$$element,d):0===d.length?K.addClass(this.$$element,c):K.setClass(this.$$element,c,d)},$set:function(a,b,c,d){var e=pc(this.$$element[0],a);e&&(this.$$element.prop(a,b),d=e);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=hb(a,"-"));e=La(this.$$element);if("A"===e&&"href"===a||"IMG"===e&&"src"===a)this[a]=b=Q(b,"src"===a);!1!==c&&(null===b||b===s?this.$$element.removeAttr(d): this.$$element.attr(d,b));(c=this.$$observers)&&q(c[a],function(a){try{a(b)}catch(c){l(c)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);J.$evalAsync(function(){e.$$inter||b(c[a])});return b}};var Da=b.startSymbol(),pa=b.endSymbol(),Z="{{"==Da||"}}"==pa?Fa:function(a){return a.replace(/\{\{/g,Da).replace(/}}/g,pa)},W=/^ngAttr[A-Z]/;return z}]}function na(b){return Wa(b.replace(ve,""))}function uc(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/), g=0;a:for(;g<d.length;g++){for(var f=d[g],k=0;k<e.length;k++)if(f==e[k])continue a;c+=(0<c.length?" ":"")+f}return c}function Pd(){var b={},a=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,d){Ba(a,"controller");U(a)?E(b,a):b[a]=d};this.$get=["$injector","$window",function(c,d){return function(e,g){var f,k,m;y(e)&&(f=e.match(a),k=f[1],m=f[3],e=b.hasOwnProperty(k)?b[k]:ec(g.$scope,k,!0)||ec(d,k,!0),Ua(e,k,!0));f=c.instantiate(e,g);if(m){if(!g||"object"!==typeof g.$scope)throw v("$controller")("noscp", k||e.name,m);g.$scope[m]=f}return f}}]}function Qd(){this.$get=["$window",function(b){return x(b.document)}]}function Rd(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function vc(b){var a={},c,d,e;if(!b)return a;q(b.split("\n"),function(b){e=b.indexOf(":");c=I(aa(b.substr(0,e)));d=aa(b.substr(e+1));c&&(a[c]=a[c]?a[c]+(", "+d):d)});return a}function wc(b){var a=U(b)?b:s;return function(c){a||(a=vc(b));return c?a[I(c)]||null:a}}function xc(b,a,c){if(O(c))return c(b, a);q(c,function(c){b=c(b,a)});return b}function Ud(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},e=this.defaults={transformResponse:[function(d){y(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=$b(d)));return d}],transformRequest:[function(a){return U(a)&&"[object File]"!==xa.call(a)&&"[object Blob]"!==xa.call(a)?sa(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:la(d),put:la(d),patch:la(d)},xsrfCookieName:"XSRF-TOKEN", xsrfHeaderName:"X-XSRF-TOKEN"},g=this.interceptors=[],f=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,d,p,n){function r(a){function b(a){var d=E({},a,{data:xc(a.data,a.headers,c.transformResponse)});return 200<=a.status&&300>a.status?d:p.reject(d)}var c={method:"get",transformRequest:e.transformRequest,transformResponse:e.transformResponse},d=function(a){function b(a){var c;q(a,function(b,d){O(b)&&(c=b(),null!=c?a[d]= c:delete a[d])})}var c=e.headers,d=E({},a.headers),g,f,c=E({},c.common,c[I(a.method)]);b(c);b(d);a:for(g in c){a=I(g);for(f in d)if(I(f)===a)continue a;d[g]=c[g]}return d}(a);E(c,a);c.headers=d;c.method=Ha(c.method);var g=[function(a){d=a.headers;var c=xc(a.data,wc(d),a.transformRequest);D(a.data)&&q(d,function(a,b){"content-type"===I(b)&&delete d[b]});D(a.withCredentials)&&!D(e.withCredentials)&&(a.withCredentials=e.withCredentials);return t(a,c,d).then(b,b)},s],f=p.when(c);for(q(u,function(a){(a.request|| a.requestError)&&g.unshift(a.request,a.requestError);(a.response||a.responseError)&&g.push(a.response,a.responseError)});g.length;){a=g.shift();var m=g.shift(),f=f.then(a,m)}f.success=function(a){f.then(function(b){a(b.data,b.status,b.headers,c)});return f};f.error=function(a){f.then(null,function(b){a(b.data,b.status,b.headers,c)});return f};return f}function t(c,g,f){function h(a,b,c,e){G&&(200<=a&&300>a?G.put(x,[a,b,vc(c),e]):G.remove(x));n(b,a,c,e);d.$$phase||d.$apply()}function n(a,b,d,e){b= Math.max(b,0);(200<=b&&300>b?u.resolve:u.reject)({data:a,status:b,headers:wc(d),config:c,statusText:e})}function t(){var a=Pa(r.pendingRequests,c);-1!==a&&r.pendingRequests.splice(a,1)}var u=p.defer(),q=u.promise,G,H,x=J(c.url,c.params);r.pendingRequests.push(c);q.then(t,t);(c.cache||e.cache)&&(!1!==c.cache&&"GET"==c.method)&&(G=U(c.cache)?c.cache:U(e.cache)?e.cache:w);if(G)if(H=G.get(x),B(H)){if(H.then)return H.then(t,t),H;L(H)?n(H[1],H[0],la(H[2]),H[3]):n(H,200,{},"OK")}else G.put(x,q);D(H)&&((H= Lb(c.url)?b.cookies()[c.xsrfCookieName||e.xsrfCookieName]:s)&&(f[c.xsrfHeaderName||e.xsrfHeaderName]=H),a(c.method,x,g,h,f,c.timeout,c.withCredentials,c.responseType));return q}function J(a,b){if(!b)return a;var c=[];Tc(b,function(a,b){null===a||D(a)||(L(a)||(a=[a]),q(a,function(a){U(a)&&(a=sa(a));c.push(Aa(b)+"="+Aa(a))}))});0<c.length&&(a+=(-1==a.indexOf("?")?"?":"&")+c.join("&"));return a}var w=c("$http"),u=[];q(g,function(a){u.unshift(y(a)?n.get(a):n.invoke(a))});q(f,function(a,b){var c=y(a)? n.get(a):n.invoke(a);u.splice(b,0,{response:function(a){return c(p.when(a))},responseError:function(a){return c(p.reject(a))}})});r.pendingRequests=[];(function(a){q(arguments,function(a){r[a]=function(b,c){return r(E(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){q(arguments,function(a){r[a]=function(b,c,d){return r(E(d||{},{method:a,url:b,data:c}))}})})("post","put");r.defaults=e;return r}]}function we(b){if(8>=P&&(!b.match(/^(get|post|head|put|delete|options)$/i)||!T.XMLHttpRequest))return new T.ActiveXObject("Microsoft.XMLHTTP"); if(T.XMLHttpRequest)return new T.XMLHttpRequest;throw v("$httpBackend")("noxhr");}function Vd(){this.$get=["$browser","$window","$document",function(b,a,c){return xe(b,we,b.defer,a.angular.callbacks,c[0])}]}function xe(b,a,c,d,e){function g(a,b,c){var g=e.createElement("script"),f=null;g.type="text/javascript";g.src=a;g.async=!0;f=function(a){Xa(g,"load",f);Xa(g,"error",f);e.body.removeChild(g);g=null;var k=-1,t="unknown";a&&("load"!==a.type||d[b].called||(a={type:"error"}),t=a.type,k="error"===a.type? 404:200);c&&c(k,t)};ob(g,"load",f);ob(g,"error",f);8>=P&&(g.onreadystatechange=function(){y(g.readyState)&&/loaded|complete/.test(g.readyState)&&(g.onreadystatechange=null,f({type:"load"}))});e.body.appendChild(g);return f}var f=-1;return function(e,m,h,l,p,n,r,t){function J(){u=f;Q&&Q();z&&z.abort()}function w(a,d,e,g,f){N&&c.cancel(N);Q=z=null;0===d&&(d=e?200:"file"==ta(m).protocol?404:0);a(1223===d?204:d,e,g,f||"");b.$$completeOutstandingRequest(A)}var u;b.$$incOutstandingRequestCount();m=m||b.url(); if("jsonp"==I(e)){var K="_"+(d.counter++).toString(36);d[K]=function(a){d[K].data=a;d[K].called=!0};var Q=g(m.replace("JSON_CALLBACK","angular.callbacks."+K),K,function(a,b){w(l,a,d[K].data,"",b);d[K]=A})}else{var z=a(e);z.open(e,m,!0);q(p,function(a,b){B(a)&&z.setRequestHeader(b,a)});z.onreadystatechange=function(){if(z&&4==z.readyState){var a=null,b=null,c="";u!==f&&(a=z.getAllResponseHeaders(),b="response"in z?z.response:z.responseText);u===f&&10>P||(c=z.statusText);w(l,u||z.status,b,a,c)}};r&& (z.withCredentials=!0);if(t)try{z.responseType=t}catch(s){if("json"!==t)throw s;}z.send(h||null)}if(0<n)var N=c(J,n);else n&&n.then&&n.then(J)}}function Sd(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function g(g,h,l){for(var p,n,r=0,t=[],J=g.length,w=!1,u=[];r<J;)-1!=(p=g.indexOf(b,r))&&-1!=(n=g.indexOf(a,p+f))?(r!=p&&t.push(g.substring(r,p)),t.push(r=c(w=g.substring(p+ f,n))),r.exp=w,r=n+k,w=!0):(r!=J&&t.push(g.substring(r)),r=J);(J=t.length)||(t.push(""),J=1);if(l&&1<t.length)throw yc("noconcat",g);if(!h||w)return u.length=J,r=function(a){try{for(var b=0,c=J,f;b<c;b++){if("function"==typeof(f=t[b]))if(f=f(a),f=l?e.getTrusted(l,f):e.valueOf(f),null==f)f="";else switch(typeof f){case "string":break;case "number":f=""+f;break;default:f=sa(f)}u[b]=f}return u.join("")}catch(k){a=yc("interr",g,k.toString()),d(a)}},r.exp=g,r.parts=t,r}var f=b.length,k=a.length;g.startSymbol= function(){return b};g.endSymbol=function(){return a};return g}]}function Td(){this.$get=["$rootScope","$window","$q",function(b,a,c){function d(d,f,k,m){var h=a.setInterval,l=a.clearInterval,p=c.defer(),n=p.promise,r=0,t=B(m)&&!m;k=B(k)?k:0;n.then(null,null,d);n.$$intervalId=h(function(){p.notify(r++);0<k&&r>=k&&(p.resolve(r),l(n.$$intervalId),delete e[n.$$intervalId]);t||b.$apply()},f);e[n.$$intervalId]=p;return n}var e={};d.cancel=function(b){return b&&b.$$intervalId in e?(e[b.$$intervalId].reject("canceled"), a.clearInterval(b.$$intervalId),delete e[b.$$intervalId],!0):!1};return d}]}function bd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "), SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return 1===b?"one":"other"}}}}function Mb(b){b=b.split("/");for(var a=b.length;a--;)b[a]= gb(b[a]);return b.join("/")}function zc(b,a,c){b=ta(b,c);a.$$protocol=b.protocol;a.$$host=b.hostname;a.$$port=Z(b.port)||ye[b.protocol]||null}function Ac(b,a,c){var d="/"!==b.charAt(0);d&&(b="/"+b);b=ta(b,c);a.$$path=decodeURIComponent(d&&"/"===b.pathname.charAt(0)?b.pathname.substring(1):b.pathname);a.$$search=bc(b.search);a.$$hash=decodeURIComponent(b.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function qa(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function ab(b){var a= b.indexOf("#");return-1==a?b:b.substr(0,a)}function Nb(b){return b.substr(0,ab(b).lastIndexOf("/")+1)}function Bc(b,a){this.$$html5=!0;a=a||"";var c=Nb(b);zc(b,this,b);this.$$parse=function(a){var e=qa(c,a);if(!y(e))throw Ob("ipthprfx",a,c);Ac(e,this,b);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Ab(this.$$search),b=this.$$hash?"#"+gb(this.$$hash):"";this.$$url=Mb(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e; if((e=qa(b,d))!==s)return d=e,(e=qa(a,e))!==s?c+(qa("/",e)||e):b+d;if((e=qa(c,d))!==s)return c+e;if(c==d+"/")return c}}function Pb(b,a){var c=Nb(b);zc(b,this,b);this.$$parse=function(d){var e=qa(b,d)||qa(c,d),e="#"==e.charAt(0)?qa(a,e):this.$$html5?e:"";if(!y(e))throw Ob("ihshprfx",d,a);Ac(e,this,b);d=this.$$path;var g=/^\/[A-Z]:(\/.*)/;0===e.indexOf(b)&&(e=e.replace(b,""));g.exec(e)||(d=(e=g.exec(d))?e[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=Ab(this.$$search),e=this.$$hash? "#"+gb(this.$$hash):"";this.$$url=Mb(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$rewrite=function(a){if(ab(b)==ab(a))return a}}function Qb(b,a){this.$$html5=!0;Pb.apply(this,arguments);var c=Nb(b);this.$$rewrite=function(d){var e;if(b==ab(d))return d;if(e=qa(c,d))return b+a+e;if(c===d+"/")return c};this.$$compose=function(){var c=Ab(this.$$search),e=this.$$hash?"#"+gb(this.$$hash):"";this.$$url=Mb(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+a+this.$$url}}function pb(b){return function(){return this[b]}} function Cc(b,a){return function(c){if(D(c))return this[b];this[b]=a(c);this.$$compose();return this}}function Wd(){var b="",a=!1;this.hashPrefix=function(a){return B(a)?(b=a,this):b};this.html5Mode=function(b){return B(b)?(a=b,this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,g){function f(a){c.$broadcast("$locationChangeSuccess",k.absUrl(),a)}var k,m,h=d.baseHref(),l=d.url(),p;a?(p=l.substring(0,l.indexOf("/",l.indexOf("//")+2))+(h||"/"),m=e.history?Bc:Qb):(p= ab(l),m=Pb);k=new m(p,"#"+b);k.$$parse(k.$$rewrite(l));g.on("click",function(a){if(!a.ctrlKey&&!a.metaKey&&2!=a.which){for(var e=x(a.target);"a"!==I(e[0].nodeName);)if(e[0]===g[0]||!(e=e.parent())[0])return;var f=e.prop("href");U(f)&&"[object SVGAnimatedString]"===f.toString()&&(f=ta(f.animVal).href);if(m===Qb){var h=e.attr("href")||e.attr("xlink:href");if(0>h.indexOf("://"))if(f="#"+b,"/"==h[0])f=p+f+h;else if("#"==h[0])f=p+f+(k.path()||"/")+h;else{for(var l=k.path().split("/"),h=h.split("/"),n= 0;n<h.length;n++)"."!=h[n]&&(".."==h[n]?l.pop():h[n].length&&l.push(h[n]));f=p+f+l.join("/")}}l=k.$$rewrite(f);f&&(!e.attr("target")&&l&&!a.isDefaultPrevented())&&(a.preventDefault(),l!=d.url()&&(k.$$parse(l),c.$apply(),T.angular["ff-684208-preventDefault"]=!0))}});k.absUrl()!=l&&d.url(k.absUrl(),!0);d.onUrlChange(function(a){k.absUrl()!=a&&(c.$evalAsync(function(){var b=k.absUrl();k.$$parse(a);c.$broadcast("$locationChangeStart",a,b).defaultPrevented?(k.$$parse(b),d.url(b)):f(b)}),c.$$phase||c.$digest())}); var n=0;c.$watch(function(){var a=d.url(),b=k.$$replace;n&&a==k.absUrl()||(n++,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",k.absUrl(),a).defaultPrevented?k.$$parse(a):(d.url(k.absUrl(),b),f(a))}));k.$$replace=!1;return n});return k}]}function Xd(){var b=!0,a=this;this.debugEnabled=function(a){return B(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&& (a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||A;a=!1;try{a=!!e.apply}catch(m){}return a?function(){var a=[];q(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function da(b,a){if("__defineGetter__"===b||"__defineSetter__"===b||"__lookupGetter__"===b||"__lookupSetter__"=== b||"__proto__"===b)throw ja("isecfld",a);return b}function Ma(b,a){if(b){if(b.constructor===b)throw ja("isecfn",a);if(b.document&&b.location&&b.alert&&b.setInterval)throw ja("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw ja("isecdom",a);if(b===Object)throw ja("isecobj",a);}return b}function qb(b,a,c,d,e){e=e||{};a=a.split(".");for(var g,f=0;1<a.length;f++){g=da(a.shift(),d);var k=b[g];k||(k={},b[g]=k);b=k;b.then&&e.unwrapPromises&&(ua(d),"$$v"in b||function(a){a.then(function(b){a.$$v= b})}(b),b.$$v===s&&(b.$$v={}),b=b.$$v)}g=da(a.shift(),d);Ma(b,d);Ma(b[g],d);return b[g]=c}function Dc(b,a,c,d,e,g,f){da(b,g);da(a,g);da(c,g);da(d,g);da(e,g);return f.unwrapPromises?function(f,m){var h=m&&m.hasOwnProperty(b)?m:f,l;if(null==h)return h;(h=h[b])&&h.then&&(ua(g),"$$v"in h||(l=h,l.$$v=s,l.then(function(a){l.$$v=a})),h=h.$$v);if(!a)return h;if(null==h)return s;(h=h[a])&&h.then&&(ua(g),"$$v"in h||(l=h,l.$$v=s,l.then(function(a){l.$$v=a})),h=h.$$v);if(!c)return h;if(null==h)return s;(h=h[c])&& h.then&&(ua(g),"$$v"in h||(l=h,l.$$v=s,l.then(function(a){l.$$v=a})),h=h.$$v);if(!d)return h;if(null==h)return s;(h=h[d])&&h.then&&(ua(g),"$$v"in h||(l=h,l.$$v=s,l.then(function(a){l.$$v=a})),h=h.$$v);if(!e)return h;if(null==h)return s;(h=h[e])&&h.then&&(ua(g),"$$v"in h||(l=h,l.$$v=s,l.then(function(a){l.$$v=a})),h=h.$$v);return h}:function(g,f){var h=f&&f.hasOwnProperty(b)?f:g;if(null==h)return h;h=h[b];if(!a)return h;if(null==h)return s;h=h[a];if(!c)return h;if(null==h)return s;h=h[c];if(!d)return h; if(null==h)return s;h=h[d];return e?null==h?s:h=h[e]:h}}function ze(b,a){da(b,a);return function(a,d){return null==a?s:(d&&d.hasOwnProperty(b)?d:a)[b]}}function Ae(b,a,c){da(b,c);da(a,c);return function(c,e){if(null==c)return s;c=(e&&e.hasOwnProperty(b)?e:c)[b];return null==c?s:c[a]}}function Ec(b,a,c){if(Rb.hasOwnProperty(b))return Rb[b];var d=b.split("."),e=d.length,g;if(a.unwrapPromises||1!==e)if(a.unwrapPromises||2!==e)if(a.csp)g=6>e?Dc(d[0],d[1],d[2],d[3],d[4],c,a):function(b,g){var f=0,k;do k= Dc(d[f++],d[f++],d[f++],d[f++],d[f++],c,a)(b,g),g=s,b=k;while(f<e);return k};else{var f="var p;\n";q(d,function(b,d){da(b,c);f+="if(s == null) return undefined;\ns="+(d?"s":'((k&&k.hasOwnProperty("'+b+'"))?k:s)')+'["'+b+'"];\n'+(a.unwrapPromises?'if (s && s.then) {\n pw("'+c.replace(/(["\r\n])/g,"\\$1")+'");\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n':"")});var f=f+"return s;",k=new Function("s","k","pw",f);k.toString=$(f);g=a.unwrapPromises? function(a,b){return k(a,b,ua)}:k}else g=Ae(d[0],d[1],c);else g=ze(d[0],c);"hasOwnProperty"!==b&&(Rb[b]=g);return g}function Yd(){var b={},a={csp:!1,unwrapPromises:!1,logPromiseWarnings:!0};this.unwrapPromises=function(b){return B(b)?(a.unwrapPromises=!!b,this):a.unwrapPromises};this.logPromiseWarnings=function(b){return B(b)?(a.logPromiseWarnings=b,this):a.logPromiseWarnings};this.$get=["$filter","$sniffer","$log",function(c,d,e){a.csp=d.csp;ua=function(b){a.logPromiseWarnings&&!Fc.hasOwnProperty(b)&& (Fc[b]=!0,e.warn("[$parse] Promise found in the expression `"+b+"`. Automatic unwrapping of promises in Angular expressions is deprecated."))};return function(d){var e;switch(typeof d){case "string":if(b.hasOwnProperty(d))return b[d];e=new Sb(a);e=(new bb(e,c,a)).parse(d);"hasOwnProperty"!==d&&(b[d]=e);return e;case "function":return d;default:return A}}}]}function $d(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return Be(function(a){b.$evalAsync(a)},a)}]}function Be(b,a){function c(a){return a} function d(a){return f(a)}var e=function(){var f=[],h,l;return l={resolve:function(a){if(f){var c=f;f=s;h=g(a);c.length&&b(function(){for(var a,b=0,d=c.length;b<d;b++)a=c[b],h.then(a[0],a[1],a[2])})}},reject:function(a){l.resolve(k(a))},notify:function(a){if(f){var c=f;f.length&&b(function(){for(var b,d=0,e=c.length;d<e;d++)b=c[d],b[2](a)})}},promise:{then:function(b,g,k){var l=e(),J=function(d){try{l.resolve((O(b)?b:c)(d))}catch(e){l.reject(e),a(e)}},w=function(b){try{l.resolve((O(g)?g:d)(b))}catch(c){l.reject(c), a(c)}},u=function(b){try{l.notify((O(k)?k:c)(b))}catch(d){a(d)}};f?f.push([J,w,u]):h.then(J,w,u);return l.promise},"catch":function(a){return this.then(null,a)},"finally":function(a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,g){var f=null;try{f=(a||c)()}catch(k){return b(k,!1)}return f&&O(f.then)?f.then(function(){return b(e,g)},function(a){return b(a,!1)}):b(e,g)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},g=function(a){return a&& O(a.then)?a:{then:function(c){var d=e();b(function(){d.resolve(c(a))});return d.promise}}},f=function(a){var b=e();b.reject(a);return b.promise},k=function(c){return{then:function(g,f){var k=e();b(function(){try{k.resolve((O(f)?f:d)(c))}catch(b){k.reject(b),a(b)}});return k.promise}}};return{defer:e,reject:f,when:function(k,h,l,p){var n=e(),r,t=function(b){try{return(O(h)?h:c)(b)}catch(d){return a(d),f(d)}},J=function(b){try{return(O(l)?l:d)(b)}catch(c){return a(c),f(c)}},w=function(b){try{return(O(p)? p:c)(b)}catch(d){a(d)}};b(function(){g(k).then(function(a){r||(r=!0,n.resolve(g(a).then(t,J,w)))},function(a){r||(r=!0,n.resolve(J(a)))},function(a){r||n.notify(w(a))})});return n.promise},all:function(a){var b=e(),c=0,d=L(a)?[]:{};q(a,function(a,e){c++;g(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise}}}function ge(){this.$get=["$window","$timeout",function(b,a){var c=b.requestAnimationFrame|| b.webkitRequestAnimationFrame||b.mozRequestAnimationFrame,d=b.cancelAnimationFrame||b.webkitCancelAnimationFrame||b.mozCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,e=!!c,g=e?function(a){var b=c(a);return function(){d(b)}}:function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};g.supported=e;return g}]}function Zd(){var b=10,a=v("$rootScope"),c=null;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(d, e,g,f){function k(){this.$id=eb();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$postDigestQueue=[];this.$$listeners={};this.$$listenerCount={};this.$$isolateBindings={}}function m(b){if(n.$$phase)throw a("inprog",n.$$phase);n.$$phase=b}function h(a,b){var c=g(a);Ua(c,b);return c}function l(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&& delete a.$$listenerCount[c];while(a=a.$parent)}function p(){}k.prototype={constructor:k,$new:function(a){a?(a=new k,a.$root=this.$root,a.$$asyncQueue=this.$$asyncQueue,a.$$postDigestQueue=this.$$postDigestQueue):(this.$$childScopeClass||(this.$$childScopeClass=function(){this.$$watchers=this.$$nextSibling=this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$id=eb();this.$$childScopeClass=null},this.$$childScopeClass.prototype=this),a=new this.$$childScopeClass); a["this"]=a;a.$parent=this;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=this.$$childTail.$$nextSibling=a:this.$$childHead=this.$$childTail=a;return a},$watch:function(a,b,d){var e=h(a,"watch"),g=this.$$watchers,f={fn:b,last:p,get:e,exp:a,eq:!!d};c=null;if(!O(b)){var k=h(b||A,"listener");f.fn=function(a,b,c){k(c)}}if("string"==typeof a&&e.constant){var m=f.fn;f.fn=function(a,b,c){m.call(this,a,b,c);Qa(g,f)}}g||(g=this.$$watchers=[]);g.unshift(f);return function(){Qa(g,f);c=null}}, $watchCollection:function(a,b){var c=this,d,e,f,k=1<b.length,h=0,m=g(a),l=[],n={},p=!0,q=0;return this.$watch(function(){d=m(c);var a,b;if(U(d))if(db(d))for(e!==l&&(e=l,q=e.length=0,h++),a=d.length,q!==a&&(h++,e.length=q=a),b=0;b<a;b++)e[b]!==e[b]&&d[b]!==d[b]||e[b]===d[b]||(h++,e[b]=d[b]);else{e!==n&&(e=n={},q=0,h++);a=0;for(b in d)d.hasOwnProperty(b)&&(a++,e.hasOwnProperty(b)?e[b]!==d[b]&&(h++,e[b]=d[b]):(q++,e[b]=d[b],h++));if(q>a)for(b in h++,e)e.hasOwnProperty(b)&&!d.hasOwnProperty(b)&&(q--, delete e[b])}else e!==d&&(e=d,h++);return h},function(){p?(p=!1,b(d,d,c)):b(d,f,c);if(k)if(U(d))if(db(d)){f=Array(d.length);for(var a=0;a<d.length;a++)f[a]=d[a]}else for(a in f={},d)yb.call(d,a)&&(f[a]=d[a]);else f=d})},$digest:function(){var d,g,f,k,h=this.$$asyncQueue,l=this.$$postDigestQueue,q,z,s=b,N,M=[],x,C,G;m("$digest");c=null;do{z=!1;for(N=this;h.length;){try{G=h.shift(),G.scope.$eval(G.expression)}catch(H){n.$$phase=null,e(H)}c=null}a:do{if(k=N.$$watchers)for(q=k.length;q--;)try{if(d=k[q])if((g= d.get(N))!==(f=d.last)&&!(d.eq?ya(g,f):"number"===typeof g&&"number"===typeof f&&isNaN(g)&&isNaN(f)))z=!0,c=d,d.last=d.eq?Ga(g,null):g,d.fn(g,f===p?g:f,N),5>s&&(x=4-s,M[x]||(M[x]=[]),C=O(d.exp)?"fn: "+(d.exp.name||d.exp.toString()):d.exp,C+="; newVal: "+sa(g)+"; oldVal: "+sa(f),M[x].push(C));else if(d===c){z=!1;break a}}catch(B){n.$$phase=null,e(B)}if(!(k=N.$$childHead||N!==this&&N.$$nextSibling))for(;N!==this&&!(k=N.$$nextSibling);)N=N.$parent}while(N=k);if((z||h.length)&&!s--)throw n.$$phase=null, a("infdig",b,sa(M));}while(z||h.length);for(n.$$phase=null;l.length;)try{l.shift()()}catch(v){e(v)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this!==n&&(q(this.$$listenerCount,zb(null,l,this)),a.$$childHead==this&&(a.$$childHead=this.$$nextSibling),a.$$childTail==this&&(a.$$childTail=this.$$prevSibling),this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling),this.$$nextSibling&&(this.$$nextSibling.$$prevSibling= this.$$prevSibling),this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=this.$root=null,this.$$listeners={},this.$$watchers=this.$$asyncQueue=this.$$postDigestQueue=[],this.$destroy=this.$digest=this.$apply=A,this.$on=this.$watch=function(){return A})}},$eval:function(a,b){return g(a)(this,b)},$evalAsync:function(a){n.$$phase||n.$$asyncQueue.length||f.defer(function(){n.$$asyncQueue.length&&n.$digest()});this.$$asyncQueue.push({scope:this,expression:a})},$$postDigest:function(a){this.$$postDigestQueue.push(a)}, $apply:function(a){try{return m("$apply"),this.$eval(a)}catch(b){e(b)}finally{n.$$phase=null;try{n.$digest()}catch(c){throw e(c),c;}}},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){c[Pa(c,b)]=null;l(e,1,a)}},$emit:function(a,b){var c=[],d,g=this,f=!1,k={name:a,targetScope:g,stopPropagation:function(){f=!0},preventDefault:function(){k.defaultPrevented= !0},defaultPrevented:!1},h=[k].concat(za.call(arguments,1)),m,l;do{d=g.$$listeners[a]||c;k.currentScope=g;m=0;for(l=d.length;m<l;m++)if(d[m])try{d[m].apply(null,h)}catch(n){e(n)}else d.splice(m,1),m--,l--;if(f)break;g=g.$parent}while(g);return k},$broadcast:function(a,b){for(var c=this,d=this,g={name:a,targetScope:this,preventDefault:function(){g.defaultPrevented=!0},defaultPrevented:!1},f=[g].concat(za.call(arguments,1)),k,h;c=d;){g.currentScope=c;d=c.$$listeners[a]||[];k=0;for(h=d.length;k<h;k++)if(d[k])try{d[k].apply(null, f)}catch(m){e(m)}else d.splice(k,1),k--,h--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}return g}};var n=new k;return n}]}function cd(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*(https?|ftp|file):|data:image\//;this.aHrefSanitizationWhitelist=function(a){return B(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return B(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,g;if(!P||8<= P)if(g=ta(c).href,""!==g&&!g.match(e))return"unsafe:"+g;return c}}}function Ce(b){if("self"===b)return b;if(y(b)){if(-1<b.indexOf("***"))throw va("iwcard",b);b=b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08").replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return RegExp("^"+b+"$")}if(fb(b))return RegExp("^"+b.source+"$");throw va("imatcher");}function Gc(b){var a=[];B(b)&&q(b,function(b){a.push(Ce(b))});return a}function be(){this.SCE_CONTEXTS=fa;var b=["self"],a=[];this.resourceUrlWhitelist= function(a){arguments.length&&(b=Gc(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&&(a=Gc(b));return a};this.$get=["$injector",function(c){function d(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var e=function(a){throw va("unsafe");};c.has("$sanitize")&&(e=c.get("$sanitize")); var g=d(),f={};f[fa.HTML]=d(g);f[fa.CSS]=d(g);f[fa.URL]=d(g);f[fa.JS]=d(g);f[fa.RESOURCE_URL]=d(f[fa.URL]);return{trustAs:function(a,b){var c=f.hasOwnProperty(a)?f[a]:null;if(!c)throw va("icontext",a,b);if(null===b||b===s||""===b)return b;if("string"!==typeof b)throw va("itype",a);return new c(b)},getTrusted:function(c,d){if(null===d||d===s||""===d)return d;var g=f.hasOwnProperty(c)?f[c]:null;if(g&&d instanceof g)return d.$$unwrapTrustedValue();if(c===fa.RESOURCE_URL){var g=ta(d.toString()),l,p,n= !1;l=0;for(p=b.length;l<p;l++)if("self"===b[l]?Lb(g):b[l].exec(g.href)){n=!0;break}if(n)for(l=0,p=a.length;l<p;l++)if("self"===a[l]?Lb(g):a[l].exec(g.href)){n=!1;break}if(n)return d;throw va("insecurl",d.toString());}if(c===fa.HTML)return e(d);throw va("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function ae(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sniffer","$sceDelegate",function(a,c,d){if(b&&c.msie&&8>c.msieDocumentMode)throw va("iequirks"); var e=la(fa);e.isEnabled=function(){return b};e.trustAs=d.trustAs;e.getTrusted=d.getTrusted;e.valueOf=d.valueOf;b||(e.trustAs=e.getTrusted=function(a,b){return b},e.valueOf=Fa);e.parseAs=function(b,c){var d=a(c);return d.literal&&d.constant?d:function(a,c){return e.getTrusted(b,d(a,c))}};var g=e.parseAs,f=e.getTrusted,k=e.trustAs;q(fa,function(a,b){var c=I(b);e[Wa("parse_as_"+c)]=function(b){return g(a,b)};e[Wa("get_trusted_"+c)]=function(b){return f(a,b)};e[Wa("trust_as_"+c)]=function(b){return k(a, b)}});return e}]}function ce(){this.$get=["$window","$document",function(b,a){var c={},d=Z((/android (\d+)/.exec(I((b.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),g=a[0]||{},f=g.documentMode,k,m=/^(Moz|webkit|O|ms)(?=[A-Z])/,h=g.body&&g.body.style,l=!1,p=!1;if(h){for(var n in h)if(l=m.exec(n)){k=l[0];k=k.substr(0,1).toUpperCase()+k.substr(1);break}k||(k="WebkitOpacity"in h&&"webkit");l=!!("transition"in h||k+"Transition"in h);p=!!("animation"in h||k+"Animation"in h);!d||l&&p||(l=y(g.body.style.webkitTransition),p=y(g.body.style.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hashchange:"onhashchange"in b&&(!f||7<f),hasEvent:function(a){if("input"==a&&9==P)return!1;if(D(c[a])){var b=g.createElement("div");c[a]="on"+a in b}return c[a]},csp:Zb(),vendorPrefix:k,transitions:l,animations:p,android:d,msie:P,msieDocumentMode:f}}]}function ee(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(b,a,c,d){function e(e,k, m){var h=c.defer(),l=h.promise,p=B(m)&&!m;k=a.defer(function(){try{h.resolve(e())}catch(a){h.reject(a),d(a)}finally{delete g[l.$$timeoutId]}p||b.$apply()},k);l.$$timeoutId=k;g[k]=h;return l}var g={};e.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return e}]}function ta(b,a){var c=b;P&&(W.setAttribute("href",c),c=W.href);W.setAttribute("href",c);return{href:W.href,protocol:W.protocol?W.protocol.replace(/:$/, ""):"",host:W.host,search:W.search?W.search.replace(/^\?/,""):"",hash:W.hash?W.hash.replace(/^#/,""):"",hostname:W.hostname,port:W.port,pathname:"/"===W.pathname.charAt(0)?W.pathname:"/"+W.pathname}}function Lb(b){b=y(b)?ta(b):b;return b.protocol===Hc.protocol&&b.host===Hc.host}function fe(){this.$get=$(T)}function jc(b){function a(d,e){if(U(d)){var g={};q(d,function(b,c){g[c]=a(c,b)});return g}return b.factory(d+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+ c)}}];a("currency",Ic);a("date",Jc);a("filter",De);a("json",Ee);a("limitTo",Fe);a("lowercase",Ge);a("number",Kc);a("orderBy",Lc);a("uppercase",He)}function De(){return function(b,a,c){if(!L(b))return b;var d=typeof c,e=[];e.check=function(a){for(var b=0;b<e.length;b++)if(!e[b](a))return!1;return!0};"function"!==d&&(c="boolean"===d&&c?function(a,b){return Ta.equals(a,b)}:function(a,b){if(a&&b&&"object"===typeof a&&"object"===typeof b){for(var d in a)if("$"!==d.charAt(0)&&yb.call(a,d)&&c(a[d],b[d]))return!0; return!1}b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)});var g=function(a,b){if("string"==typeof b&&"!"===b.charAt(0))return!g(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&g(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(g(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a= {$:a};case "object":for(var f in a)(function(b){"undefined"!==typeof a[b]&&e.push(function(c){return g("$"==b?c:c&&c[b],a[b])})})(f);break;case "function":e.push(a);break;default:return b}d=[];for(f=0;f<b.length;f++){var k=b[f];e.check(k)&&d.push(k)}return d}}function Ic(b){var a=b.NUMBER_FORMATS;return function(b,d){D(d)&&(d=a.CURRENCY_SYM);return Mc(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function Kc(b){var a=b.NUMBER_FORMATS;return function(b,d){return Mc(b,a.PATTERNS[0], a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Mc(b,a,c,d,e){if(null==b||!isFinite(b)||U(b))return"";var g=0>b;b=Math.abs(b);var f=b+"",k="",m=[],h=!1;if(-1!==f.indexOf("e")){var l=f.match(/([\d\.]+)e(-?)(\d+)/);l&&"-"==l[2]&&l[3]>e+1?(f="0",b=0):(k=f,h=!0)}if(h)0<e&&(-1<b&&1>b)&&(k=b.toFixed(e));else{f=(f.split(Nc)[1]||"").length;D(e)&&(e=Math.min(Math.max(a.minFrac,f),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);b=(""+b).split(Nc);f=b[0];b=b[1]||"";var l=0,p=a.lgSize,n=a.gSize;if(f.length>= p+n)for(l=f.length-p,h=0;h<l;h++)0===(l-h)%n&&0!==h&&(k+=c),k+=f.charAt(h);for(h=l;h<f.length;h++)0===(f.length-h)%p&&0!==h&&(k+=c),k+=f.charAt(h);for(;b.length<e;)b+="0";e&&"0"!==e&&(k+=d+b.substr(0,e))}m.push(g?a.negPre:a.posPre);m.push(k);m.push(g?a.negSuf:a.posSuf);return m.join("")}function Tb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function Y(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e= 12);return Tb(e,a,d)}}function rb(b,a){return function(c,d){var e=c["get"+b](),g=Ha(a?"SHORT"+b:b);return d[g][e]}}function Jc(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var g=0,f=0,k=b[8]?a.setUTCFullYear:a.setFullYear,m=b[8]?a.setUTCHours:a.setHours;b[9]&&(g=Z(b[9]+b[10]),f=Z(b[9]+b[11]));k.call(a,Z(b[1]),Z(b[2])-1,Z(b[3]));g=Z(b[4]||0)-g;f=Z(b[5]||0)-f;k=Z(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));m.call(a,g,f,k,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; return function(c,e){var g="",f=[],k,m;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;y(c)&&(c=Ie.test(c)?Z(c):a(c));xb(c)&&(c=new Date(c));if(!Oa(c))return c;for(;e;)(m=Je.exec(e))?(f=f.concat(za.call(m,1)),e=f.pop()):(f.push(e),e=null);q(f,function(a){k=Ke[a];g+=k?k(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function Ee(){return function(b){return sa(b,!0)}}function Fe(){return function(b,a){if(!L(b)&&!y(b))return b;a=Infinity===Math.abs(Number(a))?Number(a):Z(a); if(y(b))return a?0<=a?b.slice(0,a):b.slice(a,b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&&(a=-b.length);0<a?(d=0,e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function Lc(b){return function(a,c,d){function e(a,b){return Sa(b)?function(b,c){return a(c,b)}:a}function g(a,b){var c=typeof a,d=typeof b;return c==d?("string"==c&&(a=a.toLowerCase(),b=b.toLowerCase()),a===b?0:a<b?-1:1):c<d?-1:1}if(!L(a)||!c)return a;c=L(c)?c:[c];c=Vc(c,function(a){var c=!1,d=a||Fa;if(y(a)){if("+"== a.charAt(0)||"-"==a.charAt(0))c="-"==a.charAt(0),a=a.substring(1);d=b(a);if(d.constant){var f=d();return e(function(a,b){return g(a[f],b[f])},c)}}return e(function(a,b){return g(d(a),d(b))},c)});for(var f=[],k=0;k<a.length;k++)f.push(a[k]);return f.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function wa(b){O(b)&&(b={link:b});b.restrict=b.restrict||"AC";return $(b)}function Oc(b,a,c,d){function e(a,c){c=c?"-"+hb(c,"-"):"";d.removeClass(b,(a?sb: tb)+c);d.addClass(b,(a?tb:sb)+c)}var g=this,f=b.parent().controller("form")||ub,k=0,m=g.$error={},h=[];g.$name=a.name||a.ngForm;g.$dirty=!1;g.$pristine=!0;g.$valid=!0;g.$invalid=!1;f.$addControl(g);b.addClass(Na);e(!0);g.$addControl=function(a){Ba(a.$name,"input");h.push(a);a.$name&&(g[a.$name]=a)};g.$removeControl=function(a){a.$name&&g[a.$name]===a&&delete g[a.$name];q(m,function(b,c){g.$setValidity(c,!0,a)});Qa(h,a)};g.$setValidity=function(a,b,c){var d=m[a];if(b)d&&(Qa(d,c),d.length||(k--,k|| (e(b),g.$valid=!0,g.$invalid=!1),m[a]=!1,e(!0,a),f.$setValidity(a,!0,g)));else{k||e(b);if(d){if(-1!=Pa(d,c))return}else m[a]=d=[],k++,e(!1,a),f.$setValidity(a,!1,g);d.push(c);g.$valid=!1;g.$invalid=!0}};g.$setDirty=function(){d.removeClass(b,Na);d.addClass(b,vb);g.$dirty=!0;g.$pristine=!1;f.$setDirty()};g.$setPristine=function(){d.removeClass(b,vb);d.addClass(b,Na);g.$dirty=!1;g.$pristine=!0;q(h,function(a){a.$setPristine()})}}function ra(b,a,c,d){b.$setValidity(a,c);return c?d:s}function Pc(b,a){var c, d;if(a)for(c=0;c<a.length;++c)if(d=a[c],b[d])return!0;return!1}function Le(b,a,c,d,e){U(e)&&(b.$$hasNativeValidators=!0,b.$parsers.push(function(g){if(b.$error[a]||Pc(e,d)||!Pc(e,c))return g;b.$setValidity(a,!1)}))}function wb(b,a,c,d,e,g){var f=a.prop(Me),k=a[0].placeholder,m={};d.$$validityState=f;if(!e.android){var h=!1;a.on("compositionstart",function(a){h=!0});a.on("compositionend",function(){h=!1;l()})}var l=function(e){if(!h){var g=a.val();if(P&&"input"===(e||m).type&&a[0].placeholder!==k)k= a[0].placeholder;else if(Sa(c.ngTrim||"T")&&(g=aa(g)),e=f&&d.$$hasNativeValidators,d.$viewValue!==g||""===g&&e)b.$$phase?d.$setViewValue(g):b.$apply(function(){d.$setViewValue(g)})}};if(e.hasEvent("input"))a.on("input",l);else{var p,n=function(){p||(p=g.defer(function(){l();p=null}))};a.on("keydown",function(a){a=a.keyCode;91===a||(15<a&&19>a||37<=a&&40>=a)||n()});if(e.hasEvent("paste"))a.on("paste cut",n)}a.on("change",l);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)};var r= c.ngPattern;r&&((e=r.match(/^\/(.*)\/([gim]*)$/))?(r=RegExp(e[1],e[2]),e=function(a){return ra(d,"pattern",d.$isEmpty(a)||r.test(a),a)}):e=function(c){var e=b.$eval(r);if(!e||!e.test)throw v("ngPattern")("noregexp",r,e,ga(a));return ra(d,"pattern",d.$isEmpty(c)||e.test(c),c)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var t=Z(c.ngMinlength);e=function(a){return ra(d,"minlength",d.$isEmpty(a)||a.length>=t,a)};d.$parsers.push(e);d.$formatters.push(e)}if(c.ngMaxlength){var q=Z(c.ngMaxlength); e=function(a){return ra(d,"maxlength",d.$isEmpty(a)||a.length<=q,a)};d.$parsers.push(e);d.$formatters.push(e)}}function Ub(b,a){b="ngClass"+b;return["$animate",function(c){function d(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e=a[d],l=0;l<b.length;l++)if(e==b[l])continue a;c.push(e)}return c}function e(a){if(!L(a)){if(y(a))return a.split(" ");if(U(a)){var b=[];q(a,function(a,c){a&&(b=b.concat(c.split(" ")))});return b}}return a}return{restrict:"AC",link:function(g,f,k){function m(a,b){var c= f.data("$classCounts")||{},d=[];q(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)});f.data("$classCounts",c);return d.join(" ")}function h(b){if(!0===a||g.$index%2===a){var h=e(b||[]);if(!l){var r=m(h,1);k.$addClass(r)}else if(!ya(b,l)){var q=e(l),r=d(h,q),h=d(q,h),h=m(h,-1),r=m(r,1);0===r.length?c.removeClass(f,h):0===h.length?c.addClass(f,r):c.setClass(f,r,h)}}l=la(b)}var l;g.$watch(k[b],h,!0);k.$observe("class",function(a){h(g.$eval(k[b]))});"ngClass"!==b&&g.$watch("$index", function(c,d){var f=c&1;if(f!==(d&1)){var h=e(g.$eval(k[b]));f===a?(f=m(h,1),k.$addClass(f)):(f=m(h,-1),k.$removeClass(f))}})}}}]}var Me="validity",I=function(b){return y(b)?b.toLowerCase():b},yb=Object.prototype.hasOwnProperty,Ha=function(b){return y(b)?b.toUpperCase():b},P,x,Ca,za=[].slice,Ne=[].push,xa=Object.prototype.toString,Ra=v("ng"),Ta=T.angular||(T.angular={}),Va,La,ka=["0","0","0"];P=Z((/msie (\d+)/.exec(I(navigator.userAgent))||[])[1]);isNaN(P)&&(P=Z((/trident\/.*; rv:(\d+)/.exec(I(navigator.userAgent))|| [])[1]));A.$inject=[];Fa.$inject=[];var L=function(){return O(Array.isArray)?Array.isArray:function(b){return"[object Array]"===xa.call(b)}}(),aa=function(){return String.prototype.trim?function(b){return y(b)?b.trim():b}:function(b){return y(b)?b.replace(/^\s\s*/,"").replace(/\s\s*$/,""):b}}();La=9>P?function(b){b=b.nodeName?b:b[0];return b.scopeName&&"HTML"!=b.scopeName?Ha(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?b.nodeName:b[0].nodeName};var Yc=/[A-Z]/g,ad={full:"1.2.19", major:1,minor:2,dot:19,codeName:"precognitive-flashbacks"};S.expando="ng339";var Ya=S.cache={},ne=1,ob=T.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+a,c)},Xa=T.document.removeEventListener?function(b,a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+a,c)};S._data=function(b){return this.cache[b[this.expando]]||{}};var ie=/([\:\-\_]+(.))/g,je=/^moz([A-Z])/,Fb=v("jqLite"),ke=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,Gb=/<|&#?\w+;/, le=/<([\w:]+)/,me=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ea={option:[1,'<select multiple="multiple">',"</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ea.optgroup=ea.option;ea.tbody=ea.tfoot=ea.colgroup=ea.caption=ea.thead;ea.th=ea.td;var Ka=S.prototype={ready:function(b){function a(){c||(c=!0,b())}var c= !1;"complete"===V.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),S(T).on("load",a))},toString:function(){var b=[];q(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?x(this[b]):x(this[this.length+b])},length:0,push:Ne,sort:[].sort,splice:[].splice},lb={};q("multiple selected checked disabled readOnly required open".split(" "),function(b){lb[I(b)]=b});var qc={};q("input select option textarea button form details".split(" "),function(b){qc[Ha(b)]=!0});q({data:mc, inheritedData:kb,scope:function(b){return x(b).data("$scope")||kb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return x(b).data("$isolateScope")||x(b).data("$isolateScopeNoTemplate")},controller:nc,injector:function(b){return kb(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Jb,css:function(b,a,c){a=Wa(a);if(B(c))b.style[a]=c;else{var d;8>=P&&(d=b.currentStyle&&b.currentStyle[a],""===d&&(d="auto"));d=d||b.style[a];8>=P&&(d=""===d?s:d);return d}},attr:function(b, a,c){var d=I(a);if(lb[d])if(B(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||A).specified?d:s;else if(B(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?s:b},prop:function(b,a,c){if(B(c))b[a]=c;else return b[a]},text:function(){function b(b,d){var e=a[b.nodeType];if(D(d))return e?b[e]:"";b[e]=d}var a=[];9>P?(a[1]="innerText",a[3]="nodeValue"):a[1]=a[3]="textContent";b.$dv="";return b}(),val:function(b, a){if(D(a)){if("SELECT"===La(b)&&b.multiple){var c=[];q(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(D(a))return b.innerHTML;for(var c=0,d=b.childNodes;c<d.length;c++)Ia(d[c]);b.innerHTML=a},empty:oc},function(b,a){S.prototype[a]=function(a,d){var e,g,f=this.length;if(b!==oc&&(2==b.length&&b!==Jb&&b!==nc?a:d)===s){if(U(a)){for(e=0;e<f;e++)if(b===mc)b(this[e],a);else for(g in a)b(this[e],g,a[g]);return this}e= b.$dv;f=e===s?Math.min(f,1):f;for(g=0;g<f;g++){var k=b(this[g],a,d);e=e?e+k:k}return e}for(e=0;e<f;e++)b(this[e],a,d);return this}});q({removeData:kc,dealoc:Ia,on:function a(c,d,e,g){if(B(g))throw Fb("onargs");var f=ma(c,"events"),k=ma(c,"handle");f||ma(c,"events",f={});k||ma(c,"handle",k=oe(c,f));q(d.split(" "),function(d){var g=f[d];if(!g){if("mouseenter"==d||"mouseleave"==d){var l=V.body.contains||V.body.compareDocumentPosition?function(a,c){var d=9===a.nodeType?a.documentElement:a,e=c&&c.parentNode; return a===e||!!(e&&1===e.nodeType&&(d.contains?d.contains(e):a.compareDocumentPosition&&a.compareDocumentPosition(e)&16))}:function(a,c){if(c)for(;c=c.parentNode;)if(c===a)return!0;return!1};f[d]=[];a(c,{mouseleave:"mouseout",mouseenter:"mouseover"}[d],function(a){var c=a.relatedTarget;c&&(c===this||l(this,c))||k(a,d)})}else ob(c,d,k),f[d]=[];g=f[d]}g.push(e)})},off:lc,one:function(a,c,d){a=x(a);a.on(c,function g(){a.off(c,d);a.off(c,g)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode; Ia(a);q(new S(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];q(a.childNodes,function(a){1===a.nodeType&&c.push(a)});return c},contents:function(a){return a.contentDocument||a.childNodes||[]},append:function(a,c){q(new S(c),function(c){1!==a.nodeType&&11!==a.nodeType||a.appendChild(c)})},prepend:function(a,c){if(1===a.nodeType){var d=a.firstChild;q(new S(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=x(c)[0];var d=a.parentNode; d&&d.replaceChild(c,a);c.appendChild(a)},remove:function(a){Ia(a);var c=a.parentNode;c&&c.removeChild(a)},after:function(a,c){var d=a,e=a.parentNode;q(new S(c),function(a){e.insertBefore(a,d.nextSibling);d=a})},addClass:jb,removeClass:ib,toggleClass:function(a,c,d){c&&q(c.split(" "),function(c){var g=d;D(g)&&(g=!Jb(a,c));(g?jb:ib)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){if(a.nextElementSibling)return a.nextElementSibling;for(a=a.nextSibling;null!= a&&1!==a.nodeType;)a=a.nextSibling;return a},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Ib,triggerHandler:function(a,c,d){c=(ma(a,"events")||{})[c];d=d||[];var e=[{preventDefault:A,stopPropagation:A}];q(c,function(c){c.apply(a,e.concat(d))})}},function(a,c){S.prototype[c]=function(c,e,g){for(var f,k=0;k<this.length;k++)D(f)?(f=a(this[k],c,e,g),B(f)&&(f=x(f))):Hb(f,a(this[k],c,e,g));return B(f)?f:this};S.prototype.bind=S.prototype.on;S.prototype.unbind=S.prototype.off}); Za.prototype={put:function(a,c){this[Ja(a,this.nextUid)]=c},get:function(a){return this[Ja(a,this.nextUid)]},remove:function(a){var c=this[a=Ja(a,this.nextUid)];delete this[a];return c}};var qe=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,re=/,/,se=/^\s*(_?)(\S+?)\1\s*$/,pe=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,$a=v("$injector"),Oe=v("$animate"),Md=["$provide",function(a){this.$$selectors={};this.register=function(c,d){var e=c+"-animation";if(c&&"."!=c.charAt(0))throw Oe("notcsel",c);this.$$selectors[c.substr(1)]= e;a.factory(e,d)};this.classNameFilter=function(a){1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null);return this.$$classNameFilter};this.$get=["$timeout","$$asyncCallback",function(a,d){return{enter:function(a,c,f,k){f?f.after(a):(c&&c[0]||(c=f.parent()),c.append(a));k&&d(k)},leave:function(a,c){a.remove();c&&d(c)},move:function(a,c,d,k){this.enter(a,c,d,k)},addClass:function(a,c,f){c=y(c)?c:L(c)?c.join(" "):"";q(a,function(a){jb(a,c)});f&&d(f)},removeClass:function(a,c,f){c= y(c)?c:L(c)?c.join(" "):"";q(a,function(a){ib(a,c)});f&&d(f)},setClass:function(a,c,f,k){q(a,function(a){jb(a,c);ib(a,f)});k&&d(k)},enabled:A}}]}],ia=v("$compile");fc.$inject=["$provide","$$sanitizeUriProvider"];var ve=/^(x[\:\-_]|data[\:\-_])/i,yc=v("$interpolate"),Pe=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,ye={http:80,https:443,ftp:21},Ob=v("$location");Qb.prototype=Pb.prototype=Bc.prototype={$$html5:!1,$$replace:!1,absUrl:pb("$$absUrl"),url:function(a,c){if(D(a))return this.$$url;var d=Pe.exec(a);d[1]&& this.path(decodeURIComponent(d[1]));(d[2]||d[1])&&this.search(d[3]||"");this.hash(d[5]||"",c);return this},protocol:pb("$$protocol"),host:pb("$$host"),port:pb("$$port"),path:Cc("$$path",function(a){return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(y(a))this.$$search=bc(a);else if(U(a))this.$$search=a;else throw Ob("isrcharg");break;default:D(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:Cc("$$hash", Fa),replace:function(){this.$$replace=!0;return this}};var ja=v("$parse"),Fc={},ua,Qe=Function.prototype.call,Re=Function.prototype.apply,Qc=Function.prototype.bind,cb={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:A,"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return B(d)?B(e)?d+e:d:B(e)?e:s},"-":function(a,c,d,e){d=d(a,c);e=e(a,c);return(B(d)?d:0)-(B(e)?e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a, c,d,e){return d(a,c)%e(a,c)},"^":function(a,c,d,e){return d(a,c)^e(a,c)},"=":A,"===":function(a,c,d,e){return d(a,c)===e(a,c)},"!==":function(a,c,d,e){return d(a,c)!==e(a,c)},"==":function(a,c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a, c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},"!":function(a,c,d){return!d(a,c)}},Se={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Sb=function(a){this.options=a};Sb.prototype={constructor:Sb,lex:function(a){this.text=a;this.index=0;this.ch=s;this.lastCh=":";for(this.tokens=[];this.index<this.text.length;){this.ch=this.text.charAt(this.index);if(this.is("\"'"))this.readString(this.ch);else if(this.isNumber(this.ch)|| this.is(".")&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(this.ch))this.readIdent();else if(this.is("(){}[].,;:?"))this.tokens.push({index:this.index,text:this.ch}),this.index++;else if(this.isWhitespace(this.ch)){this.index++;continue}else{a=this.ch+this.peek();var c=a+this.peek(2),d=cb[this.ch],e=cb[a],g=cb[c];g?(this.tokens.push({index:this.index,text:c,fn:g}),this.index+=3):e?(this.tokens.push({index:this.index,text:a,fn:e}),this.index+=2):d?(this.tokens.push({index:this.index, text:this.ch,fn:d}),this.index+=1):this.throwError("Unexpected next character ",this.index,this.index+1)}this.lastCh=this.ch}return this.tokens},is:function(a){return-1!==a.indexOf(this.ch)},was:function(a){return-1!==a.indexOf(this.lastCh)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<= a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=B(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw ja("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=I(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&& e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}a*=1;this.tokens.push({index:c,text:a,literal:!0,constant:!0,fn:function(){return a}})},readIdent:function(){for(var a=this,c="",d=this.index,e,g,f,k;this.index<this.text.length;){k=this.text.charAt(this.index);if("."===k||this.isIdent(k)||this.isNumber(k))"."===k&&(e=this.index),c+=k;else break;this.index++}if(e)for(g= this.index;g<this.text.length;){k=this.text.charAt(g);if("("===k){f=c.substr(e-d+1);c=c.substr(0,e-d);this.index=g;break}if(this.isWhitespace(k))g++;else break}d={index:d,text:c};if(cb.hasOwnProperty(c))d.fn=cb[c],d.literal=!0,d.constant=!0;else{var m=Ec(c,this.options,this.text);d.fn=E(function(a,c){return m(a,c)},{assign:function(d,e){return qb(d,c,e,a.text,a.options)}})}this.tokens.push(d);f&&(this.tokens.push({index:e,text:"."}),this.tokens.push({index:e+1,text:f}))},readString:function(a){var c= this.index;this.index++;for(var d="",e=a,g=!1;this.index<this.text.length;){var f=this.text.charAt(this.index),e=e+f;if(g)"u"===f?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d=(g=Se[f])?d+g:d+f,g=!1;else if("\\"===f)g=!0;else{if(f===a){this.index++;this.tokens.push({index:c,text:e,string:d,literal:!0,constant:!0,fn:function(){return d}});return}d+=f}this.index++}this.throwError("Unterminated quote", c)}};var bb=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d};bb.ZERO=E(function(){return 0},{constant:!0});bb.prototype={constructor:bb,parse:function(a){this.text=a;this.tokens=this.lexer.lex(a);a=this.statements();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);a.literal=!!a.literal;a.constant=!!a.constant;return a},primary:function(){var a;if(this.expect("("))a=this.filterChain(),this.consume(")");else if(this.expect("["))a=this.arrayDeclaration();else if(this.expect("{"))a= this.object();else{var c=this.expect();(a=c.fn)||this.throwError("not a primary expression",c);a.literal=!!c.literal;a.constant=!!c.constant}for(var d;c=this.expect("(","[",".");)"("===c.text?(a=this.functionCall(a,d),d=null):"["===c.text?(d=a,a=this.objectIndex(a)):"."===c.text?(d=a,a=this.fieldAccess(a)):this.throwError("IMPOSSIBLE");return a},throwError:function(a,c){throw ja("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},peekToken:function(){if(0===this.tokens.length)throw ja("ueoe", this.text);return this.tokens[0]},peek:function(a,c,d,e){if(0<this.tokens.length){var g=this.tokens[0],f=g.text;if(f===a||f===c||f===d||f===e||!(a||c||d||e))return g}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},consume:function(a){this.expect(a)||this.throwError("is unexpected, expecting ["+a+"]",this.peek())},unaryFn:function(a,c){return E(function(d,e){return a(d,e,c)},{constant:c.constant})},ternaryFn:function(a,c,d){return E(function(e,g){return a(e, g)?c(e,g):d(e,g)},{constant:a.constant&&c.constant&&d.constant})},binaryFn:function(a,c,d){return E(function(e,g){return c(e,g,a,d)},{constant:a.constant&&d.constant})},statements:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.filterChain()),!this.expect(";"))return 1===a.length?a[0]:function(c,d){for(var e,g=0;g<a.length;g++){var f=a[g];f&&(e=f(c,d))}return e}},filterChain:function(){for(var a=this.expression(),c;;)if(c=this.expect("|"))a=this.binaryFn(a, c.fn,this.filter());else return a},filter:function(){for(var a=this.expect(),c=this.$filter(a.text),d=[];;)if(a=this.expect(":"))d.push(this.expression());else{var e=function(a,e,k){k=[k];for(var m=0;m<d.length;m++)k.push(d[m](a,e));return c.apply(a,k)};return function(){return e}}},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary(),c,d;return(d=this.expect("="))?(a.assign||this.throwError("implies assignment but ["+this.text.substring(0,d.index)+"] can not be assigned to", d),c=this.ternary(),function(d,g){return a.assign(d,c(d,g),g)}):a},ternary:function(){var a=this.logicalOR(),c,d;if(this.expect("?")){c=this.ternary();if(d=this.expect(":"))return this.ternaryFn(a,c,this.ternary());this.throwError("expected :",d)}else return a},logicalOR:function(){for(var a=this.logicalAND(),c;;)if(c=this.expect("||"))a=this.binaryFn(a,c.fn,this.logicalAND());else return a},logicalAND:function(){var a=this.equality(),c;if(c=this.expect("&&"))a=this.binaryFn(a,c.fn,this.logicalAND()); return a},equality:function(){var a=this.relational(),c;if(c=this.expect("==","!=","===","!=="))a=this.binaryFn(a,c.fn,this.equality());return a},relational:function(){var a=this.additive(),c;if(c=this.expect("<",">","<=",">="))a=this.binaryFn(a,c.fn,this.relational());return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.fn,this.multiplicative());return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a, c.fn,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn(bb.ZERO,a.fn,this.unary()):(a=this.expect("!"))?this.unaryFn(a.fn,this.unary()):this.primary()},fieldAccess:function(a){var c=this,d=this.expect().text,e=Ec(d,this.options,this.text);return E(function(c,d,k){return e(k||a(c,d))},{assign:function(e,f,k){return qb(a(e,k),d,f,c.text,c.options)}})},objectIndex:function(a){var c=this,d=this.expression();this.consume("]");return E(function(e, g){var f=a(e,g),k=d(e,g),m;da(k,c.text);if(!f)return s;(f=Ma(f[k],c.text))&&(f.then&&c.options.unwrapPromises)&&(m=f,"$$v"in f||(m.$$v=s,m.then(function(a){m.$$v=a})),f=f.$$v);return f},{assign:function(e,g,f){var k=d(e,f);return Ma(a(e,f),c.text)[k]=g}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());while(this.expect(","))}this.consume(")");var e=this;return function(g,f){for(var k=[],m=c?c(g,f):g,h=0;h<d.length;h++)k.push(d[h](g,f));h=a(g,f,m)|| A;Ma(m,e.text);var l=e.text;if(h){if(h.constructor===h)throw ja("isecfn",l);if(h===Qe||h===Re||Qc&&h===Qc)throw ja("isecff",l);}k=h.apply?h.apply(m,k):h(k[0],k[1],k[2],k[3],k[4]);return Ma(k,e.text)}},arrayDeclaration:function(){var a=[],c=!0;if("]"!==this.peekToken().text){do{if(this.peek("]"))break;var d=this.expression();a.push(d);d.constant||(c=!1)}while(this.expect(","))}this.consume("]");return E(function(c,d){for(var f=[],k=0;k<a.length;k++)f.push(a[k](c,d));return f},{literal:!0,constant:c})}, object:function(){var a=[],c=!0;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;var d=this.expect(),d=d.string||d.text;this.consume(":");var e=this.expression();a.push({key:d,value:e});e.constant||(c=!1)}while(this.expect(","))}this.consume("}");return E(function(c,d){for(var e={},m=0;m<a.length;m++){var h=a[m];e[h.key]=h.value(c,d)}return e},{literal:!0,constant:c})}};var Rb={},va=v("$sce"),fa={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},W=V.createElement("a"), Hc=ta(T.location.href,!0);jc.$inject=["$provide"];Ic.$inject=["$locale"];Kc.$inject=["$locale"];var Nc=".",Ke={yyyy:Y("FullYear",4),yy:Y("FullYear",2,0,!0),y:Y("FullYear",1),MMMM:rb("Month"),MMM:rb("Month",!0),MM:Y("Month",2,1),M:Y("Month",1,1),dd:Y("Date",2),d:Y("Date",1),HH:Y("Hours",2),H:Y("Hours",1),hh:Y("Hours",2,-12),h:Y("Hours",1,-12),mm:Y("Minutes",2),m:Y("Minutes",1),ss:Y("Seconds",2),s:Y("Seconds",1),sss:Y("Milliseconds",3),EEEE:rb("Day"),EEE:rb("Day",!0),a:function(a,c){return 12>a.getHours()? c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(Tb(Math[0<a?"floor":"ceil"](a/60),2)+Tb(Math.abs(a%60),2))}},Je=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,Ie=/^\-?\d+$/;Jc.$inject=["$locale"];var Ge=$(I),He=$(Ha);Lc.$inject=["$parse"];var dd=$({restrict:"E",compile:function(a,c){8>=P&&(c.href||c.name||c.$set("href",""),a.append(V.createComment("IE fix")));if(!c.href&&!c.xlinkHref&&!c.name)return function(a,c){var g="[object SVGAnimatedString]"=== xa.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(g)||a.preventDefault()})}}}),Db={};q(lb,function(a,c){if("multiple"!=a){var d=na("ng-"+c);Db[d]=function(){return{priority:100,link:function(a,g,f){a.$watch(f[d],function(a){f.$set(c,!!a)})}}}}});q(["src","srcset","href"],function(a){var c=na("ng-"+a);Db[c]=function(){return{priority:99,link:function(d,e,g){var f=a,k=a;"href"===a&&"[object SVGAnimatedString]"===xa.call(e.prop("href"))&&(k="xlinkHref",g.$attr[k]="xlink:href", f=null);g.$observe(c,function(a){a&&(g.$set(k,a),P&&f&&e.prop(f,g[k]))})}}}});var ub={$addControl:A,$removeControl:A,$setValidity:A,$setDirty:A,$setPristine:A};Oc.$inject=["$element","$attrs","$scope","$animate"];var Rc=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Oc,compile:function(){return{pre:function(a,e,g,f){if(!g.action){var k=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};ob(e[0],"submit",k);e.on("$destroy",function(){c(function(){Xa(e[0], "submit",k)},0,!1)})}var m=e.parent().controller("form"),h=g.name||g.ngForm;h&&qb(a,h,f,h);if(m)e.on("$destroy",function(){m.$removeControl(f);h&&qb(a,h,s,h);E(f,ub)})}}}}}]},ed=Rc(),rd=Rc(!0),Te=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,Ue=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i,Ve=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,Sc={text:wb,number:function(a,c,d,e,g,f){wb(a,c,d,e,g,f);e.$parsers.push(function(a){var c=e.$isEmpty(a);if(c||Ve.test(a))return e.$setValidity("number", !0),""===a?null:c?a:parseFloat(a);e.$setValidity("number",!1);return s});Le(e,"number",We,null,e.$$validityState);e.$formatters.push(function(a){return e.$isEmpty(a)?"":""+a});d.min&&(a=function(a){var c=parseFloat(d.min);return ra(e,"min",e.$isEmpty(a)||a>=c,a)},e.$parsers.push(a),e.$formatters.push(a));d.max&&(a=function(a){var c=parseFloat(d.max);return ra(e,"max",e.$isEmpty(a)||a<=c,a)},e.$parsers.push(a),e.$formatters.push(a));e.$formatters.push(function(a){return ra(e,"number",e.$isEmpty(a)|| xb(a),a)})},url:function(a,c,d,e,g,f){wb(a,c,d,e,g,f);a=function(a){return ra(e,"url",e.$isEmpty(a)||Te.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},email:function(a,c,d,e,g,f){wb(a,c,d,e,g,f);a=function(a){return ra(e,"email",e.$isEmpty(a)||Ue.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){D(d.name)&&c.attr("name",eb());c.on("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=d.value==e.$viewValue}; d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var g=d.ngTrueValue,f=d.ngFalseValue;y(g)||(g=!0);y(f)||(f=!1);c.on("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return a!==g};e.$formatters.push(function(a){return a===g});e.$parsers.push(function(a){return a?g:f})},hidden:A,button:A,submit:A,reset:A,file:A},We=["badInput"],gc=["$browser","$sniffer",function(a,c){return{restrict:"E",require:"?ngModel", link:function(d,e,g,f){f&&(Sc[I(g.type)]||Sc.text)(d,e,g,f,c,a)}}}],tb="ng-valid",sb="ng-invalid",Na="ng-pristine",vb="ng-dirty",Xe=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate",function(a,c,d,e,g,f){function k(a,c){c=c?"-"+hb(c,"-"):"";f.removeClass(e,(a?sb:tb)+c);f.addClass(e,(a?tb:sb)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name= d.name;var m=g(d.ngModel),h=m.assign;if(!h)throw v("ngModel")("nonassign",d.ngModel,ga(e));this.$render=A;this.$isEmpty=function(a){return D(a)||""===a||null===a||a!==a};var l=e.inheritedData("$formController")||ub,p=0,n=this.$error={};e.addClass(Na);k(!0);this.$setValidity=function(a,c){n[a]!==!c&&(c?(n[a]&&p--,p||(k(!0),this.$valid=!0,this.$invalid=!1)):(k(!1),this.$invalid=!0,this.$valid=!1,p++),n[a]=!c,k(c,a),l.$setValidity(a,c,this))};this.$setPristine=function(){this.$dirty=!1;this.$pristine= !0;f.removeClass(e,vb);f.addClass(e,Na)};this.$setViewValue=function(d){this.$viewValue=d;this.$pristine&&(this.$dirty=!0,this.$pristine=!1,f.removeClass(e,Na),f.addClass(e,vb),l.$setDirty());q(this.$parsers,function(a){d=a(d)});this.$modelValue!==d&&(this.$modelValue=d,h(a,d),q(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}}))};var r=this;a.$watch(function(){var c=m(a);if(r.$modelValue!==c){var d=r.$formatters,e=d.length;for(r.$modelValue=c;e--;)c=d[e](c);r.$viewValue!==c&&(r.$viewValue= c,r.$render())}return c})}],Gd=function(){return{require:["ngModel","^?form"],controller:Xe,link:function(a,c,d,e){var g=e[0],f=e[1]||ub;f.$addControl(g);a.$on("$destroy",function(){f.$removeControl(g)})}}},Id=$({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),hc=function(){return{require:"?ngModel",link:function(a,c,d,e){if(e){d.required=!0;var g=function(a){if(d.required&&e.$isEmpty(a))e.$setValidity("required",!1);else return e.$setValidity("required", !0),a};e.$formatters.push(g);e.$parsers.unshift(g);d.$observe("required",function(){g(e.$viewValue)})}}}},Hd=function(){return{require:"ngModel",link:function(a,c,d,e){var g=(a=/\/(.*)\//.exec(d.ngList))&&RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){if(!D(a)){var c=[];a&&q(a.split(g),function(a){a&&c.push(aa(a))});return c}});e.$formatters.push(function(a){return L(a)?a.join(", "):s});e.$isEmpty=function(a){return!a||!a.length}}}},Ye=/^(true|false|\d+)$/,Jd=function(){return{priority:100, compile:function(a,c){return Ye.test(c.ngValue)?function(a,c,g){g.$set("value",a.$eval(g.ngValue))}:function(a,c,g){a.$watch(g.ngValue,function(a){g.$set("value",a)})}}}},jd=wa({compile:function(a){a.addClass("ng-binding");return function(a,d,e){d.data("$binding",e.ngBind);a.$watch(e.ngBind,function(a){d.text(a==s?"":a)})}}}),ld=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}], kd=["$sce","$parse",function(a,c){return function(d,e,g){e.addClass("ng-binding").data("$binding",g.ngBindHtml);var f=c(g.ngBindHtml);d.$watch(function(){return(f(d)||"").toString()},function(c){e.html(a.getTrustedHtml(f(d))||"")})}}],md=Ub("",!0),od=Ub("Odd",0),nd=Ub("Even",1),pd=wa({compile:function(a,c){c.$set("ngCloak",s);a.removeClass("ng-cloak")}}),qd=[function(){return{scope:!0,controller:"@",priority:500}}],ic={};q("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "), function(a){var c=na("ng-"+a);ic[c]=["$parse",function(d){return{compile:function(e,g){var f=d(g[c]);return function(c,d){d.on(I(a),function(a){c.$apply(function(){f(c,{$event:a})})})}}}}]});var td=["$animate",function(a){return{transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,g,f){var k,m,h;c.$watch(e.ngIf,function(g){Sa(g)?m||(m=c.$new(),f(m,function(c){c[c.length++]=V.createComment(" end ngIf: "+e.ngIf+" ");k={clone:c};a.enter(c,d.parent(),d)})):(h&&(h.remove(), h=null),m&&(m.$destroy(),m=null),k&&(h=Cb(k.clone),a.leave(h,function(){h=null}),k=null))})}}}],ud=["$http","$templateCache","$anchorScroll","$animate","$sce",function(a,c,d,e,g){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:Ta.noop,compile:function(f,k){var m=k.ngInclude||k.src,h=k.onload||"",l=k.autoscroll;return function(f,k,q,t,J){var w=0,u,s,x,z=function(){s&&(s.remove(),s=null);u&&(u.$destroy(),u=null);x&&(e.leave(x,function(){s=null}),s=x,x=null)};f.$watch(g.parseAsResourceUrl(m), function(g){var m=function(){!B(l)||l&&!f.$eval(l)||d()},q=++w;g?(a.get(g,{cache:c}).success(function(a){if(q===w){var c=f.$new();t.template=a;a=J(c,function(a){z();e.enter(a,null,k,m)});u=c;x=a;u.$emit("$includeContentLoaded");f.$eval(h)}}).error(function(){q===w&&z()}),f.$emit("$includeContentRequested")):(z(),t.template=null)})}}}}],Kd=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,g){d.html(g.template);a(d.contents())(c)}}}],vd=wa({priority:450, compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),wd=wa({terminal:!0,priority:1E3}),xd=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,g,f){var k=f.count,m=f.$attr.when&&g.attr(f.$attr.when),h=f.offset||0,l=e.$eval(m)||{},p={},n=c.startSymbol(),r=c.endSymbol(),t=/^when(Minus)?(.+)$/;q(f,function(a,c){t.test(c)&&(l[I(c.replace("when","").replace("Minus","-"))]=g.attr(f.$attr[c]))});q(l,function(a,e){p[e]=c(a.replace(d,n+k+"-"+h+r))});e.$watch(function(){var c= parseFloat(e.$eval(k));if(isNaN(c))return"";c in l||(c=a.pluralCat(c-h));return p[c](e,g,!0)},function(a){g.text(a)})}}}],yd=["$parse","$animate",function(a,c){var d=v("ngRepeat");return{transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,link:function(e,g,f,k,m){var h=f.ngRepeat,l=h.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),p,n,r,t,s,w,u={$id:Ja};if(!l)throw d("iexp",h);f=l[1];k=l[2];(l=l[3])?(p=a(l),n=function(a,c,d){w&&(u[w]=a);u[s]=c;u.$index=d;return p(e, u)}):(r=function(a,c){return Ja(c)},t=function(a){return a});l=f.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!l)throw d("iidexp",f);s=l[3]||l[1];w=l[2];var B={};e.$watchCollection(k,function(a){var f,k,l=g[0],p,u={},C,G,H,v,y,A,D=[];if(db(a))y=a,p=n||r;else{p=n||t;y=[];for(H in a)a.hasOwnProperty(H)&&"$"!=H.charAt(0)&&y.push(H);y.sort()}C=y.length;k=D.length=y.length;for(f=0;f<k;f++)if(H=a===y?f:y[f],v=a[H],v=p(H,v,f),Ba(v,"`track by` id"),B.hasOwnProperty(v))A=B[v],delete B[v],u[v]= A,D[f]=A;else{if(u.hasOwnProperty(v))throw q(D,function(a){a&&a.scope&&(B[a.id]=a)}),d("dupes",h,v);D[f]={id:v};u[v]=!1}for(H in B)B.hasOwnProperty(H)&&(A=B[H],f=Cb(A.clone),c.leave(f),q(f,function(a){a.$$NG_REMOVED=!0}),A.scope.$destroy());f=0;for(k=y.length;f<k;f++){H=a===y?f:y[f];v=a[H];A=D[f];D[f-1]&&(l=D[f-1].clone[D[f-1].clone.length-1]);if(A.scope){G=A.scope;p=l;do p=p.nextSibling;while(p&&p.$$NG_REMOVED);A.clone[0]!=p&&c.move(Cb(A.clone),null,x(l));l=A.clone[A.clone.length-1]}else G=e.$new(); G[s]=v;w&&(G[w]=H);G.$index=f;G.$first=0===f;G.$last=f===C-1;G.$middle=!(G.$first||G.$last);G.$odd=!(G.$even=0===(f&1));A.scope||m(G,function(a){a[a.length++]=V.createComment(" end ngRepeat: "+h+" ");c.enter(a,null,x(l));l=a;A.scope=G;A.clone=a;u[A.id]=A})}B=u})}}}],zd=["$animate",function(a){return function(c,d,e){c.$watch(e.ngShow,function(c){a[Sa(c)?"removeClass":"addClass"](d,"ng-hide")})}}],sd=["$animate",function(a){return function(c,d,e){c.$watch(e.ngHide,function(c){a[Sa(c)?"addClass":"removeClass"](d, "ng-hide")})}}],Ad=wa(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&q(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Bd=["$animate",function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,g){var f=[],k=[],m=[],h=[];c.$watch(e.ngSwitch||e.on,function(d){var p,n;p=0;for(n=m.length;p<n;++p)m[p].remove();p=m.length=0;for(n=h.length;p<n;++p){var r=k[p];h[p].$destroy();m[p]=r;a.leave(r,function(){m.splice(p,1)})}k.length=0;h.length= 0;if(f=g.cases["!"+d]||g.cases["?"])c.$eval(e.change),q(f,function(d){var e=c.$new();h.push(e);d.transclude(e,function(c){var e=d.element;k.push(c);a.enter(c,e.parent(),e)})})})}}}],Cd=wa({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,c,d,e,g){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:g,element:c})}}),Dd=wa({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,c,d,e,g){e.cases["?"]=e.cases["?"]|| [];e.cases["?"].push({transclude:g,element:c})}}),Fd=wa({link:function(a,c,d,e,g){if(!g)throw v("ngTransclude")("orphan",ga(c));g(function(a){c.empty();c.append(a)})}}),fd=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Ze=v("ngOptions"),Ed=$({terminal:!0}),gd=["$compile","$parse",function(a,c){var d=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, e={$setViewValue:A};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(a,c,d){var m=this,h={},l=e,p;m.databound=d.ngModel;m.init=function(a,c,d){l=a;p=d};m.addOption=function(c){Ba(c,'"option value"');h[c]=!0;l.$viewValue==c&&(a.val(c),p.parent()&&p.remove())};m.removeOption=function(a){this.hasOption(a)&&(delete h[a],l.$viewValue==a&&this.renderUnknownOption(a))};m.renderUnknownOption=function(c){c="? "+Ja(c)+" ?";p.val(c);a.prepend(p);a.val(c);p.prop("selected", !0)};m.hasOption=function(a){return h.hasOwnProperty(a)};c.$on("$destroy",function(){m.renderUnknownOption=A})}],link:function(e,f,k,m){function h(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(y.parent()&&y.remove(),c.val(a),""===a&&w.prop("selected",!0)):D(a)&&w?c.val(""):e.renderUnknownOption(a)};c.on("change",function(){a.$apply(function(){y.parent()&&y.remove();d.$setViewValue(c.val())})})}function l(a,c,d){var e;d.$render=function(){var a=new Za(d.$viewValue);q(c.find("option"), function(c){c.selected=B(a.get(c.value))})};a.$watch(function(){ya(e,d.$viewValue)||(e=la(d.$viewValue),d.$render())});c.on("change",function(){a.$apply(function(){var a=[];q(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function p(e,f,g){function k(){var a={"":[]},c=[""],d,h,s,t,z;t=g.$modelValue;z=x(e)||[];var D=n?Vb(z):z,G,R,C;R={};s=!1;var E,I;if(r)if(w&&L(t))for(s=new Za([]),C=0;C<t.length;C++)R[m]=t[C],s.put(w(e,R),t[C]);else s=new Za(t);for(C=0;G=D.length, C<G;C++){h=C;if(n){h=D[C];if("$"===h.charAt(0))continue;R[n]=h}R[m]=z[h];d=p(e,R)||"";(h=a[d])||(h=a[d]=[],c.push(d));r?d=B(s.remove(w?w(e,R):q(e,R))):(w?(d={},d[m]=t,d=w(e,d)===w(e,R)):d=t===q(e,R),s=s||d);E=l(e,R);E=B(E)?E:"";h.push({id:w?w(e,R):n?D[C]:C,label:E,selected:d})}r||(v||null===t?a[""].unshift({id:"",label:"",selected:!s}):s||a[""].unshift({id:"?",label:"",selected:!0}));R=0;for(D=c.length;R<D;R++){d=c[R];h=a[d];y.length<=R?(t={element:A.clone().attr("label",d),label:h.label},z=[t],y.push(z), f.append(t.element)):(z=y[R],t=z[0],t.label!=d&&t.element.attr("label",t.label=d));E=null;C=0;for(G=h.length;C<G;C++)s=h[C],(d=z[C+1])?(E=d.element,d.label!==s.label&&E.text(d.label=s.label),d.id!==s.id&&E.val(d.id=s.id),d.selected!==s.selected&&E.prop("selected",d.selected=s.selected)):(""===s.id&&v?I=v:(I=u.clone()).val(s.id).prop("selected",s.selected).text(s.label),z.push({element:I,label:s.label,id:s.id,selected:s.selected}),E?E.after(I):t.element.append(I),E=I);for(C++;z.length>C;)z.pop().element.remove()}for(;y.length> R;)y.pop()[0].element.remove()}var h;if(!(h=t.match(d)))throw Ze("iexp",t,ga(f));var l=c(h[2]||h[1]),m=h[4]||h[6],n=h[5],p=c(h[3]||""),q=c(h[2]?h[1]:m),x=c(h[7]),w=h[8]?c(h[8]):null,y=[[{element:f,label:""}]];v&&(a(v)(e),v.removeClass("ng-scope"),v.remove());f.empty();f.on("change",function(){e.$apply(function(){var a,c=x(e)||[],d={},h,k,l,p,t,u,v;if(r)for(k=[],p=0,u=y.length;p<u;p++)for(a=y[p],l=1,t=a.length;l<t;l++){if((h=a[l].element)[0].selected){h=h.val();n&&(d[n]=h);if(w)for(v=0;v<c.length&& (d[m]=c[v],w(e,d)!=h);v++);else d[m]=c[h];k.push(q(e,d))}}else{h=f.val();if("?"==h)k=s;else if(""===h)k=null;else if(w)for(v=0;v<c.length;v++){if(d[m]=c[v],w(e,d)==h){k=q(e,d);break}}else d[m]=c[h],n&&(d[n]=h),k=q(e,d);1<y[0].length&&y[0][1].id!==h&&(y[0][1].selected=!1)}g.$setViewValue(k)})});g.$render=k;e.$watch(k)}if(m[1]){var n=m[0];m=m[1];var r=k.multiple,t=k.ngOptions,v=!1,w,u=x(V.createElement("option")),A=x(V.createElement("optgroup")),y=u.clone();k=0;for(var z=f.children(),E=z.length;k<E;k++)if(""=== z[k].value){w=v=z.eq(k);break}n.init(m,v,y);r&&(m.$isEmpty=function(a){return!a||0===a.length});t?p(e,f,m):r?l(e,f,m):h(e,f,m,n)}}}}],id=["$interpolate",function(a){var c={addOption:A,removeOption:A};return{restrict:"E",priority:100,compile:function(d,e){if(D(e.value)){var g=a(d.text(),!0);g||e.$set("value",d.text())}return function(a,d,e){var h=d.parent(),l=h.data("$selectController")||h.parent().data("$selectController");l&&l.databound?d.prop("selected",!1):l=c;g?a.$watch(g,function(a,c){e.$set("value", a);a!==c&&l.removeOption(c);l.addOption(a)}):l.addOption(e.value);d.on("$destroy",function(){l.removeOption(e.value)})}}}}],hd=$({restrict:"E",terminal:!0});T.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):((Ca=T.jQuery)&&Ca.fn.on?(x=Ca,E(Ca.fn,{scope:Ka.scope,isolateScope:Ka.isolateScope,controller:Ka.controller,injector:Ka.injector,inheritedData:Ka.inheritedData}),Eb("remove",!0,!0,!1),Eb("empty",!1,!1,!1),Eb("html",!1,!1,!0)):x=S,Ta.element=x,$c(Ta),x(V).ready(function(){Xc(V, cc)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}.ng-animate-block-transitions{transition:0s all!important;-webkit-transition:0s all!important;}.ng-hide-add-active,.ng-hide-remove{display:block!important;}</style>');
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var fs = require('fs'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'File from renamer' }); }); router.get('/#/Users', function(req, res) { res.send({"res":"gogo"}); }); //To have launchd start mongodb at login: // ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents //Then to load mongodb now: // launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist //Or, if you don't want/need launchctl, you can just run: // mongod --config /usr/local/etc/mongod.conf // >mongod --dbpath mongoose.connect("mongodb://localhost/files"); // See files.js mongoose.model('files', { path: String, filename: String, size: Number, owner: String, created: Date, modified: Date }); router.get("/files", function(req,res){ console.log("Entering in REST api"); mongoose.model('files').find(function(err,files){ res.send(files); }); }); router.get("/ls/:node/:dir(*)", function(req,res){ console.log("Entering in REST api"); var out = {}; console.log("Dir=" + req.params.dir); console.log("Node=" + req.params.node); //out.network = req.params.node; out.directoryListing = []; try { var counter=0; fs.readdirSync("/" + req.params.dir).forEach(function(filename){ out.directoryListing.push({ "index": counter++, "filename": filename, "Owner": "alainlavoie", "lastModification": 4332, "fileSize": 142 }); }); res.send(out.directoryListing); } catch (dirError){ if (dirError instanceof Error && dirError.code === 'ENOENT'){ res.send(404); } else { res.send({Error: dirError}); } } }); module.exports = router;
module.exports = function (grunt) { grunt.initConfig({ karma: { options: { configFile: 'tests/config/karma.conf.js' }, watch: { autoWatch: true }, singleRun: { singleRun: true }, travis: { singleRun: true, browsers: ['PhantomJS'] } } }); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('testRun', ['karma:singleRun']); grunt.registerTask('testWatch', ['karma:watch']); grunt.registerTask('test', ['karma:travis']); };
/** * @ngdoc directive * @name mdMenu * @module material.components.menu * @restrict E * @description * * Menus are elements that open when clicked. They are useful for displaying * additional options within the context of an action. * * Every `md-menu` must specify exactly two child elements. The first element is what is * left in the DOM and is used to open the menu. This element is called the trigger element. * The trigger element's scope has access to `$mdOpenMenu($event)` * which it may call to open the menu. By passing $event as argument, the * corresponding event is stopped from propagating up the DOM-tree. * * The second element is the `md-menu-content` element which represents the * contents of the menu when it is open. Typically this will contain `md-menu-item`s, * but you can do custom content as well. * * <hljs lang="html"> * <md-menu> * <!-- Trigger element is a md-button with an icon --> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button" aria-label="Open sample menu"> * <md-icon md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * ## Sizing Menus * * The width of the menu when it is open may be specified by specifying a `width` * attribute on the `md-menu-content` element. * See the [Material Design Spec](http://www.google.com/design/spec/components/menus.html#menus-specs) * for more information. * * * ## Aligning Menus * * When a menu opens, it is important that the content aligns with the trigger element. * Failure to align menus can result in jarring experiences for users as content * suddenly shifts. To help with this, `md-menu` provides serveral APIs to help * with alignment. * * ### Target Mode * * By default, `md-menu` will attempt to align the `md-menu-content` by aligning * designated child elements in both the trigger and the menu content. * * To specify the alignment element in the `trigger` you can use the `md-menu-origin` * attribute on a child element. If no `md-menu-origin` is specified, the `md-menu` * will be used as the origin element. * * Similarly, the `md-menu-content` may specify a `md-menu-align-target` for a * `md-menu-item` to specify the node that it should try and align with. * * In this example code, we specify an icon to be our origin element, and an * icon in our menu content to be our alignment target. This ensures that both * icons are aligned when the menu opens. * * <hljs lang="html"> * <md-menu> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button" aria-label="Open some menu"> * <md-icon md-menu-origin md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item> * <md-button ng-click="doSomething()" aria-label="Do something"> * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon> * Do Something * </md-button> * </md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * * Sometimes we want to specify alignment on the right side of an element, for example * if we have a menu on the right side a toolbar, we want to right align our menu content. * * We can specify the origin by using the `md-position-mode` attribute on both * the `x` and `y` axis. Right now only the `x-axis` has more than one option. * You may specify the default mode of `target target` or * `target-right target` to specify a right-oriented alignment target. See the * position section of the demos for more examples. * * ### Menu Offsets * * It is sometimes unavoidable to need to have a deeper level of control for * the positioning of a menu to ensure perfect alignment. `md-menu` provides * the `md-offset` attribute to allow pixel level specificty of adjusting the * exact positioning. * * This offset is provided in the format of `x y` or `n` where `n` will be used * in both the `x` and `y` axis. * * For example, to move a menu by `2px` from the top, we can use: * <hljs lang="html"> * <md-menu md-offset="2 0"> * <!-- menu-content --> * </md-menu> * </hljs> * * ### Auto Focus * By default, when a menu opens, `md-menu` focuses the first button in the menu content. * * But sometimes you would like to focus another specific menu item instead of the first.<br/> * This can be done by applying the `md-autofocus` directive on the given element. * * <hljs lang="html"> * <md-menu-item> * <md-button md-autofocus ng-click="doSomething()"> * Auto Focus * </md-button> * </md-menu-item> * </hljs> * * * ### Preventing close * * Sometimes you would like to be able to click on a menu item without having the menu * close. To do this, ngMaterial exposes the `md-prevent-menu-close` attribute which * can be added to a button inside a menu to stop the menu from automatically closing. * You can then close the menu programatically by injecting `$mdMenu` and calling * `$mdMenu.hide()`. * * <hljs lang="html"> * <md-menu-item> * <md-button ng-click="doSomething()" aria-label="Do something" md-prevent-menu-close="md-prevent-menu-close"> * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon> * Do Something * </md-button> * </md-menu-item> * </hljs> * * @usage * <hljs lang="html"> * <md-menu> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button"> * <md-icon md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * * @param {string} md-position-mode The position mode in the form of * `x`, `y`. Default value is `target`,`target`. Right now the `x` axis * also suppports `target-right`. * @param {string} md-offset An offset to apply to the dropdown after positioning * `x`, `y`. Default value is `0`,`0`. * */ angular .module('material.components.menu') .directive('mdMenu', MenuDirective); /** * @ngInject */ function MenuDirective($mdUtil) { var INVALID_PREFIX = 'Invalid HTML for md-menu: '; return { restrict: 'E', require: ['mdMenu', '?^mdMenuBar'], controller: 'mdMenuCtrl', // empty function to be built by link scope: true, compile: compile }; function compile(templateElement) { templateElement.addClass('md-menu'); var triggerElement = templateElement.children()[0]; var prefixer = $mdUtil.prefixer(); if (!prefixer.hasAttribute(triggerElement, 'ng-click')) { triggerElement = triggerElement .querySelector(prefixer.buildSelector(['ng-click', 'ng-mouseenter'])) || triggerElement; } if (triggerElement && ( triggerElement.nodeName == 'MD-BUTTON' || triggerElement.nodeName == 'BUTTON' ) && !triggerElement.hasAttribute('type')) { triggerElement.setAttribute('type', 'button'); } if (templateElement.children().length != 2) { throw Error(INVALID_PREFIX + 'Expected two children elements.'); } // Default element for ARIA attributes has the ngClick or ngMouseenter expression triggerElement && triggerElement.setAttribute('aria-haspopup', 'true'); var nestedMenus = templateElement[0].querySelectorAll('md-menu'); var nestingDepth = parseInt(templateElement[0].getAttribute('md-nest-level'), 10) || 0; if (nestedMenus) { angular.forEach($mdUtil.nodesToArray(nestedMenus), function(menuEl) { if (!menuEl.hasAttribute('md-position-mode')) { menuEl.setAttribute('md-position-mode', 'cascade'); } menuEl.classList.add('_md-nested-menu'); menuEl.setAttribute('md-nest-level', nestingDepth + 1); }); } return link; } function link(scope, element, attr, ctrls) { var mdMenuCtrl = ctrls[0]; var isInMenuBar = ctrls[1] != undefined; // Move everything into a md-menu-container and pass it to the controller var menuContainer = angular.element( '<div class="_md md-open-menu-container md-whiteframe-z2"></div>'); var menuContents = element.children()[1]; element.addClass('_md'); // private md component indicator for styling if (!menuContents.hasAttribute('role')) { menuContents.setAttribute('role', 'menu'); } menuContainer.append(menuContents); element.on('$destroy', function() { menuContainer.remove(); }); element.append(menuContainer); menuContainer[0].style.display = 'none'; mdMenuCtrl.init(menuContainer, { isInMenuBar: isInMenuBar }); } }
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { connect } from 'umi' import { Page } from 'components' import styles from './index.less' @connect(({ userDetail }) => ({ userDetail })) class UserDetail extends PureComponent { render() { const { userDetail } = this.props const { data } = userDetail const content = [] for (let key in data) { if ({}.hasOwnProperty.call(data, key)) { content.push( <div key={key} className={styles.item}> <div>{key}</div> <div>{String(data[key])}</div> </div> ) } } return ( <Page inner> <div className={styles.content}>{content}</div> </Page> ) } } UserDetail.propTypes = { userDetail: PropTypes.object, } export default UserDetail
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name Item * * @class The Item type allows you to access and modify the items in * Paper.js projects. Its functionality is inherited by different project * item types such as {@link Path}, {@link CompoundPath}, {@link Group}, * {@link Layer} and {@link Raster}. They each add a layer of functionality that * is unique to their type, but share the underlying properties and functions * that they inherit from Item. */ var Item = Base.extend(Callback, /** @lends Item# */{ statics: { /** * Override Item.extend() to merge the subclass' _serializeFields with * the parent class' _serializeFields. * * @private */ extend: function extend(src) { if (src._serializeFields) src._serializeFields = Base.merge( this.prototype._serializeFields, src._serializeFields); var res = extend.base.apply(this, arguments), proto = res.prototype, name = proto._class; // Derive the _type string from class name if (name) proto._type = Base.hyphenate(name); return res; } }, _class: 'Item', // All items apply their matrix by default. // Exceptions are Raster, PlacedSymbol, Clip and Shape. _transformContent: true, _boundsSelected: false, // Provide information about fields to be serialized, with their defaults // that can be ommited. _serializeFields: { name: null, matrix: new Matrix(), locked: false, visible: true, blendMode: 'normal', opacity: 1, guide: false, selected: false, clipMask: false, data: {} }, initialize: function Item() { // Do nothing. }, _initialize: function(props, point) { // Define this Item's unique id. this._id = Item._id = (Item._id || 0) + 1; // If _project is already set, the item was already moved into the DOM // hierarchy. Used by Layer, where it's added to project.layers instead if (!this._project) { var project = paper.project, layer = project.activeLayer; // Do not insert into DOM if props.insert is false. if (layer && !(props && props.insert === false)) { layer.addChild(this); } else { this._setProject(project); } } this._style = new Style(this._project._currentStyle, this); this._matrix = new Matrix(); if (point) this._matrix.translate(point); return props ? this._set(props, { insert: true }) : true; }, _events: new function() { // Flags defining which native events are required by which Paper events // as required for counting amount of necessary natives events. // The mapping is native -> virtual var mouseFlags = { mousedown: { mousedown: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mouseup: { mouseup: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mousemove: { mousedrag: 1, mousemove: 1, mouseenter: 1, mouseleave: 1 } }; // Entry for all mouse events in the _events list var mouseEvent = { install: function(type) { // If the view requires counting of installed mouse events, // increase the counters now according to mouseFlags var counters = this._project.view._eventCounters; if (counters) { for (var key in mouseFlags) { counters[key] = (counters[key] || 0) + (mouseFlags[key][type] || 0); } } }, uninstall: function(type) { // If the view requires counting of installed mouse events, // decrease the counters now according to mouseFlags var counters = this._project.view._eventCounters; if (counters) { for (var key in mouseFlags) counters[key] -= mouseFlags[key][type] || 0; } } }; return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick', 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'], function(name) { this[name] = mouseEvent; }, { onFrame: { install: function() { this._project.view._animateItem(this, true); }, uninstall: function() { this._project.view._animateItem(this, false); } }, // Only for external sources, e.g. Raster onLoad: {} } ); }, _serialize: function(options, dictionary) { var props = {}, that = this; function serialize(fields) { for (var key in fields) { var value = that[key]; // Style#leading is a special case, as its default value is // dependent on the fontSize. Handle this here separately. if (!Base.equals(value, key === 'leading' ? fields.fontSize * 1.2 : fields[key])) { props[key] = Base.serialize(value, options, // Do not use compact mode for data key !== 'data', dictionary); } } } // Serialize fields that this Item subclass defines first serialize(this._serializeFields); // Serialize style fields, but only if they differ from defaults. // Do not serialize styles on Groups and Layers, since they just unify // their children's own styles. if (!(this instanceof Group)) serialize(this._style._defaults); // There is no compact form for Item serialization, we always keep the // class. return [ this._class, props ]; }, /** * Private notifier that is called whenever a change occurs in this item or * its sub-elements, such as Segments, Curves, Styles, etc. * * @param {ChangeFlag} flags describes what exactly has changed. */ _changed: function(flags) { var parent = this._parent, project = this._project, symbol = this._parentSymbol; // Reset _drawCount on each change. this._drawCount = null; if (flags & /*#=*/ ChangeFlag.GEOMETRY) { // Clear cached bounds and position whenever geometry changes delete this._bounds; delete this._position; } if (parent && (flags & (/*#=*/ ChangeFlag.GEOMETRY | /*#=*/ ChangeFlag.STROKE))) { // Clear cached bounds of all items that this item contributes to. // We call this on the parent, since the information is cached on // the parent, see getBounds(). parent._clearBoundsCache(); } if (flags & /*#=*/ ChangeFlag.HIERARCHY) { // Clear cached bounds of all items that this item contributes to. // We don't call this on the parent, since we're already the parent // of the child that modified the hierarchy (that's where these // HIERARCHY notifications go) this._clearBoundsCache(); } if (project) { if (flags & /*#=*/ ChangeFlag.APPEARANCE) { project._needsRedraw = true; } // Have project keep track of changed items so they can be iterated. // This can be used for example to update the SVG tree. Needs to be // activated in Project if (project._changes) { var entry = project._changesById[this._id]; if (entry) { entry.flags |= flags; } else { entry = { item: this, flags: flags }; project._changesById[this._id] = entry; project._changes.push(entry); } } } // If this item is a symbol's definition, notify it of the change too if (symbol) symbol._changed(flags); }, /** * Sets those properties of the passed object literal on this item to * the values defined in the object literal, if the item has property of the * given name (or a setter defined for it). * @param {Object} props * @return {Item} the item itself. * * @example {@paperscript} * // Setting properties through an object literal * var circle = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * * circle.set({ * strokeColor: 'red', * strokeWidth: 10, * fillColor: 'black', * selected: true * }); */ set: function(props) { if (props) this._set(props); return this; }, /** * The unique id of the item. * * @type Number * @bean */ getId: function() { return this._id; }, /** * The type of the item as a string. * * @type String('group', 'layer', 'path', 'compound-path', 'raster', * 'placed-symbol', 'point-text') * @bean */ getType: function() { return this._type; }, /** * The name of the item. If the item has a name, it can be accessed by name * through its parent's children list. * * @type String * @bean * * @example {@paperscript} * var path = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * // Set the name of the path: * path.name = 'example'; * * // Create a group and add path to it as a child: * var group = new Group(); * group.addChild(path); * * // The path can be accessed by name: * group.children['example'].fillColor = 'red'; */ getName: function() { return this._name; }, setName: function(name, unique) { // Note: Don't check if the name has changed and bail out if it has not, // because setName is used internally also to update internal structures // when an item is moved from one parent to another. // If the item already had a name, remove the reference to it from the // parent's children object: if (this._name) this._removeNamed(); // See if the name is a simple number, which we cannot support due to // the named lookup on the children array. if (name === (+name) + '') throw new Error( 'Names consisting only of numbers are not supported.'); if (name && this._parent) { var children = this._parent._children, namedChildren = this._parent._namedChildren, orig = name, i = 1; // If unique is true, make sure we're not overriding other names while (unique && children[name]) name = orig + ' ' + (i++); (namedChildren[name] = namedChildren[name] || []).push(this); children[name] = this; } this._name = name || undefined; this._changed(/*#=*/ ChangeFlag.ATTRIBUTE); }, /** * The path style of the item. * * @name Item#getStyle * @type Style * @bean * * @example {@paperscript} * // Applying several styles to an item in one go, by passing an object * // to its style property: * var circle = new Path.Circle({ * center: [80, 50], * radius: 30 * }); * circle.style = { * fillColor: 'blue', * strokeColor: 'red', * strokeWidth: 5 * }; * * @example {@paperscript split=true height=100} * // Copying the style of another item: * var path = new Path.Circle({ * center: [50, 50], * radius: 30, * fillColor: 'red' * }); * * var path2 = new Path.Circle({ * center: new Point(180, 50), * radius: 20 * }); * * // Copy the path style of path: * path2.style = path.style; * * @example {@paperscript} * // Applying the same style object to multiple items: * var myStyle = { * fillColor: 'red', * strokeColor: 'blue', * strokeWidth: 4 * }; * * var path = new Path.Circle({ * center: [50, 50], * radius: 30 * }); * path.style = myStyle; * * var path2 = new Path.Circle({ * center: new Point(150, 50), * radius: 20 * }); * path2.style = myStyle; */ getStyle: function() { return this._style; }, setStyle: function(style) { // Don't access _style directly so Path#getStyle() can be overriden for // CompoundPaths. this.getStyle().set(style); }, // DOCS: Item#hasFill() hasFill: function() { return this.getStyle().hasFill(); }, // DOCS: Item#hasStroke() hasStroke: function() { return this.getStyle().hasStroke(); }, // DOCS: Item#hasShadow() hasShadow: function() { return this.getStyle().hasShadow(); } }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'], // Produce getter/setters for properties. We need setters because we want to // call _changed() if a property was modified. function(name) { var part = Base.capitalize(name), name = '_' + name; this['get' + part] = function() { return this[name]; }; this['set' + part] = function(value) { if (value != this[name]) { this[name] = value; // #locked does not change appearance, all others do: this._changed(name === '_locked' ? /*#=*/ ChangeFlag.ATTRIBUTE : /*#=*/ Change.ATTRIBUTE); } }; }, {}), /** @lends Item# */{ // Note: These properties have their getter / setters produced in the // injection scope above. /** * Specifies whether the item is locked. * * @name Item#locked * @type Boolean * @default false * @ignore */ _locked: false, /** * Specifies whether the item is visible. When set to {@code false}, the * item won't be drawn. * * @name Item#visible * @type Boolean * @default true * * @example {@paperscript} * // Hiding an item: * var path = new Path.Circle({ * center: [50, 50], * radius: 20, * fillColor: 'red' * }); * * // Hide the path: * path.visible = false; */ _visible: true, /** * The blend mode with which the item is composited onto the canvas. Both * the standard canvas compositing modes, as well as the new CSS blend modes * are supported. If blend-modes cannot be rendered natively, they are * emulated. Be aware that emulation can have an impact on performance. * * @name Item#blendMode * @type String('normal', 'multiply', 'screen', 'overlay', 'soft-light', * 'hard-light', 'color-dodge', 'color-burn', 'darken', 'lighten', * 'difference', 'exclusion', 'hue', 'saturation', 'luminosity', 'color', * 'add', 'subtract', 'average', 'pin-light', 'negation', 'source-over', * 'source-in', 'source-out', 'source-atop', 'destination-over', * 'destination-in', 'destination-out', 'destination-atop', 'lighter', * 'darker', 'copy', 'xor') * @default 'normal' * * @example {@paperscript} * // Setting an item's blend mode: * * // Create a white rectangle in the background * // with the same dimensions as the view: * var background = new Path.Rectangle(view.bounds); * background.fillColor = 'white'; * * var circle = new Path.Circle({ * center: [80, 50], * radius: 35, * fillColor: 'red' * }); * * var circle2 = new Path.Circle({ * center: new Point(120, 50), * radius: 35, * fillColor: 'blue' * }); * * // Set the blend mode of circle2: * circle2.blendMode = 'multiply'; */ _blendMode: 'normal', /** * The opacity of the item as a value between {@code 0} and {@code 1}. * * @name Item#opacity * @type Number * @default 1 * * @example {@paperscript} * // Making an item 50% transparent: * var circle = new Path.Circle({ * center: [80, 50], * radius: 35, * fillColor: 'red' * }); * * var circle2 = new Path.Circle({ * center: new Point(120, 50), * radius: 35, * fillColor: 'blue', * strokeColor: 'green', * strokeWidth: 10 * }); * * // Make circle2 50% transparent: * circle2.opacity = 0.5; */ _opacity: 1, // TODO: Implement guides /** * Specifies whether the item functions as a guide. When set to * {@code true}, the item will be drawn at the end as a guide. * * @name Item#guide * @type Boolean * @default true * @ignore */ _guide: false, /** * Specifies whether an item is selected and will also return {@code true} * if the item is partially selected (groups with some selected or partially * selected paths). * * Paper.js draws the visual outlines of selected items on top of your * project. This can be useful for debugging, as it allows you to see the * construction of paths, position of path curves, individual segment points * and bounding boxes of symbol and raster items. * * @type Boolean * @default false * @bean * @see Project#selectedItems * @see Segment#selected * @see Point#selected * * @example {@paperscript} * // Selecting an item: * var path = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * path.selected = true; // Select the path */ isSelected: function() { if (this._children) { for (var i = 0, l = this._children.length; i < l; i++) if (this._children[i].isSelected()) return true; } return this._selected; }, setSelected: function(selected /*, noChildren */) { // Don't recursively call #setSelected() if it was called with // noChildren set to true, see #setFullySelected(). if (this._children && !arguments[1]) { for (var i = 0, l = this._children.length; i < l; i++) this._children[i].setSelected(selected); } if ((selected = !!selected) != this._selected) { this._selected = selected; this._project._updateSelection(this); this._changed(/*#=*/ Change.ATTRIBUTE); } }, _selected: false, isFullySelected: function() { if (this._children && this._selected) { for (var i = 0, l = this._children.length; i < l; i++) if (!this._children[i].isFullySelected()) return false; return true; } // If there are no children, this is the same as #selected return this._selected; }, setFullySelected: function(selected) { if (this._children) { for (var i = 0, l = this._children.length; i < l; i++) this._children[i].setFullySelected(selected); } // Pass true for hidden noChildren argument this.setSelected(selected, true); }, /** * Specifies whether the item defines a clip mask. This can only be set on * paths, compound paths, and text frame objects, and only if the item is * already contained within a clipping group. * * @type Boolean * @default false * @bean */ isClipMask: function() { return this._clipMask; }, setClipMask: function(clipMask) { // On-the-fly conversion to boolean: if (this._clipMask != (clipMask = !!clipMask)) { this._clipMask = clipMask; if (clipMask) { this.setFillColor(null); this.setStrokeColor(null); } this._changed(/*#=*/ Change.ATTRIBUTE); // Tell the parent the clipping mask has changed if (this._parent) this._parent._changed(/*#=*/ ChangeFlag.CLIPPING); } }, _clipMask: false, // TODO: get/setIsolated (print specific feature) // TODO: get/setKnockout (print specific feature) // TODO: get/setAlphaIsShape /** * A plain javascript object which can be used to store * arbitrary data on the item. * * @type Object * @bean * * @example * var path = new Path(); * path.data.remember = 'milk'; * * @example * var path = new Path(); * path.data.malcolm = new Point(20, 30); * console.log(path.data.malcolm.x); // 20 * * @example * var path = new Path(); * path.data = { * home: 'Omicron Theta', * found: 2338, * pets: ['Spot'] * }; * console.log(path.data.pets.length); // 1 * * @example * var path = new Path({ * data: { * home: 'Omicron Theta', * found: 2338, * pets: ['Spot'] * } * }); * console.log(path.data.pets.length); // 1 */ getData: function() { if (!this._data) this._data = {}; return this._data; }, setData: function(data) { this._data = data; }, /** * {@grouptitle Position and Bounding Boxes} * * The item's position within the project. This is the * {@link Rectangle#center} of the item's {@link #bounds} rectangle. * * @type Point * @bean * * @example {@paperscript} * // Changing the position of a path: * * // Create a circle at position { x: 10, y: 10 } * var circle = new Path.Circle({ * center: new Point(10, 10), * radius: 10, * fillColor: 'red' * }); * * // Move the circle to { x: 20, y: 20 } * circle.position = new Point(20, 20); * * // Move the circle 100 points to the right and 50 points down * circle.position += new Point(100, 50); * * @example {@paperscript split=true height=100} * // Changing the x coordinate of an item's position: * * // Create a circle at position { x: 20, y: 20 } * var circle = new Path.Circle({ * center: new Point(20, 20), * radius: 10, * fillColor: 'red' * }); * * // Move the circle 100 points to the right * circle.position.x += 100; */ getPosition: function(/* dontLink */) { // Cache position value. // Pass true for dontLink in getCenter(), so receive back a normal point var pos = this._position || (this._position = this.getBounds().getCenter(true)); // Do not cache LinkedPoints directly, since we would not be able to // use them to calculate the difference in #setPosition, as when it is // modified, it would hold new values already and only then cause the // calling of #setPosition. return new (arguments[0] ? Point : LinkedPoint) (pos.x, pos.y, this, 'setPosition'); }, setPosition: function(/* point */) { // Calculate the distance to the current position, by which to // translate the item. Pass true for dontLink, as we do not need a // LinkedPoint to simply calculate this distance. this.translate(Point.read(arguments).subtract(this.getPosition(true))); }, /** * The item's transformation matrix, defining position and dimensions in * relation to its parent item in which it is contained. * * @type Matrix * @bean */ getMatrix: function() { return this._matrix; }, setMatrix: function(matrix) { // Use Matrix#initialize to easily copy over values. this._matrix.initialize(matrix); if (this._transformContent) this.applyMatrix(true); this._changed(/*#=*/ Change.GEOMETRY); }, /** * The item's global transformation matrix in relation to the global project * coordinate space. * * @type Matrix * @bean */ getGlobalMatrix: function() { // TODO: if drawCount is out of sync, we still need to walk up the chain // and concatenate the matrices. return this._drawCount === this._project._drawCount && this._globalMatrix || null; }, /** * Converts the specified point from global project coordinates to local * coordinates in relation to the the item's own coordinate space. * * @param {Point} point the point to be transformed * @return {Point} the transformed point as a new instance */ globalToLocal: function(/* point */) { var matrix = this.getGlobalMatrix(); return matrix && matrix._transformPoint(Point.read(arguments)); }, /** * Converts the specified point from local coordinates to global coordinates * in relation to the the project coordinate space. * * @param {Point} point the point to be transformed * @return {Point} the transformed point as a new instance */ localToGlobal: function(/* point */) { var matrix = this.getGlobalMatrix(); return matrix && matrix._inverseTransform(Point.read(arguments)); }, /** * Specifies whether the item has any content or not. The meaning of what * content is differs from type to type. For example, a {@link Group} with * no children, a {@link TextItem} with no text content and a {@link Path} * with no segments all are considered empty. * * @type Boolean */ isEmpty: function() { return !this._children || this._children.length == 0; } }, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'], function(name) { // Produce getters for bounds properties. These handle caching, matrices // and redirect the call to the private _getBounds, which can be // overridden by subclasses, see below. this[name] = function(/* matrix */) { var getter = this._boundsGetter, // Allow subclasses to override _boundsGetter if they use // the same calculations for multiple type of bounds. // The default is name: bounds = this._getCachedBounds(typeof getter == 'string' ? getter : getter && getter[name] || name, arguments[0]); // If we're returning 'bounds', create a LinkedRectangle that uses // the setBounds() setter to update the Item whenever the bounds are // changed: return name === 'getBounds' ? new LinkedRectangle(bounds.x, bounds.y, bounds.width, bounds.height, this, 'setBounds') : bounds; }; }, /** @lends Item# */{ /** * Private method that deals with the calling of _getBounds, recursive * matrix concatenation and handles all the complicated caching mechanisms. */ _getCachedBounds: function(getter, matrix, cacheItem) { // See if we can cache these bounds. We only cache the bounds // transformed with the internally stored _matrix, (the default if no // matrix is passed). var cache = (!matrix || matrix.equals(this._matrix)) && getter; // Set up a boundsCache structure that keeps track of items that keep // cached bounds that depend on this item. We store this in our parent, // for multiple reasons: // The parent receives HIERARCHY change notifications for when its // children are added or removed and can thus clear the cache, and we // save a lot of memory, e.g. when grouping 100 items and asking the // group for its bounds. If stored on the children, we would have 100 // times the same structure. // Note: This needs to happen before returning cached values, since even // then, _boundsCache needs to be kept up-to-date. if (cacheItem && this._parent) { // Set-up the parent's boundsCache structure if it does not // exist yet and add the cacheItem to it. var id = cacheItem._id, ref = this._parent._boundsCache = this._parent._boundsCache || { // Use both a hashtable for ids and an array for the list, // so we can keep track of items that were added already ids: {}, list: [] }; if (!ref.ids[id]) { ref.list.push(cacheItem); ref.ids[id] = cacheItem; } } if (cache && this._bounds && this._bounds[cache]) return this._bounds[cache].clone(); // If the result of concatinating the passed matrix with our internal // one is an identity transformation, set it to null for faster // processing var identity = this._matrix.isIdentity(); matrix = !matrix || matrix.isIdentity() ? identity ? null : this._matrix : identity ? matrix : matrix.clone().concatenate(this._matrix); // If we're caching bounds on this item, pass it on as cacheItem, so the // children can setup the _boundsCache structures for it. var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem); // If we can cache the result, update the _bounds cache structure // before returning if (cache) { if (!this._bounds) this._bounds = {}; this._bounds[cache] = bounds.clone(); } return bounds; }, /** * Clears cached bounds of all items that the children of this item are * contributing to. See #_getCachedBounds() for an explanation why this * information is stored on parents, not the children themselves. */ _clearBoundsCache: function() { if (this._boundsCache) { for (var i = 0, list = this._boundsCache.list, l = list.length; i < l; i++) { var item = list[i]; delete item._bounds; // We need to recursively call _clearBoundsCache, because if the // cache for this item's children is not valid anymore, that // propagates up the DOM tree. if (item != this && item._boundsCache) item._clearBoundsCache(); } delete this._boundsCache; } }, /** * Protected method used in all the bounds getters. It loops through all the * children, gets their bounds and finds the bounds around all of them. * Subclasses override it to define calculations for the various required * bounding types. */ _getBounds: function(getter, matrix, cacheItem) { // Note: We cannot cache these results here, since we do not get // _changed() notifications here for changing geometry in children. // But cacheName is used in sub-classes such as PlacedSymbol and Raster. var children = this._children; // TODO: What to return if nothing is defined, e.g. empty Groups? // Scriptographer behaves weirdly then too. if (!children || children.length == 0) return new Rectangle(); var x1 = Infinity, x2 = -x1, y1 = x1, y2 = x2; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; if (child._visible && !child.isEmpty()) { var rect = child._getCachedBounds(getter, matrix, cacheItem); x1 = Math.min(rect.x, x1); y1 = Math.min(rect.y, y1); x2 = Math.max(rect.x + rect.width, x2); y2 = Math.max(rect.y + rect.height, y2); } } return isFinite(x1) ? new Rectangle(x1, y1, x2 - x1, y2 - y1) : new Rectangle(); }, setBounds: function(rect) { rect = Rectangle.read(arguments); var bounds = this.getBounds(), matrix = new Matrix(), center = rect.getCenter(); // Read this from bottom to top: // Translate to new center: matrix.translate(center); // Scale to new Size, if size changes and avoid divisions by 0: if (rect.width != bounds.width || rect.height != bounds.height) { matrix.scale( bounds.width != 0 ? rect.width / bounds.width : 1, bounds.height != 0 ? rect.height / bounds.height : 1); } // Translate to bounds center: center = bounds.getCenter(); matrix.translate(-center.x, -center.y); // Now execute the transformation this.transform(matrix); } /** * The bounding rectangle of the item excluding stroke width. * * @name Item#getBounds * @type Rectangle * @bean */ /** * The bounding rectangle of the item including stroke width. * * @name Item#getStrokeBounds * @type Rectangle * @bean */ /** * The bounding rectangle of the item including handles. * * @name Item#getHandleBounds * @type Rectangle * @bean */ /** * The rough bounding rectangle of the item that is shure to include all of * the drawing, including stroke width. * * @name Item#getRoughBounds * @type Rectangle * @bean * @ignore */ }), /** @lends Item# */{ /** * {@grouptitle Project Hierarchy} * The project that this item belongs to. * * @type Project * @bean */ getProject: function() { return this._project; }, _setProject: function(project) { if (this._project != project) { this._project = project; if (this._children) { for (var i = 0, l = this._children.length; i < l; i++) { this._children[i]._setProject(project); } } } }, /** * The layer that this item is contained within. * * @type Layer * @bean */ getLayer: function() { var parent = this; while (parent = parent._parent) { if (parent instanceof Layer) return parent; } return null; }, /** * The item that this item is contained within. * * @type Item * @bean * * @example * var path = new Path(); * * // New items are placed in the active layer: * console.log(path.parent == project.activeLayer); // true * * var group = new Group(); * group.addChild(path); * * // Now the parent of the path has become the group: * console.log(path.parent == group); // true * * @example // Setting the parent of the item to another item * var path = new Path(); * * // New items are placed in the active layer: * console.log(path.parent == project.activeLayer); // true * * var group = new Group(); * group.parent = path; * * // Now the parent of the path has become the group: * console.log(path.parent == group); // true * * // The path is now contained in the children list of group: * console.log(group.children[0] == path); // true * * @example // Setting the parent of an item in the constructor * var group = new Group(); * * var path = new Path({ * parent: group * }); * * // The parent of the path is the group: * console.log(path.parent == group); // true * * // The path is contained in the children list of group: * console.log(group.children[0] == path); // true */ getParent: function() { return this._parent; }, setParent: function(item) { return item.addChild(this); }, /** * The children items contained within this item. Items that define a * {@link #name} can also be accessed by name. * * <b>Please note:</b> The children array should not be modified directly * using array functions. To remove single items from the children list, use * {@link Item#remove()}, to remove all items from the children list, use * {@link Item#removeChildren()}. To add items to the children list, use * {@link Item#addChild(item)} or {@link Item#insertChild(index,item)}. * * @type Item[] * @bean * * @example {@paperscript} * // Accessing items in the children array: * var path = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * * // Create a group and move the path into it: * var group = new Group(); * group.addChild(path); * * // Access the path through the group's children array: * group.children[0].fillColor = 'red'; * * @example {@paperscript} * // Accessing children by name: * var path = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * // Set the name of the path: * path.name = 'example'; * * // Create a group and move the path into it: * var group = new Group(); * group.addChild(path); * * // The path can be accessed by name: * group.children['example'].fillColor = 'orange'; * * @example {@paperscript} * // Passing an array of items to item.children: * var path = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * * var group = new Group(); * group.children = [path]; * * // The path is the first child of the group: * group.firstChild.fillColor = 'green'; */ getChildren: function() { return this._children; }, setChildren: function(items) { this.removeChildren(); this.addChildren(items); }, /** * The first item contained within this item. This is a shortcut for * accessing {@code item.children[0]}. * * @type Item * @bean */ getFirstChild: function() { return this._children && this._children[0] || null; }, /** * The last item contained within this item.This is a shortcut for * accessing {@code item.children[item.children.length - 1]}. * * @type Item * @bean */ getLastChild: function() { return this._children && this._children[this._children.length - 1] || null; }, /** * The next item on the same level as this item. * * @type Item * @bean */ getNextSibling: function() { return this._parent && this._parent._children[this._index + 1] || null; }, /** * The previous item on the same level as this item. * * @type Item * @bean */ getPreviousSibling: function() { return this._parent && this._parent._children[this._index - 1] || null; }, /** * The index of this item within the list of its parent's children. * * @type Number * @bean */ getIndex: function() { return this._index; }, /** * Checks whether the item and all its parents are inserted into the DOM or * not. * * @return {Boolean} {@true if the item is inserted into the DOM} */ isInserted: function() { return this._parent ? this._parent.isInserted() : false; }, equals: function(item) { // Note: We do not compare name and selected state. return item === this || item && this._class === item._class && this._style.equals(item._style) && this._matrix.equals(item._matrix) && this._locked === item._locked && this._visible === item._visible && this._blendMode === item._blendMode && this._opacity === item._opacity && this._clipMask === item._clipMask && this._guide === item._guide && this._equals(item) || false; }, /** * A private helper for #equals(), to be overridden in sub-classes. When it * is called, item is always defined, of the same class as `this` and has * equal general state attributes such as matrix, style, opacity, etc. */ _equals: function(item) { return Base.equals(this._children, item._children); }, /** * Clones the item within the same project and places the copy above the * item. * * @param {Boolean} [insert=true] specifies whether the copy should be * inserted into the DOM. When set to {@code true}, it is inserted above the * original. * @return {Item} the newly cloned item * * @example {@paperscript} * // Cloning items: * var circle = new Path.Circle({ * center: [50, 50], * radius: 10, * fillColor: 'red' * }); * * // Make 20 copies of the circle: * for (var i = 0; i < 20; i++) { * var copy = circle.clone(); * * // Distribute the copies horizontally, so we can see them: * copy.position.x += i * copy.bounds.width; * } */ clone: function(insert) { return this._clone(new this.constructor({ insert: false }), insert); }, _clone: function(copy, insert) { // Copy over style copy.setStyle(this._style); // If this item has children, clone and append each of them: if (this._children) { // Clone all children and add them to the copy. tell #addChild we're // cloning, as needed by CompoundPath#insertChild(). for (var i = 0, l = this._children.length; i < l; i++) copy.addChild(this._children[i].clone(false), true); } // Insert is true by default. if (insert || insert === undefined) copy.insertAbove(this); // Only copy over these fields if they are actually defined in 'this', // meaning the default value has been overwritten (default is on // prototype). var keys = ['_locked', '_visible', '_blendMode', '_opacity', '_clipMask', '_guide']; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (this.hasOwnProperty(key)) copy[key] = this[key]; } // Use Matrix#initialize to easily copy over values. copy._matrix.initialize(this._matrix); // Copy over the selection state, use setSelected so the item // is also added to Project#selectedItems if it is selected. copy.setSelected(this._selected); // Clone the name too, but make sure we're not overriding the original // in the same parent, by passing true for the unique parameter. if (this._name) copy.setName(this._name, true); return copy; }, /** * When passed a project, copies the item to the project, * or duplicates it within the same project. When passed an item, * copies the item into the specified item. * * @param {Project|Layer|Group|CompoundPath} item the item or project to * copy the item to * @return {Item} the new copy of the item */ copyTo: function(itemOrProject) { var copy = this.clone(); if (itemOrProject.layers) { itemOrProject.activeLayer.addChild(copy); } else { itemOrProject.addChild(copy); } return copy; }, /** * Rasterizes the item into a newly created Raster object. The item itself * is not removed after rasterization. * * @param {Number} [resolution=72] the resolution of the raster in dpi * @return {Raster} the newly created raster item * * @example {@paperscript} * // Rasterizing an item: * var circle = new Path.Circle({ * center: [50, 50], * radius: 5, * fillColor: 'red' * }); * * // Create a rasterized version of the path: * var raster = circle.rasterize(); * * // Move it 100pt to the right: * raster.position.x += 100; * * // Scale the path and the raster by 300%, so we can compare them: * circle.scale(5); * raster.scale(5); */ rasterize: function(resolution) { var bounds = this.getStrokeBounds(), scale = (resolution || 72) / 72, // floor top-left corner and ceil bottom-right corner, to never // blur or cut pixels. topLeft = bounds.getTopLeft().floor(), bottomRight = bounds.getBottomRight().ceil() size = new Size(bottomRight.subtract(topLeft)), canvas = CanvasProvider.getCanvas(size), ctx = canvas.getContext('2d'), matrix = new Matrix().scale(scale).translate(topLeft.negate()); ctx.save(); matrix.applyToContext(ctx); // See Project#draw() for an explanation of Base.merge() this.draw(ctx, Base.merge({ transforms: [matrix] })); ctx.restore(); var raster = new Raster({ canvas: canvas, insert: false }); raster.setPosition(topLeft.add(size.divide(2))); raster.insertAbove(this); // NOTE: We don't need to release the canvas since it now belongs to the // Raster! return raster; }, /** * Checks whether the item's geometry contains the given point. * * @example {@paperscript} // Click within and outside the star below * // Create a star shaped path: * var path = new Path.Star({ * center: [50, 50], * points: 12, * radius1: 20, * radius2: 40, * fillColor: 'black' * }); * * // Whenever the user presses the mouse: * function onMouseDown(event) { * // If the position of the mouse is within the path, * // set its fill color to red, otherwise set it to * // black: * if (path.contains(event.point)) { * path.fillColor = 'red'; * } else { * path.fillColor = 'black'; * } * } * * @param {Point} point The point to check for. */ contains: function(/* point */) { // See CompoundPath#_contains() for the reason for !! return !!this._contains( this._matrix._inverseTransform(Point.read(arguments))); }, _contains: function(point) { if (this._children) { for (var i = this._children.length - 1; i >= 0; i--) { if (this._children[i].contains(point)) return true; } return false; } // We only implement it here for items with rectangular content, // for anything else we need to override #contains() // TODO: There currently is no caching for the results of direct calls // to this._getBounds('getBounds') (without the application of the // internal matrix). Performance improvements could be achieved if // these were cached too. See #_getCachedBounds(). return point.isInside(this._getBounds('getBounds')); }, /** * Perform a hit test on the item (and its children, if it is a * {@link Group} or {@link Layer}) at the location of the specified point. * * The options object allows you to control the specifics of the hit test * and may contain a combination of the following values: * <b>options.tolerance:</b> {@code Number} – the tolerance of the hit test * in points. Can also be controlled through * {@link Project#options}{@code .hitTolerance}. * <b>options.type:</b> Only hit test again a certain item * type: {@link PathItem}, {@link Raster}, {@link TextItem}, etc. * <b>options.fill:</b> {@code Boolean} – hit test the fill of items. * <b>options.stroke:</b> {@code Boolean} – hit test the curves of path * items, taking into account stroke width. * <b>options.segment:</b> {@code Boolean} – hit test for * {@link Segment#point} of {@link Path} items. * <b>options.handles:</b> {@code Boolean} – hit test for the handles * ({@link Segment#handleIn} / {@link Segment#handleOut}) of path segments. * <b>options.ends:</b> {@code Boolean} – only hit test for the first or * last segment points of open path items. * <b>options.bounds:</b> {@code Boolean} – hit test the corners and * side-centers of the bounding rectangle of items ({@link Item#bounds}). * <b>options.center:</b> {@code Boolean} – hit test the * {@link Rectangle#center} of the bounding rectangle of items * ({@link Item#bounds}). * <b>options.guides:</b> {@code Boolean} – hit test items that have * {@link Item#guide} set to {@code true}. * <b>options.selected:</b> {@code Boolean} – only hit selected items.<b * * @param {Point} point The point where the hit test should be performed * @param {Object} [options={ fill: true, stroke: true, segments: true, * tolerance: 2 }] * @return {HitResult} a hit result object that contains more * information about what exactly was hit or {@code null} if nothing was * hit */ hitTest: function(point, options) { point = Point.read(arguments); options = HitResult.getOptions(Base.read(arguments)); if (this._locked || !this._visible || this._guide && !options.guides) return null; // Check if the point is withing roughBounds + tolerance, but only if // this item does not have children, since we'd have to travel up the // chain already to determine the rough bounds. if (!this._children && !this.getRoughBounds() .expand(2 * options.tolerance)._containsPoint(point)) return null; // Transform point to local coordinates but use untransformed point // for bounds check above. point = this._matrix._inverseTransform(point); var that = this, res; function checkBounds(type, part) { var pt = bounds['get' + part](); // TODO: We need to transform the point back to the coordinate // system of the DOM level on which the inquiry was started! if (point.getDistance(pt) < options.tolerance) return new HitResult(type, that, { name: Base.hyphenate(part), point: pt }); } if ((options.center || options.bounds) && // Ignore top level layers: !(this instanceof Layer && !this._parent)) { // Don't get the transformed bounds, check against transformed // points instead var bounds = this._getBounds('getBounds'); if (options.center) res = checkBounds('center', 'Center'); if (!res && options.bounds) { // TODO: Move these into a private scope var points = [ 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter' ]; for (var i = 0; i < 8 && !res; i++) res = checkBounds('bounds', points[i]); } } // TODO: Support option.type even for things like CompoundPath where // children are matched but the parent is returned. // Filter for guides or selected items if that's required if ((res || (res = this._children || !(options.guides && !this._guide || options.selected && !this._selected) ? this._hitTest(point, options) : null)) && res.point) { // Transform the point back to the outer coordinate system. res.point = that._matrix.transform(res.point); } return res; }, _hitTest: function(point, options) { var children = this._children; if (children) { // Loop backwards, so items that get drawn last are tested first for (var i = children.length - 1, res; i >= 0; i--) if (res = children[i].hitTest(point, options)) return res; } else if (options.fill && this.hasFill() && this._contains(point)) { return new HitResult('fill', this); } }, // DOCS: Item#matches matches: function(match) { // matchObject() is used to match against objects in a nested manner. // This is useful for matching against Item#data. function matchObject(obj1, obj2) { for (var i in obj1) { if (obj1.hasOwnProperty(i)) { var val1 = obj1[i], val2 = obj2[i]; if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) { if (!matchObject(val1, val2)) return false; } else if (!Base.equals(val1, val2)) { return false; } } } return true; } for (var key in match) { if (match.hasOwnProperty(key)) { var value = this[key], compare = match[key]; if (compare instanceof RegExp) { if (!compare.test(value)) return false; } else if (typeof compare === 'function') { if (!compare(value)) return false; } else if (Base.isPlainObject(compare)) { if (!matchObject(compare, value)) return false; } else if (!Base.equals(value, compare)) { return false; } } } return true; } }, new function() { function getItems(item, match, list) { var children = item._children, items = list && []; for (var i = 0, l = children && children.length; i < l; i++) { var child = children[i]; if (child.matches(match)) { if (list) { items.push(child); } else { return child; } } var res = getItems(child, match, list); if (list) { items.push.apply(items, res); } else if (res) { return res; } } return list ? items : null; } return /** @lends Item# */{ // DOCS: Item#getItems getItems: function(match) { return getItems(this, match, true); }, // DOCS: Item#getItem getItem: function(match) { return getItems(this, match, false); } }; }, /** @lends Item# */{ /** * {@grouptitle Importing / Exporting JSON and SVG} * * Exports (serializes) the item with its content and child items to a JSON * data string. * * The options object offers control over some aspects of the SVG export: * <b>options.precision:</b> {@code Number} – the amount of fractional * digits in numbers used in JSON data. * * @name Item#exportJSON * @function * @param {Object} [options={ precision: 5 }] the serialization options * @return {String} the exported JSON data */ /** * Imports (deserializes) the stored JSON data into this item. If the data * describes an item of the same class or a parent class of the item, the * data is imported into the item itself. If not, the imported item is added * to this item's {@link Item#children} list. Note that not all type of * items can have children. * * @param {String} json the JSON data to import from. */ importJSON: function(json) { // Try importing into `this`. If another item is returned, try adding // it as a child (this won't be successful on some classes, returning // null). var res = Base.importJSON(json, this); return res !== this ? this.addChild(res) : res; }, /** * Exports the item with its content and child items as an SVG DOM. * * The options object offers control over some aspects of the SVG export: * <b>options.asString:</b> {@code Boolean} – wether a SVG node or a String * is to be returned. * <b>options.precision:</b> {@code Number} – the amount of fractional * digits in numbers used in SVG data. * <b>options.matchShapes:</b> {@code Boolean} – wether imported path * items should tried to be converted to shape items, if their geometries * match. * * @name Item#exportSVG * @function * @param {Object} [options={ asString: false, precision: 5, * matchShapes: false }] the export options. * @return {SVGSVGElement} the item converted to an SVG node */ /** * Converts the provided SVG content into Paper.js items and adds them to * the this item's children list. * Note that the item is not cleared first. You can call * {@link Item#removeChildren()} to do so. * * The options object offers control over some aspects of the SVG import: * <b>options.expandShapes:</b> {@code Boolean} – wether imported shape * items should be expanded to path items. * * @name Item#importSVG * @function * @param {SVGSVGElement|String} svg the SVG content to import * @param {Object} [options={ expandShapes: false }] the import options * @return {Item} the imported Paper.js parent item */ /** * {@grouptitle Hierarchy Operations} * Adds the specified item as a child of this item at the end of the * its children list. You can use this function for groups, compound * paths and layers. * * @param {Item} item the item to be added as a child * @return {Item} the added item, or {@code null} if adding was not * possible. */ addChild: function(item, _preserve) { return this.insertChild(undefined, item, _preserve); }, /** * Inserts the specified item as a child of this item at the specified * index in its {@link #children} list. You can use this function for * groups, compound paths and layers. * * @param {Number} index * @param {Item} item the item to be inserted as a child * @return {Item} the inserted item, or {@code null} if inserting was not * possible. */ insertChild: function(index, item, _preserve) { var res = this.insertChildren(index, [item], _preserve); return res && res[0]; }, /** * Adds the specified items as children of this item at the end of the * its children list. You can use this function for groups, compound * paths and layers. * * @param {Item[]} items The items to be added as children * @return {Item[]} the added items, or {@code null} if adding was not * possible. */ addChildren: function(items, _preserve) { return this.insertChildren(this._children.length, items, _preserve); }, /** * Inserts the specified items as children of this item at the specified * index in its {@link #children} list. You can use this function for * groups, compound paths and layers. * * @param {Number} index * @param {Item[]} items The items to be appended as children * @return {Item[]} the inserted items, or {@code null} if inserted was not * possible. */ insertChildren: function(index, items, _preserve, _type) { // CompoundPath#insertChildren() requires _preserve and _type: // _preserve avoids changing of the children's path orientation // _type enforces the inserted type. var children = this._children; if (children && items && items.length > 0) { // We need to clone items because it might be // an Item#children array. Also, we're removing elements if they // don't match _type. Use Array.prototype.slice becaus items can be // an arguments object. items = Array.prototype.slice.apply(items); // Remove the items from their parents first, since they might be // inserted into their own parents, affecting indices. // Use the loop also to filter out wrong _type. for (var i = items.length - 1; i >= 0; i--) { var item = items[i]; if (_type && item._type !== _type) items.splice(i, 1); else item._remove(true); } Base.splice(children, items, index, 0); for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; item._parent = this; item._setProject(this._project); // Setting the name again makes sure all name lookup structures // are kept in sync. if (item._name) item.setName(item._name); } this._changed(/*#=*/ Change.HIERARCHY); } else { items = null; } return items; }, // Private helper for #insertAbove() / #insertBelow() _insert: function(above, item, _preserve) { if (!item._parent) return null; var index = item._index + (above ? 1 : 0); // If the item is removed and inserted it again further above, // the index needs to be adjusted accordingly. if (item._parent === this._parent && index > this._index) index--; return item._parent.insertChild(index, this, _preserve); }, /** * Inserts this item above the specified item. * * @param {Item} item the item above which it should be inserted * @return {Item} the inserted item, or {@code null} if inserting was not * possible. */ insertAbove: function(item, _preserve) { return this._insert(true, item, _preserve); }, /** * Inserts this item below the specified item. * * @param {Item} item the item above which it should be inserted * @return {Item} the inserted item, or {@code null} if inserting was not * possible. */ insertBelow: function(item, _preserve) { return this._insert(false, item, _preserve); }, /** * Sends this item to the back of all other items within the same parent. */ sendToBack: function() { return this._parent.insertChild(0, this); }, /** * Brings this item to the front of all other items within the same parent. */ bringToFront: function() { return this._parent.addChild(this); }, /** * Inserts the specified item as a child of this item by appending it to * the list of children and moving it above all other children. You can * use this function for groups, compound paths and layers. * * @param {Item} item The item to be appended as a child * @deprecated use {@link #addChild(item)} instead. */ appendTop: '#addChild', /** * Inserts the specified item as a child of this item by appending it to * the list of children and moving it below all other children. You can * use this function for groups, compound paths and layers. * * @param {Item} item The item to be appended as a child * @deprecated use {@link #insertChild(index, item)} instead. */ appendBottom: function(item) { return this.insertChild(0, item); }, /** * Moves this item above the specified item. * * @param {Item} item The item above which it should be moved * @return {Boolean} {@true it was moved} * @deprecated use {@link #insertAbove(item)} instead. */ moveAbove: '#insertAbove', /** * Moves the item below the specified item. * * @param {Item} item the item below which it should be moved * @return {Boolean} {@true it was moved} * @deprecated use {@link #insertBelow(item)} instead. */ moveBelow: '#insertBelow', /** * If this is a group, layer or compound-path with only one child-item, * the child-item is moved outside and the parent is erased. Otherwise, the * item itself is returned unmodified. * * @return {Item} the reduced item */ reduce: function() { if (this._children && this._children.length === 1) { var child = this._children[0]; child.insertAbove(this); this.remove(); return child; } return this; }, /** * Removes the item from its parent's named children list. */ _removeNamed: function() { var children = this._parent._children, namedChildren = this._parent._namedChildren, name = this._name, namedArray = namedChildren[name], index = namedArray ? namedArray.indexOf(this) : -1; if (index == -1) return; // Remove the named reference if (children[name] == this) delete children[name]; // Remove this entry namedArray.splice(index, 1); // If there are any items left in the named array, set // the last of them to be this.parent.children[this.name] if (namedArray.length) { children[name] = namedArray[namedArray.length - 1]; } else { // Otherwise delete the empty array delete namedChildren[name]; } }, /** * Removes the item from its parent's children list. */ _remove: function(notify) { if (this._parent) { if (this._name) this._removeNamed(); if (this._index != null) Base.splice(this._parent._children, null, this._index, 1); // Notify parent of changed hierarchy if (notify) this._parent._changed(/*#=*/ Change.HIERARCHY); this._parent = null; return true; } return false; }, /** * Removes the item from the project. If the item has children, they are also * removed. * * @return {Boolean} {@true the item was removed} */ remove: function() { return this._remove(true); }, /** * Removes all of the item's {@link #children} (if any). * * @name Item#removeChildren * @alias Item#clear * @function * @return {Item[]} an array containing the removed items */ /** * Removes the children from the specified {@code from} index to the * {@code to} index from the parent's {@link #children} array. * * @name Item#removeChildren * @function * @param {Number} from the beginning index, inclusive * @param {Number} [to=children.length] the ending index, exclusive * @return {Item[]} an array containing the removed items */ removeChildren: function(from, to) { if (!this._children) return null; from = from || 0; to = Base.pick(to, this._children.length); // Use Base.splice(), wich adjusts #_index for the items above, and // deletes it for the removed items. Calling #_remove() afterwards is // fine, since it only calls Base.splice() if #_index is set. var removed = Base.splice(this._children, null, from, to - from); for (var i = removed.length - 1; i >= 0; i--) removed[i]._remove(false); if (removed.length > 0) this._changed(/*#=*/ Change.HIERARCHY); return removed; }, clear: '#removeChildren', /** * Reverses the order of the item's children */ reverseChildren: function() { if (this._children) { this._children.reverse(); // Adjust inidces for (var i = 0, l = this._children.length; i < l; i++) this._children[i]._index = i; this._changed(/*#=*/ Change.HIERARCHY); } }, // TODO: Item#isEditable is currently ignored in the documentation, as // locking an item currently has no effect /** * {@grouptitle Tests} * Checks whether the item is editable. * * @return {Boolean} {@true when neither the item, nor its parents are * locked or hidden} * @ignore */ isEditable: function() { var item = this; while (item) { if (!item._visible || item._locked) return false; item = item._parent; } return true; }, /** * Checks whether the item is valid, i.e. it hasn't been removed. * * @return {Boolean} {@true the item is valid} */ // TODO: isValid / checkValid /** * Returns -1 if 'this' is above 'item', 1 if below, 0 if their order is not * defined in such a way, e.g. if one is a descendant of the other. */ _getOrder: function(item) { // Private method that produces a list of anchestors, starting with the // root and ending with the actual element as the last entry. function getList(item) { var list = []; do { list.unshift(item); } while (item = item._parent); return list; } var list1 = getList(this), list2 = getList(item); for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) { if (list1[i] != list2[i]) { // Found the position in the parents list where the two start // to differ. Look at who's above who. return list1[i]._index < list2[i]._index ? 1 : -1; } } return 0; }, /** * {@grouptitle Hierarchy Tests} * * Checks if the item contains any children items. * * @return {Boolean} {@true it has one or more children} */ hasChildren: function() { return this._children && this._children.length > 0; }, /** * Checks if this item is above the specified item in the stacking order * of the project. * * @param {Item} item The item to check against * @return {Boolean} {@true if it is above the specified item} */ isAbove: function(item) { return this._getOrder(item) === -1; }, /** * Checks if the item is below the specified item in the stacking order of * the project. * * @param {Item} item The item to check against * @return {Boolean} {@true if it is below the specified item} */ isBelow: function(item) { return this._getOrder(item) === 1; }, /** * Checks whether the specified item is the parent of the item. * * @param {Item} item The item to check against * @return {Boolean} {@true if it is the parent of the item} */ isParent: function(item) { return this._parent === item; }, /** * Checks whether the specified item is a child of the item. * * @param {Item} item The item to check against * @return {Boolean} {@true it is a child of the item} */ isChild: function(item) { return item && item._parent === this; }, /** * Checks if the item is contained within the specified item. * * @param {Item} item The item to check against * @return {Boolean} {@true if it is inside the specified item} */ isDescendant: function(item) { var parent = this; while (parent = parent._parent) { if (parent == item) return true; } return false; }, /** * Checks if the item is an ancestor of the specified item. * * @param {Item} item the item to check against * @return {Boolean} {@true if the item is an ancestor of the specified * item} */ isAncestor: function(item) { return item ? item.isDescendant(this) : false; }, /** * Checks whether the item is grouped with the specified item. * * @param {Item} item * @return {Boolean} {@true if the items are grouped together} */ isGroupedWith: function(item) { var parent = this._parent; while (parent) { // Find group parents. Check for parent._parent, since don't want // top level layers, because they also inherit from Group if (parent._parent && /^(group|layer|compound-path)$/.test(parent._type) && item.isDescendant(parent)) return true; // Keep walking up otherwise parent = parent._parent; } return false; }, // Document all style properties which get injected into Item by Style: /** * {@grouptitle Stroke Style} * * The color of the stroke. * * @name Item#strokeColor * @property * @type Color * * @example {@paperscript} * // Setting the stroke color of a path: * * // Create a circle shaped path at { x: 80, y: 50 } * // with a radius of 35: * var circle = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * * // Set its stroke color to RGB red: * circle.strokeColor = new Color(1, 0, 0); */ /** * The width of the stroke. * * @name Item#strokeWidth * @property * @type Number * * @example {@paperscript} * // Setting an item's stroke width: * * // Create a circle shaped path at { x: 80, y: 50 } * // with a radius of 35: * var circle = new Path.Circle({ * center: [80, 50], * radius: 35, * strokeColor: 'red' * }); * * // Set its stroke width to 10: * circle.strokeWidth = 10; */ /** * The shape to be used at the end of open {@link Path} items, when they * have a stroke. * * @name Item#strokeCap * @property * @default 'butt' * @type String('round', 'square', 'butt') * * @example {@paperscript height=200} * // A look at the different stroke caps: * * var line = new Path({ * segments: [[80, 50], [420, 50]], * strokeColor: 'black', * strokeWidth: 20, * selected: true * }); * * // Set the stroke cap of the line to be round: * line.strokeCap = 'round'; * * // Copy the path and set its stroke cap to be square: * var line2 = line.clone(); * line2.position.y += 50; * line2.strokeCap = 'square'; * * // Make another copy and set its stroke cap to be butt: * var line2 = line.clone(); * line2.position.y += 100; * line2.strokeCap = 'butt'; */ /** * The shape to be used at the corners of paths when they have a stroke. * * @name Item#strokeJoin * @property * @default 'miter' * @type String('miter', 'round', 'bevel') * * * @example {@paperscript height=120} * // A look at the different stroke joins: * var path = new Path({ * segments: [[80, 100], [120, 40], [160, 100]], * strokeColor: 'black', * strokeWidth: 20, * // Select the path, in order to see where the stroke is formed: * selected: true * }); * * var path2 = path.clone(); * path2.position.x += path2.bounds.width * 1.5; * path2.strokeJoin = 'round'; * * var path3 = path2.clone(); * path3.position.x += path3.bounds.width * 1.5; * path3.strokeJoin = 'bevel'; */ /** * The dash offset of the stroke. * * @name Item#dashOffset * @property * @default 0 * @type Number */ /** * Specifies an array containing the dash and gap lengths of the stroke. * * @example {@paperscript} * var path = new Path.Circle({ * center: [80, 50], * radius: 40, * strokeWidth: 2, * strokeColor: 'black' * }); * * // Set the dashed stroke to [10pt dash, 4pt gap]: * path.dashArray = [10, 4]; * * @name Item#dashArray * @property * @default [] * @type Array */ /** * The miter limit of the stroke. * When two line segments meet at a sharp angle and miter joins have been * specified for {@link Item#strokeJoin}, it is possible for the miter to * extend far beyond the {@link Item#strokeWidth} of the path. The * miterLimit imposes a limit on the ratio of the miter length to the * {@link Item#strokeWidth}. * * @property * @name Item#miterLimit * @default 10 * @type Number */ /** * The winding-rule with which the shape gets filled. Please note that only * modern browsers support winding-rules other than {@code 'nonzero'}. * * @property * @name Item#windingRule * @default 'nonzero' * @type String('nonzero', 'evenodd') */ /** * {@grouptitle Fill Style} * * The fill color of the item. * * @name Item#fillColor * @property * @type Color * * @example {@paperscript} * // Setting the fill color of a path to red: * * // Create a circle shaped path at { x: 80, y: 50 } * // with a radius of 35: * var circle = new Path.Circle({ * center: [80, 50], * radius: 35 * }); * * // Set the fill color of the circle to RGB red: * circle.fillColor = new Color(1, 0, 0); */ // TODO: Find a better name than selectedColor. It should also be used for // guides, etc. /** * {@grouptitle Selection Style} * * The color the item is highlighted with when selected. If the item does * not specify its own color, the color defined by its layer is used instead. * * @name Item#selectedColor * @property * @type Color */ // DOCS: Document the different arguments that this function can receive. /** * {@grouptitle Transform Functions} * * Scales the item by the given value from its center point, or optionally * from a supplied point. * * @name Item#scale * @function * @param {Number} scale the scale factor * @param {Point} [center={@link Item#position}] * * @example {@paperscript} * // Scaling an item from its center point: * * // Create a circle shaped path at { x: 80, y: 50 } * // with a radius of 20: * var circle = new Path.Circle({ * center: [80, 50], * radius: 20, * fillColor: 'red' * }); * * // Scale the path by 150% from its center point * circle.scale(1.5); * * @example {@paperscript} * // Scaling an item from a specific point: * * // Create a circle shaped path at { x: 80, y: 50 } * // with a radius of 20: * var circle = new Path.Circle({ * center: [80, 50], * radius: 20, * fillColor: 'red' * }); * * // Scale the path 150% from its bottom left corner * circle.scale(1.5, circle.bounds.bottomLeft); */ /** * Scales the item by the given values from its center point, or optionally * from a supplied point. * * @name Item#scale * @function * @param {Number} hor the horizontal scale factor * @param {Number} ver the vertical scale factor * @param {Point} [center={@link Item#position}] * * @example {@paperscript} * // Scaling an item horizontally by 300%: * * // Create a circle shaped path at { x: 100, y: 50 } * // with a radius of 20: * var circle = new Path.Circle({ * center: [100, 50], * radius: 20, * fillColor: 'red' * }); * * // Scale the path horizontally by 300% * circle.scale(3, 1); */ scale: function(hor, ver /* | scale */, center) { // See Matrix#scale for explanation of this: if (arguments.length < 2 || typeof ver === 'object') { center = ver; ver = hor; } return this.transform(new Matrix().scale(hor, ver, center || this.getPosition(true))); }, /** * Translates (moves) the item by the given offset point. * * @param {Point} delta the offset to translate the item by */ translate: function(/* delta */) { var mx = new Matrix(); return this.transform(mx.translate.apply(mx, arguments)); }, /** * Rotates the item by a given angle around the given point. * * Angles are oriented clockwise and measured in degrees. * * @param {Number} angle the rotation angle * @param {Point} [center={@link Item#position}] * @see Matrix#rotate * * @example {@paperscript} * // Rotating an item: * * // Create a rectangle shaped path with its top left * // point at {x: 80, y: 25} and a size of {width: 50, height: 50}: * var path = new Path.Rectangle(new Point(80, 25), new Size(50, 50)); * path.fillColor = 'black'; * * // Rotate the path by 30 degrees: * path.rotate(30); * * @example {@paperscript height=200} * // Rotating an item around a specific point: * * // Create a rectangle shaped path with its top left * // point at {x: 175, y: 50} and a size of {width: 100, height: 100}: * var topLeft = new Point(175, 50); * var size = new Size(100, 100); * var path = new Path.Rectangle(topLeft, size); * path.fillColor = 'black'; * * // Draw a circle shaped path in the center of the view, * // to show the rotation point: * var circle = new Path.Circle({ * center: view.center, * radius: 5, * fillColor: 'white' * }); * * // Each frame rotate the path 3 degrees around the center point * // of the view: * function onFrame(event) { * path.rotate(3, view.center); * } */ rotate: function(angle, center) { return this.transform(new Matrix().rotate(angle, center || this.getPosition(true))); }, // TODO: Add test for item shearing, as it might be behaving oddly. /** * Shears the item by the given value from its center point, or optionally * by a supplied point. * * @name Item#shear * @function * @param {Point} point * @param {Point} [center={@link Item#position}] * @see Matrix#shear */ /** * Shears the item by the given values from its center point, or optionally * by a supplied point. * * @name Item#shear * @function * @param {Number} hor the horizontal shear factor. * @param {Number} ver the vertical shear factor. * @param {Point} [center={@link Item#position}] * @see Matrix#shear */ shear: function(hor, ver, center) { // See Matrix#scale for explanation of this: if (arguments.length < 2 || typeof ver === 'object') { center = ver; ver = hor; } return this.transform(new Matrix().shear(hor, ver, center || this.getPosition(true))); }, /** * Transform the item. * * @param {Matrix} matrix the matrix by which the item shall be transformed. */ // Remove this for now: // @param {String[]} flags Array of any of the following: 'objects', // 'children', 'fill-gradients', 'fill-patterns', 'stroke-patterns', // 'lines'. Default: ['objects', 'children'] transform: function(matrix /*, applyMatrix */) { // Calling _changed will clear _bounds and _position, but depending // on matrix we can calculate and set them again. var bounds = this._bounds, position = this._position; // Simply preconcatenate the internal matrix with the passed one: this._matrix.preConcatenate(matrix); // Call applyMatrix if we need to directly apply the accumulated // transformations to the item's content. if (this._transformContent || arguments[1]) this.applyMatrix(true); // We always need to call _changed since we're caching bounds on all // items, including Group. this._changed(/*#=*/ Change.GEOMETRY); // Detect matrices that contain only translations and scaling // and transform the cached _bounds and _position without having to // fully recalculate each time. if (bounds && matrix.getRotation() % 90 === 0) { // Transform the old bound by looping through all the cached bounds // in _bounds and transform each. for (var key in bounds) { var rect = bounds[key]; matrix._transformBounds(rect, rect); } // If we have cached bounds, update _position again as its // center. We need to take into account _boundsGetter here too, in // case another getter is assigned to it, e.g. 'getStrokeBounds'. var getter = this._boundsGetter, rect = bounds[getter && getter.getBounds || getter || 'getBounds']; if (rect) this._position = rect.getCenter(true); this._bounds = bounds; } else if (position) { // Transform position as well. this._position = matrix._transformPoint(position, position); } // Allow chaining here, since transform() is related to Matrix functions return this; }, _applyMatrix: function(matrix, applyMatrix) { var children = this._children; if (children && children.length > 0) { for (var i = 0, l = children.length; i < l; i++) children[i].transform(matrix, applyMatrix); return true; } }, applyMatrix: function(_dontNotify) { // Call #_applyMatrix() with the internal _matrix and pass true for // applyMatrix. Application is not possible on Raster, PointText, // PlacedSymbol, since the matrix is where the actual location / // transformation state is stored. // Pass on the transformation to the content, and apply it there too, // by passing true for the 2nd hidden parameter. var matrix = this._matrix; if (this._applyMatrix(matrix, true)) { // When the matrix could be applied, we also need to transform // color styles with matrices (only gradients so far): var style = this._style, // pass true for dontMerge so we don't recursively transform // styles on groups' children. fillColor = style.getFillColor(true), strokeColor = style.getStrokeColor(true); if (fillColor) fillColor.transform(matrix); if (strokeColor) strokeColor.transform(matrix); // Reset the internal matrix to the identity transformation if it // was possible to apply it. matrix.reset(); } if (!_dontNotify) this._changed(/*#=*/ Change.GEOMETRY); }, /** * Transform the item so that its {@link #bounds} fit within the specified * rectangle, without changing its aspect ratio. * * @param {Rectangle} rectangle * @param {Boolean} [fill=false] * * @example {@paperscript height=100} * // Fitting an item to the bounding rectangle of another item's bounding * // rectangle: * * // Create a rectangle shaped path with its top left corner * // at {x: 80, y: 25} and a size of {width: 75, height: 50}: * var path = new Path.Rectangle({ * point: [80, 25], * size: [75, 50], * fillColor: 'black' * }); * * // Create a circle shaped path with its center at {x: 80, y: 50} * // and a radius of 30. * var circlePath = new Path.Circle({ * center: [80, 50], * radius: 30, * fillColor: 'red' * }); * * // Fit the circlePath to the bounding rectangle of * // the rectangular path: * circlePath.fitBounds(path.bounds); * * @example {@paperscript height=100} * // Fitting an item to the bounding rectangle of another item's bounding * // rectangle with the fill parameter set to true: * * // Create a rectangle shaped path with its top left corner * // at {x: 80, y: 25} and a size of {width: 75, height: 50}: * var path = new Path.Rectangle({ * point: [80, 25], * size: [75, 50], * fillColor: 'black' * }); * * // Create a circle shaped path with its center at {x: 80, y: 50} * // and a radius of 30. * var circlePath = new Path.Circle({ * center: [80, 50], * radius: 30, * fillColor: 'red' * }); * * // Fit the circlePath to the bounding rectangle of * // the rectangular path: * circlePath.fitBounds(path.bounds, true); * * @example {@paperscript height=200} * // Fitting an item to the bounding rectangle of the view * var path = new Path.Circle({ * center: [80, 50], * radius: 30, * fillColor: 'red' * }); * * // Fit the path to the bounding rectangle of the view: * path.fitBounds(view.bounds); */ fitBounds: function(rectangle, fill) { // TODO: Think about passing options with various ways of defining // fitting. rectangle = Rectangle.read(arguments); var bounds = this.getBounds(), itemRatio = bounds.height / bounds.width, rectRatio = rectangle.height / rectangle.width, scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio) ? rectangle.width / bounds.width : rectangle.height / bounds.height, newBounds = new Rectangle(new Point(), new Size(bounds.width * scale, bounds.height * scale)); newBounds.setCenter(rectangle.getCenter()); this.setBounds(newBounds); }, /** * {@grouptitle Event Handlers} * Item level handler function to be called on each frame of an animation. * The function receives an event object which contains information about * the frame event: * * <b>{@code event.count}</b>: the number of times the frame event was * fired. * <b>{@code event.time}</b>: the total amount of time passed since the * first frame event in seconds. * <b>{@code event.delta}</b>: the time passed in seconds since the last * frame event. * * @see View#onFrame * @example {@paperscript} * // Creating an animation: * * // Create a rectangle shaped path with its top left point at: * // {x: 50, y: 25} and a size of {width: 50, height: 50} * var path = new Path.Rectangle(new Point(50, 25), new Size(50, 50)); * path.fillColor = 'black'; * * path.onFrame = function(event) { * // Every frame, rotate the path by 3 degrees: * this.rotate(3); * } * * @name Item#onFrame * @property * @type Function */ /** * The function to be called when the mouse button is pushed down on the * item. The function receives a {@link MouseEvent} object which contains * information about the mouse event. * * @name Item#onMouseDown * @property * @type Function * * @example {@paperscript} * // Press the mouse button down on the circle shaped path, to make it red: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse is pressed on the item, * // set its fill color to red: * path.onMouseDown = function(event) { * this.fillColor = 'red'; * } * * @example {@paperscript} * // Press the mouse on the circle shaped paths to remove them: * * // Loop 30 times: * for (var i = 0; i < 30; i++) { * // Create a circle shaped path at a random position * // in the view: * var path = new Path.Circle({ * center: Point.random() * view.size, * radius: 25, * fillColor: 'black', * strokeColor: 'white' * }); * * // When the mouse is pressed on the item, remove it: * path.onMouseDown = function(event) { * this.remove(); * } * } */ /** * The function to be called when the mouse button is released over the item. * The function receives a {@link MouseEvent} object which contains * information about the mouse event. * * @name Item#onMouseUp * @property * @type Function * * @example {@paperscript} * // Release the mouse button over the circle shaped path, to make it red: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse is released over the item, * // set its fill color to red: * path.onMouseUp = function(event) { * this.fillColor = 'red'; * } */ /** * The function to be called when the mouse clicks on the item. The function * receives a {@link MouseEvent} object which contains information about the * mouse event. * * @name Item#onClick * @property * @type Function * * @example {@paperscript} * // Click on the circle shaped path, to make it red: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse is clicked on the item, * // set its fill color to red: * path.onClick = function(event) { * this.fillColor = 'red'; * } * * @example {@paperscript} * // Click on the circle shaped paths to remove them: * * // Loop 30 times: * for (var i = 0; i < 30; i++) { * // Create a circle shaped path at a random position * // in the view: * var path = new Path.Circle({ * center: Point.random() * view.size, * radius: 25, * fillColor: 'black', * strokeColor: 'white' * }); * * // When the mouse clicks on the item, remove it: * path.onClick = function(event) { * this.remove(); * } * } */ /** * The function to be called when the mouse double clicks on the item. The * function receives a {@link MouseEvent} object which contains information * about the mouse event. * * @name Item#onDoubleClick * @property * @type Function * * @example {@paperscript} * // Double click on the circle shaped path, to make it red: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse is double clicked on the item, * // set its fill color to red: * path.onDoubleClick = function(event) { * this.fillColor = 'red'; * } * * @example {@paperscript} * // Double click on the circle shaped paths to remove them: * * // Loop 30 times: * for (var i = 0; i < 30; i++) { * // Create a circle shaped path at a random position * // in the view: * var path = new Path.Circle({ * center: Point.random() * view.size, * radius: 25, * fillColor: 'black', * strokeColor: 'white' * }); * * // When the mouse is double clicked on the item, remove it: * path.onDoubleClick = function(event) { * this.remove(); * } * } */ /** * The function to be called repeatedly when the mouse moves on top of the * item. The function receives a {@link MouseEvent} object which contains * information about the mouse event. * * @name Item#onMouseMove * @property * @type Function * * @example {@paperscript} * // Move over the circle shaped path, to change its opacity: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse moves on top of the item, set its opacity * // to a random value between 0 and 1: * path.onMouseMove = function(event) { * this.opacity = Math.random(); * } */ /** * The function to be called when the mouse moves over the item. This * function will only be called again, once the mouse moved outside of the * item first. The function receives a {@link MouseEvent} object which * contains information about the mouse event. * * @name Item#onMouseEnter * @property * @type Function * * @example {@paperscript} * // When you move the mouse over the item, its fill color is set to red. * // When you move the mouse outside again, its fill color is set back * // to black. * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse enters the item, set its fill color to red: * path.onMouseEnter = function(event) { * this.fillColor = 'red'; * } * * // When the mouse leaves the item, set its fill color to black: * path.onMouseLeave = function(event) { * this.fillColor = 'black'; * } * @example {@paperscript} * // When you click the mouse, you create new circle shaped items. When you * // move the mouse over the item, its fill color is set to red. When you * // move the mouse outside again, its fill color is set back * // to black. * * function enter(event) { * this.fillColor = 'red'; * } * * function leave(event) { * this.fillColor = 'black'; * } * * // When the mouse is pressed: * function onMouseDown(event) { * // Create a circle shaped path at the position of the mouse: * var path = new Path.Circle(event.point, 25); * path.fillColor = 'black'; * * // When the mouse enters the item, set its fill color to red: * path.onMouseEnter = enter; * * // When the mouse leaves the item, set its fill color to black: * path.onMouseLeave = leave; * } */ /** * The function to be called when the mouse moves out of the item. * The function receives a {@link MouseEvent} object which contains * information about the mouse event. * * @name Item#onMouseLeave * @property * @type Function * * @example {@paperscript} * // Move the mouse over the circle shaped path and then move it out * // of it again to set its fill color to red: * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse leaves the item, set its fill color to red: * path.onMouseLeave = function(event) { * this.fillColor = 'red'; * } */ /** * {@grouptitle Event Handling} * * Attaches an event handler to the item. * * @name Item#attach * @alias Item#on * @function * @param {String('mousedown', 'mouseup', 'mousedrag', 'click', * 'doubleclick', 'mousemove', 'mouseenter', 'mouseleave')} type the event * type * @param {Function} function The function to be called when the event * occurs * * @example {@paperscript} * // Change the fill color of the path to red when the mouse enters its * // shape and back to black again, when it leaves its shape. * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25, * fillColor: 'black' * }); * * // When the mouse enters the item, set its fill color to red: * path.on('mouseenter', function() { * this.fillColor = 'red'; * }); * * // When the mouse leaves the item, set its fill color to black: * path.on('mouseleave', function() { * this.fillColor = 'black'; * }); */ /** * Attaches one or more event handlers to the item. * * @name Item#attach * @alias Item#on * @function * @param {Object} object an object literal containing one or more of the * following properties: {@code mousedown, mouseup, mousedrag, click, * doubleclick, mousemove, mouseenter, mouseleave}. * * @example {@paperscript} * // Change the fill color of the path to red when the mouse enters its * // shape and back to black again, when it leaves its shape. * * // Create a circle shaped path at the center of the view: * var path = new Path.Circle({ * center: view.center, * radius: 25 * }); * path.fillColor = 'black'; * * // When the mouse enters the item, set its fill color to red: * path.on({ * mouseenter: function(event) { * this.fillColor = 'red'; * }, * mouseleave: function(event) { * this.fillColor = 'black'; * } * }); * @example {@paperscript} * // When you click the mouse, you create new circle shaped items. When you * // move the mouse over the item, its fill color is set to red. When you * // move the mouse outside again, its fill color is set black. * * var pathHandlers = { * mouseenter: function(event) { * this.fillColor = 'red'; * }, * mouseleave: function(event) { * this.fillColor = 'black'; * } * } * * // When the mouse is pressed: * function onMouseDown(event) { * // Create a circle shaped path at the position of the mouse: * var path = new Path.Circle({ * center: event.point, * radius: 25, * fillColor: 'black' * }); * * // Attach the handers inside the object literal to the path: * path.on(pathHandlers); * } */ /** * Detach an event handler from the item. * * @name Item#detach * @alias Item#off * @function * @param {String('mousedown', 'mouseup', 'mousedrag', 'click', * 'doubleclick', 'mousemove', 'mouseenter', 'mouseleave')} type the event * type * @param {Function} function The function to be detached */ /** * Detach one or more event handlers to the item. * * @name Item#detach * @alias Item#off * @function * @param {Object} object an object literal containing one or more of the * following properties: {@code mousedown, mouseup, mousedrag, click, * doubleclick, mousemove, mouseenter, mouseleave} */ /** * Fire an event on the item. * * @name Item#fire * @alias Item#trigger * @function * @param {String('mousedown', 'mouseup', 'mousedrag', 'click', * 'doubleclick', 'mousemove', 'mouseenter', 'mouseleave')} type the event * type * @param {Object} event an object literal containing properties describing * the event. */ /** * Check if the item has one or more event handlers of the specified type. * * @name Item#responds * @function * @param {String('mousedown', 'mouseup', 'mousedrag', 'click', * 'doubleclick', 'mousemove', 'mouseenter', 'mouseleave')} type the event * type * @return {Boolean} {@true if the item has one or more event handlers of * the specified type} */ /** * Private method that sets Path related styles on the canvas context. * Not defined in Path as it is required by other classes too, * e.g. PointText. */ _setStyles: function(ctx) { // We can access internal properties since we're only using this on // items without children, where styles would be merged. var style = this._style, fillColor = style.getFillColor(), strokeColor = style.getStrokeColor(), shadowColor = style.getShadowColor(); if (fillColor) ctx.fillStyle = fillColor.toCanvasStyle(ctx); if (strokeColor) { var strokeWidth = style.getStrokeWidth(); if (strokeWidth > 0) { ctx.strokeStyle = strokeColor.toCanvasStyle(ctx); ctx.lineWidth = strokeWidth; var strokeJoin = style.getStrokeJoin(), strokeCap = style.getStrokeCap(), miterLimit = style.getMiterLimit(); if (strokeJoin) ctx.lineJoin = strokeJoin; if (strokeCap) ctx.lineCap = strokeCap; if (miterLimit) ctx.miterLimit = miterLimit; if (paper.support.nativeDash) { var dashArray = style.getDashArray(), dashOffset = style.getDashOffset(); if (dashArray && dashArray.length) { if ('setLineDash' in ctx) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashOffset; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashOffset; } } } } } if (shadowColor) { var shadowBlur = style.getShadowBlur(); if (shadowBlur > 0) { ctx.shadowColor = shadowColor.toCanvasStyle(ctx); ctx.shadowBlur = shadowBlur; var offset = this.getShadowOffset(); ctx.shadowOffsetX = offset.x; ctx.shadowOffsetY = offset.y; } } }, // TODO: Implement View into the drawing. // TODO: Optimize temporary canvas drawing to ignore parts that are // outside of the visible view. draw: function(ctx, param) { if (!this._visible || this._opacity === 0) return; // Each time the project gets drawn, it's _drawCount is increased. // Keep the _drawCount of drawn items in sync, so we have an easy // way to know for which selected items we need to draw selection info. this._drawCount = this._project._drawCount; // Keep calculating the current global matrix, by keeping a history // and pushing / popping as we go along. var trackTransforms = param.trackTransforms, transforms = param.transforms, parentMatrix = transforms[transforms.length - 1], globalMatrix = parentMatrix.clone().concatenate(this._matrix); // Only keep track of transformation if told so. See Project#draw() if (trackTransforms) transforms.push(this._globalMatrix = globalMatrix); // If the item has a blendMode or is defining an opacity, draw it on // a temporary canvas first and composite the canvas afterwards. // Paths with an opacity < 1 that both define a fillColor // and strokeColor also need to be drawn on a temporary canvas // first, since otherwise their stroke is drawn half transparent // over their fill. // Exclude Raster items since they never draw a stroke and handle // opacity by themselves (they also don't call _setStyles) var blendMode = this._blendMode, opacity = this._opacity, normalBlend = blendMode === 'normal', nativeBlend = BlendMode.nativeModes[blendMode], // Determine if we can draw directly, or if we need to draw into a // separate canvas and then composite onto the main canvas. direct = normalBlend && opacity === 1 // If native blending is possible, see if the item allows it || (nativeBlend || normalBlend && opacity < 1) && this._canComposite(), mainCtx, itemOffset, prevOffset; if (!direct) { // Apply the paren't global matrix to the calculation of correct // bounds. var bounds = this.getStrokeBounds(parentMatrix); if (!bounds.width || !bounds.height) return; // Store previous offset and save the main context, so we can // draw onto it later. prevOffset = param.offset; // Floor the offset and ceil the size, so we don't cut off any // antialiased pixels when drawing onto the temporary canvas. itemOffset = param.offset = bounds.getTopLeft().floor(); // Set ctx to the context of the temporary canvas, so we draw onto // it, instead of the mainCtx. mainCtx = ctx; ctx = CanvasProvider.getContext( bounds.getSize().ceil().add(new Size(1, 1)), param.ratio); } ctx.save(); // If drawing directly, handle opacity and native blending now, // otherwise we will do it later when the temporary canvas is composited. if (direct) { ctx.globalAlpha = opacity; if (nativeBlend) ctx.globalCompositeOperation = blendMode; } else { // Translate the context so the topLeft of the item is at (0, 0) // on the temporary canvas. ctx.translate(-itemOffset.x, -itemOffset.y); } // Apply globalMatrix when drawing into temporary canvas. (direct ? this._matrix : globalMatrix).applyToContext(ctx); // If we're drawing into a separate canvas and a clipItem is defined for // the current rendering loop, we need to draw the clip item again. if (!direct && param.clipItem) param.clipItem.draw(ctx, param.extend({ clip: true })); this._draw(ctx, param); ctx.restore(); if (trackTransforms) transforms.pop(); if (param.clip) ctx.clip(); // If a temporary canvas was created, composite it onto the main canvas: if (!direct) { // Use BlendMode.process even for processing normal blendMode with // opacity. BlendMode.process(blendMode, ctx, mainCtx, opacity, // Calculate the pixel offset of the temporary canvas to the // main canvas. We also need to factor in the pixel ratio. itemOffset.subtract(prevOffset).multiply(param.ratio)); // Return the temporary context, so it can be reused CanvasProvider.release(ctx); // Restore previous offset. param.offset = prevOffset; } }, _canComposite: function() { return false; } }, Base.each(['down', 'drag', 'up', 'move'], function(name) { this['removeOn' + Base.capitalize(name)] = function() { var hash = {}; hash[name] = true; return this.removeOn(hash); }; }, /** @lends Item# */{ /** * {@grouptitle Remove On Event} * * Removes the item when the events specified in the passed object literal * occur. * The object literal can contain the following values: * Remove the item when the next {@link Tool#onMouseMove} event is * fired: {@code object.move = true} * * Remove the item when the next {@link Tool#onMouseDrag} event is * fired: {@code object.drag = true} * * Remove the item when the next {@link Tool#onMouseDown} event is * fired: {@code object.down = true} * * Remove the item when the next {@link Tool#onMouseUp} event is * fired: {@code object.up = true} * * @name Item#removeOn * @function * @param {Object} object * * @example {@paperscript height=200} * // Click and drag below: * function onMouseDrag(event) { * // Create a circle shaped path at the mouse position, * // with a radius of 10: * var path = new Path.Circle({ * center: event.point, * radius: 10, * fillColor: 'black' * }); * * // Remove the path on the next onMouseDrag or onMouseDown event: * path.removeOn({ * drag: true, * down: true * }); * } */ /** * Removes the item when the next {@link Tool#onMouseMove} event is fired. * * @name Item#removeOnMove * @function * * @example {@paperscript height=200} * // Move your mouse below: * function onMouseMove(event) { * // Create a circle shaped path at the mouse position, * // with a radius of 10: * var path = new Path.Circle({ * center: event.point, * radius: 10, * fillColor: 'black' * }); * * // On the next move event, automatically remove the path: * path.removeOnMove(); * } */ /** * Removes the item when the next {@link Tool#onMouseDown} event is fired. * * @name Item#removeOnDown * @function * * @example {@paperscript height=200} * // Click a few times below: * function onMouseDown(event) { * // Create a circle shaped path at the mouse position, * // with a radius of 10: * var path = new Path.Circle({ * center: event.point, * radius: 10, * fillColor: 'black' * }); * * // Remove the path, next time the mouse is pressed: * path.removeOnDown(); * } */ /** * Removes the item when the next {@link Tool#onMouseDrag} event is fired. * * @name Item#removeOnDrag * @function * * @example {@paperscript height=200} * // Click and drag below: * function onMouseDrag(event) { * // Create a circle shaped path at the mouse position, * // with a radius of 10: * var path = new Path.Circle({ * center: event.point, * radius: 10, * fillColor: 'black' * }); * * // On the next drag event, automatically remove the path: * path.removeOnDrag(); * } */ /** * Removes the item when the next {@link Tool#onMouseUp} event is fired. * * @name Item#removeOnUp * @function * * @example {@paperscript height=200} * // Click a few times below: * function onMouseDown(event) { * // Create a circle shaped path at the mouse position, * // with a radius of 10: * var path = new Path.Circle({ * center: event.point, * radius: 10, * fillColor: 'black' * }); * * // Remove the path, when the mouse is released: * path.removeOnUp(); * } */ // TODO: implement Item#removeOnFrame removeOn: function(obj) { for (var name in obj) { if (obj[name]) { var key = 'mouse' + name, project = this._project, sets = project._removeSets = project._removeSets || {}; sets[key] = sets[key] || {}; sets[key][this._id] = this; } } return this; } }));
/*! * CanJS - 2.2.5 * http://canjs.com/ * Copyright (c) 2015 Bitovi * Wed, 22 Apr 2015 15:03:29 GMT * Licensed MIT */ /*can@2.2.5#control/route/route*/ steal('can/util', 'can/route', 'can/control', function (can) { // ## control/route.js // _Controller route integration._ can.Control.processors.route = function (el, event, selector, funcName, controller) { selector = selector || ""; if (!can.route.routes[selector]) { if (selector[0] === '/') { selector = selector.substring(1); } can.route(selector); } var batchNum, check = function (ev, attr, how) { if (can.route.attr('route') === (selector) && (ev.batchNum === undefined || ev.batchNum !== batchNum)) { batchNum = ev.batchNum; var d = can.route.attr(); delete d.route; if (can.isFunction(controller[funcName])) { controller[funcName](d); } else { controller[controller[funcName]](d); } } }; can.route.bind('change', check); return function () { can.route.unbind('change', check); }; }; return can; });
exports.pathResolver = function pathResolver(base, path) { base = base.slice(); path = path.slice(); while (base.length && path[0] === '..') { path.shift(); base.pop(); } return base.concat(path); }; exports.pathSpliter = function pathSpliter(path) { var splitPath; if (path instanceof Array) { splitPath = path; } else if (typeof path === 'string') { if (path.match(/[/]|[.][.]/)) { splitPath = path.split('/'); } else { splitPath = path.split('.'); } if (!splitPath[0] && !splitPath[1]) { splitPath = ['.']; } var barsProp = splitPath.pop() .split('@'); if (barsProp[0]) { splitPath.push(barsProp[0]); } if (barsProp[1]) { splitPath.push('@' + barsProp[1]); } } else { throw 'bad arrgument: expected String | Array<String>.'; } return splitPath; }; function findPath(arg) { if (arg) { if (arg.type === 'insert') { return arg.path; } else if ( arg.type === 'operator' || arg.type === 'transform' ) { for (var i = 0; i < arg.arguments.length; i++) { var argI = findPath(arg.arguments[i]); if (argI.type === 'insert') { return argI.argument; } } } } return ''; } exports.findPath = findPath;
"use strict"; var logger = require('./misc/debug.js'); var TPDU_Client = require('./tpdu_client.js'); var PDU_TYPE = require('./types.js').PDU_TYPE; var S7_Req_Header = require('./types.js').S7_Req_Header; var S7_ReqFun_PlcStop = require('./types.js').S7_ReqFun_PlcStop; var S7_Client = function(host, rack, slot, callback) { var self = this; host = host || '127.0.0.1'; rack = rack || 0x01; slot = slot || 0x02; self.host = host; self.tsap_client = 0x0100; self.tsap_server = 0x0104; logger.debug('TSAP Client: ' + self.tsap_client); logger.debug('TSAP Server: ' + self.tsap_server); self.tpdu_client = new TPDU_Client({ host: self.host, tsap_client: self.tsap_client, tsap_server: self.tsap_server }); }; S7_Client.prototype.ReadArea = function() { }; S7_Client.prototype.WriteArea = function() { }; S7_Client.prototype.DBRead = function() { }; S7_Client.prototype.DBWrite = function() { }; S7_Client.prototype.MBRead = function() { }; S7_Client.prototype.MBWrite = function() { }; S7_Client.prototype.IBRead = function() { }; S7_Client.prototype.IBWrite = function() { }; S7_Client.prototype.QBRead = function() { }; S7_Client.prototype.QBWrite = function() { }; // Control functions S7_Client.prototype.PlcHotStart = function() { }; S7_Client.prototype.PlcColdStart = function() { }; S7_Client.prototype.PlcStop = function() { var s7_pdu = Buffer(0); var header = new S7_Req_Header(); var para = new S7_ReqFun_PlcStop(); header.PDUType = PDU_TYPE.Request; header.ParLen.value = para.length(); s7_pdu = Buffer.concat([s7_pdu, header.toBytes()]); s7_pdu = Buffer.concat([s7_pdu, para.toBytes()]); logger.debug('S7 PDU - PlcStop: \n' + s7_pdu.toString('hex')); this.tpdu_client.send(s7_pdu); }; S7_Client.prototype.CopyRamToRom = function() { }; S7_Client.prototype.Compress = function() { }; S7_Client.prototype.GetPlcStatus = function() { }; module.exports = S7_Client;
version https://git-lfs.github.com/spec/v1 oid sha256:9a780e07e8e76443bb024c3b81e3f0fd6b43faa74024bd26a78ac61292bc0c06 size 21167
/** * Created by NGUYENVU on 2/6/2016. */ var currentDir = window.location.origin + window.location.pathname + "#"; var urlUser = 'user'; var urlSearch = 'user/search'; var urlCreateUser = 'user/create'; var urlEditUser = 'user/edit'; var urlDeleteUser = 'user/delete'; var urlProject = 'project'; var urlProjectSearch = 'project/search'; var urlCreateProject = 'project/create'; var urlEditProject = 'project/edit'; var urlDeleteProject = 'project/delete'; var urlStakeholderProject = 'project/stakeholders';
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define({zoom:"Aplicar zoom a",next:"Pr\u00f3xima elemento",previous:"Elemento anterior",close:"Fechar",dock:"Doca",undock:"Desencaixar",menu:"Menu",untitled:"Sem t\u00edtulo",pageText:"{index} do {total}",selectedFeature:"Elemento selecionado",selectedFeatures:"{total} resultados",loading:"A Carregar",collapse:"Recolher",expand:"Expandir"});
'use strict'; var genBase = require('../genBase') , Generator; Generator = module.exports = genBase.extend(); Generator.prototype.prompting = function prompting() { this.askForModuleName(); }; Generator.prototype.writing = function writing() { var config = this.getConfig(); this.fs.copyTpl( this.templatePath('_constant.' + config.appScript), this.destinationPath(config.appDir + '/' + config.modulePath + '/' + config.hyphenName + '-constant.' + config.appScript), config ); this.fs.copyTpl( this.templatePath('_spec.' + config.testScript), this.destinationPath(config.testDir + '/' + config.modulePath + '/' + config.hyphenName + '-constant_test.' + config.testScript), config ); };
'use strict'; angular.module('myApp.unit7', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/unit7', { templateUrl: 'unit7/unit7.html', controller: 'Unit7Ctrl' }); }]).controller('Unit7Ctrl', ['Unit7', '$scope', function(Unit7, $scope) { $scope.ex = Unit7.ex; Unit7.refreshPage(); }]);
'use strict'; /* Controllers */ var phonecatControllers = angular.module('phonecatControllers', []); phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.orderProp = 'age'; }]); phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { $http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) { $scope.phone = data; }); }]);
exports.config = { namespace: "better-img-stencil", outputTargets: [ { type: "dist" }, { type: "www", serviceWorker: false } ] }; exports.devServer = { root: "www", watchGlob: "**/**" };
Blockly.Language.message = { helpUrl: 'http://www.example.com/', init: function() { this.setColour(190); this.appendDummyInput("").appendTitle(new Blockly.FieldImage("img/message.png", 16, 16)).appendTitle("Message") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.appendValueInput("value", Text) this.setTooltip('message'); } }; Blockly.JavaScript.message = function() { var argument0 = Blockly.JavaScript.valueToCode(this, 'value', Blockly.JavaScript.ORDER_COMMA) || 'false'; if (!Blockly.JavaScript.definitions_['message']) { var functionName = Blockly.JavaScript.variableDB_.getDistinctName('message', Blockly.Generator.NAME_TYPE); Blockly.JavaScript.message.functionName = functionName; var func = []; func.push('function ' + functionName + '(message) {'); func.push(' console.log(message);'); func.push('}'); Blockly.JavaScript.definitions_['message'] = func.join('\n'); } var code = Blockly.JavaScript.message.functionName + '(' + argument0 + ');\n'; return code; };
declare export type class A {}
/***Generated Resource **/ var resource = require('resource'); var BusStop = resource.define('BusStop'); BusStop.schema.description = "A bus stop."; BusStop.persist('fs'); BusStop.property('additionalType', { "name" : "additionalType", "displayName" : "Additional Type", "description" : "An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the &#x27;typeof&#x27; attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.", "type": "string" }); BusStop.property('description', { "name" : "description", "displayName" : "Description", "description" : "A short description of the item.", "type": "string" }); BusStop.property('image', { "name" : "image", "displayName" : "Image", "description" : "URL of an image of the item.", "type": "string" }); BusStop.property('name', { "name" : "name", "displayName" : "Name", "description" : "The name of the item.", "type": "string" }); BusStop.property('sameAs', { "name" : "sameAs", "displayName" : "Same as", "description" : "URL of a reference Web page that unambiguously indicates the item&#x27;s identity. E.g. the URL of the item&#x27;s Wikipedia page, Freebase page, or official website.", "type": "string" }); BusStop.property('url', { "name" : "url", "displayName" : "Url", "description" : "URL of the item.", "type": "string" }); exports.BusStop = BusStop; BusStop.property('address', { "name" : "address", "displayName" : "Address", "description" : "Physical address of the item.", "type":"object","properties" : {"PostalAddress" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('aggregateRating', { "name" : "aggregateRating", "displayName" : "Aggregate Rating", "description" : "The overall rating, based on a collection of reviews or ratings, of the item.", "type":"object","properties" : {"AggregateRating" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('containedIn', { "name" : "containedIn", "displayName" : "Contained in", "description" : "The basic containment relation between places.", "type":"object","properties" : {"Place" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('event', { "name" : "event", "displayName" : "Event", "description" : "Upcoming or past event associated with this place or organization.", "type":"object","properties" : {"Event" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('events', { "name" : "events", "displayName" : "Events", "description" : "Upcoming or past events associated with this place or organization (legacy spelling; see singular form, event).", "type":"object","properties" : {"Event" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('faxNumber', { "name" : "faxNumber", "displayName" : "Fax Number", "description" : "The fax number.", "type": "string" }); BusStop.property('geo', { "name" : "geo", "displayName" : "Geo", "description" : "The geo coordinates of the place.", "type":"object","properties" : {"GeoCoordinates" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"GeoShape" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('globalLocationNumber', { "name" : "globalLocationNumber", "displayName" : "Global Locationnumber", "description" : "The Global Location Number (GLN, sometimes also referred to as International Location Number or ILN) of the respective organization, person, or place. The GLN is a 13-digit number used to identify parties and physical locations.", "type": "string" }); BusStop.property('interactionCount', { "name" : "interactionCount", "displayName" : "Interaction Count", "description" : "A count of a specific user interactions with this item—for example, 20 UserLikes, 5 UserComments, or 300 UserDownloads. The user interaction type should be one of the sub types of UserInteraction.", "type": "string" }); BusStop.property('isicV4', { "name" : "isicV4", "displayName" : "Isic v4", "description" : "The International Standard of Industrial Classification of All Economic Activities (ISIC), Revision 4 code for a particular organization, business person, or place.", "type": "string" }); BusStop.property('logo', { "name" : "logo", "displayName" : "Logo", "description" : "URL of an image for the logo of the item.", "type":"object","properties" : {"ImageObject" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('map', { "name" : "map", "displayName" : "Map", "description" : "A URL to a map of the place.", "type": "string" }); BusStop.property('maps', { "name" : "maps", "displayName" : "Maps", "description" : "A URL to a map of the place (legacy spelling; see singular form, map).", "type": "string" }); BusStop.property('openingHoursSpecification', { "name" : "openingHoursSpecification", "displayName" : "Opening Hoursspecification", "description" : "The opening hours of a certain place.", "type":"object","properties" : {"OpeningHoursSpecification" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('photo', { "name" : "photo", "displayName" : "Photo", "description" : "A photograph of this place.", "type":"object","properties" : {"ImageObject" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Photograph" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('photos', { "name" : "photos", "displayName" : "Photos", "description" : "Photographs of this place (legacy spelling; see singular form, photo).", "type":"object","properties" : {"ImageObject" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Photograph" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('review', { "name" : "review", "displayName" : "Review", "description" : "A review of the item.", "type":"object","properties" : {"Review" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('reviews', { "name" : "reviews", "displayName" : "Reviews", "description" : "Review of the item (legacy spelling; see singular form, review).", "type":"object","properties" : {"Review" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}} }); BusStop.property('telephone', { "name" : "telephone", "displayName" : "Telephone", "description" : "The telephone number.", "type": "string" }); exports.BusStop = BusStop; BusStop.property('openingHours', { "name" : "openingHours", "displayName" : "Opening Hours", "description" : "The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas &#x27;,&#x27; separating each day. Day or time ranges are specified using a hyphen &#x27;-&#x27;.- Days are specified using the following two-letter combinations: Mo, Tu, We, Th, Fr, Sa, Su.- Times are specified using 24:00 time. For example, 3pm is specified as 15:00. - Here is an example: Tuesdays and Thursdays 4-8pm. - If a business is open 7 days a week, then it can be specified as Monday through Sunday, all day.", "type": "string" }); exports.BusStop = BusStop;
import { fork, join } from 'redux-saga/effects'; // This utility takes the array of sagas as a param, and maps it to an array of runnable tasks. export default sagas => function* waitAll() { const tasks = yield sagas.map(([saga, ...params]) => fork(saga, ...params)); yield join(...tasks); };
/* Name: Mag-register v0.1.1 Description: run mag.module for by tagName(s) Example: var instances = mag.register( 'my-tag', component, props); Author: Michael Glazer License: MIT Homepage: https://github.com/magnumjs/mag.js @requires mag.js & mag addons (c) 2017 */ (function(mag, document) { 'use strict'; var nodeCache = []; //Allow for by TagName? //wrapper for mag.module for tagNames - returns multiple instances mag.register = function(tagName, mod, props) { //Are we in a parent run? // mag.mod.runningViewInstance var cacheId = tagName + (mag.mod.runningViewInstance ? mag.mod.runningViewInstance : 0); //Check if in cache? if (nodeCache[cacheId]) { //console.log('cached', cacheId, nodeCache[cacheId]); } var nodes = setIdByTagName(tagName); var instances = []; if (nodes.length) { for (var item of nodes) { var instance = mag.module(item, mod, props); instances.push(instance); } } return instances; }; function setIdByTagName(id) { var parentNode; if (typeof mag.mod.runningViewInstance != 'undefined') { var parentID = mag.utils.items.getItemVal(mag.mod.runningViewInstance); parentNode = getNode(parentID); } var nodes = (parentNode || mag.doc).getElementsByTagName(id); if (nodes.length) { for (var node of nodes) { if (!node.id) node.id = performance.now(); nodeCache[node.id] = node; } } return nodes; } })(mag, document);
import React from 'react'; import "./styles.css"; import logo from '../../../assets/logo.png' const PersluLogo = (props) => <img src={logo} alt="logo" className="PersluLogo" />; export default PersluLogo
/* Magic Mirror * Module: MMM-MovieListing * * By Christian Jens https://tueti.github.io * Modified by Kyle Johnson * MIT Licensed. */ Module.register('MMM-MovieListings', { // Default module config. defaults: { apiKey: '', region: 'DE', language: 'de-DE', interface: 'poster', //'list', 'poster', 'detailed' includeMoviePlot: false, maxPlotLength: 198, header: 'Kinofilme', moviesPerPage: 0, refreshInterval: 1000 * 60 * 60 * 24, //Once a day baseUrl: 'https://api.themoviedb.org/3/movie/now_playing', animationSpeed: 2.5 * 1000, pageChangeInterval: 30 * 1000 }, getStyles: function() { return ['MMM-MovieListings.css']; }, getTranslations: function() { return { en: "translations/en.json", de: "translations/de.json", sv: "translations/sv.json", es: "translations/es.json" } }, start: function() { Log.log(this.name + ' is started'); this.movies = {}; var self = this; self.sendSocketNotification('FETCH_MOVIE_LIST', this.config); //run once now, then set Interval for once a day setInterval(function() { self.sendSocketNotification('FETCH_MOVIE_LIST', this.config); }, this.config.refreshInterval); }, socketNotificationReceived: function(notification, payload) { Log.log(this.name + ': received socket notification ' + notification + ' with payload:', payload); if (notification === 'MOVIE_ERROR') { Log.log(this.name + ': Error'); } if (notification === 'MOVIE_LIST_DONE') { // Log.log(this.name + ': Got movies'); // Prepare DOM data this.movies = payload.results; this.prepareDomUpdate(this.movies); } if (notification === 'MOVIE_ID_DONE') { // Log.log(this.name + ': Got movie details', payload); this.posterToDisplay = payload this.updateDom(this.config.animationSpeed); } }, /* * DOM MANIPULATION */ getDom: function() { var wrapper = document.createElement('div') var header = document.createElement('header'); header.innerHTML = this.config.header; wrapper.appendChild(header); // No movies fetched yet if (!this.moviesToDisplay && !this.posterToDisplay) { var loadingPlaceholder = document.createElement('div'); loadingPlaceholder.className = 'small dimmed'; loadingPlaceholder.innerHTML = this.translate('LOADING'); wrapper.appendChild(loadingPlaceholder); return wrapper; } switch (this.config.interface) { case 'list': var tableContainer = document.createElement('div').appendChild(this.createTableView(this.moviesToDisplay)); wrapper.appendChild(tableContainer); return wrapper; case 'poster': var posterContainer = document.createElement('div').appendChild(this.createPosterView(this.posterToDisplay)); wrapper.appendChild(posterContainer); return wrapper; default: break; } }, // Different view styles createTableView: function(movies) { var table = document.createElement('table'); table.className = 'small'; for (var i = 0; i <= movies.length - 1; i++) { var movie = movies[i]; var tableRow = document.createElement('tr'); var tableData = document.createElement('td'); var cell = document.createElement('span'); cell.innerHTML = movie.title; tableData.appendChild(cell); tableRow.appendChild(tableData); table.appendChild(tableRow); } return table; }, createPosterView: function(movieSet) { var movie = movieSet.details; var credits = movieSet.credits; // create container var posterWrapper = document.createElement('div'); posterWrapper.className = 'xsmall'; // set up title var title = document.createElement('div'); title.classList = 'small'; title.innerHTML = movie.title; // set up tagline var tagline = document.createElement('div'); tagline.classList = 'dimmed'; tagline.innerHTML = movie.tagline; // set up plot if (this.config.includeMoviePlot) { var plot = document.createElement('div'); plot.classList = 'dimmed'; var plotContent = ""; if (this.config.maxPlotLength == 0) { plotContent = movie.overview } else { plotContent = movie.overviewShort; } plot.innerHTML = plotContent.split(/((?:\S+ ){10})/g).filter(Boolean).join("<br/>");; } // Set up details => image var image = document.createElement('img'); image.src = 'https://image.tmdb.org/t/p/w154/' + movie.poster_path; // "w92", "w154", "w185", "w342", "w500", "w780", or "original" // Set up details => textArea var detailsContainer = document.createElement('p'); detailsContainer.className = this.data.position.toLowerCase().indexOf('right') < 0 ? 'marginLeft' : 'marginRight'; // Set up details => rating var detailsRatingContainer = document.createElement('div'); detailsRatingContainer.className = 'xsmall'; var detailsRatingVote = document.createElement('span'); detailsRatingVote.innerHTML = movie.vote_average + ' / 10'; var detailsRatingVotings = document.createElement('span'); detailsRatingVotings.className = 'xsmall dimmed'; detailsRatingVotings.innerHTML = ' (' + movie.vote_count + ' ' + this.translate('RATINGS') + ')'; detailsRatingContainer.appendChild(detailsRatingVote); detailsRatingContainer.appendChild(detailsRatingVotings); // Set up details => runtime var runtimeContent = document.createElement('div'); runtimeContent.className = 'xsmall'; runtimeContent.innerHTML = movie.runtime + ' ' + this.translate('MIN'); // Set up details => credits actors var creditsContainer = document.createElement('div'); creditsContainer.className = 'marginTop xsmall'; /* Header(?) var castHeader = document.createElement('div'); castHeader.className = 'xsmall dimmed'; castHeader.innerHTML = this.translate('CAST'); creditsContainer.appendChild(castHeader); */ var castContent = document.createElement('div'); castContent.className = 'xsmall'; if (credits.cast && credits.cast.length > 0) { for (var i = 0; i < Math.min(6, credits.cast.length); i++) { castContent.innerHTML += credits.cast[i].name + '<br />'; } } creditsContainer.appendChild(castContent); // Set up details => credits director var directorContainer = document.createElement('div'); var directorHeader = document.createElement('span'); directorHeader.className = 'xsmall dimmed'; directorHeader.innerHTML = ', ' + this.translate('DIRECTOR'); var directorContent = document.createElement('span'); directorContent.className = 'xsmall'; if (credits.crew && credits.crew.length > 0) { for (var i = 0; i <= credits.crew.length - 1; i++) { if (credits.crew[i].job === 'Director') { directorContent.innerHTML = credits.crew[i].name; }; }; } directorContainer.appendChild(directorContent); directorContainer.appendChild(directorHeader); creditsContainer.appendChild(directorContainer); // Set up details => genres if (movie.genres) { var genres = ''; for (var i = 0; i <= movie.genres.length -1; i++) { genres += movie.genres[i].name; if (i < movie.genres.length - 1) { genres += ', '; } } } // Add all details detailsContainer.appendChild(detailsRatingContainer); detailsContainer.appendChild(runtimeContent); detailsContainer.appendChild(creditsContainer); // Set up details => table var detailsTable = document.createElement('table'); detailsTable.className = 'xsMarginTop'; var tableRow = document.createElement('tr'); var imageCell = document.createElement('td'); var textCell = document.createElement('td'); textCell.className = 'top'; imageCell.className = 'top'; imageCell.appendChild(image); textCell.appendChild(detailsContainer); if (this.data.position.toLowerCase().indexOf('right') < 0) { tableRow.appendChild(imageCell); textCell.className = 'top left'; tableRow.appendChild(textCell); } else { tableRow.appendChild(textCell); tableRow.appendChild(imageCell); }; detailsTable.appendChild(tableRow); // Set up entire view in container posterWrapper.appendChild(title); posterWrapper.appendChild(tagline); posterWrapper.appendChild(detailsTable); if (this.config.includeMoviePlot) { posterWrapper.appendChild(plot); } return posterWrapper; }, /* * HELPER */ prepareDomUpdate: function(movies) { switch (this.config.interface) { case 'list': // If pagination enabled, turn to DOM update scheduler, else just display all movies if (this.config.moviesPerPage > 0) { this.scheduleDomUpdatesForList(movies); } else { this.moviesToDisplay = movies this.updateDom(); } break; case 'poster': this.scheduleDomUpdatesForPoster(movies); default: break; } }, scheduleDomUpdatesForList: function(movies) { var self = this; var pages = Math.ceil(movies.length / self.config.moviesPerPage); self.movieChunks = []; self.nextIndex = 0; for (var i = 0; i < pages; i++) { self.movieChunks.push(movies.splice(0, self.config.moviesPerPage)) } self.moviesToDisplay = self.movieChunks[self.nextIndex]; self.nextIndex++; self.updateDom(); setInterval(function() { self.moviesToDisplay = self.movieChunks[self.nextIndex]; self.nextIndex++; // reset index if end is reached if (self.nextIndex > self.movieChunks.length - 1) { self.nextIndex = 0; } self.updateDom(self.config.animationSpeed); }, this.config.pageChangeInterval); }, scheduleDomUpdatesForPoster: function(movies) { var self = this; self.nextIndex = 0; self.sendSocketNotification('FETCH_MOVIE_ID', { movieId: movies[self.nextIndex].id, apiKey: self.config.apiKey, language: self.config.language, config: self.config }); self.nextIndex++; setInterval(function() { self.sendSocketNotification('FETCH_MOVIE_ID', { movieId: movies[self.nextIndex].id, apiKey: self.config.apiKey, language: self.config.language, config: self.config }); self.nextIndex++; // reset when end of array is reached if (self.nextIndex > movies.length - 1) { self.nextIndex = 0; } }, this.config.pageChangeInterval); }, });
var VERSION = '0.0.0', http = require('http'), querystring = require('querystring'), oauth = require('oauth'); function merge(defaults, options) { defaults = defaults || {}; if (options && typeof options === 'object') { var keys = Object.keys(options); for (var i = 0, len = keys.length; i < len; i++) { var k = keys[i]; if (options[k] !== undefined) defaults[k] = options[k]; } } return defaults; } function Withings(options) { if (!(this instanceof Withings)) return new Withings(options); var defaults = { consumer_key: null, consumer_secret: null, access_token_key: null, access_token_secret: null, headers: { 'Accept': '*/*', 'Connection': 'close', 'User-Agent': 'node-withings/' + VERSION }, callback_url: null, rest_base: 'http://wbsapi.withings.net', }; this.options = merge(defaults, options); this.oauth = new oauth.OAuth( this.options.request_token_url, this.options.access_token_url, this.options.consumer_key, this.options.consumer_secret, '1.0', this.options.callback_url, 'HMAC-SHA1', null, this.options.headers ); } Withings.prototype.get = function(url, params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } if (url.charAt(0) == '/') url = this.options.rest_base + url; this.oauth.get( url + '?' + querystring.stringify(params), this.options.access_token_key, this.options.access_token_secret, function(error, data, response) { if (error) { var err = new Error( 'HTTP Error ' + error.statusCode + ': ' + http.STATUS_CODES[error.statusCode] ); err.statusCode = error.statusCode; err.data = error.data; callback(err); } else { try { var json = JSON.parse(data); callback(json); } catch(err) { callback(err); } } } ); return this; } // CONVENIENCE METHODS // USER /* * User: Get by id */ Withings.prototype.user_getbyuserid = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'getbyuserid'; this.get('/user', params, callback); return this; } // MEASURE /* * Measure: Get measurement */ Withings.prototype.measure_getmeas = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'getmeas'; this.get('/measure', params, callback); return this; } /* * Measure: Get Activity */ Withings.prototype.measure_getactivity = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'getactivity'; this.get('/v2/measure', params, callback); return this; } // NOTIFY /* * Notify: Subscribe */ Withings.prototype.notify_subscribe = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'subscribe'; this.get('/notify', params, callback); return this; } /* * Notify: Get */ Withings.prototype.notify_get = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'subscribe'; this.get('/notify', params, callback); return this; } /* * Notify: List */ Withings.prototype.notify_list = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'subscribe'; this.get('/notify', params, callback); return this; } /* * Notify: Revoke */ Withings.prototype.notify_revoke = function(params, callback) { if (typeof params === 'function') { callback = params; params = null; } if ( typeof callback !== 'function' ) { throw "FAIL: INVALID CALLBACK."; return this; } params.action = 'subscribe'; this.get('/notify', params, callback); return this; } module.version = VERSION module.exports = Withings;
const express = require('express'); const router = express.Router(); const authHelpers = require('../controllers/signin'); const gameBoard = require('../controllers/gameBoard.js'); const players = require('../controllers/players.js'); const indexController = require('../controllers/index'); router.get('/', authHelpers.loginRequired, (req, res, next) => { const renderObject = {}; authHelpers.logCheck(renderObject, req); renderObject.sessionID = req.sessionID; renderObject.name = req.session.user.username; res.render('./pages/findGame', renderObject); }); router.post('/gameBoard', authHelpers.loginRequired, (req, res, next) => { gameBoard.setUpBoard(req.body.random).then((result) => { res.json(result[0].board); }).catch((err) => { console.log(err); }); }); router.get('/findGame', authHelpers.loginRequired, (req, res, next) => { gameBoard.findGame().then((results) => { res.json(results); }).catch((err) => { console.log(err); }); }); router.get('/:gameID', authHelpers.loginRequired, (req, res, next) => { const renderObject = {}; authHelpers.logCheck(renderObject, req); renderObject.title = 'Play!'; renderObject.sessionID = req.sessionID; renderObject.name = req.session.user.username; renderObject.first = true; res.render('./pages/play', renderObject); }); router.get('/:gameID/notFirst', authHelpers.loginRequired, (req, res, next) => { const renderObject = {}; authHelpers.logCheck(renderObject, req); renderObject.title = 'Play!'; renderObject.sessionID = req.sessionID; renderObject.name = req.session.user.username; renderObject.first = false; res.render('./pages/play', renderObject); }); router.get('/:gameID/join', authHelpers.loginRequired, (req, res, next) => { gameBoard.getBoard(req.params.gameID).then((result) => { console.log(result); res.json(result[0].board); }); }); router.get('/:gameID/player', authHelpers.loginRequired, (req, res, next) => { gameBoard.getPlayerBoard(req.params.gameID, req.session.user.user_id).then((result) => { res.json(result[0]); }); }); router.post('/player/new', authHelpers.loginRequired, (req, res, next) => { const playerObject = { color: req.body.color, avatar_url: req.body.avatar_url, user_id: req.session.user.user_id, game_id: req.body.game_id }; players.setUpPlayer(playerObject).then((result) => { res.json(result[0]); }).catch((err) => { console.log(err); return next(); }); }); router.get('/:gameID/yourPlace', authHelpers.loginRequired, (req, res, next) => { const playerPromise = gameBoard.getPlayerBoard(req.params.gameID, req.session.user.user_id); const boardPromise = gameBoard.getBoard(req.params.gameID); }); module.exports = router;
import { TreeView } from "@bosket/vue" import { dragndrop } from "@bosket/core" /* Model */ const dragModel = [ { name: "< Drag these items >" }, { name: 1, children: [{ name: 11 }, { name: 12 }, { name: 13 }]}, { name: 2, children: [{ name: 21 }, { name: 22 }]}, { name: 3 }, { name: 4 } ] /* Common conf. */ const conf = { category: "children", onSelect: function(_) { this.selection = _ }, display: i => i.name, strategies: { fold: [() => false]} } /* Drag only tree */ export const DragTree = { name: "DragTree", data: () => ({ selection: [], model: dragModel, ...conf }), render: function(h) { const props = { props: { ...this.$data }} return <div class="tree-sample"> <TreeView { ...props } // Pluck preset dragndrop={{ ...dragndrop.pluck(() => this.model, m => this.model = m) }} /> </div> } } /* Drop only tree */ export const DropTree = { name: "DropTree", data: () => ({ selection: [], model: [{ name: "< Drop items here >", children: []}], ...conf }), render: function(h) { const props = { props: { ...this.$data } } return <div class="tree-sample"> <TreeView { ...props } // Paste preset + only drop on items with children dragndrop={{ ...dragndrop.paste(() => this.model, m => this.model = m), droppable: item => item && item.children }} /> </div> } }
#!/usr/bin/env node /* Saves the DB to country specific downloads packages */ const fs = require("fs"); const path = require("path"); const zlib = require("zlib"); const async = require("async"); const ndjson = require("ndjson"); const status = require("node-status"); const Store = require("../lib/store.js"); const config = require("../config.js"); const console = status.console(); const Utils = require("../lib/utils"); const CSV = require("../lib/csv"); const Library = require("../lib/library.js"); const archiver = require("archiver"); const now = new Date().valueOf(); const library = new Library(config); const csv = new CSV(library); let currentCountry = "-"; let currentAction = ""; let status_items = status.addItem("items"); status.addItem("country", { custom: () => { return currentCountry; } }); let status_portals = status.addItem("portals"); status.addItem("current", { custom: () => { return currentAction; } }); let downloadsFolder = path.join(config.data.shared, "downloads"); let portals = JSON.parse(fs.readFileSync(path.join(config.data.shared, "portals.json")).toString()).reverse(); portals.push({ id: "ted", name: "TED" }); let store = new Store(config); let results = []; let compressStream = (stream) => { let compress = zlib.createGzip(); compress.pipe(stream); return compress; }; let uncompressStream = (stream) => { let uncompress = zlib.createGunzip(); stream.pipe(uncompress); return uncompress; }; let streamItems = (country_id, onItems, onEnd) => { let query = { match_all: {} }; if (country_id.toUpperCase() !== "ALL") { query = { term: { "ot.country": country_id.toUpperCase() } }; } if (country_id.toUpperCase() == "TED") { query = { bool: { should: [ { bool: { must: [ { match: { "publications.source": "http://ted.europa.eu" } }, { match: { "publications.isIncluded": true } } ] } }, { bool: { must: [ { match: { "publications.source": "http://data.europa.eu" } }, { match: { "publications.isIncluded": true } } ] } } ] } }; } let pos = 0; store.Tender.streamQuery( 1000, query, (items, total) => { pos += items.length; if (!onItems(items, pos, total)) { return false; } status_items.count = pos; status_items.max = total; return true; }, (err) => { onEnd(err, pos); } ); }; let downloadFolderFileStream = (filename) => { let fullFilename = path.join(downloadsFolder, filename); let outputStream = fs.createWriteStream(fullFilename); return outputStream; }; class DownloadPack { constructor(format, filename) { this.format = format; this.filename = filename; this.zipfilename = filename + "-" + this.format + ".zip"; this.streams = {}; } openStream(filename) { let filestream = downloadFolderFileStream(filename); let stream = compressStream(filestream); stream.orgstream = filestream; return stream; } closeStream(stream, cb) { stream.orgstream.on("close", (err) => { cb(); }); stream.end(); } validateStream(year) { if (!this.streams[year]) { let filename = this.filename + "-" + year + "." + this.format; this.streams[year] = { filename: filename, stream: this.openStream(filename + ".gz"), count: 0 }; } return this.streams[year]; } write(year, data) { let yearstream = this.validateStream(year); yearstream.stream.write(data); yearstream.count++; } zip(cb) { let toZipFilenames = Object.keys(this.streams).map((key) => this.streams[key].filename); const stream = downloadFolderFileStream(this.zipfilename); const archive = archiver("zip", { // store: true zlib: { level: 9 } // Sets the compression level. }); stream.on("close", function () { currentAction = ""; // console.log(archive.pointer() + ' total bytes'); cb(); }); stream.on("end", function () { // console.log('Data has been drained'); }); archive.on("entry", function (entry) { currentAction = "Zipping: " + entry.name; }); archive.on("warning", function (err) { console.log(err); }); archive.on("error", function (err) { console.log(err); }); archive.on("progress", function (progress) { // console.log(progress); }); toZipFilenames.forEach((toZipFilename) => { let fullFilename = path.join(downloadsFolder, toZipFilename + ".gz"); let filestream = fs.createReadStream(fullFilename); let stream = uncompressStream(filestream); archive.append(stream, { name: toZipFilename }); // archive.file(fullFilename, {name: toZipFilename}); }); // console.log('Zipping', filename, 'Files:', JSON.stringify(toZipFilenames)); archive.pipe(stream); archive.finalize(); } removeFiles(cb) { async.forEach( Object.keys(this.streams), (key, next) => { let fullFilename = path.join(downloadsFolder, this.streams[key].filename + ".gz"); fs.unlink(fullFilename, (err) => { next(err); }); }, (err) => { cb(err); } ); } closeStreams(cb) { async.forEach( Object.keys(this.streams), (key, next) => { this.closeStream(this.streams[key].stream, next); }, (err) => { cb(err); } ); } close(cb) { this.closeStreams((err) => { if (err) { return cb(err); } this.zip((err) => { if (err) { return cb(err); } this.removeFiles((err) => { cb(err, { filename: this.zipfilename, size: fs.statSync(path.join(downloadsFolder, this.zipfilename)).size }); }); }); }); } writeTender(data, index, total) {} } class DownloadPackCSV extends DownloadPack { constructor(filename) { super("csv", filename); } writeTender(year, tender) { let yearstream = this.validateStream(year); if (yearstream.count === 0) { yearstream.stream.write(csv.header()); } this.write(year, csv.transform(tender, yearstream.count + 1)); } } class DownloadPackJSON extends DownloadPack { constructor(filename) { super("json", filename); } openStream(filename) { let filestream = downloadFolderFileStream(filename); let stream = compressStream(filestream); stream.orgstream = filestream; stream.write("["); return stream; } closeStream(stream, cb) { stream.write("]"); stream.orgstream.on("close", (err) => { cb(); }); stream.end(); } writeTender(year, tender) { let yearstream = this.validateStream(year); this.write(year, (yearstream.count !== 0 ? "," : "") + JSON.stringify(tender)); } } class DownloadPackNDJSON extends DownloadPack { constructor(filename) { super("ndjson", filename); } openStream(filename) { let filestream = downloadFolderFileStream(filename); let compressstream = compressStream(filestream); let stream = ndjson.serialize(); stream.compressstream = compressstream; stream.orgstream = filestream; stream.on("data", (line) => { compressstream.write(line); }); return stream; } closeStream(stream, cb) { stream.orgstream.on("close", () => { cb(); }); stream.end(); stream.compressstream.end(); } writeTender(year, tender) { this.write(year, tender); } } let dump = (country, cb) => { currentCountry = country.name; let countryId = country.id ? country.id.toLowerCase() : "all"; let filename = "data-" + countryId; console.log("Saving downloads for " + currentCountry); let totalItems = 0; let csvpack = new DownloadPackCSV(filename); let jsonpack = new DownloadPackJSON(filename); let ndjsonpack = new DownloadPackNDJSON(filename); currentAction = "Streaming: " + filename; streamItems( countryId, (items, pos, total) => { items.forEach((item, index) => { let year = (item._source.ot.date || "").slice(0, 4); if (year.length !== 4) { year = "year-unavailable"; } Utils.cleanOtFields(item._source); csvpack.writeTender(year, item._source); jsonpack.writeTender(year, item._source); ndjsonpack.writeTender(year, item._source); }); status_items.count = pos; status_items.max = total; totalItems = total; return true; }, (err, total) => { totalItems = total; csvpack.close((err, file_csv) => { jsonpack.close((err, file_json) => { ndjsonpack.close((err, file_ndjson) => { let result = { country: countryId, count: totalItems, lastUpdate: now, formats: { json: file_json, ndjson: file_ndjson, csv: file_csv } }; results.push(result); cb(); }); }); }); } ); }; store.init((err) => { if (err) { return console.log(err); } status.start({ pattern: "@{uptime} | {spinner.cyan} | {items} | {country.custom} | {portals} | {current.custom}" }); let pos = 0; status_portals.count = 0; status_portals.max = portals.length; async.forEachSeries( portals, (portal, next) => { status_portals.count = ++pos; // if (!portal.id) return next(); dump(portal, next); }, (err) => { if (err) { console.log(err); } store.close(() => { status.stop(); fs.writeFileSync(path.join(downloadsFolder, "downloads.json"), JSON.stringify(results, null, "\t")); console.log("done"); }); } ); });
import React from 'react' import PropTypes from 'prop-types' import { EditorialOverlay } from '../editorials/EditorialParts' import { css, media } from '../../styles/jss' import * as s from '../../styles/jso' import * as ENV from '../../../env' const spinGif = '/static/images/support/ello-spin.gif' const imageStyle = css(s.block, { margin: '0 auto 75px' }) const errorStyle = css( { maxWidth: 780 }, s.px10, s.mb30, s.fontSize14, media(s.minBreak2, s.px0), ) export const ErrorStateImage = () => <img className={imageStyle} src={spinGif} alt="Ello" width="130" height="130" /> export const ErrorState = ({ children = 'Something went wrong.' }) => (<div className={errorStyle}> {children} </div>) ErrorState.propTypes = { children: PropTypes.node, } export const ErrorState4xx = ({ withImage = true }) => (<ErrorState> {withImage ? <ErrorStateImage /> : null} <p>This doesn&rsquo;t happen often, but it looks like something is broken. Hitting the back button and trying again might be your best bet. If that doesn&rsquo;t work you can <a href="http://ello.co/">head back to the homepage.</a></p> <p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p> <p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p> </ErrorState>) ErrorState4xx.propTypes = { withImage: PropTypes.bool, } export const ErrorState5xx = ({ withImage = true }) => (<ErrorState> {withImage ? <ErrorStateImage /> : null} <p>It looks like something is broken and we couldn&rsquo;t complete your request. Please try again in a few minutes. If that doesn&rsquo;t work you can <a href="http://ello.co/">head back to the homepage.</a></p> <p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p> <p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p> </ErrorState>) ErrorState5xx.propTypes = { withImage: PropTypes.bool, } // ------------------------------------- const errorEditorialStyle = css( s.absolute, s.flood, s.flex, s.justifyCenter, s.itemsCenter, s.fontSize14, s.colorWhite, s.bgcRed, s.pointerNone, ) const errorEditorialTextStyle = css( s.relative, s.zIndex2, s.colorWhite, ) export const ErrorStateEditorial = () => ( <div className={errorEditorialStyle}> <span className={errorEditorialTextStyle}>Something went wrong.</span> <EditorialOverlay /> </div> )
var framework = require('framework'); exports.info = function() { return 'fooPlugin (in Framework v' + framework.version + ')'; };
$('document').ready(function() { initTooltips(); }); $(window).on('action:posts.loaded action:topic.loaded action:posts.edited', function() { initTooltips(); }); $(window).on('action:ajaxify.contentLoaded', function(){ $('.item-tooltip').hide(); }); function initTooltips() { $('.vanilla-tooltip').each(function(tooltip){ var name = $(this).attr('data-name'); var $this = $(this); $.getJSON('http://api.theorycraft.fi/v1/item', {name: name}, function(response){ $this.text('['+response.data[0].name+']').attr('rel', 'item='+response.data[0].entry).addClass('q'+response.data[0].quality); ajaxify('http://db.vanillagaming.org/ajax.php?item='+response.data[0].entry+'&power'); }); $this.mouseenter(function(){ showTooltip($this.data('id'), $this.data('tooltip')); }).mouseleave(function(){ $('.item-tooltip').hide(); }); }); $(document).mousemove(function(event) { $('.item-tooltip').css({ left: event.pageX+10, top: event.pageY+10 }); }); } function showTooltip(id, data) { if(!$('.item-tooltip#'+id).length) { var iconUrl = typeof data.icon == 'undefined' ? '' : 'http://db.vanillagaming.org/images/icons/medium/'+data.icon.toLowerCase()+'.jpg'; var $tooltip = $('<div id="'+id+'" class="item-tooltip"><p style="background-image: url('+iconUrl+');"><span></span></p><table><tr><td>'+data.tooltip_enus+'</td><th style="background-position: 100% 0%;"></th></tr><tr><th style="background-position: 0% 100%;"></th><th style="background-position: 100% 100%;"></th></tr></div>'); $tooltip.css('visibility', 'visible').appendTo('body').show(); } else $('.item-tooltip#'+id).show(); } function ajaxify(url) { $('<script type="text/javascript" src="'+url+'"></script>').appendTo('body'); } $WowheadPower = { registerItem: function(a,b,item) { $('a.vanilla-tooltip[rel="item='+a+'"]').data('tooltip', item).data('id', a); } }
var fs = require("fs"); var glob = require("glob"); var IOUtils = require("./IOUtils"); var DirectiveHandler = require("./DirectiveHandler"); var DIRECTIVE_MATCHER = /<!--#([a-z]+)([ ]+([a-z]+)="(.+?)")* -->/g; (function() { "use strict"; var ssi = function(inputDirectory, outputDirectory, matcher) { this.inputDirectory = inputDirectory; this.documentRoot = inputDirectory; this.outputDirectory = outputDirectory; this.matcher = matcher; this.ioUtils = new IOUtils(this.documentRoot); this.directiveHandler = new DirectiveHandler(this.ioUtils); this.directiveHandler.parser = this; }; ssi.prototype = { compile: function() { //noinspection JSUnresolvedFunction var files = glob.sync(this.inputDirectory + this.matcher); for (var i = 0; i < files.length; i++) { var input = files[i]; var contents = fs.readFileSync(input, {encoding: "utf8"}); var data = this.parse(input, contents); var output = input.replace(this.inputDirectory, this.outputDirectory); this.ioUtils.writeFileSync(output, data.contents); } }, parse: function(filename, contents, variables) { var instance = this; variables = variables || {}; contents = contents.replace(new RegExp(DIRECTIVE_MATCHER), function(directive, directiveName) { var data = instance.directiveHandler.handleDirective(directive, directiveName, filename, variables); if (data.error) { throw data.error; } for (var key in data.variables) { if (data.variables.hasOwnProperty(key)) { variables[data.variables[key].name] = data.variables[key].value; } } return (data && data.output) || ""; }); return {contents: contents, variables: variables}; } }; module.exports = ssi; })();
function changeOfBaseQuestion(randomStream, params) { var number = randomStream.nextIntRange(240)+15; var baseArray = [ {base: "decimal", value: number.toString(10), radix: 10}, {base: "hexadecimal", value: number.toString(16), radix: 16}, {base: "binary", value: number.toString(2), radix: 2} ]; randomStream.shuffle(baseArray); this.a = baseArray[0]; this.b = baseArray[1]; //Array of {String, bool} pairs: the string representation of a number in a particular base //and a flag indicating whether or not it is the correct answer. this.answerChoices = [ {value: this.b.value, flag: true}, {value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false}, {value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false}, {value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false} ] randomStream.shuffle(this.answerChoices); //Find the correct answer this.correctIndex = 0; for(var i=0; i<this.answerChoices.length; i++) { if(this.answerChoices[i].flag == true) this.correctIndex = i; } this.formatQuestion = function(format) { switch (format) { case "HTML": return this.formatQuestionHTML(); } return "unknown format"; }; this.formatQuestionHTML = function () { var questionText = "<p>Convert " + this.a.value + " from " + this.a.base + " to " + this.b.base + ".</p>"; questionText += "<p><strong>a) </strong>" + this.answerChoices[0].value + "<br><strong>b) </strong>" + this.answerChoices[1].value + "<br><strong>c) </strong>" + this.answerChoices[2].value + "<br><strong>d) </strong>" + this.answerChoices[3].value + "</p>"; return questionText; }; this.formatAnswer = function(format) { switch (format) { case "HTML": return this.formatAnswerHTML(); } return "unknown format"; // TODO: consider exception }; this.formatAnswerHTML = function () { var text = String.fromCharCode(this.correctIndex + 97); //0 = 'a', 1 = 'b', 2 = 'c', etc... return text; }; };
'use strict'; var flight; function coerceToInt(number) { if (number === 'NA') { return null; } var int = parseInt(number); if (isNaN(int)) { return null; } else { return int; } } // http://www.epochconverter.com/ // http://momentjs.com var beginningOf2001 = moment('2001-01-01'); var beginningOf2002 = moment('2002-01-01'); var months = [beginningOf2001]; var weeks = [beginningOf2001]; for (var i = 1; i <= 11; i++) { var nextMonth = beginningOf2001.clone().add(i, 'months'); months.push(nextMonth); } const monthNames = months.map(month => month.format('MMMM')); // https://developer.mozilla.org/en/docs/Web/HTML/Element/select const timeRangeMonthDisplay = document.querySelector('#time-range-month'); monthNames.forEach((name, index) => { const option = document.createElement('option'); option.setAttribute('value', index); option.appendChild(document.createTextNode(name)); timeRangeMonthDisplay.appendChild(option); }); timeRangeMonthDisplay.addEventListener('change', event => { const selectedMonth = event.target.value; if (selectedMonth != -1) { handleRangeChangeMonth(selectedMonth); } }); for (var i = 1; i <= 51; i++) { var nextWeek = beginningOf2001.clone().add(i, 'weeks'); if ( nextWeek.isAfter(beginningOf2002) ) { break; } weeks.push(nextWeek); } const weekNames = weeks.map(week => week.format('Wo')); const timeRangeWeekDisplay = document.querySelector('#time-range-week'); weekNames.forEach((name, index) => { const option = document.createElement('option'); option.setAttribute('value', index); option.appendChild(document.createTextNode(name)); timeRangeWeekDisplay.appendChild(option); }); timeRangeWeekDisplay.addEventListener('change', event => { const selectedWeek = event.target.value; if (selectedWeek != -1) { handleRangeChangeWeek(selectedWeek); } }); var dayInMS = +moment.duration(1, 'day'); var weekInMS = +moment.duration(1, 'week'); var beginningOfSeptember = +months[8]; var beginningOfOctober = +months[9]; // var endOf2001 = 1009839600000; // var allOf2001 = endOf2001 - beginningOf2001; // var beginningOfFebruary = beginningOf2001 + 31 * dayInMS; // var beginningOfMarch = beginningOfFebruary + 28 * dayInMS; // var beginningOfApril = beginningOfMarch + 31 * dayInMS; // var beginningOfMai = beginningOfApril + 30 * dayInMS; // var beginningOfMonths = [beginningOf2001, beginningOfFebruary, beginningOfMarch, beginningOfApril]; var createQuery = function (fields, from, to) { // reduced data from = from || beginningOfSeptember + 1 * weekInMS; to = to || beginningOfSeptember + 2 * weekInMS; // from = from || beginningOfSeptember; // to = to || beginningOfOctober; // set index.max_result_window in elasticsearch.yml to 1000000 to allow for large result sets return { "size": 500000, "query": { "filtered": { "query": { "query_string": { "query": "Cancelled: false", "analyze_wildcard": true } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": from, "lte": to, "format": "epoch_millis" } } } ], "must_not": [] } } } }, "aggs": {}, "fields": fields }; } function unwrap(hit, fields) { const unwrapped = {}; fields.forEach((field) => { unwrapped[field] = hit.fields[field][0] }); return unwrapped; } function handleRangeChangeMonth(monthIndex) { const month = months[monthIndex]; document.querySelector('#time-range-name').innerHTML = monthNames[monthIndex]; const from = +month; const to = +month.clone().add(1, 'month'); load((cf) => render(cf, from, to, 31), from, to); } function handleRangeChangeWeek(weekIndex) { const week = weeks[weekIndex]; document.querySelector('#time-range-name').innerHTML = `${weekNames[weekIndex]} week of`; const from = +week; const to = +week.clone().add(1, 'week'); load((cf) => render(cf, from, to, 7), from, to); } function load(callback, from, to) { signalLoadingStart(); const fields = ["Year", "Month", "DayofMonth", "Origin", "Dest", "UniqueCarrier"]; const query = createQuery(fields, from, to); // be sure to enable CORS in elasticsearch // https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html // fetch('http://localhost:9200/expo2009_airline/_search', { fetch('http://localhost:9200/expo2009_pandas/_search', { method: 'POST', //mode: 'no-cors', // we need cors, otherwise we get no response back body: JSON.stringify(query), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then((response) => { return response.json(); }).catch((ex) => { console.error('parsing failed', ex); }).then(data => handleData(data, fields, callback)); } function handleData(data, fields, callback) { console.log('Loading done'); console.log(new Date()); //console.log(data); console.log(data.hits.total); console.log(data.hits.hits[0]); const flights = data.hits.hits.map((hit) => unwrap(hit, fields)); //console.log(flights); console.log(flights[0]); d3.json("helper_data/airports_by_state.json", function (airportsArray) { // make airports a map using airport code as key var airports = {}; airportsArray.forEach(function (airport) { airports[airport.airport] = airport; }); // FCA missing in data set // https://en.wikipedia.org/wiki/Glacier_Park_International_Airport // https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations var fca = { airport: 'FCA', name: 'Glacier Park International Airport', state: 'MT' }; airports[fca.airport] = fca; // MQT missing in data set // https://en.wikipedia.org/wiki/Sawyer_International_Airport var mqt = { airport: 'MQT', name: 'Sawyer International Airport', state: 'MI' }; airports[mqt.airport] = mqt; console.log('Adding state information'); // add state of origin and departure using airport code flights.forEach(function (flight) { if (airports[flight.Origin]) { flight.stateOrigin = airports[flight.Origin].state; } else { flight.stateOrigin = 'N/A'; console.warn('Missing airport code', flight.Origin); } if (airports[flight.Dest]) { flight.stateDest = airports[flight.Dest].state; } else { flight.stateDest = 'N/A'; console.warn('Missing airport code', flight.Dest); } }); console.log('Done'); console.log('Processed flight:'); console.log(flights[0]); flight = crossfilter(flights); console.log('Conversion done'); console.log(new Date()); callback && callback(flight); }); }
var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var browserSync = require('browser-sync').create(); var reload = browserSync.reload; var sass = require('gulp-sass'); var compass = require('gulp-compass'); var watch = require('gulp-watch'); var gutil = require('gulp-util'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); // Load all gulp plugins automatically // and attach them to the `plugins` object var plugins = require('gulp-load-plugins')(); // Temporary solution until gulp 4 // https://github.com/gulpjs/gulp/issues/355 var runSequence = require('run-sequence'); var pkg = require('./package.json'); var dirs = pkg['h5bp-configs'].directories; // --------------------------------------------------------------------- // | Helper tasks | // --------------------------------------------------------------------- gulp.task('archive:create_archive_dir', function () { fs.mkdirSync(path.resolve(dirs.archive), '0755'); }); gulp.task('archive:zip', function (done) { var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip'); var archiver = require('archiver')('zip'); var files = require('glob').sync('**/*.*', { 'cwd': dirs.dist, 'dot': true // include hidden files }); var output = fs.createWriteStream(archiveName); archiver.on('error', function (error) { done(); throw error; }); output.on('close', done); files.forEach(function (file) { var filePath = path.resolve(dirs.dist, file); // `archiver.bulk` does not maintain the file // permissions, so we need to add files individually archiver.append(fs.createReadStream(filePath), { 'name': file, 'mode': fs.statSync(filePath).mode }); }); archiver.pipe(output); archiver.finalize(); }); gulp.task('clean', function (done) { require('del')([ dirs.archive, dirs.dist ]).then(function () { done(); }); }); gulp.task('copy', [ 'copy:.htaccess', 'copy:index.html', 'copy:jquery', 'copy:license', 'copy:normalize', 'copy:image', 'copy:rangeslider', 'copy:misc' ]); gulp.task('copy:.htaccess', function () { return gulp.src('node_modules/apache-server-configs/dist/.htaccess') .pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument')) .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:rangeslider', function () { return gulp.src(['node_modules/rangeslider.js/dist/rangeslider.min.js']) .pipe(gulp.dest(dirs.dist + '/vendor')); }); gulp.task('copy:index.html', function () { return gulp.src(dirs.app + '/index.html') .pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery)) .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:jquery', function () { return gulp.src(['node_modules/jquery/dist/jquery.min.js']) .pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js')) .pipe(gulp.dest(dirs.dist + '/js/vendor')); }); gulp.task('copy:license', function () { return gulp.src('LICENSE.txt') .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:image', function () { return gulp.src(dirs.app + '/img/**/*') .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:misc', function () { return gulp.src([ // Copy all files dirs.app + '/**/*', // Exclude the following files // (other tasks will handle the copying of these files) '!' + dirs.app + '/css/main.css', '!' + dirs.app + '/index.html', '!' + dirs.app + '/scss/**/*', '!' + dirs.app + '/js/**/*' ], { // Include hidden files by default dot: true }).pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:normalize', function () { return gulp.src('node_modules/normalize.css/normalize.css') .pipe(gulp.dest(dirs.dist + '/css')); }); //WE'RE JUST NOT GONNA LINT -- SORRY gulp.task('lint:js', function () { return gulp.src([ 'gulpfile.js', dirs.app + '/js/*.js', dirs.test + '/*.js' ]).pipe(plugins.jscs()) .pipe(plugins.jshint()) .pipe(plugins.jshint.reporter('jshint-stylish')) .pipe(plugins.jshint.reporter('fail')); }); gulp.task('jsprep', function () { gutil.log(gutil.colors.grey('preparing JS for production')); return gulp.src(dirs.app + '/js/**/*.js') .pipe(concat('production.min.js')) .pipe(uglify({mangle: true, compress: true})) .pipe(gulp.dest(dirs.dist + '/js')) }); gulp.task('compassify', function () { gutil.log(gutil.colors.grey('running compass compile')); return gulp.src(dirs.app + '/scss/**/*.scss') .pipe(compass({ config_file: dirs.app + '/config.rb', sass: dirs.app + '/scss', css: dirs.dist + '/css' })) //ERROR LOGGING .on('error', function(error) { gutil.log(gutil.colors.red('ERROR --', error)); this.emit('end'); }) .pipe(plugins.autoprefixer({ browsers: ['last 2 versions', 'ie >= 8', '> 1%'], cascade: false })) .pipe(gulp.dest(dirs.dist + '/css')) .pipe(browserSync.stream()); }); // --------------------------------------------------------------------- // | Main tasks | // --------------------------------------------------------------------- gulp.task('archive', function (done) { runSequence( 'build', 'archive:create_archive_dir', 'archive:zip', done); }); gulp.task('build', function (done) { runSequence( ['clean'], 'compassify', 'jsprep', 'copy', done); }); gulp.task('serve', function () { browserSync.init({ server: { baseDir: "dist" } }); //gulp.watch(dirs.app + '/scss/**/*.scss', ['sassify']); gulp.watch(dirs.app + '/scss/**/*.scss', ['compassify']); //WATCH EVERYTHING ELSE gulp.watch(dirs.app + '/js/**', ['jsprep']); gulp.watch(dirs.app + '/index.html', ['copy']); gulp.watch(dirs.app + '/img/**/*', ['copy']); gulp.watch(dirs.dist + '/index.html').on('change', browserSync.reload); gulp.watch(dirs.dist + '/js/**').on('change', browserSync.reload); }); gulp.task('default', ['build']);
(function() { var url = new URL(location.href); /** * This represents one oscillator of Kuramoto-Network. * @constructor */ var Oscillator = function () { /** * References to coupled oscillators. * @type {Array.<Oscillator>} */ this.coupled = []; this.omega = 0; this.nextTheta = 0; this.lastTheta = 0; this.step = 0; // 1st term // Value between 0 and 1.0 will be stored var times = parseInt(url.searchParams.get("gaussianLargeness"), 10); this.omega = gaussianRand(isNaN(times) ? 10 : times ); }; // Coefficient of 2nd term (K in Wikipedia) Oscillator.coeff = 1.0; Oscillator.prototype.addCoupledOscillator = function (oscilattor) { this.coupled.push(oscilattor); }; Oscillator.prototype.calculateNextTheta = function () { // Calculates the 2nd term if (this.coupled.length < 1) { this.nextTheta = this.omega; return; } // Here is Kuramoto Model var sum = 0.0; for (var i = 0; i < this.coupled.length; i++) { sum += Math.sin(this.lastTheta - this.coupled[ i ].lastTheta); } this.nextTheta += this.omega - ((Oscillator.coeff / this.coupled.length) * sum); }; Oscillator.prototype.updateTheta = function () { this.lastTheta = this.nextTheta; this.step++; }; Oscillator.prototype.getPhase = function () { return this.lastTheta; } /** * This class uses d3.js * @param {Array.<Array.<Number>>} data * @constructor */ function LineGraph(data, orderParameters) { // Specifies the parent element this graph add to. this.container = d3.select("#debugLineGraphs"); this.width = 960; this.height = 200; var margin = {}; margin.top = margin.right = margin.bottom = margin.left = 30; this.margin = margin; this.data = data; this.orderParameters = orderParameters; this.x = d3.scaleLinear().range([0, this.width]); this.color = d3.scaleOrdinal(d3.schemeCategory10); } LineGraph.prototype.render = function() { var self = this; if (!self.svg) { // render first time self.y = d3.scaleLinear() .range([self.height, 0]); self.yOrderParam = d3.scaleLinear() .range([self.height, 0]) self.yOrderParam.domain([0,1]); self.xAxis = d3.axisBottom() .scale(self.x); self.yAxis = d3.axisLeft() .scale(self.y); self.yAxis2 = d3.axisRight() .scale(self.yOrderParam); self.line = d3.line() .x(function(d, i) { return self.x(i); }) .y(function(d) { return self.y(d); }); // Really need this? //.interpolate("basis"); self.orderParamLine = d3.line() .x(function(d, i) { /*console.log("x)d:" + d + ",i:" + i);*/ return self.x(i); }) .y(function(d) { /*console.log("y)d:" + d);*/ return self.yOrderParam(d);}); self.svg = self.container.append("svg") .attr("width", self.width + self.margin.left + self.margin.right) .attr("height", self.height + self.margin.top + self.margin.bottom) .append("g") .attr("transform", "translate(" + self.margin.left + "," + self.margin.top + ")"); //self.x.domain(d3.extent(data, function(d) { return d.x; })); //self.y.domain(d3.extent(data, function(d) { return d.y; })); self.svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + self.height + ")") .call(self.xAxis); self.svg.append("g") .attr("class", "y axis") .call(self.yAxis); self.svg.append("g") .attr("class", "y axis2") .attr("transform", "translate(" + self.width + ",0)") .call(self.yAxis2); self.lines = self.svg.append("g") .attr("class", "lines"); self.lines .selectAll("path.line") .data(self.data, function(ts, i) {return i;}) .enter() .append("path") .attr("class", "line") .attr("stroke", "red") .attr("fill", "none") .attr("d", self.line); self.orderParameter = self.svg.append("g") .attr("class", "orderParameterLine"); self.orderParameter .append("path") .data(self.orderParameters) .attr("fill", "none") .attr("stroke", "silver") .attr("d", self.orderParamLine); } else { // Resets the target domain (min and max values of each axis) self.x.domain([0, d3.max(self.data, function(d) {return d.length;})]); self.y.domain(d3.extent(d3.merge(self.data))); self.svg.select("g.y") .transition() .duration(100) .call(self.yAxis); self.svg.select("g.x") .transition() .duration(100) .call(self.xAxis); self.lines .selectAll("path.line") .data(self.data) .attr("d", self.line).style("stroke", function(d, i) {return self.color(i);}); self.orderParameter .select("path") .attr("stroke", "black") .attr("d", self.orderParamLine(self.orderParameters)); } }; /** * Generate gaussian-distributed numbers with the Central number theorem. * @param {Number} times Integer representing how large numbers to add to simulate gaussian distribution. */ function gaussianRand (times) { var rand = 0; for (var i = 1; i <= times; i++) { rand += Math.random(); } return rand / times; } /** * * @constructor */ function OrderParameterCell() { this.td = document.createElement("td"); this.svg = d3.select(this.td).append("svg"); this.text = document.createTextNode(""); this.td.appendChild(this.text); } window.App = !(typeof window['App'] !== 'undefined') ? (function () { var oscillators = parseInt(url.searchParams.get("oscillators") ,10); var NUMBERS_OF_OSCILLATOR = isNaN(oscillators) ? 10 : oscillators; var STEPS_TO_REMEMBER = 50; var intervalTimer = null; return { init: function () { var oscillators = []; /** * Stores old values of the oscillators. * @type {Array.<Array.<Number>>} * */ var oscillatorValues = [ // Elements such below come here // - Time series values (an array) of oscillator #1, // - Time series values (an array) of oscillator #2,.. ]; var orderParameters = []; var orderParameterTable = document.getElementById("orderParameterTable"); /* @type {Array.<Array.{Element(td)}>} */ var orderParameterCells = []; // Set K var k = parseFloat(document.getElementById("k").value); if (Number.isNaN(k)) { alert("K is NaN"); return; } else { Oscillator.coeff = k; } var omegaDist = {0.0: 0, 0.1:0, 0.2:0, 0.3:0, 0.4: 0, 0.5: 0, 0.6:0, 0.7:0, 0.8:0, 0.9: 0}; for (var i = 0; i < NUMBERS_OF_OSCILLATOR; i++) { // Constructs an oscillator. var oscillator = new Oscillator() oscillators.push(oscillator); // Constructs an oscillator value holder. oscillatorValues.push([]); // Appends a row of the order parameter table var tr = document.createElement("tr"); var cells = []; for (var k = 0; k < NUMBERS_OF_OSCILLATOR; k++) { if (k === i) { var td = document.createElement("td"); td.appendChild(document.createTextNode("Osc #" + i)); td.setAttribute("class", "diagonal"); tr.appendChild(td); cells.push(td); } else { var cell = new OrderParameterCell(); tr.appendChild(cell.td); cells.push(cell); } } orderParameterTable.appendChild(tr); orderParameterCells.push(cells); omegaDist[oscillator.omega.toFixed(1)] += 1; } console.log("Omega distribution:"); for (var key in omegaDist) { console.log("[" + key + "]" + omegaDist[key]); } var lineGraph = new LineGraph(oscillatorValues, orderParameters); // Sets coupled oscillators for (var target = 0; target < oscillators.length; target++) { //console.log("connecting #" + target + " to:"); for (i = 0; i < oscillators.length; i++) { if (i === target) { // Skips if the setting target and the oscillator to be set are same. continue; } oscillators[target].addCoupledOscillator(oscillators[i]); //console.log("\t#" + i); } } // Sets up interval oscillator updates. var x = 0; intervalTimer = window.setInterval(function() { for (var i = 0; i < oscillators.length; i++) { oscillators[i].calculateNextTheta(); } // Its absolute value will be taken when we calculate the order parameter. var sum_of_euler_real = 0.0; var sum_of_euler_imaginary = 0.0; for (var i = 0; i < oscillators.length; i++) { oscillators[i].updateTheta(); // Saves the value onto oscillatorValues. if (oscillatorValues[i].length >= STEPS_TO_REMEMBER) { // Removes the oldest value if the array exceeds the limit. oscillatorValues[i].shift(); } oscillatorValues[i].push(Math.sin(oscillators[i].lastTheta % (Math.PI * 2))); // Updates the order parameter table. for (var k = i + 1; k < oscillators.length; k++) { // Calculates an order parameter just for the 2 oscillators. var real = Math.cos(oscillators[i].getPhase()) + Math.cos(oscillators[k].getPhase()); var imaginary = Math.sin(oscillators[i].getPhase()) + Math.sin(oscillators[k].getPhase()); var partialOrderParameter = Math.sqrt(Math.pow(real, 2) + Math.pow(imaginary, 2)) / 2; // Updates the target cell. if (orderParameterCells[i][k] instanceof OrderParameterCell) { orderParameterCells[i][k].text.textContent = partialOrderParameter.toFixed(3); // Updates: #FFFFFF // ^^^^ here, like if 0.0 -> FFFFFF, 1.0 -> FF0000 var blueOrGreen = Math.round((1 - partialOrderParameter) * 255).toString(16); // Add leading zeros blueOrGreen = ("00" + blueOrGreen).substr(-2); orderParameterCells[i][k].td.style.backgroundColor = "#FF" + blueOrGreen + blueOrGreen; } } // Calculates order parameter components for the whole system (all oscillators). sum_of_euler_real += Math.cos(oscillators[i].getPhase()); sum_of_euler_imaginary += Math.sin(oscillators[i].getPhase()); } if (orderParameters.length >= STEPS_TO_REMEMBER) { // Removes the oldest value if the array exceeds the limit. orderParameters.shift(); } // Calculates the order parameter var absoluteSum = Math.sqrt(Math.pow(sum_of_euler_real, 2) + Math.pow(sum_of_euler_imaginary, 2)); //console.log("m=" + (absoluteSum / oscillators.length)); orderParameters.push((absoluteSum / oscillators.length)); lineGraph.render(); x++; }, 300); }, stop: function() { if (intervalTimer !== null) { clearInterval(intervalTimer); } } }; })() : window.app; })();
angular.module('inviteFactory', ['firebase']) .factory('invite', ['$firebaseObject', '$http' , function ($firebaseObject, $http) { var inviteFactory = {}; // mandrill API key ** free version API key only for production ** // in real use case, should store this securely var mandrillKey = 'ul35c_Y39BxIZUIUa_HIog'; inviteFactory.sendEmailInvitation = function (sender, orgName, recipient, recipientEmail) { // in production: use localhost for testing // change link when deployed var link = 'http://'+window.host+':3000/#/'+orgName+'/signup'; var orgId; var orgRef = new Firebase('https://bizgramer.firebaseio.com/'+orgName); var orgObj = $firebaseObject(orgRef); orgObj.$loaded() .then(function() { // query firebase db to get the orgId for the logged in user's org orgId = orgObj.orgKey; var params = { "key": mandrillKey, "message": { "from_email": sender+"."+orgName+"@Hiver.com", "to":[{"email":recipientEmail}], "subject": "Hey "+recipient+" go signup at Hive!", "html": "<h1>"+sender+" invited you to sign up for "+orgName+" at Hive</h1><h2>Your OrgID is "+orgId+"</h2><h3><a href='"+link+"''>"+link+"</a></h3>", "autotext": true, "track_opens": true, "track_clicks": true } }; // end params // send ajax request to Mandrill api for email invite $http.post('https://mandrillapp.com/api/1.0/messages/send.json', params) .success(function() { console.log('email invite sent successfully'); }) .error(function() { console.log('error sending email invite'); }); }) .catch(function (error) { console.log('error', error); }); }; //end .sendEmailInvitation return inviteFactory; }]);
/** * Created by DOCer on 2017/7/11. */ import {connect} from 'app'; import UI from './UI/'; export default connect( ({test}) => (test), { onStart({dispatch, getState}){ dispatch({ type: "test/showTableLoading" }); // ajax request after empty completing setTimeout(() => { dispatch({ type: "test/hideTableLoading", }); dispatch({ type: "test/setSelectedRowKeys", payload: [2] }); }, 800); }, onChange({dispatch, getState}, selectedRowKeys){ dispatch({ type: "test/setSelectedRowKeys", payload: selectedRowKeys }); }, onPanelChange({dispatch, getState}, {mode, data}){ console.log(data, mode); }, onCascaderChange({dispatch, getState}, value){ console.log(value); }, onCollapseChange({dispatch, getState}, key){ console.log(key); }, onDecline ({dispatch, getState}){ let percent = getState().test.progressData.percent - 10; if (percent < 0) { percent = 0; } dispatch({ type: "test/decline", payload: percent }); }, onIncrease ({dispatch, getState}){ let percent = getState().test.progressData.percent + 10; if (percent > 100) { percent = 100; } dispatch({ type: "test/increase", payload: percent }); }, } )(UI);
function AddressBook () { this.contacts=[]; this.initialComplete = false; AddressBook.prototype.addContact= function(newContact) { this.contacts.push(newContact); }; AddressBook.prototype.getContact = function(index) { return this.contacts[index]; }; AddressBook.prototype.deleteContact = function(index) { this.contacts.splice(index, 1); }; AddressBook.prototype.getInitialContacts = function(cb) { var self = this; setTimeout(function() { self.initialComplete = true; if (cb) { return cb(); } }, 3); }; }
import ListaDeNotas from "./ListaDeNotas" export default ListaDeNotas
'use strict'; const {BrowserWindow, app} = require('electron'); const test = require('tape-async'); const delay = require('delay'); const { appReady, focusWindow, minimizeWindow, restoreWindow, windowVisible } = require('.'); let win; test('exports an appReady function', async t => { t.is(typeof appReady, 'function'); }); test('appReady return a promise that resolve when electron app is ready', async t => { await appReady(); // We could create a window, because the app is ready win = new BrowserWindow({show: false}); await delay(400); t.is(typeof win, 'object'); }); test('focusWindow return a promise that resolve when window is focused', async t => { const browser = new BrowserWindow(); // browser.loadURL(`file://${__dirname}/index.html`); await windowVisible(browser); t.true(await focusWindow(browser)); t.true(browser.isFocused()); browser.close(); }); test('minimizeWindow return a promise that resolve when window is minimized', async t => { const browser = new BrowserWindow(); await windowVisible(browser); t.false(browser.isMinimized()); t.true(await minimizeWindow(browser)); t.true(browser.isMinimized()); browser.close(); }); test('restoreWindow return a promise that resolve when window is restored', async t => { const browser = new BrowserWindow(); await windowVisible(browser); t.true(await minimizeWindow(browser)); t.true(browser.isMinimized()); t.true(await restoreWindow(browser)); await delay(100); t.false(browser.isMinimized()); browser.close(); }); test('app quit', t => { app.on('window-all-closed', () => app.quit()); t.end(); win.close(); });
(function() { var modules = window.modules || []; var navigation_graphCache = null; var navigation_graphFunc = function() { return (function() { var NavigationGraph, NavigationNode, Navigator; Navigator = require('gator/navigator'); NavigationNode = require('gator/navigation_node'); NavigationGraph = (function() { var _setFrom; function NavigationGraph(navigator) { this.navigator = navigator; this.nodes = []; this.currentFrom = 'initial'; this.navigator.transitionFinished.add(_setFrom.call(this)); } NavigationGraph.create = function() { return new this(new Navigator()); }; NavigationGraph.prototype.registerTransition = function(from, to) { if (!this.hasTransition(from, to)) { return this.nodes.push(new NavigationNode(from, to)); } }; NavigationGraph.prototype.hasTransition = function(from, to) { return this.getTransition(from, to) != null; }; NavigationGraph.prototype.getTransition = function(from, to) { var node; return ((function() { var _i, _len, _ref, _results; _ref = this.nodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if (node.matches(from, to)) { _results.push(node); } } return _results; }).call(this))[0] || null; }; NavigationGraph.prototype.registerAction = function(action, from, to) { var node, _i, _len, _ref, _results; if (from == null) { from = null; } if (to == null) { to = null; } _ref = this.nodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if (node.matches(from, to)) { _results.push(node.registerAction(action)); } } return _results; }; NavigationGraph.prototype.registerActionAt = function(position, action, from, to) { var node, _i, _len, _ref, _results; if (from == null) { from = null; } if (to == null) { to = null; } _ref = this.nodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if (node.matches(from, to)) { _results.push(node.registerActionAt(position, action)); } } return _results; }; NavigationGraph.prototype.canTransitionTo = function(to) { return this.hasTransition(this.currentFrom, to); }; NavigationGraph.prototype.transitionTo = function(to, context, failedAction) { if (context == null) { context = null; } if (failedAction == null) { failedAction = null; } if (this.canTransitionTo(to)) { return this.navigator.perform(this.getTransition(this.currentFrom, to), context, failedAction); } else { return typeof failedAction === "function" ? failedAction() : void 0; } }; _setFrom = function() { var _this = this; return function(to) { return _this.currentFrom = to; }; }; return NavigationGraph; })(); return NavigationGraph; }).call(this); }; modules.gator__navigation_graph = function() { if (navigation_graphCache === null) { navigation_graphCache = navigation_graphFunc(); } return navigation_graphCache; }; window.modules = modules; })(); (function() { var modules = window.modules || []; var navigation_nodeCache = null; var navigation_nodeFunc = function() { return (function() { var NavigationNode; NavigationNode = (function() { var _getIndexFrom; function NavigationNode(from, to) { this.from = from; this.to = to; this.actions = []; } NavigationNode.prototype.registerAction = function(action) { return this.actions.push(action); }; NavigationNode.prototype.registerActionAt = function(position, action) { return this.actions.splice(_getIndexFrom.call(this, position), 0, action); }; NavigationNode.prototype.matches = function(from, to) { return ((from == null) || this.from === from) && ((to == null) || this.to === to); }; _getIndexFrom = function(position) { if (typeof position === 'number') { if (position < 0) { return 0; } if (position <= this.actions.length) { return position; } return this.actions.length; } else { if (position === "first") { return 0; } if (position === "last") { return this.actions.length; } } }; return NavigationNode; })(); return NavigationNode; }).call(this); }; modules.gator__navigation_node = function() { if (navigation_nodeCache === null) { navigation_nodeCache = navigation_nodeFunc(); } return navigation_nodeCache; }; window.modules = modules; })(); (function() { var modules = window.modules || []; var navigatorCache = null; var navigatorFunc = function() { return (function() { var Navigator, Signal, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Signal = require('cronus/signal'); Navigator = (function() { var _run; function Navigator() { this.halt = __bind(this.halt, this); this["continue"] = __bind(this["continue"], this); this.hold = __bind(this.hold, this); var _this = this; this.inTransition = false; this.shouldHold = false; this.failedAction = null; this.transitionFinished = new Signal(); this.transitionFinished.add(function() { return _this.inTransition = false; }); } Navigator.prototype.perform = function(node, context, failedAction) { var action; if (node == null) { node = null; } if (context == null) { context = null; } if (failedAction == null) { failedAction = null; } if (this.inTransition) { throw new Error("The previous transition ('" + this.node.from + "' to '" + this.node.to + "') is not closed."); } this.node = node; this.context = context; this.failedAction = failedAction; this.pendingActions = (function() { var _i, _len, _ref, _results; _ref = this.node.actions; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { action = _ref[_i]; _results.push(action); } return _results; }).call(this); return _run.call(this, this.pendingActions); }; Navigator.prototype.hold = function() { if (this.inTransition) { return this.shouldHold = true; } }; Navigator.prototype["continue"] = function() { if (this.inTransition) { this.shouldHold = false; return _run.call(this, this.pendingActions); } }; Navigator.prototype.halt = function() { if (this.inTransition) { if (this.shouldHold) { this.shouldHold = false; this.inTransition = false; return typeof this.failedAction === "function" ? this.failedAction() : void 0; } else { throw new Error("Halt"); } } }; _run = function(actions) { var action, e; this.inTransition = true; try { this.allActionsRun = true; while (this.pendingActions.length) { this.allActionsRun = false; action = this.pendingActions.shift(); action(this, this.context); if (this.shouldHold) { break; } if (!this.pendingActions.length) { this.allActionsRun = true; } } if (this.allActionsRun) { return this.transitionFinished.dispatch(this.node.to); } } catch (_error) { e = _error; if (e.message === "Halt") { return typeof this.failedAction === "function" ? this.failedAction() : void 0; } else { throw e; } } }; return Navigator; })(); return Navigator; }).call(this); }; modules.gator__navigator = function() { if (navigatorCache === null) { navigatorCache = navigatorFunc(); } return navigatorCache; }; window.modules = modules; })(); (function() { var modules = window.modules || []; window.require = function(path) { var transformedPath = path.replace(/\//g, '__'); if (transformedPath.indexOf('__') === -1) { transformedPath = '__' + transformedPath; } var factory = modules[transformedPath]; if (factory === null) { return null; } else { return modules[transformedPath](); } }; })(); (function() { var modules = window.modules || []; var multi_signal_relayCache = null; var multi_signal_relayFunc = function() { return (function() { var MultiSignalRelay, Signal, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Signal = require("cronus/signal"); MultiSignalRelay = (function(_super) { __extends(MultiSignalRelay, _super); function MultiSignalRelay(signals) { var signal, _i, _len; MultiSignalRelay.__super__.constructor.call(this); for (_i = 0, _len = signals.length; _i < _len; _i++) { signal = signals[_i]; signal.add(this.dispatch); } } MultiSignalRelay.prototype.applyListeners = function(rest) { var listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; _results.push(listener.apply(listener, rest)); } return _results; }; return MultiSignalRelay; })(Signal); return MultiSignalRelay; }).call(this); }; modules.cronus__multi_signal_relay = function() { if (multi_signal_relayCache === null) { multi_signal_relayCache = multi_signal_relayFunc(); } return multi_signal_relayCache; }; window.modules = modules; })(); (function() { var modules = window.modules || []; var signalCache = null; var signalFunc = function() { return (function() { var Signal, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __slice = [].slice; Signal = (function() { function Signal() { this.dispatch = __bind(this.dispatch, this); this.isApplyingListeners = false; this.listeners = []; this.onceListeners = []; this.removeCache = []; } Signal.prototype.add = function(listener) { return this.listeners.push(listener); }; Signal.prototype.addOnce = function(listener) { this.onceListeners.push(listener); return this.add(listener); }; Signal.prototype.remove = function(listener) { if (this.isApplyingListeners) { return this.removeCache.push(listener); } else { if (this.listeners.indexOf(listener) !== -1) { return this.listeners.splice(this.listeners.indexOf(listener), 1); } } }; Signal.prototype.removeAll = function() { return this.listeners = []; }; Signal.prototype.numListeners = function() { return this.listeners.length; }; Signal.prototype.dispatch = function() { var rest; rest = 1 <= arguments.length ? __slice.call(arguments, 0) : []; this.isApplyingListeners = true; this.applyListeners(rest); this.removeOnceListeners(); this.isApplyingListeners = false; return this.clearRemoveCache(); }; Signal.prototype.applyListeners = function(rest) { var listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; _results.push(listener.apply(listener, rest)); } return _results; }; Signal.prototype.removeOnceListeners = function() { var listener, _i, _len, _ref; _ref = this.onceListeners; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; this.remove(listener); } return this.onceListeners = []; }; Signal.prototype.clearRemoveCache = function() { var listener, _i, _len, _ref; _ref = this.removeCache; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; this.remove(listener); } return this.removeCache = []; }; return Signal; })(); return Signal; }).call(this); }; modules.cronus__signal = function() { if (signalCache === null) { signalCache = signalFunc(); } return signalCache; }; window.modules = modules; })(); (function() { var modules = window.modules || []; var signal_relayCache = null; var signal_relayFunc = function() { return (function() { var Signal, SignalRelay, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Signal = require("cronus/signal"); SignalRelay = (function(_super) { __extends(SignalRelay, _super); function SignalRelay(signal) { SignalRelay.__super__.constructor.call(this); signal.add(this.dispatch); } SignalRelay.prototype.applyListeners = function(rest) { var listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { listener = _ref[_i]; _results.push(listener.apply(listener, rest)); } return _results; }; return SignalRelay; })(Signal); return SignalRelay; }).call(this); }; modules.cronus__signal_relay = function() { if (signal_relayCache === null) { signal_relayCache = signal_relayFunc(); } return signal_relayCache; }; window.modules = modules; })();
/*! @package noty - jQuery Notification Plugin @version version: 2.3.7 @contributors https://github.com/needim/noty/graphs/contributors @documentation Examples and Documentation - http://needim.github.com/noty/ @license Licensed under the MIT licenses: http://www.opensource.org/licenses/mit-license.php */ if(typeof Object.create !== 'function') { Object.create = function(o) { function F() { } F.prototype = o; return new F(); }; } var NotyObject = { init: function(options) { // Mix in the passed in options with the default options this.options = $.extend({}, $.noty.defaults, options); this.options.layout = (this.options.custom) ? $.noty.layouts['inline'] : $.noty.layouts[this.options.layout]; if($.noty.themes[this.options.theme]) this.options.theme = $.noty.themes[this.options.theme]; else options.themeClassName = this.options.theme; delete options.layout; delete options.theme; this.options = $.extend({}, this.options, this.options.layout.options); this.options.id = 'noty_' + (new Date().getTime() * Math.floor(Math.random() * 1000000)); this.options = $.extend({}, this.options, options); // Build the noty dom initial structure this._build(); // return this so we can chain/use the bridge with less code. return this; }, // end init _build: function() { // Generating noty bar var $bar = $('<div class="noty_bar noty_type_' + this.options.type + '"></div>').attr('id', this.options.id); $bar.append(this.options.template).find('.noty_text').html(this.options.text); this.$bar = (this.options.layout.parent.object !== null) ? $(this.options.layout.parent.object).css(this.options.layout.parent.css).append($bar) : $bar; if(this.options.themeClassName) this.$bar.addClass(this.options.themeClassName).addClass('noty_container_type_' + this.options.type); // Set buttons if available if(this.options.buttons) { // If we have button disable closeWith & timeout options this.options.closeWith = []; this.options.timeout = false; var $buttons = $('<div/>').addClass('noty_buttons'); (this.options.layout.parent.object !== null) ? this.$bar.find('.noty_bar').append($buttons) : this.$bar.append($buttons); var self = this; $.each(this.options.buttons, function(i, button) { var $button = $('<button/>').addClass((button.addClass) ? button.addClass : 'gray').html(button.text).attr('id', button.id ? button.id : 'button-' + i) .attr('title', button.title) .appendTo(self.$bar.find('.noty_buttons')) .on('click', function(event) { if($.isFunction(button.onClick)) { button.onClick.call($button, self, event); } }); }); } // For easy access this.$message = this.$bar.find('.noty_message'); this.$closeButton = this.$bar.find('.noty_close'); this.$buttons = this.$bar.find('.noty_buttons'); $.noty.store[this.options.id] = this; // store noty for api }, // end _build show: function() { var self = this; (self.options.custom) ? self.options.custom.find(self.options.layout.container.selector).append(self.$bar) : $(self.options.layout.container.selector).append(self.$bar); if(self.options.theme && self.options.theme.style) self.options.theme.style.apply(self); ($.type(self.options.layout.css) === 'function') ? this.options.layout.css.apply(self.$bar) : self.$bar.css(this.options.layout.css || {}); self.$bar.addClass(self.options.layout.addClass); self.options.layout.container.style.apply($(self.options.layout.container.selector), [self.options.within]); self.showing = true; if(self.options.theme && self.options.theme.style) self.options.theme.callback.onShow.apply(this); if($.inArray('click', self.options.closeWith) > -1) self.$bar.css('cursor', 'pointer').one('click', function(evt) { self.stopPropagation(evt); if(self.options.callback.onCloseClick) { self.options.callback.onCloseClick.apply(self); } self.close(); }); if($.inArray('hover', self.options.closeWith) > -1) self.$bar.one('mouseenter', function() { self.close(); }); if($.inArray('button', self.options.closeWith) > -1) self.$closeButton.one('click', function(evt) { self.stopPropagation(evt); self.close(); }); if($.inArray('button', self.options.closeWith) == -1) self.$closeButton.remove(); if(self.options.callback.onShow) self.options.callback.onShow.apply(self); if (typeof self.options.animation.open == 'string') { self.$bar.css('height', self.$bar.innerHeight()); self.$bar.show().addClass(self.options.animation.open).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self); self.showing = false; self.shown = true; }); } else { self.$bar.animate( self.options.animation.open, self.options.animation.speed, self.options.animation.easing, function() { if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self); self.showing = false; self.shown = true; }); } // If noty is have a timeout option if(self.options.timeout) self.$bar.delay(self.options.timeout).promise().done(function() { self.close(); }); return this; }, // end show close: function() { if(this.closed) return; if(this.$bar && this.$bar.hasClass('i-am-closing-now')) return; var self = this; if(this.showing) { self.$bar.queue( function() { self.close.apply(self); } ); return; } if(!this.shown && !this.showing) { // If we are still waiting in the queue just delete from queue var queue = []; $.each($.noty.queue, function(i, n) { if(n.options.id != self.options.id) { queue.push(n); } }); $.noty.queue = queue; return; } self.$bar.addClass('i-am-closing-now'); if(self.options.callback.onClose) { self.options.callback.onClose.apply(self); } if (typeof self.options.animation.close == 'string') { self.$bar.addClass(self.options.animation.close).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self); self.closeCleanUp(); }); } else { self.$bar.clearQueue().stop().animate( self.options.animation.close, self.options.animation.speed, self.options.animation.easing, function() { if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self); }) .promise().done(function() { self.closeCleanUp(); }); } }, // end close closeCleanUp: function() { var self = this; // Modal Cleaning if(self.options.modal) { $.notyRenderer.setModalCount(-1); if($.notyRenderer.getModalCount() == 0) $('.noty_modal').fadeOut(self.options.animation.fadeSpeed, function() { $(this).remove(); }); } // Layout Cleaning $.notyRenderer.setLayoutCountFor(self, -1); if($.notyRenderer.getLayoutCountFor(self) == 0) $(self.options.layout.container.selector).remove(); // Make sure self.$bar has not been removed before attempting to remove it if(typeof self.$bar !== 'undefined' && self.$bar !== null) { if (typeof self.options.animation.close == 'string') { self.$bar.css('transition', 'all 100ms ease').css('border', 0).css('margin', 0).height(0); self.$bar.one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() { self.$bar.remove(); self.$bar = null; self.closed = true; if(self.options.theme.callback && self.options.theme.callback.onClose) { self.options.theme.callback.onClose.apply(self); } }); } else { self.$bar.remove(); self.$bar = null; self.closed = true; } } delete $.noty.store[self.options.id]; // deleting noty from store if(self.options.theme.callback && self.options.theme.callback.onClose) { self.options.theme.callback.onClose.apply(self); } if(!self.options.dismissQueue) { // Queue render $.noty.ontap = true; $.notyRenderer.render(); } if(self.options.maxVisible > 0 && self.options.dismissQueue) { $.notyRenderer.render(); } }, // end close clean up setText: function(text) { if(!this.closed) { this.options.text = text; this.$bar.find('.noty_text').html(text); } return this; }, setType: function(type) { if(!this.closed) { this.options.type = type; this.options.theme.style.apply(this); this.options.theme.callback.onShow.apply(this); } return this; }, setTimeout: function(time) { if(!this.closed) { var self = this; this.options.timeout = time; self.$bar.delay(self.options.timeout).promise().done(function() { self.close(); }); } return this; }, stopPropagation: function(evt) { evt = evt || window.event; if(typeof evt.stopPropagation !== "undefined") { evt.stopPropagation(); } else { evt.cancelBubble = true; } }, closed : false, showing: false, shown : false }; // end NotyObject $.notyRenderer = {}; $.notyRenderer.init = function(options) { // Renderer creates a new noty var notification = Object.create(NotyObject).init(options); if(notification.options.killer) $.noty.closeAll(); (notification.options.force) ? $.noty.queue.unshift(notification) : $.noty.queue.push(notification); $.notyRenderer.render(); return ($.noty.returns == 'object') ? notification : notification.options.id; }; $.notyRenderer.render = function() { var instance = $.noty.queue[0]; if($.type(instance) === 'object') { if(instance.options.dismissQueue) { if(instance.options.maxVisible > 0) { if($(instance.options.layout.container.selector + ' li').length < instance.options.maxVisible) { $.notyRenderer.show($.noty.queue.shift()); } else { } } else { $.notyRenderer.show($.noty.queue.shift()); } } else { if($.noty.ontap) { $.notyRenderer.show($.noty.queue.shift()); $.noty.ontap = false; } } } else { $.noty.ontap = true; // Queue is over } }; $.notyRenderer.show = function(notification) { if(notification.options.modal) { $.notyRenderer.createModalFor(notification); $.notyRenderer.setModalCount(+1); } // Where is the container? if(notification.options.custom) { if(notification.options.custom.find(notification.options.layout.container.selector).length == 0) { notification.options.custom.append($(notification.options.layout.container.object).addClass('i-am-new')); } else { notification.options.custom.find(notification.options.layout.container.selector).removeClass('i-am-new'); } } else { if($(notification.options.layout.container.selector).length == 0) { $('body').append($(notification.options.layout.container.object).addClass('i-am-new')); } else { $(notification.options.layout.container.selector).removeClass('i-am-new'); } } $.notyRenderer.setLayoutCountFor(notification, +1); notification.show(); }; $.notyRenderer.createModalFor = function(notification) { if($('.noty_modal').length == 0) { var modal = $('<div/>').addClass('noty_modal').addClass(notification.options.theme).data('noty_modal_count', 0); if(notification.options.theme.modal && notification.options.theme.modal.css) modal.css(notification.options.theme.modal.css); modal.prependTo($('body')).fadeIn(self.options.animation.fadeSpeed); if($.inArray('backdrop', notification.options.closeWith) > -1) modal.on('click', function(e) { $.noty.closeAll(); }); } }; $.notyRenderer.getLayoutCountFor = function(notification) { return $(notification.options.layout.container.selector).data('noty_layout_count') || 0; }; $.notyRenderer.setLayoutCountFor = function(notification, arg) { return $(notification.options.layout.container.selector).data('noty_layout_count', $.notyRenderer.getLayoutCountFor(notification) + arg); }; $.notyRenderer.getModalCount = function() { return $('.noty_modal').data('noty_modal_count') || 0; }; $.notyRenderer.setModalCount = function(arg) { return $('.noty_modal').data('noty_modal_count', $.notyRenderer.getModalCount() + arg); }; // This is for custom container $.fn.noty = function(options) { options.custom = $(this); return $.notyRenderer.init(options); }; $.noty = {}; $.noty.queue = []; $.noty.ontap = true; $.noty.layouts = {}; $.noty.themes = {}; $.noty.returns = 'object'; $.noty.store = {}; $.noty.get = function(id) { return $.noty.store.hasOwnProperty(id) ? $.noty.store[id] : false; }; $.noty.close = function(id) { return $.noty.get(id) ? $.noty.get(id).close() : false; }; $.noty.setText = function(id, text) { return $.noty.get(id) ? $.noty.get(id).setText(text) : false; }; $.noty.setType = function(id, type) { return $.noty.get(id) ? $.noty.get(id).setType(type) : false; }; $.noty.clearQueue = function() { $.noty.queue = []; }; $.noty.closeAll = function() { $.noty.clearQueue(); $.each($.noty.store, function(id, noty) { noty.close(); }); }; var windowAlert = window.alert; $.noty.consumeAlert = function(options) { window.alert = function(text) { if(options) options.text = text; else options = {text: text}; $.notyRenderer.init(options); }; }; $.noty.stopConsumeAlert = function() { window.alert = windowAlert; }; $.noty.defaults = { layout : 'top', theme : 'defaultTheme', type : 'alert', text : '', dismissQueue: true, template : '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>', animation : { open : {height: 'toggle'}, close : {height: 'toggle'}, easing: 'swing', speed : 500, fadeSpeed: 'fast', }, timeout : false, force : false, modal : false, maxVisible : 5, killer : false, closeWith : ['click'], callback : { onShow : function() { }, afterShow : function() { }, onClose : function() { }, afterClose : function() { }, onCloseClick: function() { } }, buttons : false }; $(window).on('resize', function() { $.each($.noty.layouts, function(index, layout) { layout.container.style.apply($(layout.container.selector)); }); }); // Helpers window.noty = function noty(options) { return $.notyRenderer.init(options); };
import Instruction from './Instruction'; import Container from './Container'; import Share from './Share'; import React from 'react'; import request from 'superagent'; var Mememe = React.createClass({ getInitialState (){ var memesGenerated = false; return{ memesGenerated: memesGenerated }; }, generateMemes (descriptions){ for(var key in descriptions) { var VALUE = descriptions[key]; var YOUR_API_KEY = "xxx"; var YOUR_CSE_ID = "yyy"; var searchQuery = `https://www.googleapis.com/customsearch/v1?key=${YOUR_API_KEY}&cx=${YOUR_CSE_ID}&q=${VALUE}&searchType=image&fileType=jpg&imgSize=small&alt=json` request .get(searchQuery) .end((err, results) => { debugger }) debugger } var memesGenerated = true; this.setState({memesGenerated: memesGenerated}); }, render (){ var generateMemes = this.generateMemes; var memesGenerated = this.state.memesGenerated; return ( <div className="mememe"> <Instruction/> <Container memesGenerated={memesGenerated} generateMemes={generateMemes}/> <Share/> </div> ) } }); module.exports = Mememe;
var Deferred = require('stupid-deferred') var Imageloader = require('stupid-imageloader'); /** * Image collection loader * @constructor */ function Imagesloader(opts){ /** * @define {object} Collection of public methods. */ var self = {}; /** * @define {object} Options for the constructor */ var opts = opts || {}; /** * @define {object} A image loader object */ var imageloader = Imageloader(); /** * @define {array} A holder for when an image is loaded */ var imgs = []; /** * @define {array} A holder for the image src that should be loaded */ var srcs = []; /** * @define {object} A promise container for promises */ var def; /** * Load a collection of images * @example imageloader.load(['img1.jpg', 'img2.jpg', 'img3.jpg']).success(function(){ // Do something }); * @param {array} images A collection of img object or img.src (paths) * @config {object} def Create a promise object * @return {object} Return the promise object */ function load(images){ def = Deferred(); /** * Check if the images is img objects or image src * return string of src */ srcs = convertImagesToSrc(images); /** * Loop through src's and load image */ for (var i = 0; i < srcs.length; i++) { imageloader.load(srcs[i]) .success(function(img){ /** call imageloaded a pass the img that is loaded */ imageLoaded(img); }) .error(function(msg){ def.reject(msg + ' couldn\'t be loaded'); }); }; return def.promise; } /** * Image loaded checker * @param {img} img The loaded image */ function imageLoaded(img){ /** Notify the promise */ def.notify("notify"); /** Add the image to the imgs array */ imgs.push(img); /** If the imgs array size is the same as the src's */ if(imgs.length == srcs.length){ /** First sort images, to have the same order as src's */ sortImages(); /** Resolve the promise with the images */ def.resolve(imgs); } } /** * Convert img to src * @param {array} imgs A collection og img/img paths * @config {array} src A temporally array for storing img path/src * @return {array} Return an array of img src's */ function convertImagesToSrc(imgs){ var src = []; for (var i = 0; i < imgs.length; i++) { /** If the img is an object (img) get the src */ if(typeof imgs[i] == 'object'){ src.push(imgs[i].src); } }; /** If the src array is null return the original imgs array */ return src.length ? src : imgs; } /** * Sort images after the originally order * @config {array} arr A temporally array for sorting images */ function sortImages(){ var arr = []; /** * Create a double loop * And match the order of the srcs array */ for (var i = 0; i < srcs.length; i++) { for (var j = 0; j < imgs.length; j++) { var str = imgs[j].src.toString(); var reg = new RegExp(srcs[i]) /** If srcs matches the imgs add it the the new array */ if(str.match(reg)) arr.push(imgs[j]); }; }; /** Override imgs array with the new sorted arr */ imgs = arr; } /** * Public methods * @public {function} */ self.load = load; /** * @return {object} Public methods */ return self; } /** @export */ module.exports = Imagesloader;
var reactTools = require('react-tools'); var path = require('path'); var mkdirp = require('mkdirp'); var fs = require('fs'); module.exports = function(root, options) { var dest = options && options.dest || root; return function(req, res, next) { if (!req.path.match(/\.js$/)) { return next(); } var jsPath = path.join(dest, req.path); var jsxPath = path.join(root, req.path + 'x'); function transform() { fs.readFile(jsxPath, 'utf8', function (err, jsx) { var annotationAdded = false; if (!jsx.match(/\/[\*\s]*\@jsx/)) { jsx = "/** @jsx React.DOM */\n\n" + jsx; annotationAdded = true; } try { var js = reactTools.transform(jsx) if (annotationAdded) { js = js.split("\n").slice(1).join("\n"); } } catch (err) { return next(err); } mkdirp(path.dirname(jsPath), 511, function() { fs.writeFile(jsPath, js, 'utf8', next); }); }); } fs.stat(jsxPath, function(err, jsxStats) { if (err) { return next('ENOENT' == err.code ? null : err); } fs.stat(jsPath, function(err, jsStats) { if (err) { return 'ENOENT' == err.code ? transform() : next(err); } if (jsxStats.mtime > jsStats.mtime) { return transform(); } else { next(); } }); }); } };
;(function(global) { "use strict"; var Rpd = global.Rpd; if (typeof Rpd === "undefined" && typeof require !== "undefined") { Rpd = require('rpd'); } Rpd.style('compact-v', 'svg', (function() { var ƒ = Rpd.unit; var δ = Rpd.Render.data; var socketPadding = 20, // distance between inlets/outlets in SVG units socketsMargin = 8; // distance between first/last inlet/outlet and body edge var headerHeight = 10; // height of a node header in SVG units function _createSvgElement(name) { return document.createElementNS(d3.namespaces.svg, name); } function getPos(elm) { var bounds = elm.getBoundingClientRect(); return { x: bounds.left, y: bounds.top } }; return function(config) { var lastCanvas; var listeners = {}; var inletToConnector = {}, outletToConnector = {}; return { edgePadding: { horizontal: 20, vertical: 40 }, boxPadding: { horizontal: 20, vertical: 80 }, createCanvas: function(patch, parent) { return { element: d3.select(_createSvgElement('g')) .classed('rpd-patch', true).node() }; }, createNode: function(node, render, description, icon) { var minContentSize = render.size ? { width: render.size.width || 60, height: render.size.height || 25 } : { width: 60, height: 25 }; var pivot = render.pivot || { x: 0.5, y: 0.5 }; function findBestNodeSize(numInlets, numOutlets, minContentSize) { var requiredContentHeight = (2 * socketsMargin) + ((Math.max(numInlets, numOutlets) - 1) * socketPadding); return { width: minContentSize.width, height: Math.max(headerHeight + requiredContentHeight, headerHeight + minContentSize.height) }; } var initialSize = findBestNodeSize(node.def.inlets ? Object.keys(node.def.inlets).length : 0, node.def.outlets ? Object.keys(node.def.outlets).length : 0, minContentSize); var width = initialSize.width, height = initialSize.height; var bodyWidth = width, bodyHeight = height - headerHeight; var nodeElm = d3.select(_createSvgElement('g')).attr('class', 'rpd-node'); // append shadow nodeElm.append('rect').attr('class', 'rpd-shadow') .attr('width', width).attr('height', height) .attr('x', 5).attr('y', 6).attr('rx', 3).attr('ry', 3); // append node header nodeElm.append('rect').attr('class', 'rpd-header').classed('rpd-drag-handle', true) .attr('x', 0).attr('y', 0) .attr('width', width).attr('height', headerHeight); nodeElm.append('g').attr('class', 'rpd-name-holder') .attr('transform', 'translate(0, 3)') .append('text').attr('class', 'rpd-name').text(node.def.title || node.type) .attr('x', 3).attr('y', 2) .style('pointer-events', 'none'); // append node body nodeElm.append('rect').attr('class', 'rpd-content') .attr('x', 0).attr('y', headerHeight) .attr('width', width).attr('height', height - headerHeight); nodeElm.append('rect').attr('class', 'rpd-body') .attr('width', width).attr('height', height) .style('pointer-events', 'none'); // append tooltip with description nodeElm.select('.rpd-header') .append(ƒ(_createSvgElement('title'))) .text(description ? (description + ' (' + node.type + ')') : node.type); // append remove button nodeElm.append('g').attr('class', 'rpd-remove-button') .attr('transform', 'translate(' + (width-10.5) + ',0.5)') .call(function(button) { button.append('rect').attr('width', 10).attr('height', headerHeight - 0.5) .attr('class', 'rpd-remove-button-handle'); button.append('text').text('x').attr('x', 3).attr('y', 1.5) .style('pointer-events', 'none'); }); // append placeholders for inlets, outlets and a target element to render body into var inletsGroup = nodeElm.append('g').attr('class', 'rpd-inlets') .attr('transform', 'translate(0,' + headerHeight + ')'); var processGroup = nodeElm.append('g').attr('class', 'rpd-process') .attr('transform', 'translate(' + (bodyWidth * pivot.x) + ',' + (headerHeight + ((height - headerHeight) * pivot.y)) + ')'); var outletsGroup = nodeElm.append('g').attr('class', 'rpd-outlets') .attr('transform', 'translate(' + bodyWidth + ',' + headerHeight + ')'); δ(inletsGroup, { position: { x: 0, y: headerHeight } }); δ(outletsGroup, { position: { x: width, y: headerHeight } }); nodeElm.classed('rpd-'+node.type.slice(0, node.type.indexOf('/'))+'-toolkit-node', true) .classed('rpd-'+node.type.replace('/','-'), true); var numInlets = 0, numOutlets = 0; var inletElms = [], outletElms = []; var lastSize = initialSize; function checkNodeSize() { var curSize = lastSize; var newSize = findBestNodeSize(numInlets, numOutlets, minContentSize); if ((newSize.width === curSize.width) && (newSize.height === curSize.height)) return; nodeElm.select('rect.rpd-shadow').attr('height', newSize.height).attr('width', newSize.width); nodeElm.select('rect.rpd-body').attr('height', newSize.height).attr('width', newSize.width); nodeElm.select('rect.rpd-content').attr('height', newSize.height - headerHeight); nodeElm.select('g.rpd-process').attr('transform', 'translate(' + (newSize.width * pivot.x) + ',' + (headerHeight + ((newSize.height - headerHeight) / 2)) + ')'); lastSize = newSize; } function recalculateSockets() { inletElms.forEach(function(inletElm, idx) { var inletPos = findInletPos(idx); inletElm.attr('transform', 'translate(' + inletPos.x + ',' + inletPos.y + ')'); //δ(inletElm).position = inletPos; }); outletElms.forEach(function(outletElm, idx) { var outletPos = findOutletPos(idx); outletElm.attr('transform', 'translate(' + outletPos.x + ',' + outletPos.y + ')'); //δ(outletElm).position = outletPos; }); } function notifyNewInlet(elm) { numInlets++; inletElms.push(elm); checkNodeSize(); recalculateSockets(); } function notifyNewOutlet(elm) { numOutlets++; outletElms.push(elm); checkNodeSize(); recalculateSockets(); } function findInletPos(idx) { // index from top to bottom return { x: 0, y: socketsMargin + (socketPadding * idx) }; } function findOutletPos(idx) { // index from top to bottom return { x: 0, y: socketsMargin + (socketPadding * idx) }; } listeners[node.id] = { inlet: notifyNewInlet, outlet: notifyNewOutlet }; return { element: nodeElm.node(), size: initialSize }; }, createInlet: function(inlet, render) { var inletElm = d3.select(_createSvgElement('g')).attr('class', 'rpd-inlet'); inletElm.call(function(group) { //group.attr('transform', 'translate(' + inletPos.x + ',' + inletPos.y + ')') group.append('rect').attr('class', 'rpd-connector') .attr('x', -2).attr('y', -2) .attr('width', 4).attr('height', 4); group.append('text').attr('class', 'rpd-name').text(inlet.def.label || inlet.alias) .attr('x', -5).attr('y', 0); group.append('g').attr('class', 'rpd-value-holder') .attr('transform', 'translate(-5,7)') .append('text').attr('class', 'rpd-value'); }); listeners[inlet.node.id].inlet(inletElm); inletToConnector[inlet.id] = inletElm.select('.rpd-connector'); return { element: inletElm.node() }; }, createOutlet: function(outlet, render) { var outletElm = d3.select(_createSvgElement('g')).attr('class', 'rpd-outlet'); outletElm.call(function(group) { //group.attr('transform', 'translate(' + outletPos.x + ',' + outletPos.y + ')') group.append('rect').attr('class', 'rpd-connector') .attr('x', -2).attr('y', -2) .attr('width', 4).attr('height', 4); group.append('text').attr('class', 'rpd-name').text(outlet.def.label || outlet.alias) .attr('x', 5).attr('y', 0); group.append('g').attr('class', 'rpd-value-holder') .attr('transform', 'translate(5,7)') .append('text').attr('class', 'rpd-value') .attr('x', 0).attr('y', 0) .style('pointer-events', 'none'); }); listeners[outlet.node.id].outlet(outletElm); outletToConnector[outlet.id] = outletElm.select('.rpd-connector'); return { element: outletElm.node() }; }, createLink: function(link) { var linkElm = d3.select(_createSvgElement( (config.linkForm && (config.linkForm == 'curve')) ? 'path' : 'line' )).attr('class', 'rpd-link'); return { element: linkElm.node(), rotate: function(x0, y0, x1, y1) { if (config.linkForm && (config.linkForm == 'curve')) { linkElm.attr('d', bezierByH(x0, y0, x1, y1)); } else { linkElm.attr('x1', x0).attr('y1', y0) .attr('x2', x1).attr('y2', y1); } }, noPointerEvents: function() { linkElm.style('pointer-events', 'none'); } }; }, getInletPos: function(inlet) { var connectorPos = getPos(inletToConnector[inlet.id].node()); return { x: connectorPos.x + 2, y: connectorPos.y + 2}; }, getOutletPos: function(outlet) { var connectorPos = getPos(outletToConnector[outlet.id].node()); return { x: connectorPos.x + 2, y: connectorPos.y + 2 }; }, getLocalPos: function(pos) { if (!lastCanvas) return pos; // calculate once on patch switch? var canvasPos = getPos(lastCanvas.node()); return { x: pos.x - canvasPos.x, y: pos.y - canvasPos.y }; }, onPatchSwitch: function(patch, canvas) { lastCanvas = d3.select(canvas); }, onNodeRemove: function(node) { listeners[node.id] = null; } }; function bezierByH(x0, y0, x1, y1) { var mx = x0 + (x1 - x0) / 2; return 'M' + x0 + ' ' + y0 + ' ' + 'C' + mx + ' ' + y0 + ' ' + mx + ' ' + y1 + ' ' + x1 + ' ' + y1; } } })()); })(this);
var is = function(x) { return (elem) => elem && elem.nodeType === x; }; // commented-out methods are not being used module.exports = { elem: is(1), attr: is(2), text: is(3), // cdata: is(4), // entity_reference: is(5), // entity: is(6), // processing_instruction: is(7), comment: is(8), doc: is(9), // document_type: is(10), doc_frag: is(11) // notation: is(12), };
const katex = require('katex') const renderKatexFormula = function(text, displayMode) { try { return katex.renderToString(text, { displayMode: displayMode }) } catch (err) { console.log( 'Katex error trying to parse: "' + text + '". Description: ' + err ) } } module.exports = function(inlineMathSelector, displayMathSelector) { const inlineVsDisplayLogic = typeof displayMathSelector !== 'undefined' ? 'separateSelector' : 'spanIsInline' inlineMathSelector = arguments.length > 0 ? inlineMathSelector : '.math' return function(deck) { let foundMath = false let mathElements switch (inlineVsDisplayLogic) { case 'separateSelector': mathElements = deck.parent.querySelectorAll(inlineMathSelector) Array.from(mathElements).forEach(el => { el.innerHTML = renderKatexFormula(el.innerHTML, false) foundMath = true }) mathElements = deck.parent.querySelectorAll(displayMathSelector) Array.from(mathElements).forEach(el => { el.innerHTML = renderKatexFormula(el.innerHTML, true) foundMath = true }) break case 'spanIsInline': mathElements = deck.parent.querySelectorAll(inlineMathSelector) Array.from(mathElements).forEach(el => { el.innerHTML = renderKatexFormula( el.textContent, el.tagName.toLowerCase() !== 'span' ) foundMath = true }) break } if (foundMath) { try { require('katex/dist/katex.min.css') } catch (e) { console.log( 'It was not possible to load the CSS from KaTeX. Details: ' + e ) } } } }
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; import Image, { thumbnailSizes } from "@crave/farmblocks-image"; import { fontTypes } from "@crave/farmblocks-text"; const Icon = styled.div` font-size: ${({ iconFontSize }) => iconFontSize || "72px"}; color: ${fontTypes.SUBTLE}; `; const Thumbnail = ({ imageSrc, icon, iconFontSize }) => { if (imageSrc) { return ( <Image className="thumbnail" size={thumbnailSizes.LARGE} src={imageSrc} /> ); } if (icon) { return ( <Icon className="icon-wrapper" iconFontSize={iconFontSize}> {icon} </Icon> ); } return null; }; Thumbnail.propTypes = { imageSrc: PropTypes.string, iconFontSize: PropTypes.string, icon: PropTypes.node, }; export default Thumbnail;
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Connect to DB var dbConfig = require('./config/db'); var mongoose = require('mongoose'); mongoose.connect(dbConfig.url,function(res,err){ if(err){ console.log('ERROR connecting to : ' + dbConfig.url + '. ' + err); process.exit(0);} else { if ( res === undefined ) console.log('connected to ' + dbConfig.url ); else { console.log('ERROR connecting to : ' + dbConfig.url + '. ' + res.errmsg); process.exit(0);} } }); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.locals.moment = require('moment'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'bower_components'))); // Configuring Passport var passport = require('passport'); var expressSession = require('express-session'); app.use(expressSession({ secret: 'mySecretKey', resave: true, saveUninitialized: true}) ); app.use(passport.initialize()); app.use(passport.session()); // Using the flash middleware provided by connect-flash to store messages in session // and displaying in templates var flash = require('connect-flash'); app.use(flash()); // Initialize Passport var initPassport = require('./passport/init'); initPassport(passport); var routes = require('./routes/index'); var auth = require('./routes/auth')(passport); var agenda = require('./routes/agenda'); app.use('/', routes); app.use('/auth', auth); app.use('/agenda', agenda); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
/** * @jest-environment ./__tests__/html/__jest__/WebChatEnvironment.js */ describe('deprecated <Localize>', () => { test('should localize text in navigator language', () => runHTMLTest('deprecated.localize.html')); test('should localize text in "en"', () => runHTMLTest('deprecated.localize.html#l=en')); test('should localize text in "yue"', () => runHTMLTest('deprecated.localize.html#l=yue')); });
/** * Created by twi18192 on 25/08/15. */ var React = require('react'); var mainPaneStore = require('../stores/mainPaneStore'); var mainPaneActions = require('../actions/mainPaneActions'); var ButtonStyle = { backgroundColor: 'grey', height: 25, width: 70, borderRadius: 8, borderStyle:'solid', borderWidth: 1, borderColor: 'black', fontFamily: 'Verdana', // color: 'white', textAlign: 'center', display: 'inline-block', cursor: 'pointer', MozUserSelect: 'none' }; var ButtonTitlePadding = { position: 'relative', top: -6 }; function getConfigButtonState(){ return { configPanelOpen:mainPaneStore.getConfigPanelState() } } var ConfigButton = React.createClass({ getInitialState: function(){ return { configPanelOpen: mainPaneStore.getConfigPanelState() } }, _onChange: function(){ this.setState(getConfigButtonState) }, handleActionConfigToggle:function(){ mainPaneActions.toggleConfigPanel("this is the item") }, componentDidMount: function(){ mainPaneStore.addChangeListener(this._onChange) }, componentWillUnmount: function(){ mainPaneStore.removeChangeListener(this._onChange) }, render: function() { return( <div> <div id="config" style={ButtonStyle} onClick={this.handleActionConfigToggle} ><span style={ButtonTitlePadding}>Config</span> </div> </div> )} }); module.exports = ConfigButton;
'use strict'; /** * Profile class that normalizes profile data fetched from authentication provider */ Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function formatAddress(address) { var result = address; if (result) { result.formatted = result.street_address + '\n' + result.postal_code + ' ' + result.locality + '\n' + result.country; return result; } return null; } var Profile = /** * @param data {object} */ exports.Profile = function Profile(data) { _classCallCheck(this, Profile); var fields = ['_raw', 'address', 'at_hash', 'birthdate', 'email_verified', 'email', 'family_name', 'gender', 'given_name', 'id', 'locale', 'middle_name', 'name', 'nickname', 'phone_number_verified', 'phone_number', 'picture', 'preferred_username', 'profile', 'provider', 'sub', 'updated_at', 'website', 'zoneinfo']; this._raw = data; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var field = _step.value; if (data.hasOwnProperty(field)) { var value = data[field]; if (field === 'address') { this.address = formatAddress(data.address); } else { this[field] = value || null; } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } };
import React from 'react'; import PureComponent from 'react-pure-render/component'; class Description extends PureComponent { render() { return ( <div><input type="text" value="" placeholder="I am description" /></div> ); } } export default Description;
'use strict'; const fs = require('fs'); const exec = require('child_process').exec; const helpers = require('yeoman-test'); const assert = require('yeoman-assert'); const util = require('./support/util'); const defaultAnswers = require('./support/defaultPromptAnswers'); const promptOptions = require("../generators/app/promptOptions"); const defaultInit = require('./support/defaultInit'); const initTest = require('./support/initTest'); const answers = Object.assign({},defaultAnswers, { "moduleType": promptOptions.moduleType.ES6_MODULES, "language": promptOptions.language.ES6, "advancedOptions": [ promptOptions.advanced.DEVLIB, promptOptions.advanced.WEBSTORM ] }); describe('ES Modules + ES6 + WebStorm', function () { this.timeout(125000) before(initTest(answers)) before(function(done) { const that = this; this.app = helpers .run(require.resolve('../generators/app')) .withGenerators([[helpers.createDummyGenerator(),require.resolve('../generators/class')]]) .withOptions({ 'skip-welcome-message': true, 'skip-message': true, 'skip-install': false }) .withPrompts(answers).then(function(dir) {return defaultInit(__filename, dir)}).then(function(dir) { that.dir = dir; done(); }) }); describe('check files', function() { it('generates base files', function () { assert.file([ 'app/index.html', 'app/scripts/app.js', 'app/typings/yfiles-api-modules-ts43-webstorm.d.ts', 'package.json', 'webpack.config.js', 'app/lib/yfiles/yfiles.js', '.idea/libraries/yFiles_for_HTML.xml', '.idea/jsLibraryMappings.xml', '.idea/testApp.iml', '.idea/modules.xml', '.idea/misc.xml', '.idea/webResources.xml' ]); assert.noFile([ 'app/lib/es2015-shim.js', 'app/styles/yfiles.css', 'jsconfig.json', 'bower.json', 'tsconfig.json', 'app/scripts/license.json', 'app/typings/yfiles-api-umd-ts43-vscode.d.ts', 'app/typings/yfiles-api-umd-ts43-webstorm.d.ts', 'Gruntfile.js' ]); }); }); describe('build result', function() { it('created the bundles and sourcemaps', function() { assert.file([ 'app/dist/app.js', 'app/dist/app.js.map', 'app/dist/lib.js' ]); }); it('uses webpack 4', function() { assert.fileContent('package.json', /"webpack": "\^?4/) }) it('runs', function (done) { util.maybeOpenInBrowser(this.dir,done); }); it('succeeds to run production build', function (done) { const dir = this.dir; const child = exec('npm run production', {cwd: dir.cwd}, function(error, stdout, stderr) { console.log("\nbuild done!") assert.ok(error === null, "Production build failed: "+error); util.maybeOpenInBrowser(dir,done); }); child.stdout.on('data', function(data) { console.log(data.toString()); }); }); }); });
import { expect } from 'chai'; import { createTheme } from '@mui/material/styles'; import defaultTheme from './defaultTheme'; import responsiveFontSizes from './responsiveFontSizes'; describe('responsiveFontSizes', () => { it('should support unitless line height', () => { const defaultVariant = { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '6rem', fontWeight: 300, letterSpacing: '-0.01562em', lineHeight: 1, }; const theme = createTheme({ typography: { h1: defaultVariant, }, }); const { typography } = responsiveFontSizes(theme); expect(typography.h1).to.deep.equal({ ...defaultVariant, fontSize: '3.5rem', [`@media (min-width:${defaultTheme.breakpoints.values.sm}px)`]: { fontSize: '4.75rem' }, [`@media (min-width:${defaultTheme.breakpoints.values.md}px)`]: { fontSize: '5.5rem' }, [`@media (min-width:${defaultTheme.breakpoints.values.lg}px)`]: { fontSize: defaultVariant.fontSize, }, }); }); it('should disable vertical alignment', () => { const defaultVariant = { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '6rem', fontWeight: 300, letterSpacing: '-0.01562em', lineHeight: '6rem', }; const theme = createTheme({ typography: { h1: defaultVariant, }, }); const { typography } = responsiveFontSizes(theme, { disableAlign: true, }); expect(typography.h1).to.deep.equal({ ...defaultVariant, fontSize: '3.5rem', [`@media (min-width:${defaultTheme.breakpoints.values.sm}px)`]: { fontSize: '4.75rem' }, [`@media (min-width:${defaultTheme.breakpoints.values.md}px)`]: { fontSize: '5.375rem' }, [`@media (min-width:${defaultTheme.breakpoints.values.lg}px)`]: { fontSize: defaultVariant.fontSize, }, }); }); describe('when requesting a responsive typography with non unitless line height and alignment', () => { it('should throw an error, as this is not supported', () => { const theme = createTheme({ typography: { h1: { lineHeight: '6rem', }, }, }); expect(() => { responsiveFontSizes(theme); }).toThrowMinified( 'MUI: Unsupported non-unitless line height with grid alignment.\n' + 'Use unitless line heights instead.', ); }); }); });
import * as THREE from 'three'; import PropTypes from 'prop-types'; import MaterialDescriptorBase from './MaterialDescriptorBase'; class LineBasicMaterialDescriptor extends MaterialDescriptorBase { constructor(react3RendererInstance) { super(react3RendererInstance); this.hasColor(); this.hasProp('linewidth', { type: PropTypes.number, simple: true, default: 1, }); // what are these properties used for? [ 'linecap', 'linejoin', ].forEach((propName) => { this.hasProp(propName, { type: PropTypes.oneOf([ 'round', ]), simple: true, default: 'round', }); }); this.hasProp('fog', { type: PropTypes.bool, update(threeObject, fog, existsInProps) { if (existsInProps) { threeObject.fog = fog; } threeObject.needsUpdate = true; }, updateInitial: true, default: true, }); } construct(props) { const materialDescription = this.getMaterialDescription(props); return new THREE.LineBasicMaterial(materialDescription); } } module.exports = LineBasicMaterialDescriptor;
#!/usr/bin/env node var util = require('util'), http = require('http'), fs = require('fs'), url = require('url'), events = require('events'); var DEFAULT_PORT = 8123; function main(argv) { new HttpServer({ 'GET': createServlet(StaticServlet), 'HEAD': createServlet(StaticServlet) }).start(Number(argv[2]) || DEFAULT_PORT); } function escapeHtml(value) { return value.toString(). replace('<', '&lt;'). replace('>', '&gt;'). replace('"', '&quot;'); } function createServlet(Class) { var servlet = new Class(); return servlet.handleRequest.bind(servlet); } /** * An Http server implementation that uses a map of methods to decide * action routing. * * @param {Object} Map of method => Handler function */ function HttpServer(handlers) { this.handlers = handlers; this.server = http.createServer(this.handleRequest_.bind(this)); } HttpServer.prototype.start = function(port) { this.port = port; this.server.listen(port); util.puts('Http Server running at http://localhost:' + port + '/'); }; HttpServer.prototype.parseUrl_ = function(urlString) { var parsed = url.parse(urlString); parsed.pathname = url.resolve('/', parsed.pathname); return url.parse(url.format(parsed), true); }; HttpServer.prototype.handleRequest_ = function(req, res) { var logEntry = req.method + ' ' + req.url; if (req.headers['user-agent']) { logEntry += ' ' + req.headers['user-agent']; } util.puts(logEntry); req.url = this.parseUrl_(req.url); var handler = this.handlers[req.method]; if (!handler) { res.writeHead(501); res.end(); } else { handler.call(this, req, res); } }; /** * Handles static content. */ function StaticServlet() {} StaticServlet.MimeMap = { 'txt': 'text/plain', 'html': 'text/html', 'css': 'text/css', 'xml': 'application/xml', 'json': 'application/json', 'js': 'application/javascript', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif', 'png': 'image/png',   'svg': 'image/svg+xml' }; StaticServlet.prototype.handleRequest = function(req, res) { var self = this; var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){ return String.fromCharCode(parseInt(hex, 16)); }); var parts = path.split('/'); if (parts[parts.length-1].charAt(0) === '.') return self.sendForbidden_(req, res, path); fs.stat(path, function(err, stat) { if (err) return self.sendMissing_(req, res, path); if (stat.isDirectory()) return self.sendDirectory_(req, res, path); return self.sendFile_(req, res, path); }); } StaticServlet.prototype.sendError_ = function(req, res, error) { res.writeHead(500, { 'Content-Type': 'text/html' }); res.write('<!doctype html>\n'); res.write('<title>Internal Server Error</title>\n'); res.write('<h1>Internal Server Error</h1>'); res.write('<pre>' + escapeHtml(util.inspect(error)) + '</pre>'); util.puts('500 Internal Server Error'); util.puts(util.inspect(error)); }; StaticServlet.prototype.sendMissing_ = function(req, res, path) { path = path.substring(1); res.writeHead(404, { 'Content-Type': 'text/html' }); res.write('<!doctype html>\n'); res.write('<title>404 Not Found</title>\n'); res.write('<h1>Not Found</h1>'); res.write( '<p>The requested URL ' + escapeHtml(path) + ' was not found on this server.</p>' ); res.end(); util.puts('404 Not Found: ' + path); }; StaticServlet.prototype.sendForbidden_ = function(req, res, path) { path = path.substring(1); res.writeHead(403, { 'Content-Type': 'text/html' }); res.write('<!doctype html>\n'); res.write('<title>403 Forbidden</title>\n'); res.write('<h1>Forbidden</h1>'); res.write( '<p>You do not have permission to access ' + escapeHtml(path) + ' on this server.</p>' ); res.end(); util.puts('403 Forbidden: ' + path); }; StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) { res.writeHead(301, { 'Content-Type': 'text/html', 'Location': redirectUrl }); res.write('<!doctype html>\n'); res.write('<title>301 Moved Permanently</title>\n'); res.write('<h1>Moved Permanently</h1>'); res.write( '<p>The document has moved <a href="' + redirectUrl + '">here</a>.</p>' ); res.end(); util.puts('301 Moved Permanently: ' + redirectUrl); }; StaticServlet.prototype.sendFile_ = function(req, res, path) { var self = this; var file = fs.createReadStream(path); res.writeHead(200, { 'Content-Type': StaticServlet. MimeMap[path.split('.').pop()] || 'text/plain' }); if (req.method === 'HEAD') { res.end(); } else { file.on('data', res.write.bind(res)); file.on('close', function() { res.end(); }); file.on('error', function(error) { self.sendError_(req, res, error); }); } }; StaticServlet.prototype.sendDirectory_ = function(req, res, path) { var self = this; if (path.match(/[^\/]$/)) { req.url.pathname += '/'; var redirectUrl = url.format(url.parse(url.format(req.url))); return self.sendRedirect_(req, res, redirectUrl); } fs.readdir(path, function(err, files) { if (err) return self.sendError_(req, res, error); if (!files.length) return self.writeDirectoryIndex_(req, res, path, []); var remaining = files.length; files.forEach(function(fileName, index) { fs.stat(path + '/' + fileName, function(err, stat) { if (err) return self.sendError_(req, res, err); if (stat.isDirectory()) { files[index] = fileName + '/'; } if (!(--remaining)) return self.writeDirectoryIndex_(req, res, path, files); }); }); }); }; StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) { path = path.substring(1); res.writeHead(200, { 'Content-Type': 'text/html' }); if (req.method === 'HEAD') { res.end(); return; } res.write('<!doctype html>\n'); res.write('<title>' + escapeHtml(path) + '</title>\n'); res.write('<style>\n'); res.write(' ol { list-style-type: none; font-size: 1.2em; }\n'); res.write('</style>\n'); res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>'); res.write('<ol>'); files.forEach(function(fileName) { if (fileName.charAt(0) !== '.') { res.write('<li><a href="' + escapeHtml(fileName) + '">' + escapeHtml(fileName) + '</a></li>'); } }); res.write('</ol>'); res.end(); }; // Must be last, main(process.argv);