code stringlengths 2 1.05M |
|---|
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
overrides: [
{
files: ['index.d.ts', 'tests.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-this-alias': [
'error',
{
'allowDestructuring': false,
'allowedNames': ['self']
}
]
}
}
]
}
|
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');
var index = require('./routes/index');
var app = express();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');
// 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('/api/v1', index);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
var server = angular.module('server', [])
server.factory('productsInterface', ['$http', function($http){
productsInterface = {};
var timeoutLength = 10000;
var baseUrl = 'http://web.manthanhd.com:3000/product',
url,
method,
params = {};
productsInterface.getProduct = function(){
url = baseUrl + '/:id';
method = 'GET';
}
productsInterface.getProductsByTag = function(){
url = baseUrl + '/all/:tagId';
method = 'GET';
}
productsInterface.getAllProducts = function(){
url = baseUrl + '/all';
method = 'GET';
// $http(request)
// .success(function(data, status, headers, config){
// success(data, status, headers, config);
// })
// .error(function(data, status, headers, config){
// error(data, status, headers, config);
// });
}
productsInterface.uploadImage = function(data, success, error){
url = baseUrl + '/:id/upload';
method = 'POST';
params = { 'photos': data.photos};
}
productsInterface.registerProduct = function(data, success, error){
url = baseUrl + '/register';
method = 'POST';
params = { 'name': data.name,
'description' : data.description,
'unitsAvailable' : data.units,
'price' : data.price,
'tags' : 'tag1,tag2,tag3,tag4',
'hId' : data.hid}
var request = {
method: method,
url: url,
timeout: timeoutLength,
headers: {
'Content-Type': 'application/json'
},
data: params
};
console.log(request);
$http(request)
.success(function(data, status, headers, config){
success(data, status, headers, config);
})
.error(function(data, status, headers, config){
error(data, status, headers, config);
});
}
return productsInterface;
}]) |
'use strict';
/**
* This module defines a singleton that handles the communication between the dat.GUI controller
* and the hex-grid parameters.
*
* @module parameters
*/
(function () {
var parameters = {},
config = {},
originalHgConfigs = {};
config.datGuiWidth = 300;
config.folders = [
createMiscellaneousFolders,
{
name: 'Animations',
isOpen: false,
createItems: null,
children: [
createTransientAnimationsFolder,
createPersistentAnimationsFolder
]
}
];
// --- --- //
parameters.config = config;
parameters.initDatGui = initDatGui;
parameters.updateForNewPostData = updateForNewPostData;
parameters.goHome = goHome;
parameters.hideMenu = hideMenu;
parameters.updateToPreSetConfigs = updateToPreSetConfigs;
parameters.filterPosts = filterPosts;
parameters.recordOpenChildFolders = recordOpenChildFolders;
parameters.grid = null;
parameters.gui = null;
parameters.categoriesFolder = null;
parameters.allCategories = [];
parameters.categoryData = {};
window.app = window.app || {};
app.parameters = parameters;
// --- --- //
/**
* Sets up the dat.GUI controller.
*
* @param {Grid} grid
*/
function initDatGui(grid) {
parameters.grid = grid;
storeOriginalConfigValues();
window.app.miscParams.init(grid);
window.app.persistentParams.init(grid);
window.app.transientParams.init(grid);
createDatGui();
window.app.parameters.updateToPreSetConfigs.call(window.app.parameters,
window.app.miscParams.config.preSetConfigs[window.app.miscParams.config.defaultPreSet]);
var debouncedResize = window.hg.util.debounce(resize, 300);
window.addEventListener('resize', debouncedResize, false);
debouncedResize();
}
function resize() {
setTimeout(function () {
// Don't show the menu on smaller screens.
if (window.hg.controller.isSmallScreen) {
hideMenu();
} else {
showMenu();
}
}, 10);
}
function createDatGui() {
parameters.gui = new dat.GUI();
parameters.gui.close();
parameters.gui.width = config.datGuiWidth;
window.gui = parameters.gui;
// Don't show the menu on smaller screens.
if (window.hg.controller.isSmallScreen) {
hideMenu();
} else {
showMenu();
}
createFolders();
}
function createFolders() {
createChildFolders(config.folders, parameters.gui);
}
function createChildFolders(childFolderConfigs, parentFolder) {
childFolderConfigs.forEach(function (folderConfig) {
if (typeof folderConfig === 'function') {
folderConfig(parentFolder);
} else {
var folder = parentFolder.addFolder(folderConfig.name);
folderConfig.folder = folder;
if (folderConfig.isOpen) {
folder.open();
}
if (folderConfig.createItems) {
folderConfig.createItems(folder);
}
// Recursively create descendent folders
if (folderConfig.children) {
createChildFolders(folderConfig.children, folder);
}
}
});
}
function createMiscellaneousFolders(parentFolder) {
createChildFolders(window.app.miscParams.config.folders, parentFolder);
}
function createTransientAnimationsFolder(parentFolder) {
createChildFolders(window.app.transientParams.config.folders, parentFolder);
}
function createPersistentAnimationsFolder(parentFolder) {
createChildFolders(window.app.persistentParams.config.folders, parentFolder);
}
function recordOpenFolders() {
recordOpenChildFolders(config.folders);
window.app.parameters.recordOpenChildFolders(window.app.miscParams.config.folders);
window.app.parameters.recordOpenChildFolders(window.app.transientParams.config.folders);
window.app.parameters.recordOpenChildFolders(window.app.persistentParams.config.folders);
}
function recordOpenChildFolders(childFolderConfigs) {
childFolderConfigs.forEach(function (folderConfig) {
if (typeof folderConfig !== 'function') {
folderConfig.isOpen = !folderConfig.folder.closed;
// Recurse
if (folderConfig.children) {
recordOpenChildFolders(folderConfig.children);
}
}
});
}
/**
* @param {Array.<PostData>} postData
*/
function updateForNewPostData(postData) {
parameters.allCategories = getAllCategories(postData);
addCategoryMenuItems();
// --- --- //
function getAllCategories(postData) {
// Collect a mapping from each category to its number of occurrences
var categoryMap = postData.reduce(function (map, datum) {
return datum.categories.reduce(function (map, category) {
map[category] = map[category] ? map[category] + 1 : 1;
return map;
}, map);
}, {});
// Collect an array containing each category, sorted by the number of occurrences of each category (in
// DESCENDING order)
var categoryArray = Object.keys(categoryMap)
.sort(function (category1, category2) {
return categoryMap[category2] - categoryMap[category1];
});
return categoryArray;
}
function addCategoryMenuItems() {
parameters.categoryData = {};
// Add an item for showing all categories
addCategoryItem(parameters.categoryData, 'all', parameters.categoriesFolder);
parameters.categoryData['all']['all'] = true;
// Add an item for showing each individual category
parameters.allCategories.forEach(function (category) {
addCategoryItem(parameters.categoryData, category, parameters.categoriesFolder);
});
// --- --- //
function addCategoryItem(categoryData, label, folder) {
categoryData[label] = {};
categoryData[label][label] = false;
categoryData[label].menuItem = folder.add(categoryData[label], label)
.onChange(function () {
filterPosts(label);
});
}
}
}
function storeOriginalConfigValues() {
// Each module/file in the hex-grid project stores a reference to its constructor or singleton in the global hg
// namespace
originalHgConfigs = Object.keys(window.hg).reduce(function (configs, key) {
if (window.hg[key].config) {
configs[key] = window.hg.util.deepCopy(window.hg[key].config);
}
return configs;
}, {});
}
var categoryStackSize = 0;
function filterPosts(category) {
categoryStackSize++;
// Only filter when the checkbox is checked
if (parameters.categoryData[category][category]) {
// Make sure all other category filters are off (manual radio button logic)
Object.keys(parameters.categoryData).forEach(function (key) {
// Only turn off the other filters that are turned on
if (parameters.categoryData[key][key] && key !== category) {
parameters.categoryData[key].menuItem.setValue(false);
}
});
window.hg.controller.filterGridPostDataByCategory(parameters.grid, category);
} else if (categoryStackSize === 1) {
// If unchecking a textbox, turn on the 'all' filter
parameters.categoryData['all'].menuItem.setValue(true);
}
categoryStackSize--;
}
function goHome() {
console.log('Go Home clicked');
window.location.href = '/';
}
function hideMenu() {
// console.log('Hide Menu clicked');
document.querySelector('body > .dg').style.display = 'none';
}
function showMenu() {
document.querySelector('body > .dg').style.display = 'block';
}
function updateToPreSetConfigs(preSetConfig) {
console.log('Updating to pre-set configuration', preSetConfig);
recordOpenFolders();
resetAllConfigValues();
setPreSetConfigValues(preSetConfig);
parameters.grid.annotations.refresh();
window.hg.Grid.config.computeDependentValues();
window.hg.controller.resetGrid(parameters.grid);
parameters.grid.setBackgroundColor();
parameters.grid.resize();
refreshDatGui();
}
function resetAllConfigValues() {
// Reset each module's configuration parameters back to their default values
Object.keys(window.hg).forEach(function (moduleName) {
if (window.hg[moduleName].config) {
Object.keys(originalHgConfigs[moduleName]).forEach(function (parameterName) {
window.hg[moduleName].config[parameterName] =
window.hg.util.deepCopy(originalHgConfigs[moduleName][parameterName]);
});
}
});
}
function setPreSetConfigValues(preSetConfig) {
Object.keys(preSetConfig).forEach(function (moduleName) {
// Set all of the special parameters for this new pre-set configuration
Object.keys(preSetConfig[moduleName]).forEach(function (key) {
setModuleToMatchPreSet(window.hg[moduleName].config, preSetConfig[moduleName], key);
});
// Update the recurrence of any transient job
if (window.hg.controller.transientJobs[moduleName] &&
window.hg.controller.transientJobs[moduleName].toggleRecurrence) {
window.hg.controller.transientJobs[moduleName].toggleRecurrence(
parameters.grid,
window.hg[moduleName].config.isRecurring,
window.hg[moduleName].config.avgDelay,
window.hg[moduleName].config.delayDeviationRange);
}
});
// --- --- //
function setModuleToMatchPreSet(moduleConfig, preSetConfig, key) {
// Recurse on nested objects in the configuration
if (typeof preSetConfig[key] === 'object') {
Object.keys(preSetConfig[key]).forEach(function (childKey) {
setModuleToMatchPreSet(moduleConfig[key], preSetConfig[key], childKey);
});
} else {
moduleConfig[key] = preSetConfig[key];
}
}
}
function refreshDatGui() {
parameters.gui.destroy();
createDatGui();
}
console.log('parameters module loaded');
})();
|
'use strict';
const async = require('async');
const intercept = require('./intercept');
const util = require('../utils');
const value = require('./value');
const _ = require('lodash');
/**
* Process an expression
* @param {Object} service - the active service
* @param {String} field - field name
* @param {*} expression - the expression to process
* @param {Object} options
* @param {Function} cb
*/
module.exports = function processExpression(service, field, expression, options, cb) {
const err = service._error;
// if expression is actually an expression, process it
if (util.isExpression(expression)) {
return value(service, field, expression, options, cb);
}
// if expression is array, process each element as an expression
if (_.isArray(expression)) {
return async.map(expression, function(exp, fn) {
processExpression(service, field, exp, options, fn);
}, function(err, normalized) {
if (err) {
return cb(err);
}
cb(null, normalized);
});
}
// otherwise, we assume that the expression is actually just a value
intercept(field, expression, options, cb);
};
|
/**
* bearerAuth Policy
*
* Policy for authorizing API requests. The request is authenticated if the
* it contains the accessToken in header, body or as a query param.
* Unlike other strategies bearer doesn't require a session.
* Add this policy (in config/policies.js) to controller actions which are not
* accessed through a session. For example: API request from another client
*
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
var passport = require('passport');
module.exports = function (req, res, next) {
return passport.authenticate('bearer', { session: false })(req, res, next);
};
|
class ContextMenuConstants {
constructor() {
this.COPY_TEXT = "copyText";
}
}
export default new ContextMenuConstants();
|
/*
---
script: Keyboard.js
description: Enhances Keyboard by adding the ability to name and describe keyboard shortcuts, and the ability to grab shortcuts by name and bind the shortcut to different keys.
license: MIT-style license
authors:
- Perrin Westrich
requires:
- core:1.2.4/Function
- /Keyboard.Extras
provides: [Keyboard.Extras]
...
*/
Keyboard.prototype.options.nonParsedEvents.combine(['rebound', 'onrebound']);
Keyboard.implement({
/*
shortcut should be in the format of:
{
'keys': 'shift+s', // the default to add as an event.
'description': 'blah blah blah', // a brief description of the functionality.
'handler': function(){} // the event handler to run when keys are pressed.
}
*/
addShortcut: function(name, shortcut) {
this.shortcuts = this.shortcuts || [];
this.shortcutIndex = this.shortcutIndex || {};
shortcut.getKeyboard = $lambda(this);
shortcut.name = name;
this.shortcutIndex[name] = shortcut;
this.shortcuts.push(shortcut);
if(shortcut.keys) this.addEvent(shortcut.keys, shortcut.handler);
return this;
},
addShortcuts: function(obj){
for(var name in obj) this.addShortcut(name, obj[name]);
return this;
},
getShortcuts: function(){
return this.shortcuts || [];
},
getShortcut: function(name){
return (this.shortcutIndex || {})[name];
}
});
Keyboard.rebind = function(newKeys, shortcuts){
$splat(shortcuts).each(function(shortcut){
shortcut.getKeyboard().removeEvent(shortcut.keys, shortcut.handler);
shortcut.getKeyboard().addEvent(newKeys, shortcut.handler);
shortcut.keys = newKeys;
shortcut.getKeyboard().fireEvent('rebound');
});
};
Keyboard.getActiveShortcuts = function(keyboard) {
var activeKBS = [], activeSCS = [];
Keyboard.each(keyboard, [].push.bind(activeKBS));
activeKBS.each(function(kb){ activeSCS.extend(kb.getShortcuts()); });
return activeSCS;
};
Keyboard.getShortcut = function(name, keyboard, opts){
opts = opts || {};
var shortcuts = opts.many ? [] : null,
set = opts.many ? function(kb){
var shortcut = kb.getShortcut(name);
if(shortcut) shortcuts.push(shortcut);
} : function(kb) {
if(!shortcuts) shortcuts = kb.getShortcut(name);
};
Keyboard.each(keyboard, set);
return shortcuts;
};
Keyboard.getShortcuts = function(name, keyboard) {
return Keyboard.getShortcut(name, keyboard, { many: true });
};
|
import Confidence from 'confidence'
import path from 'path'
var criteria = {
env: process.env.NODE_ENV
};
var config = {
$meta: {
name: 'React Redux Example Development'
},
pkg: require('../../package.json'),
connections: [{
labels: ['ui'],
host: '0.0.0.0',
port: 3000
},{
labels: ['api'],
host: '0.0.0.0',
port: 3030
}],
logging : {
opsInterval: 1000,
reporters: [{
reporter: require('good-console'),
events: { log: '*', response: '*' }
}]
}
}
var store = new Confidence.Store(config);
exports.get = (key) => {
return store.get(key, criteria);
};
exports.meta = (key) => {
return store.meta(key, criteria);
};
|
var Calculator = (function() {
// Private stuff up here
var calculatorAddValue = 2 + 2;
var calculatorSubtractValue = 5 - 2;
var calculatorMultiplyValue = 3 * 3;
var calculatorDivideValue = 3 / 3;
// Public methods here
return {
addValueAtoValueB: function(result) {
var num = parseInt(result);
if (isNaN(num) == true) {
throw new Error ("Not a number");
}
num = calculatorAddValue;
return Math.round(num);
},
subtractValueAFromValueB: function(result) {
var num = parseInt(result);
if (isNaN(num) == true) {
throw new Error ("Not a number");
}
num = calculatorSubtractValue;
return Math.round(num);
},
multiplyValueAbyValueB: function(result) {
var num = parseInt(result);
if (isNaN(num) == true) {
throw new Error ("Not a number");
}
num = calculatorMultiplyValue;
return Math.round(num);
},
divideValueAbyValueB: function(result) {
var num = parseInt(result);
if (isNaN(num) == true) {
throw new Error ("Not a number");
}
num = calculatorDivideValue;
return Math.round(num);
}
}
}());
|
'use strict';
angular.module('badeseenApp').directive('lakeRating', ['$window','RatingModal', 'LakeUtils',function ($window,RatingModal, LakeUtils) {
function getRating(rating){
var stars = 0;
var icon = 'fa-question';
var buttonclass = 'button-calm';
switch(rating.rating){
case 1:
stars = 3;
icon = 'fa-smile-o';
buttonclass = 'button-positive';
break;
case 2:
stars = 2;
icon = 'fa-smile-o';
buttonclass = 'button-balanced';
break;
case 3:
stars = 1;
icon = 'fa-meh-o';
buttonclass = 'button-energized';
break;
case 4:
icon = 'fa-frown-o';
stars = 0;
buttonclass = 'button-assertive';
break;
case 5:
case 6:
stars = 0;
icon = 'fa-ban';
buttonclass = 'button-assertive';
break;
}
return {
icon: icon,
stars: stars,
buttonclass: buttonclass,
};
}
return {
templateUrl: 'templates/lake-rating.html',
restrict: 'E',
scope: {
year: '=year',
lake: '=lake'
},
link: function (scope, element, attrs) {
if(attrs.notClickable === ''){
scope.notClickable = true;
}
scope.onResize = function(){
var panelsize = element.width();
element.find('.indicator').css({
'top': panelsize * 0.05 + 'px',
'font-size': panelsize * 0.65 + 'px',
'line-height': panelsize * 0.65 + 'px'
});
element.find('.star').css({
'bottom': panelsize * 0.05 + 'px',
'font-size': panelsize * 0.25 + 'px',
'line-height': panelsize * 0.25 + 'px'
});
};
angular.element($window).bind('resize', function() {
scope.onResize();
});
scope.$watch(function(){
return element.width();
},scope.onResize);
var changed = function(){
if(scope.lake && scope.lake.yearratings){
var rating;
if(!scope.year){
rating = LakeUtils.getLatestYearRating(scope.lake);
}else{
rating = LakeUtils.getRatingByYear(scope.lake,scope.year);
}
var newRating = getRating(rating);
angular.extend(scope,newRating);
}
};
scope.$watch('lake',changed);
scope.$watch('year', changed);
scope.openModal = function(){
if(scope.lake && !scope.notClickable){
RatingModal.openModal(scope.lake._id);
}
};
scope.onResize();
}
};
}]); |
import styled from 'styled-components';
const Column5 = styled.div`
display: flex;
width: 80%;
`;
export default Column5;
|
// Constants
const ACTION = 'ACTION'
const ACTION_HANDLERS = {
[ACTION]: handleAction
}
// Action Creators
export function myAction (payload) {
return {
type: ACTION,
payload
}
}
function handleAction (state, action) {
}
// Reducer
export const initialState = {}
export default function (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
/*! jQuery UI - v1.10.4 - 2014-06-15
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.bg={closeText:"затвори",prevText:"<назад",nextText:"напред>",nextBigText:">>",currentText:"днес",monthNames:["Януари","Февруари","Март","Април","Май","Юни","Юли","Август","Септември","Октомври","Ноември","Декември"],monthNamesShort:["Яну","Фев","Мар","Апр","Май","Юни","Юли","Авг","Сеп","Окт","Нов","Дек"],dayNames:["Неделя","Понеделник","Вторник","Сряда","Четвъртък","Петък","Събота"],dayNamesShort:["Нед","Пон","Вто","Сря","Чет","Пет","Съб"],dayNamesMin:["Не","По","Вт","Ср","Че","Пе","Съ"],weekHeader:"Wk",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.bg)}); |
"use strict";
var XboxController = require('xbox-controller'),
controller = new XboxController();
controller.on('a:press', function (key) {
console.log('a press');
});
controller.on('b:release', function (key) {
console.log('b release');
});
controller.on('righttrigger', function (position) {
console.log('righttrigger', position);
});
controller.on('left:move', function (position) {
console.log('left:move', position);
}); |
import Sticky from 'semantic-ui-ember/components/ui-sticky';
export default Sticky;
|
var assert = require('assert'),
fs = require('fs'),
pdfinfo = require('../lib/pdfinfo.js');
describe('pdfinfo', function(){
describe('add_options', function(){
it('should add options', function(){
var pinfo = new pdfinfo(__dirname + '/pdfs/invalidfile.pdf');
pinfo.add_options(['--space-as-offset 1', '--css-draw 0', '-h']);
assert.equal(1, pinfo.options.additional.indexOf('--space-as-offset'));
assert.equal(3, pinfo.options.additional.indexOf('--css-draw'));
})
});
describe('file_name_with_spaces', function(){
it('should add options', function(){
var pinfo = new pdfinfo(__dirname + '/pdfs/sample 1.pdf');
pinfo.add_options(['--space-as-offset 1', '--css-draw 0', '-h']);
assert.equal(1, pinfo.options.additional.indexOf('--space-as-offset'));
assert.equal(3, pinfo.options.additional.indexOf('--css-draw'));
})
});
describe('get_info', function(){
it('should get pdf info', function(done){
var pinfo = new pdfinfo(__dirname + '/pdfs/sample.pdf');
pinfo.getInfo().then(function(ret) {
assert.equal('4', ret.pages);
done();
});
});
});
describe('sync_info', function(){
it('should get pdf info sync call', function(){
var pinfo = new pdfinfo(__dirname + '/pdfs/sample.pdf');
var ret = pinfo.getInfoSync();
assert.equal('4', ret.pages);
});
});
describe('file_with_spaces_get_info', function(){
it('should get pdf info', function(done){
var pinfo = new pdfinfo(__dirname + '/pdfs/sample 1.pdf');
pinfo.getInfo().then(function(ret) {
assert.equal('4', ret.pages);
done();
});
});
});
describe('error', function(){
it('should call error callback', function(done){
var pinfo = new pdfinfo(__dirname + '/pdfs/invalidfile.pdf');
pinfo.getInfo()
.catch(function(err) {
done();
});
});
it('should call error callback when pdfinfo chokes (since it cannot handle a password protected file)', function(done){
var pinfo = new pdfinfo(__dirname + '/pdfs/pdf-with-password.pdf');
pinfo.getInfo()
.catch(function(err) {
assert.equal(err, 'Command Line Error: Incorrect password\n');
done();
});
});
it('should call error callback when pdfinfo chokes (since it cannot handle a password protected file) in sync mode', function(done){
var pinfo = new pdfinfo(__dirname + '/pdfs/pdf-with-password.pdf');
try {
var resp = pinfo.getInfoSync();
} catch (err) {
done();
}
});
it('should call error when command is not found', async function() {
var pinfo = new pdfinfo(__dirname + '/pdfs/sample 1.pdf', {command: 'pdfinfofake'});
try {
await pinfo.getInfo()
} catch (err) {
assert.ok(true)
}
});
});
})
|
// Defines the ExplodeBox type.
var ExplodeBox = function(x, y, config) {
this.x = x;
this.y = y;
this.width = config.box.explode.size.width;
this.height = config.box.explode.size.height;
this.colour = config.box.explode.colour;
this.currentColour= config.box.explode.colour[0];
this.end = false;
this.count = 0;
}
// Define the ExplodeBox type's update method.
ExplodeBox.prototype.update = function() {
this.count++;
this.width += 2;
this.height += 2;
this.currentColour = this.colour[Math.floor(this.count / 10)];
if (this.count == 50) {
this.end = true;
}
};
ExplodeBox.prototype.endOfExplode = function() {
return this.end;
};
// Returns an object with x an y coords, the box's current position
ExplodeBox.prototype.getPosition = function() {
return {x: this.x, y: this.y};
};
// Returns an object with width and height of the box
ExplodeBox.prototype.getSize = function() {
return {width: this.width, height: this.height};
};
module.exports = ExplodeBox; |
import Icon from '../../components/Icon.vue'
Icon.register({
'regular/smile-wink': {
width: 496,
height: 512,
paths: [
{
d: 'M248 8c137 0 248 111 248 248s-111 248-248 248-248-111-248-248 111-248 248-248zM248 456c110.3 0 200-89.7 200-200s-89.7-200-200-200-200 89.7-200 200 89.7 200 200 200zM365.8 309.6c10.2 8.5 11.6 23.6 3.1 33.8-30 36-74.1 56.6-120.9 56.6s-90.9-20.6-120.9-56.6c-8.4-10.2-7.1-25.3 3.1-33.8 10.1-8.4 25.3-7.1 33.8 3.1 20.8 25.1 51.5 39.4 84 39.4s63.2-14.4 84-39.4c8.5-10.2 23.6-11.6 33.8-3.1zM168 240c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zM328 180c25.7 0 55.9 16.9 59.7 42.1 1.8 11.1-11.3 18.2-19.8 10.8l-9.5-8.5c-14.8-13.2-46.2-13.2-61 0l-9.5 8.5c-8.3 7.4-21.5 0.4-19.8-10.8 4-25.2 34.2-42.1 59.9-42.1z'
}
]
}
})
|
var myutil = require('../lib/myutil');
var LOG = myutil.LOG;
var ERROR = myutil.ERROR;
var op = require('./op');
var Socket = require('../lib/socket');
var connSocket = null;
var state = 0;
var account = "2234";
var charname = "abc";
function succ(session)
{
var inst = new op.testMessage({hello:"hello"});
session.sendByteBuffer(1, inst.toBuffer());
}
function err(sockObj)
{
ERROR("error");
}
function msgCB(sockObj, msgID, buf)
{
if(msgID == 2){
LOG("recv msg 2 from server");
}
}
var connectServer = function(ip, port){
var connOption = {}
connOption.client = true;
connOption.port = port;
connOption.host = ip;
connOption.errCB = err;
connOption.connSuccCB = succ;
connOption.msgCB = msgCB;
connSocket = new Socket(connOption);
LOG("connecting "+ip+" "+port);
}
connectServer("127.0.0.1", 1234);
|
/* eslint-disable import/no-unresolved */
import { expect, assert } from 'chai';
import { describe, it } from 'mocha';
import BirdknifeText from '../libs/text';
import DummyStatus from './DummyStatus';
describe('BirdknifeText', () => {
describe('#isCommand', () => {
it('recognizes commands', () => {
const c1 = BirdknifeText.isCommand('/a');
const c2 = BirdknifeText.isCommand('/reply');
const c3 = BirdknifeText.isCommand('/asdofi4329 arg1 arg2');
assert.isTrue(c1, 'is a command');
assert.isTrue(c2, 'is a command');
assert.isTrue(c3, 'is a command');
const s1 = BirdknifeText.isCommand('reply');
const s2 = BirdknifeText.isCommand('reply arg1 arg2');
const s3 = BirdknifeText.isCommand('reply /command');
assert.isFalse(s1, 'is not a command');
assert.isFalse(s2, 'is not a command');
assert.isFalse(s3, 'is not a command');
});
});
describe('#isQuote', () => {
it('recognizes quote commands', () => {
const q1 = BirdknifeText.isQuote('/quote a0 ');
const q2 = BirdknifeText.isQuote('/quote be This is a comment');
const q3 = BirdknifeText.isQuote('/quote ax try /quote');
const q4 = BirdknifeText.isQuote('/quote zz ');
assert.isTrue(q1, 'is a quote command');
assert.isTrue(q2, 'is a quote command');
assert.isTrue(q3, 'is a quote command');
assert.isTrue(q4, 'is a quote command');
const nq1 = BirdknifeText.isQuote('a');
const nq2 = BirdknifeText.isQuote('/a');
const nq3 = BirdknifeText.isQuote('/quote');
const nq4 = BirdknifeText.isQuote('/quote ai');
const nq5 = BirdknifeText.isQuote('/quote a ');
const nq6 = BirdknifeText.isQuote('/quote /quote c6 ');
const nq7 = BirdknifeText.isQuote('/quote al ');
const nq8 = BirdknifeText.isQuote('/reply al ');
assert.isFalse(nq1, 'is not a quote command');
assert.isFalse(nq2, 'is not a quote command');
assert.isFalse(nq3, 'is not a quote command');
assert.isFalse(nq4, 'is not a quote command');
assert.isFalse(nq5, 'is not a quote command');
assert.isFalse(nq6, 'is not a quote command');
assert.isFalse(nq7, 'is not a quote command');
assert.isFalse(nq8, 'is not a quote command');
});
});
describe('#isReply', () => {
it('recognizes reply commands', () => {
const r1 = BirdknifeText.isReply('/reply a0 ');
const r2 = BirdknifeText.isReply('/reply be This is a reply');
const r3 = BirdknifeText.isReply('/reply ax try /quote');
const r4 = BirdknifeText.isReply('/reply zz ');
assert.isTrue(r1, 'is a reply command');
assert.isTrue(r2, 'is a reply command');
assert.isTrue(r3, 'is a reply command');
assert.isTrue(r4, 'is a reply command');
const nr1 = BirdknifeText.isReply('a');
const nr2 = BirdknifeText.isReply('/a');
const nr3 = BirdknifeText.isReply('/reply');
const nr4 = BirdknifeText.isReply('/reply ai');
const nr5 = BirdknifeText.isReply('/reply a ');
const nr6 = BirdknifeText.isReply('/reply /reply c6 ');
const nr7 = BirdknifeText.isReply('/reply al ');
const nr8 = BirdknifeText.isReply('/quote al ');
assert.isFalse(nr1, 'is not a reply command');
assert.isFalse(nr2, 'is not a reply command');
assert.isFalse(nr3, 'is not a reply command');
assert.isFalse(nr4, 'is not a reply command');
assert.isFalse(nr5, 'is not a reply command');
assert.isFalse(nr6, 'is not a reply command');
assert.isFalse(nr7, 'is not a reply command');
assert.isFalse(nr8, 'is not a reply command');
});
});
describe('#getStatusURL', () => {
it('returns a valid status url', () => {
const ex = 'https://twitter.com/screenname/status/123456789012345678';
/* eslint-disable camelcase */
const dummy = {
id_str: '123456789012345678',
user: {
screen_name: 'screenname'
}
};
/* eslint-enable camelcase */
const res = BirdknifeText.getStatusURL(dummy);
expect(res).to.equal(ex);
});
});
describe('#autoBoldStatusEntities', () => {
it('bolds entities in a dummy status', () => {
const text = BirdknifeText.autoBoldStatusEntities(DummyStatus);
expect(text).to.equal(
'\u001b[1m@_vanita5\u001b[22m asdf \u001b[1m#odersp\u001b[22m'
);
});
});
});
|
//"use strict";
//
function defaults (arg1 = 1, arg2, {prop1= 'p1', prop2} = {}, arg4 = 'sono null'){
console.log("arg1 ", arg1);
console.log("arg2 ",arg2);
console.log("prop1 ",prop1);
console.log("prop1 ",prop2);
console.log("arg4 ",arg4);
}
defaults(1, 2, {prop1: 'p1', prop2 :'p2'}, null);
defaults();
|
'use strict';
var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORT || 3000;
app.use(express.static('./src'));
//For html5mode support
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, './src') });
});
app.listen(port);
console.log('Server is listening on ' + port); |
var html = require('choo/html')
var choo = require('choo')
var xhr = require('xhr')
var app = choo()
app.router([
['/done.html', doneView],
['/', mainView]
])
document.body.appendChild(app.start())
function mainView () {
var buttonClass = 'f6 f5-ns fw6 dib ba b--black-20 bg-blue white ph3 ph4-ns pv2 pv3-ns br2 grow no-underline pointer'
return html`
<body class="">
<main class="mw6 center">
<h1>Login</h1>
<button onclick=${redirect} class=${buttonClass}>
Continue with GitHub
</button>
</main>
</body>
`
}
function doneView () {
var code = window.location.href.match(/\?code=(.*)/)[1]
var json = {
code: code
}
var opts = {
uri: '/login',
json: json,
method: 'POST'
}
xhr(opts, function (err, res, body) {
if (err) return console.log(err)
})
return html`
<a href="/">done</a>
`
}
function redirect () {
var url = '/redirect'
xhr(url, function (err, res, body) {
if (err) return console.log(err)
var location = res.headers['x-github-oauth-redirect']
window.location = location
})
}
|
import test from 'ava';
import { assert } from 'chai';
import service from '../src/multi-service';
test('should throw an error of nonexistent app', () => {
assert.throws(() => {
service({ collectionName: 'test', schema: { } });
});
});
test('should throw an error of nonexistent collectionName', () => {
assert.throws(() => {
service({ app: { }, schema: { } });
});
});
test('should throw an error on nonexistent schema', () => {
assert.throws(() => {
service({ app: { }, collectionName: 'test' });
});
});
test('should return a multi-service instance', () => {
const options = {
app: {
get: () => 'test'
},
collectionName: 'test',
schema: {}
};
assert.isObject(service(options));
});
test('should return a dbUrl and dbPrefix from config', () => {
const config = { dbUrl: 'mongodb://localhost', dbPrefix: 'some' };
const options = {
app: {
get(key) {
return config[key];
}
},
collectionName: 'test',
schema: {}
};
const result = service(options);
assert.equal(result.dbUrl, config.dbUrl);
assert.equal(result.dbPrefix, config.dbPrefix);
});
test('should return a dbUrl and dbPrefix from options', () => {
const options = {
app: { },
collectionName: 'test',
schema: {},
dbUrl: 'mongodb://localhost',
dbPrefix: 'some'
};
const result = service(options);
assert.equal(result.dbUrl, options.dbUrl);
assert.equal(result.dbPrefix, options.dbPrefix);
});
|
var Transmitter = require('./transmitter');
var Receiver = require('./receiver');
export default class AFSK {
constructor () {
this.defaultSignature = [33, 35, 31, 37];
}
transmit(bytes, signature = null) {
var transmitter = new Transmitter(signature || this.defaultSignature);
transmitter.transmit(bytes);
}
receive(callback, signature = null) {
var receiver = new Receiver(signature || this.defaultSignature);
receiver.receive(callback);
}
}
|
/**
* Created by Qiaodan on 2017/5/25.
*/
//懒加载以及异步加载
var jfLazyLoading = {
//图片懒加载
lazyLoadInit: function (details) {
var _this = this;
if (!details) {//如果details未输入,则防止报错
details = {};
}
_this.thisImgEle = details.thisImgEle || 'loading_img';//显示的图片,class选择器
_this.bottomDistance = details.bottomDistance || '50';//图片未显示时距离底部的距离。触发加载的距离
_this.getLazyDistance(); //页面初始化先执行一次;
//鼠标滚动事件,触发事件
addEventListener("scroll", function () {
_this.getLazyDistance()
}, false)
},
//获取图片距离底部的距离
getLazyDistance: function () {
var _this = this;
var thisScrollTop = document.body.scrollTop;//获取滚动条的距离
var thisWindowHeight = window.innerHeight;//屏幕可视窗口高度
var thisMaxHeight = parseFloat(thisScrollTop) + parseFloat(thisWindowHeight);//变化的距离(窗口高度+滚动条距离)
var allLazyEle = document.getElementsByClassName(_this.thisImgEle);
for (var i = 0; i < allLazyEle.length; i++) {
var thisTopDistance = allLazyEle[i].offsetTop;//元素距离文档顶部的距离
var thisImgSrc = allLazyEle[i].getAttribute('data-src');//获取当前元素的地址
if (parseFloat(thisTopDistance) - thisMaxHeight <= _this.bottomDistance) {
allLazyEle[i].setAttribute('src', thisImgSrc)//替换图片地址
}
}
},
/*异步加载*/
ajaxLoadInit: function (details) {
var _this = this;
if (!details) {//如果details未输入,则防止报错
details = {};
}
_this.ajaxLoadDistance = details.ajaxLoadDistance || '50';//元素未显示时距离底部的距离。触发加载的距离
_this.fn = details.fn || 0;//默认执行的脚本
//鼠标滚动事件
addEventListener("scroll", function () {
_this.getAjaxLoadDistance();
}, false)
},
//获取异步加载的触发距离
getAjaxLoadDistance: function () {
var _this = this;
var thisScrollTop = document.body.scrollTop;//获取滚动条的距离
var thisDocumentHeight = document.body.scrollHeight;//获取当前文档的高度
var thisWindowHeight = window.innerHeight;//屏幕可视窗口高度
if (parseFloat(thisDocumentHeight) - parseFloat(thisScrollTop + thisWindowHeight) <= _this.ajaxLoadDistance) {//如果当前文档底部距离窗口底部的距离小于50,执行相应的脚本
if (_this.fn) {
_this.fn();
}
}
},
//异步加载的内容
ajaxContentInit: function (details) {
var _this = this;
if (!details) {//如果details未输入,则防止报错
details = {};
}
_this.productdata = details.productdata || [
{
"data_href": "javascript:",
"loading_src": "../../images/img_loading.gif",
"data_src": "../../images/img_loading.gif",
"acc_text": false,
"gift_text": false,
"product": "***",
"price_text": "0.00",
"praise": "100%",
}
];
var thisInner = '';
for (var i = 0; i < _this.productdata.length; i++) {
thisInner =
'<div class="product_main_img"><img class="loading_img" data-src='
+ _this.productdata[i].data_src +
' src='
+ _this.productdata[i].loading_src +
'></div><div class="product_main_title">';
if (_this.productdata[i].acc_text) {
thisInner +=
'<span class="acc">'
+ '附' +
'</span>'
}
if (_this.productdata[i].gift_text) {
thisInner +=
'<span class="gift">'
+ '赠' +
'</span>'
}
/*+'<span class="acc">'
+ _this.productdata[i].acc_text+
'</span>'
+'<span class="gift">'
+ _this.productdata[i].gift_text+
'</span>'*/
thisInner += _this.productdata[i].product +
'</div><div class="product_main_price"><span class="price">¥'
+ _this.productdata[i].price_text +
'</span><span class="praise"><span>'
+ _this.productdata[i].praise +
'</span>好评</span></div>';
var thisAddEle = _this.ajaxAddnode('a', thisInner, 'product');//增加a标签
thisAddEle.setAttribute('href', _this.productdata[i].data_href)
}
var allAccEle = document.getElementsByClassName('hot_goods_list')[0].getElementsByClassName('acc');//所有‘附’字的span元素;
var allGiftEle = document.getElementsByClassName('hot_goods_list')[0].getElementsByClassName('gift');//所有‘赠’字的span元素
//判断当前有没有‘附’字
/*for(var i=0;i<allAccEle.length;i++){
if(allAccEle[i].innerHTML==""){
allAccEle[i].style.display="none"
}
}
//判断当前有没有‘赠’字
for(var i=0;i<allGiftEle.length;i++){
if(allGiftEle[i].innerHTML==""){
allGiftEle[i].style.display="none"
}
}*/
},
//添加元素
ajaxAddnode: function (tag, innerHtml, className) {
var _this = this;
var obj = document.createElement(tag);
if (className) {
obj.className = className
}
obj.innerHTML = innerHtml;
//obj.setAttribute('href',_this.productdata[i].data_href);
document.getElementsByClassName('hot_goods_list')[0].appendChild(obj);
return obj
}
}
//懒加载以及异步加载结束
|
var async = require('async')
, util = require('util')
, AirAir = require('./index')
;
AirAir.discover(function(sensor) {
console.log('found ' + sensor.uuid);
sensor.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
sensor.on('sensorDataChange', function(err, results) {
if (!!err) console.log('\tvalues error: ' + err.message); else console.log(util.inspect(results, { depth: null }));
});
async.series([
function(callback) {
console.log('connectAndSetup');
sensor.connectAndSetup(callback);
},
function(callback) {
console.log('notifySensorData');
sensor.notifySensorData(callback);
},
function(callback) {
setTimeout(callback, 60000);
},
function(callback) {
console.log('unnotifySensorData');
sensor.unnotifySensorData(callback);
},
function(callback) {
console.log('readDeviceName');
sensor.readDeviceName(function(deviceName) {
console.log('\tdevice name = ' + deviceName);
deviceName = 'SENSOR ONE';
console.log('writeDeviceName');
sensor.writeDeviceName(deviceName, callback);
});
},
function(callback) {
console.log('disconnect');
sensor.disconnect(callback);
}
]
);
});
|
var
path = require("path");
var
_ = require("lodash");
var
webpackConfig = require("./webpack.config");
module.exports = _.merge(webpackConfig, {
cache: true,
devtool: "sourcemap",
debug: true,
output: {
sourceMapFilename: "[file].map",
hotUpdateMainFilename: "updates/[hash]/update.json",
hotUpdateChunkFilename: "updates/[hash]/js/[id].update.js"
},
recordsOutputPath: path.join(__dirname, "records.json")
});
module.exports.module.loaders.push({
test: /sinon\.js$/, loader: "imports?define=>false"
});
module.exports.plugins = [];
|
var Request = require('request');
var FeedParser = require('feedparser');
var fs = require('fs');
var http = require('http');
var colors = require('colors');
var sprintf = require('sprintf-js').sprintf;
// local configuration
var config = require('./podcasts_fetcher.json');
function run(RSSFeed) {
var request = new Request(RSSFeed);
var feedparser = new FeedParser([]);
var feedFolder = '';
var feedMeta = {title: "", author: ""};
var podcasts = [];
request.on('error', function(error) {
console.error("request error:", error);
});
request.on('response', function(res) {
if (res.statusCode !== 200) {
return this.emit('error', new Error('Bad status code'));
}
this.pipe(feedparser);
});
feedparser.on('error', function(error) {
console.error('feedparser error:', error);
});
feedparser.on('meta', function(meta) {
feedMeta = meta;
feedFolder = config.download_folder + '/' + feedMeta.author + '/' + feedMeta.title + '/';
});
feedparser.on('readable', function() {
var item;
while (item = this.read()) {
podcasts.push(parseItem(item));
}
});
feedparser.on('end', function() {
mkdirSync(config.download_folder);
mkdirSync(config.download_folder + '/' + feedMeta.author);
mkdirSync(feedFolder);
console.log(String(podcasts.length).cyan + ' podcasts have been downloaded to '.yellow + feedFolder.cyan + ' folder'.yellow);
// saving playlist of all feed podcast
savePodcastPlaylist(config.download_folder + '/' + feedMeta.author + '/' + feedMeta.title + '.m3u',
podcasts.map(function(elem){
return '#EXTINF:,' + elem.title + '\n' + elem.url_m;
}).join("\n"));;
processNextPodcast();
});
function processNextPodcast() {
var podcast = podcasts.shift();
if (typeof podcast === 'undefined') {
return;
}
savePodcastPlaylist(podcast.playlist, podcast.url_m);
if (config.media_download === true && podcast.length <= config.max_media_download_size) {
savePodcastMedia(podcast, processNextPodcast);
}
else {
processNextPodcast();
}
}
function parseItem(item) {
// \u00E0-\u00FC means to keep the accents :)
var title = item['title'].replace(/[^a-zA-Z- 0-9.\u00E0-\u00FC]/gi, '');
var dateObj = new Date(item['pubDate']);
var date = sprintf('%d-%02d-%02d',
dateObj.getFullYear(),
dateObj.getMonth() + 1,
dateObj.getDate());
var podcast = {
"title": title,
"date": date,
"length": parseInt(item.enclosures[0].length),
"url_m": item.enclosures[0].url,
"url": item.guid,
"playlist": feedFolder + date + '-' + title + '.m3u',
"file": feedFolder + date + '-' + title + '.mp3'
};
return podcast;
}
function savePodcastPlaylist(file, playlist) {
fs.writeFile(file, '#EXTM3U\n' + playlist, function(error) {
if (error) {
console.error("The file [" + file + "] could not be saved :", error);
}
});
}
function savePodcastMedia(podcast, callback) {
var file = fs.createWriteStream(podcast.file);
var start_date = Date.now();
http.get(podcast.url, function(response) {
response.pipe(file);
file.on('finish', function() {
var download_time = (Date.now() - start_date) / 1000; // in seconds
var download_speed = podcast.length / 1000000 / download_time; // download speed in MByte/sec
console.log('Downloaded', podcast.length, 'Bytes in', download_time, 'seconds (', download_speed, 'MB/s)');
file.close(callback);
});
file.on('error', function(err) {
fs.unlink(podcast.file);
if (typeof callback === 'function') {
callback(err.message);
}
});
});
}
}
function mkdirSync(path) {
try {
fs.mkdirSync(path);
} catch (error) {
if (error.code !== 'EEXIST') {
throw error;
}
}
}
try {
// browsing feeds from configuration file
for (var i = 0; i < config.rss_feeds.length; i++) {
run(config.rss_feeds[i]);
}
}
catch (error) {
console.error('Error: ', error);
}
|
const concat = require('concat-stream')
const h = require('virtual-dom/h')
const test = require('tape')
const vdom = require('./')
test('should assert input types', function (t) {
t.plan(1)
t.throws(vdom, /object/)
})
test('should render a vdom tree to an html stream', function (t) {
t.plan(1)
vdom(h('div.foo', [ 'hello world' ])).pipe(concat(function (buf) {
const str = String(buf)
t.equal(str, '<div class="foo">hello world</div>', 'is html')
}))
})
|
import fs from 'fs';
import tracker from './tracker';
import semver from 'semver';
import path from 'path';
import knexPackage from 'knex/package.json';
import {
MockSymbol,
} from './util/transformer';
const platforms = [
'knex',
];
const knexVersion = knexPackage.version;
class MockKnex {
adapter = null;
_adapter = null;
_extractVersion(version, versions) {
if (! semver.valid(version)) {
version += '.0';
}
const extracted = versions.some((v) => {
let found = 0;
if (semver.satisfies(version, '^' + v)) {
found = version = v;
}
return found > 0;
});
if (! extracted) {
throw new Error('Unable to locate version: ' + version);
}
return version;
}
_setAdapter(db, platform = 'knex', version = knexVersion) {
let versions = fs.readdirSync(path.join(__dirname, './platforms', platform));
if (platforms.indexOf(platform) === -1) {
throw new Error('invalid platform: ' + platform);
}
versions = versions.sort((a, b) => {
return a - b;
});
if (version) {
version = this._extractVersion(version, versions);
} else {
version = versions.pop();
}
this.adapter = {
platform,
version,
};
this._adapter = require(
path.join(
__dirname,
'platforms',
this.adapter.platform,
this.adapter.version,
'index'
)
).default;
return this;
}
getTracker() {
return tracker;
}
mock(db) {
this._setAdapter(db);
return this._adapter.mock(db);
}
unmock(db) {
this._setAdapter(db);
return this._adapter.unmock(db);
}
isMocked(db) {
return !! db[MockSymbol];
}
getAdapter() {
return this._adapter;
}
}
export default new MockKnex();
|
'use strict';
angular.module('copayApp.controllers').controller('createController',
function($scope, $rootScope, $timeout, $log, lodash, $state, $ionicScrollDelegate, $ionicHistory, profileService, configService, gettextCatalog, ledger, trezor, intelTEE, derivationPathHelper, ongoingProcess, walletService, storageService, popupService, appConfigService) {
/* For compressed keys, m*73 + n*34 <= 496 */
var COPAYER_PAIR_LIMITS = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 4,
6: 4,
7: 3,
8: 3,
9: 2,
10: 2,
11: 1,
12: 1,
};
$scope.init = function(tc) {
$scope.formData = {};
var defaults = configService.getDefaults();
$scope.formData.account = 1;
$scope.formData.bwsurl = defaults.bws.url;
$scope.TCValues = lodash.range(2, defaults.limits.totalCopayers + 1);
$scope.formData.totalCopayers = defaults.wallet.totalCopayers;
$scope.formData.derivationPath = derivationPathHelper.default;
$scope.setTotalCopayers(tc);
updateRCSelect(tc);
};
$scope.showAdvChange = function() {
$scope.showAdv = !$scope.showAdv;
$scope.resizeView();
};
$scope.resizeView = function() {
$timeout(function() {
$ionicScrollDelegate.resize();
}, 10);
checkPasswordFields();
};
function checkPasswordFields() {
if (!$scope.encrypt) {
$scope.formData.passphrase = $scope.formData.createPassphrase = $scope.formData.passwordSaved = null;
$timeout(function() {
$scope.$apply();
});
}
};
function updateRCSelect(n) {
$scope.formData.totalCopayers = n;
var maxReq = COPAYER_PAIR_LIMITS[n];
$scope.RCValues = lodash.range(1, maxReq + 1);
$scope.formData.requiredCopayers = Math.min(parseInt(n / 2 + 1), maxReq);
};
function updateSeedSourceSelect(n) {
var seedOptions = [{
id: 'new',
label: gettextCatalog.getString('Random'),
supportsTestnet: true
}, {
id: 'set',
label: gettextCatalog.getString('Specify Recovery Phrase...'),
supportsTestnet: false
}];
$scope.seedSource = seedOptions[0];
/*
Disable Hardware Wallets for BitPay distribution
*/
if (appConfigService.name == 'copay') {
if (n > 1 && walletService.externalSource.ledger.supported)
seedOptions.push({
id: walletService.externalSource.ledger.id,
label: walletService.externalSource.ledger.longName,
supportsTestnet: walletService.externalSource.ledger.supportsTestnet
});
if (walletService.externalSource.trezor.supported) {
seedOptions.push({
id: walletService.externalSource.trezor.id,
label: walletService.externalSource.trezor.longName,
supportsTestnet: walletService.externalSource.trezor.supportsTestnet
});
}
if (walletService.externalSource.intelTEE.supported) {
seedOptions.push({
id: walletService.externalSource.intelTEE.id,
label: walletService.externalSource.intelTEE.longName,
supportsTestnet: walletService.externalSource.intelTEE.supportsTestnet
});
}
}
$scope.seedOptions = seedOptions;
};
$scope.setTotalCopayers = function(tc) {
$scope.formData.totalCopayers = tc;
updateRCSelect(tc);
updateSeedSourceSelect(tc);
};
$scope.create = function(form) {
if (form && form.$invalid) {
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Please enter the required fields'));
return;
}
var opts = {
name: $scope.formData.walletName,
m: $scope.formData.requiredCopayers,
n: $scope.formData.totalCopayers,
myName: $scope.formData.totalCopayers > 1 ? $scope.formData.myName : null,
networkName: $scope.formData.testnetEnabled ? 'testnet' : 'livenet',
bwsurl: $scope.formData.bwsurl,
singleAddress: $scope.formData.singleAddressEnabled,
walletPrivKey: $scope.formData._walletPrivKey, // Only for testing
};
var setSeed = $scope.seedSource.id == 'set';
if (setSeed) {
var words = $scope.formData.privateKey || '';
if (words.indexOf(' ') == -1 && words.indexOf('prv') == 1 && words.length > 108) {
opts.extendedPrivateKey = words;
} else {
opts.mnemonic = words;
}
opts.passphrase = $scope.formData.passphrase;
var pathData = derivationPathHelper.parse($scope.formData.derivationPath);
if (!pathData) {
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Invalid derivation path'));
return;
}
opts.account = pathData.account;
opts.networkName = pathData.networkName;
opts.derivationStrategy = pathData.derivationStrategy;
} else {
opts.passphrase = $scope.formData.createPassphrase;
}
if (setSeed && !opts.mnemonic && !opts.extendedPrivateKey) {
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Please enter the wallet recovery phrase'));
return;
}
if ($scope.seedSource.id == walletService.externalSource.ledger.id || $scope.seedSource.id == walletService.externalSource.trezor.id || $scope.seedSource.id == walletService.externalSource.intelTEE.id) {
var account = $scope.formData.account;
if (!account || account < 1) {
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Invalid account number'));
return;
}
if ($scope.seedSource.id == walletService.externalSource.trezor.id || $scope.seedSource.id == walletService.externalSource.intelTEE.id)
account = account - 1;
opts.account = account;
ongoingProcess.set('connecting ' + $scope.seedSource.id, true);
var src;
switch ($scope.seedSource.id) {
case walletService.externalSource.ledger.id:
src = ledger;
break;
case walletService.externalSource.trezor.id:
src = trezor;
break;
case walletService.externalSource.intelTEE.id:
src = intelTEE;
break;
default:
popupService.showAlert(gettextCatalog.getString('Error'), 'Invalid seed source id');
return;
}
src.getInfoForNewWallet(opts.n > 1, account, opts.networkName, function(err, lopts) {
ongoingProcess.set('connecting ' + $scope.seedSource.id, false);
if (err) {
popupService.showAlert(gettextCatalog.getString('Error'), err);
return;
}
opts = lodash.assign(lopts, opts);
_create(opts);
});
} else {
_create(opts);
}
};
function _create(opts) {
ongoingProcess.set('creatingWallet', true);
$timeout(function() {
profileService.createWallet(opts, function(err, client) {
ongoingProcess.set('creatingWallet', false);
if (err) {
$log.warn(err);
popupService.showAlert(gettextCatalog.getString('Error'), err);
return;
}
walletService.updateRemotePreferences(client);
if ($scope.seedSource.id == 'set') {
profileService.setBackupFlag(client.credentials.walletId);
}
$ionicHistory.removeBackView();
if (!client.isComplete()) {
$ionicHistory.nextViewOptions({
disableAnimate: true
});
$state.go('tabs.home');
$timeout(function() {
$state.transitionTo('tabs.copayers', {
walletId: client.credentials.walletId
});
}, 100);
} else $state.go('tabs.home');
});
}, 300);
}
});
|
import { generateRoutes } from '@utils/generate-routes'
describe('Generate routes', () => {
it('has all dates', () => {
const routes = generateRoutes()
expect(routes.length).toBe(366)
})
})
|
module.exports = function (fn) {
return function () {
return fn.call(this);
}
};
|
import { Point, ObservablePoint, Rectangle } from '../math';
import { sign, TextureCache } from '../utils';
import { BLEND_MODES } from '../const';
import Texture from '../textures/Texture';
import Container from '../display/Container';
const tempPoint = new Point();
/**
* The Sprite object is the base for all textured objects that are rendered to the screen
*
* A sprite can be created directly from an image like this:
*
* ```js
* let sprite = new PIXI.Sprite.fromImage('assets/image.png');
* ```
*
* @class
* @extends PIXI.Container
* @memberof PIXI
*/
export default class Sprite extends Container
{
/**
* @param {PIXI.Texture} texture - The texture for this sprite
*/
constructor(texture)
{
super();
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the texture's origin is the top left
* Setting the anchor to 0.5,0.5 means the texture's origin is centered
* Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
*
* @member {PIXI.ObservablePoint}
* @private
*/
this._anchor = new ObservablePoint(this._onAnchorUpdate, this);
/**
* The texture that the sprite is using
*
* @private
* @member {PIXI.Texture}
*/
this._texture = null;
/**
* The width of the sprite (this is initially set by the texture)
*
* @private
* @member {number}
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @private
* @member {number}
*/
this._height = 0;
/**
* The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
*
* @private
* @member {number}
* @default 0xFFFFFF
*/
this._tint = null;
this._tintRGB = null;
this.tint = 0xFFFFFF;
/**
* The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
*
* @member {number}
* @default PIXI.BLEND_MODES.NORMAL
* @see PIXI.BLEND_MODES
*/
this.blendMode = BLEND_MODES.NORMAL;
/**
* The shader that will be used to render the sprite. Set to null to remove a current shader.
*
* @member {PIXI.Filter|PIXI.Shader}
*/
this.shader = null;
/**
* An internal cached value of the tint.
*
* @private
* @member {number}
* @default 0xFFFFFF
*/
this.cachedTint = 0xFFFFFF;
// call texture setter
this.texture = texture || Texture.EMPTY;
/**
* this is used to store the vertex data of the sprite (basically a quad)
*
* @private
* @member {Float32Array}
*/
this.vertexData = new Float32Array(8);
/**
* This is used to calculate the bounds of the object IF it is a trimmed sprite
*
* @private
* @member {Float32Array}
*/
this.vertexTrimmedData = null;
this._transformID = -1;
this._textureID = -1;
/**
* Plugin that is responsible for rendering this element.
* Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods.
*
* @member {string}
* @default 'sprite'
*/
this.pluginName = 'sprite';
}
/**
* When the texture is updated, this event will fire to update the scale and frame
*
* @private
*/
_onTextureUpdate()
{
this._textureID = -1;
// so if _width is 0 then width was not set..
if (this._width)
{
this.scale.x = sign(this.scale.x) * this._width / this.texture.orig.width;
}
if (this._height)
{
this.scale.y = sign(this.scale.y) * this._height / this.texture.orig.height;
}
}
/**
* Called when the anchor position updates.
*
* @private
*/
_onAnchorUpdate()
{
this._transformID = -1;
}
/**
* calculates worldTransform * vertices, store it in vertexData
*/
calculateVertices()
{
if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID)
{
return;
}
this._transformID = this.transform._worldID;
this._textureID = this._texture._updateID;
// set the vertex data
const texture = this._texture;
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const vertexData = this.vertexData;
const trim = texture.trim;
const orig = texture.orig;
const anchor = this._anchor;
let w0 = 0;
let w1 = 0;
let h0 = 0;
let h1 = 0;
if (trim)
{
// if the sprite is trimmed and is not a tilingsprite then we need to add the extra
// space before transforming the sprite coords.
w1 = trim.x - (anchor._x * orig.width);
w0 = w1 + trim.width;
h1 = trim.y - (anchor._y * orig.height);
h0 = h1 + trim.height;
}
else
{
w0 = orig.width * (1 - anchor._x);
w1 = orig.width * -anchor._x;
h0 = orig.height * (1 - anchor._y);
h1 = orig.height * -anchor._y;
}
// xy
vertexData[0] = (a * w1) + (c * h1) + tx;
vertexData[1] = (d * h1) + (b * w1) + ty;
// xy
vertexData[2] = (a * w0) + (c * h1) + tx;
vertexData[3] = (d * h1) + (b * w0) + ty;
// xy
vertexData[4] = (a * w0) + (c * h0) + tx;
vertexData[5] = (d * h0) + (b * w0) + ty;
// xy
vertexData[6] = (a * w1) + (c * h0) + tx;
vertexData[7] = (d * h0) + (b * w1) + ty;
}
/**
* calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData
* This is used to ensure that the true width and height of a trimmed texture is respected
*/
calculateTrimmedVertices()
{
if (!this.vertexTrimmedData)
{
this.vertexTrimmedData = new Float32Array(8);
}
// lets do some special trim code!
const texture = this._texture;
const vertexData = this.vertexTrimmedData;
const orig = texture.orig;
const anchor = this._anchor;
// lets calculate the new untrimmed bounds..
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const w0 = (orig.width) * (1 - anchor._x);
const w1 = (orig.width) * -anchor._x;
const h0 = orig.height * (1 - anchor._y);
const h1 = orig.height * -anchor._y;
// xy
vertexData[0] = (a * w1) + (c * h1) + tx;
vertexData[1] = (d * h1) + (b * w1) + ty;
// xy
vertexData[2] = (a * w0) + (c * h1) + tx;
vertexData[3] = (d * h1) + (b * w0) + ty;
// xy
vertexData[4] = (a * w0) + (c * h0) + tx;
vertexData[5] = (d * h0) + (b * w0) + ty;
// xy
vertexData[6] = (a * w1) + (c * h0) + tx;
vertexData[7] = (d * h0) + (b * w1) + ty;
}
/**
*
* Renders the object using the WebGL renderer
*
* @private
* @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use.
*/
_renderWebGL(renderer)
{
this.calculateVertices();
renderer.setObjectRenderer(renderer.plugins[this.pluginName]);
renderer.plugins[this.pluginName].render(this);
}
/**
* Renders the object using the Canvas renderer
*
* @private
* @param {PIXI.CanvasRenderer} renderer - The renderer
*/
_renderCanvas(renderer)
{
renderer.plugins[this.pluginName].render(this);
}
/**
* Updates the bounds of the sprite.
*
* @private
*/
_calculateBounds()
{
const trim = this._texture.trim;
const orig = this._texture.orig;
// First lets check to see if the current texture has a trim..
if (!trim || (trim.width === orig.width && trim.height === orig.height))
{
// no trim! lets use the usual calculations..
this.calculateVertices();
this._bounds.addQuad(this.vertexData);
}
else
{
// lets calculate a special trimmed bounds...
this.calculateTrimmedVertices();
this._bounds.addQuad(this.vertexTrimmedData);
}
}
/**
* Gets the local bounds of the sprite object.
*
* @param {Rectangle} rect - The output rectangle.
* @return {Rectangle} The bounds.
*/
getLocalBounds(rect)
{
// we can do a fast local bounds if the sprite has no children!
if (this.children.length === 0)
{
this._bounds.minX = this._texture.orig.width * -this._anchor._x;
this._bounds.minY = this._texture.orig.height * -this._anchor._y;
this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x);
if (!rect)
{
if (!this._localBoundsRect)
{
this._localBoundsRect = new Rectangle();
}
rect = this._localBoundsRect;
}
return this._bounds.getRectangle(rect);
}
return super.getLocalBounds.call(this, rect);
}
/**
* Tests if a point is inside this sprite
*
* @param {PIXI.Point} point - the point to test
* @return {boolean} the result of the test
*/
containsPoint(point)
{
this.worldTransform.applyInverse(point, tempPoint);
const width = this._texture.orig.width;
const height = this._texture.orig.height;
const x1 = -width * this.anchor.x;
let y1 = 0;
if (tempPoint.x > x1 && tempPoint.x < x1 + width)
{
y1 = -height * this.anchor.y;
if (tempPoint.y > y1 && tempPoint.y < y1 + height)
{
return true;
}
}
return false;
}
/**
* Destroys this sprite and optionally its texture and children
*
* @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
* method called as well. 'options' will be passed on to those calls.
* @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
* @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
*/
destroy(options)
{
super.destroy(options);
this._anchor = null;
const destroyTexture = typeof options === 'boolean' ? options : options && options.texture;
if (destroyTexture)
{
const destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture;
this._texture.destroy(!!destroyBaseTexture);
}
this._texture = null;
this.shader = null;
}
// some helper functions..
/**
* Helper function that creates a new sprite based on the source you provide.
* The source can be - frame id, image url, video url, canvas element, video element, base texture
*
* @static
* @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from
* @return {PIXI.Texture} The newly created texture
*/
static from(source)
{
return new Sprite(Texture.from(source));
}
/**
* Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
* The frame ids are created when a Texture packer file has been loaded
*
* @static
* @param {string} frameId - The frame Id of the texture in the cache
* @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId
*/
static fromFrame(frameId)
{
const texture = TextureCache[frameId];
if (!texture)
{
throw new Error(`The frameId "${frameId}" does not exist in the texture cache`);
}
return new Sprite(texture);
}
/**
* Helper function that creates a sprite that will contain a texture based on an image url
* If the image is not in the texture cache it will be loaded
*
* @static
* @param {string} imageId - The image url of the texture
* @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter
* @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode,
* see {@link PIXI.SCALE_MODES} for possible values
* @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id
*/
static fromImage(imageId, crossorigin, scaleMode)
{
return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode));
}
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set
*
* @member {number}
* @memberof PIXI.Sprite#
*/
get width()
{
return Math.abs(this.scale.x) * this.texture.orig.width;
}
/**
* Sets the width of the sprite by modifying the scale.
*
* @param {number} value - The value to set to.
*/
set width(value)
{
const s = sign(this.scale.x) || 1;
this.scale.x = s * value / this.texture.orig.width;
this._width = value;
}
/**
* The height of the sprite, setting this will actually modify the scale to achieve the value set
*
* @member {number}
* @memberof PIXI.Sprite#
*/
get height()
{
return Math.abs(this.scale.y) * this.texture.orig.height;
}
/**
* Sets the height of the sprite by modifying the scale.
*
* @param {number} value - The value to set to.
*/
set height(value)
{
const s = sign(this.scale.y) || 1;
this.scale.y = s * value / this.texture.orig.height;
this._height = value;
}
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the texture's origin is the top left
* Setting the anchor to 0.5,0.5 means the texture's origin is centered
* Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
*
* @member {PIXI.ObservablePoint}
* @memberof PIXI.Sprite#
*/
get anchor()
{
return this._anchor;
}
/**
* Copies the anchor to the sprite.
*
* @param {number} value - The value to set to.
*/
set anchor(value)
{
this._anchor.copy(value);
}
/**
* The tint applied to the sprite. This is a hex value. A value of
* 0xFFFFFF will remove any tint effect.
*
* @member {number}
* @memberof PIXI.Sprite#
* @default 0xFFFFFF
*/
get tint()
{
return this._tint;
}
/**
* Sets the tint of the sprite.
*
* @param {number} value - The value to set to.
*/
set tint(value)
{
this._tint = value;
this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
}
/**
* The texture that the sprite is using
*
* @member {PIXI.Texture}
* @memberof PIXI.Sprite#
*/
get texture()
{
return this._texture;
}
/**
* Sets the texture of the sprite.
*
* @param {PIXI.Texture} value - The value to set to.
*/
set texture(value)
{
if (this._texture === value)
{
return;
}
this._texture = value;
this.cachedTint = 0xFFFFFF;
this._textureID = -1;
if (value)
{
// wait for the texture to load
if (value.baseTexture.hasLoaded)
{
this._onTextureUpdate();
}
else
{
value.once('update', this._onTextureUpdate, this);
}
}
}
}
|
define([],function(){return{params:void 0,insensitiveParams:void 0,init:function(){var a=this;window.onpopstate=function(){a.populateParams()},a.populateParams()},populateParams:function(){var a,b=/\+/g,c=/([^&=]+)=?([^&]*)/g,d=function(a){return decodeURIComponent(a.replace(b," "))},e=window.location.search.substring(1);for(this.params={};null!==(a=c.exec(e));)this.params[d(a[1])]=d(a[2]);return this.params},get:function(a){return this.getParams()[a]},getCaseInsensitive:function(a){if(this.insensitiveParams)return this.insensitiveParams[a.toLowerCase()];this.insensitiveParams=this.getParams();for(var b in this.params)this.insensitiveParams[b.toLowerCase()]=this.params[b];return this.insensitiveParams[a.toLowerCase()]},getParams:function(){return void 0===this.params?this.populateParams():this.params}}}); |
module.exports = function(grunt) {
var options = {
port: 8080
};
grunt.initConfig({
options: options,
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
port: options.port,
base: '.'
}
}
},
watch: {
}
});
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('default', ['connect', 'watch']);
};
|
Sim.Vision = function() {
};
Sim.Vision.prototype.getVisibleBalls = function(polygon, x, y, orientation) {
var globalPolygon = polygon.rotate(orientation).translate(x, y),
pos = {x: x, y: y},
balls = [],
ball,
distance,
angle,
i;
for (i = 0; i < sim.game.balls.length; i++) {
ball = sim.game.balls[i];
if (
globalPolygon.containsPoint(ball.x, ball.y)
) {
distance = Sim.Math.getDistanceBetween(pos, ball);
angle = Sim.Math.getAngleBetween(pos, ball, orientation);
balls.push({
ball: ball,
distance: distance,
angle: angle
});
//sim.dbg.box('#' + i, Sim.Math.round(distance, 3) + ' / ' +Sim.Math.round(Sim.Math.radToDeg(angle), 1));
}
}
return balls;
};
Sim.Vision.prototype.getVisibleGoals = function(polygon, x, y, orientation) {
var globalPolygon = polygon.rotate(orientation).translate(x, y),
pos = {x: x, y: y},
yellowCenterPos = {
x: 0,
y: sim.config.field.height / 2
},
yellowLeftPos = {
x: 0,
y: sim.config.field.height / 2 - sim.config.field.goalWidth / 2
},
yellowRightPos = {
x: 0,
y: sim.config.field.height / 2 + sim.config.field.goalWidth / 2
},
blueCenterPos = {
x: sim.config.field.width,
y: sim.config.field.height / 2
},
blueLeftPos = {
x: sim.config.field.width,
y: sim.config.field.height / 2 - sim.config.field.goalWidth / 2
},
blueRightPos = {
x: sim.config.field.width,
y: sim.config.field.height / 2 + sim.config.field.goalWidth / 2
},
distance,
angle,
realAngle,
leftEdgeDistance,
rightEdgeDistance,
leftEdgeAngle,
rightEdgeAngle,
edgeAngleDiff,
goals = [],
camera;
if (globalPolygon.containsPoint(yellowCenterPos.x, yellowCenterPos.y)) {
distance = Sim.Math.getDistanceBetween(yellowCenterPos, pos);
angle = Sim.Math.getAngleBetween(yellowCenterPos, pos, orientation);
leftEdgeDistance = null;
rightEdgeDistance = null;
leftEdgeAngle = null;
rightEdgeAngle = null;
edgeAngleDiff = null;
if (
globalPolygon.containsPoint(yellowLeftPos.x, yellowLeftPos.y)
&& globalPolygon.containsPoint(yellowRightPos.x, yellowRightPos.y)
) {
leftEdgeDistance = Sim.Math.getDistanceBetween(yellowLeftPos, pos);
rightEdgeDistance = Sim.Math.getDistanceBetween(yellowRightPos, pos);
leftEdgeAngle = Sim.Math.getAngleBetween(yellowLeftPos, pos, orientation);
rightEdgeAngle = Sim.Math.getAngleBetween(yellowRightPos, pos, orientation);
edgeAngleDiff = Math.abs(leftEdgeAngle - rightEdgeAngle);
//sim.dbg.box('Yellow', Sim.Math.round(distance1, 3) + ' ; ' + Sim.Math.round(distance2, 3) + ' / ' + Sim.Math.round(Sim.Math.radToDeg(angle1), 1) + ' ; ' + Sim.Math.round(Sim.Math.radToDeg(angle2), 1) + ' ; ' + Sim.Math.round(Sim.Math.radToDeg(yellowGoalAngle), 1));
}
camera = Math.abs(angle) < Math.PI / 2 ? 'front' : 'rear';
/*realAngle = camera === 'front' ? angle : angle + Math.PI;
if (realAngle > Math.PI) {
realAngle -= Sim.Math.TWO_PI;
}*/
goals.push({
side: Sim.Game.Side.YELLOW,
distance: distance,
angle: angle,
camera: camera,
leftEdgeDistance: leftEdgeDistance,
rightEdgeDistance: rightEdgeDistance,
leftEdgeAngle: leftEdgeAngle,
rightEdgeAngle: rightEdgeAngle,
edgeAngleDiff: edgeAngleDiff
});
//sim.dbg.box('Yellow', yellowDistance, 1);
}
if (globalPolygon.containsPoint(blueCenterPos.x, blueCenterPos.y)) {
distance = Sim.Math.getDistanceBetween(blueCenterPos, pos);
angle = Sim.Math.getAngleBetween(blueCenterPos, pos, orientation);
leftEdgeDistance = null;
rightEdgeDistance = null;
leftEdgeAngle = null;
rightEdgeAngle = null;
edgeAngleDiff = null;
if (
globalPolygon.containsPoint(blueLeftPos.x, blueLeftPos.y)
&& globalPolygon.containsPoint(blueRightPos.x, blueRightPos.y)
) {
leftEdgeDistance = Sim.Math.getDistanceBetween(blueLeftPos, pos);
rightEdgeDistance = Sim.Math.getDistanceBetween(blueRightPos, pos);
leftEdgeAngle = Sim.Math.getAngleBetween(blueLeftPos, pos, orientation);
rightEdgeAngle = Sim.Math.getAngleBetween(blueRightPos, pos, orientation);
edgeAngleDiff = Math.abs(leftEdgeAngle - rightEdgeAngle);
//sim.dbg.box('blue', Sim.Math.round(distance1, 3) + ' ; ' + Sim.Math.round(distance2, 3) + ' / ' + Sim.Math.round(Sim.Math.radToDeg(angle1), 1) + ' ; ' + Sim.Math.round(Sim.Math.radToDeg(angle2), 1) + ' ; ' + Sim.Math.round(Sim.Math.radToDeg(blueGoalAngle), 1));
}
camera = Math.abs(angle) < Math.PI / 2 ? 'front' : 'rear';
/*realAngle = camera === 'front' ? angle : angle + Math.PI;
if (realAngle > Math.PI) {
realAngle -= Sim.Math.TWO_PI;
}*/
goals.push({
side: Sim.Game.Side.BLUE,
distance: distance,
angle: angle,
camera: camera,
leftEdgeDistance: leftEdgeDistance,
rightEdgeDistance: rightEdgeDistance,
leftEdgeAngle: leftEdgeAngle,
rightEdgeAngle: rightEdgeAngle,
edgeAngleDiff: edgeAngleDiff
});
//sim.dbg.box('Blue', blueDistance, 1);
}
return goals;
};
Sim.Vision.prototype.getMeasurements = function(polygon, x, y, orientation) {
var goals = this.getVisibleGoals(polygon, x, y, orientation),
goal,
noisyDistance,
noisyAngle,
measurements = {},
i;
for (i = 0; i < goals.length; i++) {
goal = goals[i];
noisyDistance = goal.distance + goal.distance * Sim.Util.randomGaussian(sim.config.vision.distanceDeviation);
noisyAngle = goal.angle + Sim.Util.randomGaussian(sim.config.vision.angleDeviation);
if (goal.side == Sim.Game.Side.YELLOW) {
measurements['yellow-goal-center'] = {
distance: noisyDistance,
angle: noisyAngle
};
//measurements['yellow-goal-left'] = goal.leftEdgeDistance;
//measurements['yellow-goal-right'] = goal.rightEdgeDistance;
} else if (goal.side == Sim.Game.Side.BLUE) {
measurements['blue-goal-center'] = {
distance: noisyDistance,
angle: noisyAngle
};
//measurements['blue-goal-left'] = goal.leftEdgeDistance;
//measurements['blue-goal-right'] = goal.rightEdgeDistance;
}
}
return measurements;
}; |
/**
* Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland.
*
* See the file license.txt for copying permission.
*/
define([
], function () {
'use strict';
var QUINK_ROOT = 'quink',
RES_DIR = QUINK_ROOT + '/resources',
PLUGIN_DIR = QUINK_ROOT + '/plugins',
PLUGIN_ADAPTER_DIR = QUINK_ROOT + '/pluginadapters',
DIR_INDEX_FILE_NAME = 'index.html',
root,
rootRegExp,
autoSaveUrl,
saveUrl,
urlParams = {};
function resource(name) {
return root + RES_DIR + '/' + name;
}
function plugin(name) {
return root + PLUGIN_DIR + '/' + name;
}
function pluginAdapter(name) {
return root + PLUGIN_ADAPTER_DIR + '/' + name;
}
function setRoot(value) {
root = value || './';
if (!/\/$/.test(root)) {
root += '/';
}
rootRegExp = new RegExp('^' + root);
}
/**
* Makes a value relative to the Quink root. To be of any use the value will be a url path.
* This allows Quink to be deployed anywhere and keeps quink relative paths working.
* Protect against adding the Quink root to the start of the same string more than once.
*/
function makeQuinkRelative(value) {
var result = value;
if (!rootRegExp.test(result)) {
if (/^\//.test(result)) {
result = result.substr(1);
}
result = root + result;
}
return result;
}
function getParam(name, def) {
var val = urlParams[name];
return val === undefined ? def : val;
}
/**
* Where auto save persists to.
*/
function getAutoSaveUrl() {
return autoSaveUrl;
}
/**
* Where a user initiated save persists to.
*/
function getSaveUrl() {
return saveUrl;
}
/**
* Assumes that the submit param, if present, is the last query parameter. This means that
* the submit param value doesn't need to be encoded (although it really should be).
*/
function getSubmitUrl() {
var url = location.href,
index = url.lastIndexOf('submit=');
return index >= 0 ? url.substring(index + 7) : undefined;
}
/**
* http://stackoverflow.com/a/2880929
* Multiple params with the same name will result in only the last value being used.
*/
function parseParams() {
var search = location.search.substr(1),
regex = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(/\+/g, " "));
},
match;
while ((match = regex.exec(search)) !== null) {
urlParams[decode(match[1])] = decode(match[2]);
}
}
function initParams(obj) {
_.extend(urlParams, obj);
}
/**
* Tests for a ul ending with a trailing '/'. This isn't really right as a directory url
* doesnt have to end with a trailing slash, but it won't be possible to know if it's
* a directory url unless it does and most servers will append the trailing slash onto
* directory urls to avoid potential security problems.
*/
function isDir(url) {
return url.search(/\/$/) >= 0;
}
/**
* Makes sure that the url refers to a file. If it's a directory then a file name is
* added to make it a file url. This is to stop auto save from silently doing nothing if
* the document url is a directory url. In that case auto save sucessfully saves back
* to the directory utl, but does not update the user's document.
* It's server rules that dictate what happens if a user navigates to a directory url
* so anything we do here will be wrong in some situations. Hopefully this will be right
* most of the time.
*/
function ensureUrlIsFile(srcUrl) {
var url = srcUrl;
if (isDir(url)) {
url += DIR_INDEX_FILE_NAME;
}
return url;
}
function isIos() {
return /iPhone|iPad|iPod/i.test(navigator.platform);
}
function isAndroidChrome() {
return /Android.*Chrome/.test(navigator.userAgent);
}
function init() {
var origin = location.href.split('?')[0];
setRoot(window.QUINK.root);
delete window.QUINK.root;
initParams(window.QUINK.params);
parseParams();
autoSaveUrl = ensureUrlIsFile(getParam('autosave', origin));
saveUrl = ensureUrlIsFile(origin);
}
return {
resource: resource,
plugin: plugin,
pluginAdapter: pluginAdapter,
setRoot: setRoot,
init: init,
getParam: getParam,
getAutoSaveUrl: getAutoSaveUrl,
getSaveUrl: getSaveUrl,
getSubmitUrl: getSubmitUrl,
makeQuinkRelative: makeQuinkRelative,
isIos: isIos,
isAndroidChrome: isAndroidChrome
};
});
|
/*
* aem-sling-contrib
* https://github.com/dherges/aem-sling-contrib
*
* Copyright (c) 2016 David Herges
* Licensed under the MIT license.
*/
define([
"../core",
"./var/rsingleTag",
"../manipulation" // buildFragment
], function( jQuery, rsingleTag ) {
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
return jQuery.parseHTML;
});
|
/*
Loads the correct configuration for the development and production builds
of the client and server, based on the environment variable NODE_ENV,
set in the webpack configuration file
*/
if (process.env.NODE_ENV === 'development') {
module.exports = require('./config.development');
} else {
module.exports = require('./config.production');
}
|
import { GET_GROUPS } from '../actions/types';
const initialState = [];
/**
* updates the groups property of the store
* @param {Object} state - current state
* @param {Object} action - action type and action payload
*
* @returns {state} - returns a new state.
*/
export default (state = initialState, action = {}) => {
switch (action.type) {
case GET_GROUPS:
return [
...action.groups
];
default:
return state;
}
};
|
var express = require('express');
var router = express.Router();
var passport = require('passport');
var fs = require('fs');
var utility = require('../../../index').Utility;
router.get('/', function(req, res, next) {
if(req.isAuthenticated()){
res.render('index', {
title: 'idp - management console',
user: req.user
});
}else{
res.redirect('/login');
}
});
router.get('/login',function(req,res,next){
if(req.isAuthenticated()){
res.redirect('/');
}else{
res.render('login', {
title: 'idp - Login',
messages: req.flash('info')
});
}
});
router.get('/login/external.esaml', function(req, res, next) {
var method = req.query.METHOD,
target = req.query.TARGET;
if(method && target){
res.render('login', {
title: 'idp - SSO External Login',
method: method,
target: target
});
} else {
res.redirect('/login');
}
});
router.get('/logout',function(req,res,next){
req.logout();
res.redirect('/login');
});
router.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if(req.body.method == 'post'){
return res.render('actions',JSON.parse(utility.base64Decode(req.body.target)));
} else if(req.body.method == 'get'){
return res.redirect(utility.base64Decode(req.body.target));
}
return res.redirect('/');
});
})(req, res, next);
});
module.exports = router;
|
const superagent = require('superagent');
const logger = require('../../winston');
module.exports = {
publishWebhook
};
function publishWebhook() {
return function(context) {
// Get Webhooks and publish the events
const resources = ['spaces', 'questions', 'answers'];
const events = ['create', 'patch', 'remove'];
const resource = context.path;
const event = context.method;
if (resources.indexOf(resource) !== -1 && events.indexOf(event) !== -1) {
matchWebhookEvents(context);
}
return context;
};
}
async function matchWebhookEvents(context) {
const resource = context.path;
const event = context.method;
const data = context.result;
try {
// const query = {
// $populate: {
// path: 'spaces',
// select: '_id'
// },
// $or: [{ resource: resource }, { resource: 'all' }]
// };
let match;
if (resource === 'spaces') {
match = context.result._id;
} else if (resource === 'questions') {
if (Array.isArray(data) && data.length > 0) {
match = data[0]._room;
} else {
match = data._room;
}
}
const query = {
spaceId: match,
$or: [{ resource: resource }, { resource: 'all' }]
};
const webhookQuery = await context.app.service('webhooks').find({ query });
for (const webhook of webhookQuery.data) {
try {
await superagent
.post(webhook.targetUrl)
.set('Accept', 'application/json')
.send({ event, resource, data });
} catch (error) {
logger.error('Could not post event to webhook url. ');
}
}
} catch (error) {
logger.error('Error in match webhook event');
}
}
|
require('dotenv').config()
const models = require('../models')
const User = models.User
const Message = models.Message
const crypto = require('crypto');
const BASE_URL = process.env.BASE_URL || 'http://localhost:3000/api/forgot_password'
const helper = require('sendgrid').mail
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
function makeRandomPassword()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
module.exports = {
sendRequest: (req, res) => {
User.findOne({
where: {
email: req.body.email
}
}).then((data) => {
if (data.id) {
from_email = new helper.Email("admin@brtr.com")
to_email = new helper.Email(`${req.body.email}`)
subject = "Forgot Password"
content = new helper.Content(
"text/html",
`
<div style="text-align:center; background-color:black; padding:50px">
<img src='http://i.imgur.com/5KBXgFb.png' alt='brtr'/><br/><br/>
<form action="${BASE_URL}/api/forgot_password/verify_request_password/${data.password}">
<input type="submit" value="Click here to reset your password" />
</form>
</div>
`
)
mail = new helper.Mail(from_email, subject, to_email, content)
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.API(request, function(error, response) {
res.status(200).json('email send')
})
}
}).catch((err) => {
res.status(500).json(err)
})
},
resetPassword: (req, res) => {
User.findOne({
where: {
password: req.params.password
}
}).then((data) => {
if (data.username) {
const newPass = makeRandomPassword()
const newPassHash = crypto.createHash('md5').update(newPass).digest("hex")
from_email = new helper.Email("admin@brtr.com")
to_email = new helper.Email(data.email)
subject = "Forgot Password"
content = new helper.Content(
"text/plain",
`your new password is ${newPass}`
)
mail = new helper.Mail(from_email, subject, to_email, content)
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.API(request, function(error, response) {
User.update({
password: newPassHash
}, {
where: {
email: data.email
}
}).then((data) => {
res.status(200).json('Redirecting.. Your new password will be ready in a few seconds..')
}).catch((err) => {
res.status(500).json(err)
})
})
}
})
}
}
|
import Ember from 'ember';
import layout from './template';
import Registerable from '../../mixins/registerable';
import KeyBindings from '../../mixins/key-bindings';
import ControlState from '../../mixins/control-state';
const { computed } = Ember;
const { oneWay } = computed;
export default Ember.Component.extend(ControlState, Registerable, KeyBindings, {
layout: layout,
tagName: 'deluge-item',
classNames: ['deluge-item'],
classNameBindings: ['isSelected'],
attributeBindings: [
// Applies ARIA Disabled
'disabled:aria-disabled',
// Applies disabled attribute to element or null.
'_disabledAttrValue:disabled'
],
ariaRole: 'option',
registerableType: 'item',
keyBindings: {
enter: 'activateItem',
space: 'activateItem',
},
isDisabled: true,
/**
* Selected items of parent component, usually a menu or a list.
*
* @type {Array}
*/
selectedItems: oneWay('menu.selectedItems'),
isSelected: computed('selectedItems.[]', 'menu', {
get() {
const selected = Ember.A(this.get('selectedItems'));
return selected.contains(this);
}
}),
focusIn(event) {
if (this.get('disabled')) { return; }
this.set('hasFocus', true);
if (this.get('menu')) {
event.stopPropagation();
}
let menu;
if(menu = this.get('menu')) {
menu.send('itemFocussed', this);
}
},
focusOut() {
this.set('hasFocus', false);
},
click() {
this.send('activateItem');
},
activate() {
if (this.get('disabled')) { return; }
this.sendAction('action', this);
},
actions: {
activateItem() {
this.activate();
}
}
});
|
'use strict';
/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
, expect = chai.expect
, Utils = require(__dirname + '/../../lib/utils')
, Support = require(__dirname + '/support');
describe(Support.getTestDialectTeaser('Utils'), function() {
describe('formatReferences', function () {
([
[{referencesKey: 1}, {references: {model: undefined, key: 1}, referencesKey: undefined}],
[{references: 'a'}, {references: {model: 'a', key: undefined}, referencesKey: undefined}],
[{references: 'a', referencesKey: 1}, {references: {model: 'a', key: 1}, referencesKey: undefined}],
[{references: {model: 1}}, {references: {model: 1}}]
]).forEach(function (test) {
var input = test[0];
var output = test[1];
it('converts ' + JSON.stringify(input) + ' to ' + JSON.stringify(output), function () {
expect(Utils.formatReferences(input)).to.deep.equal(output);
});
});
});
});
|
export default function routing(RouterHelper) {
const states = [{
state: 'modules',
config: {
abstract: true,
parent: 'app',
views: {
'sidenav': {
component: 'sidenavLayoutAppComponent'
},
'': {
layout:'<ui-view></ui-view>'
}
},
resolve: {
auth: (FirebaseService, $state, $q) => {
let deferred = $q.defer();
let user = FirebaseService.auth.currentUser;
// deferred.resolve();
if (user) {
deferred.resolve()
} else {
$state.go('login')
}
return deferred.promise;
}
}
},
}];
RouterHelper.configureStates(states);
}
|
'use strict';
// Load modules
const Hoek = require('hoek');
const Boom = require('boom');
// Declare internals
const internals = {};
exports = module.exports = internals.Store = function (document) {
this.load(document || {});
};
internals.Store.prototype.load = function (document) {
const err = internals.Store.validate(document);
Hoek.assert(!err, err);
this._tree = Hoek.clone(document);
};
// Get a filtered value
internals.Store.prototype.get = function (key, criteria, applied) {
const node = this._get(key, criteria, applied);
return internals.walk(node, criteria, applied);
};
internals.Store.prototype._get = function (key, criteria, applied) {
const self = this;
criteria = criteria || {};
const path = [];
if (key !== '/') {
const invalid = key.replace(/\/(\w+)/g, ($0, $1) => {
path.push($1);
return '';
});
if (invalid) {
return undefined;
}
}
let node = internals.filter(self._tree, criteria, applied);
for (let i = 0; i < path.length && node; ++i) {
if (typeof node !== 'object') {
node = undefined;
break;
}
node = internals.filter(node[path[i]], criteria, applied);
}
return node;
};
// Get a meta for node
internals.Store.prototype.meta = function (key, criteria) {
const node = this._get(key, criteria);
return (typeof node === 'object' ? node.$meta : undefined);
};
internals.defaults = function (node, base) {
base = base || {};
if (typeof node === 'object' && (Array.isArray(base) === Array.isArray(node))) {
return Hoek.merge(Hoek.clone(base), Hoek.clone(node));
}
return node;
};
// Return node or value if no filter, otherwise apply filters until node or value
internals.filter = function (node, criteria, applied) {
if (!node ||
typeof node !== 'object' ||
(!node.$filter && !node.$value)) {
return node;
}
if (node.$value) {
return internals.defaults(internals.filter(node.$value, criteria, applied), node.$base);
}
// Filter
const filter = node.$filter;
const criterion = Hoek.reach(criteria, filter);
if (criterion !== undefined) {
if (node.$range) {
for (let i = 0; i < node.$range.length; ++i) {
if (criterion <= node.$range[i].limit) {
exports._logApplied(applied, filter, node, node.$range[i]);
return internals.filter(node.$range[i].value, criteria, applied);
}
}
}
else if (node[criterion] !== undefined) {
exports._logApplied(applied, filter, node, criterion);
return internals.defaults(internals.filter(node[criterion], criteria, applied), node.$base);
}
// Falls-through for $default
}
if (Object.prototype.hasOwnProperty.call(node, '$default')) {
exports._logApplied(applied, filter, node, '$default');
return internals.defaults(internals.filter(node.$default, criteria, applied), node.$base);
}
exports._logApplied(applied, filter, node);
return undefined;
};
// Exported to make testing easier
exports._logApplied = function (applied, filter, node, criterion) {
if (!applied) {
return;
}
const record = {
filter: filter
};
if (criterion) {
if (typeof criterion === 'object') {
if (criterion.id) {
record.valueId = criterion.id;
}
else {
record.valueId = (typeof criterion.value === 'object' ? '[object]' : criterion.value.toString());
}
}
else {
record.valueId = criterion.toString();
}
}
if (node && node.$id) {
record.filterId = node.$id;
}
applied.push(record);
};
// Applies criteria on an entire tree
internals.walk = function (node, criteria, applied) {
if (!node ||
typeof node !== 'object') {
return node;
}
if (Object.prototype.hasOwnProperty.call(node, '$value')) {
return internals.walk(node.$value, criteria, applied);
}
const parent = (node instanceof Array ? [] : {});
const keys = Object.keys(node);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key === '$meta' || key === '$id') {
continue;
}
const child = internals.filter(node[key], criteria, applied);
const value = internals.walk(child, criteria, applied);
if (value !== undefined) {
parent[key] = value;
}
}
return parent;
};
// Validate tree structure
internals.Store.validate = function (node, path) {
path = path || '';
const error = function (reason) {
const e = Boom.badRequest(reason);
e.path = path || '/';
return e;
};
// Valid value
if (node === null ||
node === undefined ||
typeof node !== 'object') {
return null;
}
// Invalid object
if (node instanceof Error ||
node instanceof Date ||
node instanceof RegExp) {
return error('Invalid node object type');
}
// Invalid keys
const found = {};
const keys = Object.keys(node);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key[0] === '$') {
if (key === '$filter') {
found.filter = true;
const filter = node[key];
if (!filter) {
return error('Invalid empty filter value');
}
if (typeof filter !== 'string') {
return error('Filter value must be a string');
}
if (!filter.match(/^\w+(?:\.\w+)*$/)) {
return error('Invalid filter value ' + node[key]);
}
}
else if (key === '$range') {
found.range = true;
if (node.$range instanceof Array === false) {
return error('Range value must be an array');
}
if (!node.$range.length) {
return error('Range must include at least one value');
}
let lastLimit = undefined;
for (let j = 0; j < node.$range.length; ++j) {
const range = node.$range[j];
if (typeof range !== 'object') {
return error('Invalid range entry type');
}
if (!Object.prototype.hasOwnProperty.call(range, 'limit')) {
return error('Range entry missing limit');
}
if (typeof range.limit !== 'number') {
return error('Range limit must be a number');
}
if (lastLimit !== undefined && range.limit <= lastLimit) {
return error('Range entries not sorted in ascending order - ' + range.limit + ' cannot come after ' + lastLimit);
}
lastLimit = range.limit;
if (!Object.prototype.hasOwnProperty.call(range, 'value')) {
return error('Range entry missing value');
}
const err = internals.Store.validate(range.value, path + '/$range[' + range.limit + ']');
if (err) {
return err;
}
}
}
else if (key === '$default') {
found.default = true;
const err2 = internals.Store.validate(node.$default, path + '/$default');
if (err2) {
return err2;
}
}
else if (key === '$base') {
found.base = true;
}
else if (key === '$meta') {
found.meta = true;
}
else if (key === '$id') {
if (!node.$id ||
typeof node.$id !== 'string') {
return error('Id value must be a non-empty string');
}
found.id = true;
}
else if (key === '$value') {
found.value = true;
const err3 = internals.Store.validate(node.$value, path + '/$value');
if (err3) {
return err3;
}
}
else {
return error('Unknown $ directive ' + key);
}
}
else {
found.key = true;
const value = node[key];
const err4 = internals.Store.validate(value, path + '/' + key);
if (err4) {
return err4;
}
}
}
// Invalid directive combination
if (found.value && (found.key || found.range || found.default || found.filter)) {
return error('Value directive can only be used with meta or nothing');
}
if (found.default && !found.filter) {
return error('Default value without a filter');
}
if (found.filter && !found.default && !found.key && !found.range) {
return error('Filter without any values');
}
if (found.filter && found.default && !found.key && !found.range) {
return error('Filter with only a default');
}
if (found.range && !found.filter) {
return error('Range without a filter');
}
if (found.range && found.key) {
return error('Range with non-ranged values');
}
// Valid node
return null;
};
|
/*
* shell.h.js
* Contains all the common vars/defintion requried across the shell app.
*
*/
var shell = new Object();
/* Define a new module/namespace for each object to avoid conflicts **/
shell.module = function (ns){
var parts = ns.split(".");
var root = window;
for(var i=0; i<parts.length; i++){
if(typeof root[parts[i]] == "undefined")
root[parts[i]] = new Object();
root = root[parts[i]];
}
};
|
/**
* @file: 1.3
* @author: gejiawen
* @date: 15/10/22 12:42
* @description: 1.3
*/
var async = require('async');
var t = require('../../t');
var log = t.log;
/**
* 如果想对同一个集合中的所有元素都执行同一个异步操作,可以利用each函数。
*
* async提供了三种方式:
* 1. 集合中所有元素并行执行
* 2. 一个一个顺序执行
* 3. 分批执行,同一批内并行,批与批之间按顺序
*
* 如果中途出错,则错误将上传给最终的callback处理。其它已经启动的任务继续执行,未启动的忽略。
*/
// each(arr, iterator(item, callback), callback(err))
var arr = [{
name: 'Jack',
delay: 200
}, {
name: 'Mike',
delay: 100
}, {
name: 'Freewind',
delay: 300
}];
/**
* 分批执行,第二个参数是每一批的个数。每一批内并行执行,但批与批之间按顺序执行。
*/
async.eachLimit(arr, 2, function (item, callback) {
log('1.3 enter: ' + item.name);
setTimeout(function () {
log('1.3 handle: ' + item.name);
callback(null, item.name);
}, item.delay);
}, function (err) {
log('1.3 err: ' + err);
});
// 输出如下
//04.091> 1.3 enter: Jack
//04.101> 1.3 enter: Mike
//04.206> 1.3 handle: Mike
//04.207> 1.3 enter: Freewind
//04.305> 1.3 handle: Jack
//04.509> 1.3 handle: Freewind
//04.509> 1.3 err: null
|
(function() {
'use strict';
document.addEventListener('DOMContentLoaded', function() {
// Set key and token on Trello object
Trello.setKey(localStorage.trellifyApiKey);
Trello.authorize({
interactive: false,
success: authorizedState,
});
// Trellify the tabs
document.getElementById('btn-token').addEventListener('click', function() {
if (localStorage.getItem('trello_token') !== null) {
Trello.deauthorize();
authorizedState();
} else {
Trello.authorize({
type: 'redirect',
success: authorizedState,
interactive: true,
name: 'TrellifyTabs',
expiration: 'never',
scope: { write: true, read: true },
});
}
});
document.getElementById('btn-authOptions').addEventListener('click', function() {
var boardId = $('#board-names :selected').val();
var listName = $('#inp-listName').val();
var listNames = new Promise(function(toResolve, orReject) {
Trello.get('boards/' + boardId + '/lists', toResolve);
}).then(function(lists) {
for (var i = 0; i < lists.length; i++) {
if (lists[i].name === listName) {
return Promise.resolve(lists[i].id);
}
}
return new Promise(function(toResolve, orReject) {
Trello.post('boards/' + boardId + '/lists', {name: listName}, toResolve);
});
}).then(function(list) {
localStorage.trellifyListId = (typeof list === 'string') ? list : list.id;
localStorage.trellifyListName = listName;
localStorage.trellifyBoardId = boardId;
localStorage.trellifyTabClose = $('#inp-closeTab').is(':checked');
localStorage.trellifyDisableTrellify = $('#inp-disableTrellify').is(':checked')
localStorage.trellifyDisableBookmarking = $('#inp-disableBookmarking').is(':checked');
localStorage.trellifyDisableLabel = $('#inp-disableLabel').is(':checked');
$('.updateMsg').css("display","block");
setTimeout(function() {
$('.updateMsg').css("display","none");
}, 2000);
});
});
function populateBoardNames() {
var boardN = new Promise(function(toResolve, orReject) {
Trello.get('members/my/boards', toResolve);
}).then(function(boards) {
for (var i = 0; i < boards.length; i++) {
if (boards[i].closed) continue;
var name = boards[i].name.length > 20 ? boards[i].name.substr(0, 20) + '...' : boards[i].name;
var selected = "";
if(boards[i].id == localStorage.trellifyBoardId){
selected = "selected";
}
$('#board-names').append('<option ' + selected + ' value="' + boards[i].id + '">' + name + '</option>');
}
$('#inp-listName').val(localStorage.trellifyListName);
});
}
function authorizedState() {
if (localStorage.getItem('trello_token') !== null) {
localStorage.trellifyToken = localStorage.getItem('trello_token');
$('#btn-token').text('Deauthorize Trello');
$('#btn-token').removeClass('btn-success').addClass('btn-warning');
$('#authorizedOnly').removeClass('hidden');
populateBoardNames();
if(localStorage.trellifyTabClose == "true"){
$('#inp-closeTab').prop('checked', true);
}
if(localStorage.trellifyDisableTrellify == "true"){
$('#inp-disableTrellify').prop('checked', true);
}
if(localStorage.trellifyDisableBookmarking == "true"){
$('#inp-disableBookmarking').prop('checked', true);
}
if(localStorage.trellifyDisableLabel == "true"){
$('#inp-disableLabel').prop('checked', true);
}
} else {
localStorage.removeItem('trellifyToken');
$('#btn-token').text('Authorize Trello');
$('#btn-token').removeClass('btn-warning').addClass('btn-success');
$('#authorizedOnly').addClass('hidden');
}
}
});
})();
|
'use strict';
var React = require('react');
var Info = require('./info.js');
var Button = require('./button.js');
var messages = require('../messages.js').aboutMessages;
module.exports = React.createClass({
render: function() {
return(
<Info messages={messages}>
<Button url={'https://github.com/mrmamen/traktNRK'} text={'Read more'} />
</Info>
);
}
});
|
var searchData=
[
['tools_2ehpp',['tools.hpp',['../tools_8hpp.html',1,'']]],
['typedefs_2ehpp',['typedefs.hpp',['../typedefs_8hpp.html',1,'']]]
];
|
var express = require('express');
var router = express.Router();
var Move = require('../models/move');
var utilities = require('../services/utilities');
var validateMovement = function(newMovement){
return Move.findOne({
move: newMovement.kills.toLowerCase(),
kills: newMovement.move.toLowerCase()
}).then(function (reverse) {
if(reverse){
throw Error(['The rule is not allowed because', newMovement.kills, 'beats', newMovement.move].join(' '));
}
});
};
router.get('/', function (req, res) {
Move.find({}).exec().then(function (moves) {
res.status(200).send(moves);
}).catch(function (err) {
res.status(500).send(err);
});
});
router.post('/', function (req, res) {
var newMovement = req.body;
if (newMovement && newMovement.move && newMovement.kills) {
validateMovement(newMovement).then(function () {
return Move.create(newMovement);
}).then(function () {
res.sendStatus(200);
}).catch(function (err) {
var errorMsg = utilities.getErrorMsg(err);
res.status(500).send(errorMsg);
});
} else {
res.status(500).send("The data is required");
}
});
router.put('/', function (req, res) {
var updateMovement = req.body;
if (updateMovement && updateMovement.id && updateMovement.move && updateMovement.kills) {
validateMovement(updateMovement).then(function () {
return Move.findByIdAndUpdate(updateMovement.id, updateMovement, { runValidators: true }).exec();
}).then(function () {
res.sendStatus(200);
}).catch(function (err) {
var errorMsg = utilities.getErrorMsg(err);
res.status(500).send(errorMsg);
});
} else {
res.status(500).send("The data is required");
}
});
router.delete('/', function (req, res) {
var moveId = req.query.moveId;
if (moveId) {
Move.findByIdAndRemove(moveId).exec().then(function () {
res.sendStatus(200);
}).catch(function (err) {
res.status(500).send(err);
});
} else {
res.status(500).send("The data is required");
}
});
router.get('/compareMoves', function (req, res) {
var moveFirstPlayer = req.query.moveFirstPlayer;
var moveSecondPlayer = req.query.moveSecondPlayer;
if (!moveFirstPlayer) {
res.status(500).send("The first player's movement is required");
}
else if (!moveSecondPlayer) {
res.status(500).send("The second player's movement is required");
}
else{
Move.findOne({
$or: [
{ move: moveFirstPlayer, kills: moveSecondPlayer },
{ move: moveSecondPlayer, kills: moveFirstPlayer },
]
}).then(function(winningMoveRule){
res.status(200).send(winningMoveRule ? winningMoveRule.move : '');
}).catch(function (err) {
res.status(500).send(err);
});
}
});
module.exports = router; |
version https://git-lfs.github.com/spec/v1
oid sha256:f7094c82ffcdee90ff937f8d2db5bf965146f57866f44f0af99604c7715032c8
size 22292
|
var
sys = require("sys"),
spawn = require("child_process").spawn,
events = require("events");
/**
* A pool of child processes.
* Emits `spawn` when a child is spawned.
*
* @param {String} toRun The program to spawn and run.
* Defaults to `process.argv[0]`.
* @param {Array} args Arguments to `toRun`. Defaults to `[]`.
* @param {Object} options Options for the configuring the pool.
* `minProcs` and `maxProcs` (default: 1, 4) represent the desired
* size range of the pool.
*/
function ChildPool(toRun, args, options) {
events.EventEmitter.call(this);
this.pool = [];
this.toRun = toRun || process.argv[0];
this.args = args || [];
var opts = options || {};
this.minProcs = opts.minProcs || 1;
this.maxProcs = opts.maxProcs || 4;
if (this.minProcs <= 0 ||
this.maxProcs <= 0 ||
this.minProcs > this.maxProcs)
throw new Error("invalid minProcs/maxProcs value(s)");
while (this.pool.length < this.minProcs)
this._spawnOne();
}
sys.inherits(ChildPool, events.EventEmitter);
exports.ChildPool = ChildPool;
ChildPool.prototype.size = function () {
return this.pool.length;
};
ChildPool.prototype._spawnOne = function () {
var childProc = spawn(this.toRun, this.args);
this.pool.push(childProc);
var self = this;
childProc.addListener("exit", function (code) {
self.pool.splice(self.indexOf(childProc.pid), 1);
});
this.emit("spawn", childProc);
};
ChildPool.prototype.indexOf = function (pid) {
for (var i=0, n=this.pool.length; i<n; ++i) {
if (this.pool[i].pid == pid)
return i;
}
return -1;
};
ChildPool.prototype.spawnAnotherIfAllowed = function () {
if (this.pool.length < this.maxProcs)
this._spawnOne();
};
ChildPool.prototype.forEach = function (fn) {
this.pool.forEach(fn);
};
|
// console.log('Loading FileField...')
Spontaneous.Field.File = (function($, S) {
var dom = S.Dom;
var FileField = new JS.Class(Spontaneous.Field.String, {
selected_files: false,
preview: function() {
Spontaneous.UploadManager.register(this);
var self = this
, value = this.get('value')
, filename = this.filename(value);
var wrap = dom.div('.file-field');
var dropper = dom.div('.file-drop');
var stopEvent = function(event) {
event.stopPropagation();
event.preventDefault();
};
var drop = function(event) {
stopEvent(event);
dropper.removeClass('drop-active');
var files = event.dataTransfer.files;
if (files && files.length > 0) {
this.selected_files = files;
S.Ajax.test_field_versions(this.content, [this], this.upload_values.bind(this), this.upload_conflict.bind(this));
}
return false;
}.bind(this);
var drag_enter = function(event) {
stopEvent(event);
$(this).addClass('drop-active');
return false;
}.bind(dropper);
var drag_over = function(event) {
stopEvent(event);
return false;
}.bind(dropper);
var drag_leave = function(event) {
stopEvent(event);
$(this).removeClass('drop-active');
return false;
}.bind(dropper);
dropper.get(0).addEventListener('drop', drop, true);
dropper.bind('dragenter', drag_enter).bind('dragover', drag_over).bind('dragleave', drag_leave);
var filename_info = dom.div('.filename');
var filesize_info = dom.div('.filesize');
var set_info = function(href, filename, filesize) {
filename_info.text(filename);
if (filesize) {
filesize_info.text(parseFloat(filesize, 10).to_filesize());
}
};
if (value) {
set_info(value.html, this.filename(value), value.filesize);
}
dropper.append(this.progress_bar().parent());
wrap.append(dropper, filename_info, filesize_info);
this.drop_target = dropper;
this.value_wrap = wrap;
return wrap;
},
upload_values: function() {
var file = this.selected_files[0];
S.UploadManager.replace(this, file);
},
upload_conflict: function(conflict_data) {
var dialogue = new S.ConflictedFieldDialogue(this, conflict_data);
dialogue.open();
},
unload: function() {
this.callSuper();
this.input = null;
this._progress_bar = null;
Spontaneous.UploadManager.unregister(this);
},
upload_complete: function(values) {
this.set('value', values.processed_value);
this.set_version(values.version);
this.selected_files = null;
this.disable_progress();
},
progress_bar: function() {
if (!this._progress_bar) {
var progress_outer = dom.div('.drop-upload-outer').hide();
var progress_inner = dom.div('.drop-upload-inner').css('width', 0);
progress_outer.append(progress_inner);
this._progress_bar = progress_inner;
}
return this._progress_bar;
},
disable_progress: function() {
this.progress_bar().parent().hide();
this.drop_target.add(this.value_wrap).removeClass('uploading')
},
upload_progress: function(position, total) {
if (!this.drop_target.hasClass('uploading')) {
this.drop_target.add(this.value_wrap).addClass('uploading');
}
this.progress_bar().parent().show();
this.progress_bar().css('width', ((position/total)*100) + '%');
},
is_file: function() {
return true;
},
edit: function() {
var self = this;
var wrap = dom.div(".file-field", {'style':'position:relative;'});
var value = this.value();
var input = this.input();
var filename_info = dom.div('.filename');
var filesize_info = dom.div('.filesize');
var choose_files = dom.a('.choose').text("Choose file...");
var set_info = function(filename, filesize) {
filename_info.text(filename);
if (filesize) {
filesize_info.text(parseFloat(filesize, 10).to_filesize());
}
};
var files_selected = function(files) {
if (files.length > 0) {
var file = files[0], url = window.URL.createObjectURL(file);
this.selected_files = files;
this._edited_value = url;
window.URL.revokeObjectURL(url);
set_info(File.filename(file), file.fileSize)
}
}.bind(this);
var onchange = function() {
var files = input[0].files;
files_selected(files);
}.bind(this);
var onclick = function() {
self.focus();
input.trigger('click');
return false;
};
input.change(onchange);
var dropper = dom.div('.file-drop');
dropper.add(choose_files).click(onclick);
// dropper.append(filename_info, filesize_info)
wrap.append(dropper);
var stopEvent = function(event) {
event.stopPropagation();
event.preventDefault();
};
var drop = function(event) {
stopEvent(event);
dropper.removeClass('drop-active');
var files = event.dataTransfer.files;
files_selected(files);
return false;
}.bind(this);
var drag_enter = function(event) {
stopEvent(event);
$(this).addClass('drop-active');
return false;
}.bind(dropper);
var drag_over = function(event) {
stopEvent(event);
return false;
}.bind(dropper);
var drag_leave = function(event) {
stopEvent(event);
$(this).removeClass('drop-active');
return false;
}.bind(dropper);
dropper.get(0).addEventListener('drop', drop, true);
dropper.bind('dragenter', drag_enter).bind('dragover', drag_over).bind('dragleave', drag_leave);
if (value) {
var s = value.html.split('/'), filename = s[s.length - 1];
set_info(filename, value.filesize);
}
wrap.append(input, choose_files, filename_info, filesize_info);
return wrap;
},
filename: function(value) {
var s = value.html.split('/'), filename = s[s.length - 1];
return filename;
},
accept_mimetype: "*/*",
generate_input: function() {
return dom.input({'type':'file', 'name':this.form_name(), 'accept':this.accept_mimetype});
},
accepts_focus: false,
// called by edit dialogue in order to begin the async upload of files
save: function() {
if (!this.selected_files) { return; }
var files = this.selected_files;
if (files && files.length > 0) {
this.drop_target.addClass('uploading');
this.progress_bar().parent().show();
var file_data = new FormData();
var file = files[0];
S.UploadManager.replace(this, file);
}
this.selected_files = false;
},
is_modified: function() {
var files = this.selected_files;
return (files && files.length > 0);
},
original_value: function() {
this.processed_value();
},
set_edited_value: function(value) {
console.log('set_edited_value', value, this.edited_value(), this.original_value())
if (value === this.edited_value()) {
// do nothing
} else {
this.selected_files = null;
this.set('value', value);
}
}
});
return FileField;
})(jQuery, Spontaneous);
|
'use strict';
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
// Not using the boilerplate 'home' state. Just redirect to the newgame state as the default starting index.
$urlRouterProvider.when('/', '/newgame');
// Redirect to 404 when route not found
$urlRouterProvider.otherwise('not-found');
// Home state routing
$stateProvider
.state('home', {
url: '/',
templateUrl: 'modules/core/views/home.client.view.html',
redirectTo: 'game'
})
.state('not-found', {
url: '/not-found',
templateUrl: 'modules/core/views/404.client.view.html'
});
}
]);
|
/** @babel */
import { CompositeDisposable } from 'atom'
import ImportListView from './import-list-view'
import call from './proc'
export default {
config: {
pythonPaths: {
type: 'string',
default: '',
title: 'Python Executable Paths',
description:
'\
Paths to python executable, must be semicolon separated. \
First takes precedence. \
$PROJECT_NAME is the current project name \
$PROJECT is the current project full path',
},
useRelativeImports: {
type: 'boolean',
default: true,
title: 'Prefer relative imports if possible.',
},
reindexOnSave: {
type: 'boolean',
default: false,
title: 'Run a reindexation of imports on file save',
},
debug: {
type: 'boolean',
default: false,
title: 'Enable console debug output',
},
},
debug(...args) {
atom.config.get('python-import-magic.debug') && console.debug(...args)
},
activate() {
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(
atom.commands.add('atom-text-editor[data-grammar~=python]', {
'python-import-magic:reindex': () => this.reindex(),
'python-import-magic:import-word': () =>
atom.workspace.getActiveTextEditor() &&
this.importWord(atom.workspace.getActiveTextEditor()),
'python-import-magic:remove-unused-imports': () =>
atom.workspace.getActiveTextEditor() &&
this.cleanImports(atom.workspace.getActiveTextEditor()),
'python-import-magic:update-imports': () =>
atom.workspace.getActiveTextEditor() &&
this.updateImports(atom.workspace.getActiveTextEditor()),
})
)
this.debug('Debug is on')
this.subscriptions.add(
atom.workspace.observeTextEditors(async editor => {
if (!editor.getFileName() || !editor.getFileName().endsWith('.py')) {
return
}
if (!this.inited) {
this.inited = true
await call({ cmd: 'init' }, editor)
}
this.subscriptions.add(
editor.onDidSave(async () => {
if (
this.reindexing &&
!atom.config.get('python-import-magic.reindexOnSave')
) {
return
}
this.reindexing = true
await call({ cmd: 'reindex' }, editor, true)
this.reindexing = false
})
)
this.inited = false
this.reindexing = false
})
)
this.importListView = new ImportListView()
},
deactivate() {
this.importListView.destroy()
this.subscriptions.dispose()
},
async reindex() {
try {
await call({ cmd: 'reindex' }, atom.workspace.getActiveTextEditor())
} catch (error) {
console.error('Python Import Magic error:', error)
}
},
async updateImports(editor) {
const { unresolved } = await this.cleanImports(editor)
for (let i = 0; i < unresolved.length; i++) {
if (!await this.import(editor, unresolved[i])) {
break
}
}
},
getCurrentWord(editor) {
editor.selectWordsContainingCursors()
const wordSelection = editor.getLastSelection()
if (!wordSelection.getBufferRange().isSingleLine()) {
this.debug(wordSelection, 'is not single line')
return
}
const word = wordSelection.getText()
if (
new RegExp(
`[ \t${atom.workspace
.getActiveTextEditor()
.getNonWordCharacters()
.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')}]`
).test(word)
) {
this.debug(word, 'contains non word characters')
return
}
return word
},
async cleanImports(editor) {
try {
const { file, unresolved } = await call(
{
cmd: 'clean_imports',
source: editor.getBuffer().getText(),
},
editor
)
editor.getBuffer().setTextViaDiff(file)
return { unresolved }
} catch (error) {
console.error('Python Import Magic error:', error)
return
}
},
async importWord(editor) {
const prefix = this.getCurrentWord(editor)
if (!prefix) {
return
}
this.import(editor, prefix)
},
async import(editor, prefix) {
let imports
try {
const out = await call(
{
cmd: 'list_possible_imports',
prefix,
source: editor.getBuffer().getText(),
path: editor.getBuffer().getPath(),
relative: atom.config.get('python-import-magic.useRelativeImports'),
},
editor
)
imports = out.imports
} catch (error) {
console.error('Python Import Magic error:', error)
return false
}
if (!imports || !imports.length) {
atom.notifications.addWarning(
`Python Import Magic: No import found for \`${prefix}\``
)
return false
}
let item
if (imports.length === 1) {
item = imports[0]
} else {
try {
item = await this.importListView.pick(imports)
} catch (e) {
return false
}
}
try {
const { file } = await call(
{
cmd: 'add_import',
source: editor.getBuffer().getText(),
new_import: item,
},
editor
)
editor.getBuffer().setTextViaDiff(file)
} catch (error) {
console.error('Python Import Magic error:', error)
}
if (imports.length === 1) {
atom.notifications.addSuccess(`Python Import Magic: added \`${item}\``)
}
return true
},
}
|
/*
jQuery Coda-Slider v2.0 - http://www.ndoherty.biz/coda-slider
Copyright (c) 2009 Niall Doherty
This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
*/
$(function(){
// Remove the coda-slider-no-js class from the body
$("body").removeClass("coda-slider-no-js");
// Preloader
$(".coda-slider").children('.panel').hide().end().prepend('<p class="loading">Loading...<br /><img src="images/ajax-loader.gif" alt="loading..." /></p>');
});
var sliderCount = 1;
$.fn.codaSlider = function(settings) {
settings = $.extend({
autoHeight: true,
autoHeightEaseDuration: 1000,
autoHeightEaseFunction: "easeInOutExpo",
autoSlide: false,
autoSlideInterval: 7000,
autoSlideStopWhenClicked: true,
crossLinking: true,
dynamicArrows: false,
dynamicArrowLeftText: "« left",
dynamicArrowRightText: "right »",
dynamicTabs: false,
dynamicTabsAlign: "left",
dynamicTabsPosition: "top",
externalTriggerSelector: "a.xtrig",
firstPanelToLoad: 1,
panelTitleSelector: "h2.title",
slideEaseDuration: 500,
slideEaseFunction: "easeInOutExpo"
}, settings);
return this.each(function(){
// Uncomment the line below to test your preloader
// alert("Testing preloader");
var slider = $(this);
// If we need arrows
if (settings.dynamicArrows) {
slider.parent().addClass("arrows");
slider.before('<div class="coda-nav-left" id="coda-nav-left-' + sliderCount + '"><a href="#">' + settings.dynamicArrowLeftText + '</a></div>');
slider.after('<div class="coda-nav-right" id="coda-nav-right-' + sliderCount + '"><a href="#">' + settings.dynamicArrowRightText + '</a></div>');
};
var panelWidth = slider.find(".panel").width();
var panelCount = slider.find(".panel").size();
var panelContainerWidth = panelWidth*panelCount;
var navClicks = 0; // Used if autoSlideStopWhenClicked = true
// Surround the collection of panel divs with a container div (wide enough for all panels to be lined up end-to-end)
$('.panel', slider).wrapAll('<div class="panel-container"></div>');
// Specify the width of the container div (wide enough for all panels to be lined up end-to-end)
$(".panel-container", slider).css({ width: panelContainerWidth });
// Specify the current panel.
// If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
var currentPanel = parseInt(location.hash.slice(1));
var offset = - (panelWidth*(currentPanel - 1));
$('.panel-container', slider).css({ marginLeft: offset });
// If that's not the case, check to see if we're supposed to load a panel other than Panel 1 initially...
} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
var currentPanel = settings.firstPanelToLoad;
var offset = - (panelWidth*(currentPanel - 1));
$('.panel-container', slider).css({ marginLeft: offset });
// Otherwise, we'll just set the current panel to 1...
} else {
var currentPanel = 1;
};
// Left arrow click
$("#coda-nav-left-" + sliderCount + " a").click(function(){
navClicks++;
if (currentPanel == 1) {
offset = - (panelWidth*(panelCount - 1));
alterPanelHeight(panelCount - 1);
currentPanel = panelCount;
slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('li:last a').addClass('current');
} else {
currentPanel -= 1;
alterPanelHeight(currentPanel - 1);
offset = - (panelWidth*(currentPanel - 1));
slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().prev().find('a').addClass('current');
};
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
return false;
});
// Right arrow click
$('#coda-nav-right-' + sliderCount + ' a').click(function(){
navClicks++;
if (currentPanel == panelCount) {
offset = 0;
currentPanel = 1;
alterPanelHeight(0);
slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('a:eq(0)').addClass('current');
} else {
offset = - (panelWidth*currentPanel);
alterPanelHeight(currentPanel);
currentPanel += 1;
slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().next().find('a').addClass('current');
};
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
return false;
});
// If we need a dynamic menu
if (settings.dynamicTabs) {
var dynamicTabs = '<div class="coda-nav" id="coda-nav-' + sliderCount + '"><ul></ul></div>';
switch (settings.dynamicTabsPosition) {
case "bottom":
slider.parent().append(dynamicTabs);
break;
default:
slider.parent().prepend(dynamicTabs);
break;
};
ul = $('#coda-nav-' + sliderCount + ' ul');
// Create the nav items
$('.panel', slider).each(function(n) {
ul.append('<li class="tab' + (n+1) + '"><a href="#' + (n+1) + '">' + $(this).find(settings.panelTitleSelector).text() + '</a></li>');
});
navContainerWidth = slider.width() + slider.siblings('.coda-nav-left').width() + slider.siblings('.coda-nav-right').width();
ul.parent().css({ width: navContainerWidth });
switch (settings.dynamicTabsAlign) {
case "center":
ul.css({ width: ($("li", ul).width() + 2) * panelCount });
break;
case "right":
ul.css({ float: 'right' });
break;
};
};
// If we need a tabbed nav
$('#coda-nav-' + sliderCount + ' a').each(function(z) {
// What happens when a nav link is clicked
$(this).bind("click", function() {
navClicks++;
$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
offset = - (panelWidth*z);
alterPanelHeight(z);
currentPanel = z + 1;
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
});
});
// External triggers (anywhere on the page)
$(settings.externalTriggerSelector).each(function() {
// Make sure this only affects the targeted slider
if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
$(this).bind("click", function() {
navClicks++;
targetPanel = parseInt($(this).attr("href").slice(1));
offset = - (panelWidth*(targetPanel - 1));
alterPanelHeight(targetPanel - 1);
currentPanel = targetPanel;
// Switch the current tab:
slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') a').addClass('current');
// Slide
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
});
};
});
// Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).
if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
$("#coda-nav-" + sliderCount + " a:eq(" + (location.hash.slice(1) - 1) + ")").addClass("current");
// If there's no cross-linking, check to see if we're supposed to load a panel other than Panel 1 initially...
} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
$("#coda-nav-" + sliderCount + " a:eq(" + (settings.firstPanelToLoad - 1) + ")").addClass("current");
// Otherwise we must be loading Panel 1, so make the first tab the current one.
} else {
$("#coda-nav-" + sliderCount + " a:eq(0)").addClass("current");
};
// Set the height of the first panel
if (settings.autoHeight) {
panelHeight = $('.panel:eq(' + (currentPanel - 1) + ')', slider).height();
slider.css({ height: panelHeight });
};
// Trigger autoSlide
if (settings.autoSlide) {
slider.ready(function() {
setTimeout(autoSlide,settings.autoSlideInterval);
});
};
function alterPanelHeight(x) {
if (settings.autoHeight) {
panelHeight = $('.panel:eq(' + x + ')', slider).height()
slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
};
};
function autoSlide() {
if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
if (currentPanel == panelCount) {
var offset = 0;
currentPanel = 1;
} else {
var offset = - (panelWidth*currentPanel);
currentPanel += 1;
};
alterPanelHeight(currentPanel - 1);
// Switch the current tab:
slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
// Slide:
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
setTimeout(autoSlide,settings.autoSlideInterval);
};
};
// Kill the preloader
$('.panel', slider).show().end().find("p.loading").remove();
slider.removeClass("preload");
sliderCount++;
});
};
|
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../helpers/start-app';
import destroyApp from '../../helpers/destroy-app';
import config from '../../../config/environment';
let app;
module('Unit | Service | log', {
beforeEach: function () {
app = startApp();
},
afterEach: function() {
destroyApp(app);
}
});
test('error works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = true;
let errorMessage = 'The system generated an error';
let errorMachineName = location.hostname;
let errorAppDomainName = window.navigator.userAgent;
let errorProcessId = document.location.href;
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'ERROR');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '1');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), errorMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), errorAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), errorProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('message')), errorMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.error.
Ember.run(() => {
Ember.Logger.error(errorMessage);
});
});
test('logService works properly when storeErrorMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = false;
let errorMessage = 'The system generated an error';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.error.
Ember.run(() => {
Ember.Logger.error(errorMessage);
});
});
test('logService for error works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeErrorMessages = true;
let errorMessage = 'The system generated an error';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.error.
Ember.run(() => {
Ember.Logger.error(errorMessage);
});
});
test('warn works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeWarnMessages = true;
let warnMessage = 'The system generated an warn';
let warnMachineName = location.hostname;
let warnAppDomainName = window.navigator.userAgent;
let warnProcessId = document.location.href;
logService.on('warn', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'WARN');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '2');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), warnMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), warnAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), warnProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
let savedMessageContainsWarnMessage = savedLogRecord.get('message').indexOf(warnMessage) > -1;
assert.ok(savedMessageContainsWarnMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.warn.
Ember.run(() => {
Ember.warn(warnMessage);
});
});
test('logService works properly when storeWarnMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeWarnMessages = false;
let warnMessage = 'The system generated an warn';
logService.on('warn', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.warn.
Ember.run(() => {
Ember.warn(warnMessage);
});
});
test('logService for warn works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeWarnMessages = true;
let warnMessage = 'The system generated an warn';
logService.on('warn', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.warn.
Ember.run(() => {
Ember.warn(warnMessage);
});
});
test('log works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeLogMessages = true;
let logMessage = 'Logging log message';
let logMachineName = location.hostname;
let logAppDomainName = window.navigator.userAgent;
let logProcessId = document.location.href;
logService.on('log', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'LOG');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '3');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), logMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), logAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), logProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('message')), logMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.log.
Ember.run(() => {
Ember.Logger.log(logMessage);
});
});
test('logService works properly when storeLogMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeLogMessages = false;
let logMessage = 'Logging log message';
logService.on('log', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.log.
Ember.run(() => {
Ember.Logger.log(logMessage);
});
});
test('logService for log works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeLogMessages = true;
let logMessage = 'Logging log message';
logService.on('log', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.log.
Ember.run(() => {
Ember.Logger.log(logMessage);
});
});
test('info works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeInfoMessages = true;
let infoMessage = 'Logging info message';
let infoMachineName = location.hostname;
let infoAppDomainName = window.navigator.userAgent;
let infoProcessId = document.location.href;
logService.on('info', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'INFO');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '4');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), infoMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), infoAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), infoProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('message')), infoMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.info.
Ember.run(() => {
Ember.Logger.info(infoMessage);
});
});
test('logService works properly when storeInfoMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeInfoMessages = false;
let infoMessage = 'Logging info message';
logService.on('info', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.info.
Ember.run(() => {
Ember.Logger.info(infoMessage);
});
});
test('logService for info works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeInfoMessages = true;
let infoMessage = 'Logging info message';
logService.on('info', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.Logger.info.
Ember.run(() => {
Ember.Logger.info(infoMessage);
});
});
test('debug works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeDebugMessages = true;
let debugMessage = 'Logging debug message';
let debugMachineName = location.hostname;
let debugAppDomainName = window.navigator.userAgent;
let debugProcessId = document.location.href;
logService.on('debug', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'DEBUG');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '5');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), debugMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), debugAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), debugProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
let savedMessageContainsDebugMessage = savedLogRecord.get('message').indexOf(debugMessage) > -1;
assert.ok(savedMessageContainsDebugMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.debug.
Ember.run(() => {
Ember.debug(debugMessage);
});
});
test('logService works properly when storeDebugMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeDebugMessages = false;
let debugMessage = 'Logging debug message';
logService.on('debug', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.debug.
Ember.run(() => {
Ember.debug(debugMessage);
});
});
test('logService for debug works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeDebugMessages = true;
let debugMessage = 'Logging debug message';
logService.on('debug', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.debug.
Ember.run(() => {
Ember.debug(debugMessage);
});
});
test('deprecate works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeDeprecationMessages = true;
let deprecationMessage = 'The system generated an deprecation';
let deprecationMachineName = location.hostname;
let deprecationAppDomainName = window.navigator.userAgent;
let deprecationProcessId = document.location.href;
logService.on('deprecation', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'DEPRECATION');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '6');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), deprecationMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), deprecationAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), deprecationProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
let savedMessageContainsDeprecationMessage = savedLogRecord.get('message').indexOf(deprecationMessage) > -1;
assert.ok(savedMessageContainsDeprecationMessage);
let formattedMessageIsOk = savedLogRecord.get('formattedMessage') === '';
assert.ok(formattedMessageIsOk);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.deprecate.
Ember.run(() => {
Ember.deprecate(deprecationMessage, false, { id: 'ember-flexberry-debug.feature-logger-deprecate-test', until: '0' });
});
});
test('logService works properly when storeDeprecationMessages disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeDeprecationMessages = false;
let deprecationMessage = 'The system generated an deprecation';
logService.on('deprecation', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.deprecate.
Ember.run(() => {
Ember.deprecate(deprecationMessage, false, { id: 'ember-flexberry-debug.feature-logger-deprecate-test', until: '0' });
});
});
test('logService for deprecate works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeDeprecationMessages = true;
let deprecationMessage = 'The system generated an deprecation';
logService.on('deprecation', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.deprecate.
Ember.run(() => {
Ember.deprecate(deprecationMessage, false, { id: 'ember-flexberry-debug.feature-logger-deprecate-test', until: '0' });
});
});
test('assert works properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = true;
let assertMessage = 'The system generated an error';
let assertMachineName = location.hostname;
let assertAppDomainName = window.navigator.userAgent;
let assertProcessId = document.location.href;
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'ERROR');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '1');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), assertMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), assertAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), assertProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
let savedMessageContainsAssertMessage = savedLogRecord.get('message').indexOf(assertMessage) > -1;
assert.ok(savedMessageContainsAssertMessage);
let formattedMessageContainsAssertMessage = savedLogRecord.get('formattedMessage').indexOf(assertMessage) > -1;
assert.ok(formattedMessageContainsAssertMessage);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.assert.
Ember.run(() => {
Ember.assert(assertMessage, false);
});
});
test('logService works properly when storeErrorMessages for assert disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = false;
let assertMessage = 'The system generated an error';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.assert.
Ember.run(() => {
Ember.assert(assertMessage, false);
});
});
test('logService for assert works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeErrorMessages = true;
let assertMessage = 'The system generated an error';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Call to Ember.assert.
Ember.run(() => {
Ember.assert(assertMessage, false);
});
});
test('throwing exceptions logs properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = true;
let errorMessage = 'The system thrown an exception';
let errorMachineName = location.hostname;
let errorAppDomainName = window.navigator.userAgent;
let errorProcessId = document.location.href;
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'ERROR');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '1');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), errorMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), errorAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), errorProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('message')), errorMessage);
let formattedMessageContainsErrorMessage = savedLogRecord.get('formattedMessage').indexOf(errorMessage) > -1;
assert.ok(formattedMessageContainsErrorMessage);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
throw new Error(errorMessage);
});
});
test('logService works properly when storeErrorMessages for throw disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storeErrorMessages = false;
let errorMessage = 'The system thrown an exception';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
throw new Error(errorMessage);
});
});
test('logService for throw works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storeErrorMessages = true;
let errorMessage = 'The system thrown an exception';
logService.on('error', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
throw new Error(errorMessage);
});
});
test('promise errors logs properly', function(assert) {
let done = assert.async();
assert.expect(10);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Override default QUnitAdapter.exception method to avoid calling additional assertion when rejecting promise.
let oldTestAdapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => { };
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storePromiseErrors = true;
logService.showPromiseErrors = false;
let promiseErrorMessage = 'Promise error';
let promiseMachineName = location.hostname;
let promiseAppDomainName = window.navigator.userAgent;
let promiseProcessId = document.location.href;
logService.on('promise', this, (savedLogRecord) => {
// Check results asyncronously.
assert.strictEqual(Ember.$.trim(savedLogRecord.get('category')), 'PROMISE');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('eventId')), '0');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('priority')), '7');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('machineName')), promiseMachineName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('appDomainName')), promiseAppDomainName);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processId')), promiseProcessId);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('processName')), 'EMBER-FLEXBERRY');
assert.strictEqual(Ember.$.trim(savedLogRecord.get('threadName')), config.modulePrefix);
assert.strictEqual(Ember.$.trim(savedLogRecord.get('message')), promiseErrorMessage);
let formattedMessageContainsPromiseErrorMessage = savedLogRecord.get('formattedMessage').indexOf(promiseErrorMessage) > -1;
assert.ok(formattedMessageContainsPromiseErrorMessage);
//Restore default QUnitAdapter.exception method
Ember.Test.adapter.exception = oldTestAdapterException;
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
Ember.RSVP.reject(promiseErrorMessage);
});
});
test('logService works properly when storePromiseErrors disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Override default QUnitAdapter.exception method to avoid calling additional assertion when rejecting promise.
let oldTestAdapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => { };
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = true;
logService.storePromiseErrors = false;
logService.showPromiseErrors = false;
let promiseErrorMessage = 'Promise error';
logService.on('promise', this, (savedLogRecord) => {
// Check results asyncronously.
assert.notOk(savedLogRecord);
//Restore default QUnitAdapter.exception method
Ember.Test.adapter.exception = oldTestAdapterException;
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
Ember.RSVP.reject(promiseErrorMessage);
});
});
test('logService for promise works properly when it\'s disabled', function(assert) {
let done = assert.async();
assert.expect(1);
// Stub save method of i-i-s-caseberry-logging-objects-application-log base model.
let originalSaveMethod = DS.Model.prototype.save;
let savedLogRecord;
DS.Model.prototype.save = function() {
savedLogRecord = this;
return Ember.RSVP.resolve(savedLogRecord);
};
// Get log-service instance & enable errors logging.
let logService = app.__container__.lookup('service:log');
logService.enabled = false;
logService.storePromiseErrors = true;
let promiseErrorMessage = 'Promise error';
logService.on('promise', this, (savedLogRecord) => {
// Check results asyncronously.
if (savedLogRecord) {
throw new Error('Log is disabled, DB isn\'t changed');
} else {
assert.ok(true, 'Check log call, DB isn\'t changed');
}
// Restore save method of i-i-s-caseberry-logging-objects-application-log base model.
DS.Model.prototype.save = originalSaveMethod;
done();
});
// Throwing an exception.
Ember.run(() => {
Ember.RSVP.reject(promiseErrorMessage);
});
});
|
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var words = require('./words')
inherits(Document, EventEmitter)
module.exports = Document
function Document() {
this.row = this.column = this.preferred = 0
this.lines = ['\n']
this.marks = null
}
//compare marked positions
function cmp (m, n) {
return m.y - n.y === 0 ? m.x - n.x : m.y - n.y
}
function sameLine(m, n) {
return m.y == n.y
}
var methods = {
//get line relative to current
line: function (n) {
n = n || 0
return this.lines[this.row + n]
},
//set the current line
setLine: function (val) {
this.lines[this.row] = val
},
//force the column inside the string
fixColumn: function () {
var l
if(this.column + 1 > (l = this.line().length))
this.column = l - 1
return this
},
//check if cursor is on first line
isFirstLine: function () {
return this.row === 0
},
//check if cursor is on last line
isLastLine: function () {
return this.row + 1 >= this.lines.length
},
//check if cursor is at start of line
isFirst: function () {
return this.column === 0
},
//check if cursor is at end of line
isLast: function () {
return this.column + 1 >= this.line().length
},
//set cursor position
pos: function (x, y) {
this.column = x
this.row = y
return this
},
//move cursor to end of line
end: function () {
this.column = this.line().length - 1
return this
},
//move cursor to start of line
start: function () {
this.column = 0
return this
},
//move cursor up a line
up: function () {
if(this.row > 0)
(--this.row, this.fixColumn())
return this
},
//move cursor down a line
down: function () {
if(this.row + 1 < this.lines.length)
(++this.row, this.fixColumn())
return this
},
//move cursor left
left: function () {
if(this.column > 0) --this.column
return this
},
//move cursor to right
right: function () {
if(this.column + 1 < this.line().length) ++this.column
return this
},
//move to previous word
prev: function () {
var m = words.prev(this.line(), this.column)
if(m) this.column = m.index
else if(this.isFirstLine()) this.start()
else this.up().end()
return this
},
//move to the end of the word
next: function () {
var m = words.current(this.line(), this.column)
if(m) this.column = m.index + m[0].length
else if(this.isLastLine()) this.end()
else this.down().start()
return this
},
//move to prev section (start of non whitespace block)
prevSection: function () {
this.up()
while(! this.isFirstLine() && !/^\s*$/.test(this.line(-1)))
this.up()
while(! this.isFirstLine() && /^\s*$/.test(this.line()))
this.up()
return this
},
//move to next section (start of non whitespace block)
nextSection: function () {
this.down()
while(! this.isLastLine() && /^\s*$/.test(this.line()))
this.down()
while(! this.isLastLine() && !/^\s*$/.test(this.line()))
this.down()
return this
},
//go to the first line
firstLine: function () {
this.row = 0
return this
},
//go to the last line
lastLine: function () {
this.row = this.lines.length - 1
return this
},
//ACTUALLY MOVE THE TERMINAL CURSOR.
//IMPORTANT.
move: function () {
return this._emit('cursor')
},
//set the preferred column to be in.
//when you enter text, then move up a line
//editor should be in the same column.
//if the line is shorter, need to remember this
//should be set when ever the user enters text,
//or moves left or right
pref: function pref () {
this.preferred = this.column
return this
},
toPref: function toPref() {
console.error('TO_PREF', this.preferred, this.column)
if('undefined' === typeof this.preferred) return this
if(this.line().length <= this.preferred)
this.column = this.line().length - 1
else
this.column = this.preferred
return this
},
//set a mark, to mark a section just call this twice
mark: function (x, y) {
if(x == null && y == null)
x = this.column, y = this.row
var mark = {x: x, y: y}
if(!this.firstMark) this.firstMark = mark
this.secondMark = mark
this.marks = [this.firstMark, this.secondMark].sort(cmp)
this.emit('mark', this.marks[0], this.marks[1])
return this
},
//remove marks
unmark: function () {
console.error('UNMARK', this.marks)
var old = this.marks
this.firstMark = this.secondMark = this.marks = null
if(old)
this.emit('unmark', old[0], old[1])
return this
},
getMarked: function () {
if(!this.marks) return null
var m = this.marks[0], M = this.marks[1]
if(sameLine(m, M))
return this.lines[m.y].substring(m.x, M.x)
var lines = this.lines[m.y].substring(m.x)
for (var Y = m.y + 1; Y < M.y; Y++) {
lines += this.lines[Y]
}
lines += this.lines[M.y].substring(0, M.x)
return lines
},
clearMarked: function () {
if(!this.marks) return this
//basic thing here is delete.
//I want te remove the current, then replace.
//maybe I should use the jumprope module from
//the sharejs guy. would need to be able to fix the lengths
//though, to lines, or 80 chars, and be able to address by line too.
if(!this.marks) return null
var m = this.marks[0], M = this.marks[1]
this.pos(m.x,m.y)
if(sameLine(m, M))
return this.unmark().delete(M.x - m.x)
//get the remainder of the last line
var last = this.lines[M.y].substring(M.x)
//get the start of the first line
var first = this.lines[m.y].substring(0, m.x)
//delete all the middle lines
var lines = M.y - m.y
this.deleteLines(m.y, lines)
//join the remainers together
this.pos(m.x,m.y).setLine(first + last)
console.error('LINE', this.line())
return this.unmark().move()
},
insert: function (lines) {
var self = this
lines.split('\n').forEach(function (line, i, lines) {
self.write(line)
if(i + 1 < lines.length)
self.newline()
})
return this.move()
},
//internal. emit an event with current line and cursor pos.
_emit: function (m, l) {
this.emit(m, l || this.line(), this.column + 1, this.row + 1)
return this
},
//create a new line under the cursor
newline: function () {
var nl, l = this.line()
this.setLine(l.slice(0, this.column) + '\n')
this._emit('update_line')
this.lines.splice(++this.row, 0, nl = l.slice(this.column))
//could it be nice to have options to veto stuff?
this.column = 0
this._emit('new_line').move()
return this
},
//write some data
write: function (data) {
var l = this.line()
this.setLine(l.slice(0, this.column) + data + l.slice(this.column))
this.column += data.length
this._emit('update_line').move()
return this
},
updateLine: function(line, data) {
this.lines[line] = data
this.emit('update_line', data, 1, line + 1)
},
deleteLines: function (line, lines) {
this.lines.splice(line, lines)
if (!lines.length)
this.lines.push('\n')
while (lines)
this.emit('delete_line', '', 1, line + (lines --))
return this
},
//delete (+-charsToDelete)
delete: function (data) {
data = data == null ? 1 : data
if(this.isFirst() && data < 0 ) {
if(this.isFirstLine()) return this
this.up()
//we want to be on the first character of what was the
//next line, so that we delete the \n character
this.column = this.line().length
this._emit('delete_line')
this.lines.splice(this.row, 2, this.line() + this.line(1))
} else if (this.isLast() && data > 0) {
if(this.isLastLine()) return this
this._emit('delete_line')
this.end()
this.lines.splice(this.row, 2, this.line() + this.line(+1))
}
var nc = this.column + data
var l = this.line()
var s = Math.min(this.column, nc)
var e = Math.max(this.column, nc)
this.lines[this.row] =
l.slice(0, s) + l.slice(e)
this.column = s
if(this.line() == '')
this.deleteLines(this.row, 1)
else
this._emit('update_line').move()
return this
},
//delete backwards
backspace: function (n) {
return this.delete(-1 * (n || 1))
}
}
for (var m in methods)
Document.prototype[m] = methods[m]
|
#!/bin/sh
':' //; exec "$(command -v nodejs || command -v node)" "$0" "$@"
'use strict';
// Represents a GUI option with 4 selection
function toggleMode(oldMode) {
if(oldMode === 'bar-chart') {
return 'total-view';
} else if(oldMode === 'total-view') {
return 'percentage-view';
} else if(oldMode === 'percentage-view') {
return 'grid-view';
} else if(oldMode === 'grid-view') {
return 'bar-chart';
}
}
console.log('Toggle mode with conditionals:');
console.info(toggleMode('bar-chart'));
// total-view
console.info(toggleMode('total-view'));
// percentage-view
console.info(toggleMode('percentage-view'));
// grid-view
console.info(toggleMode('grid-view'));
// bar-chart
console.log('\nToggle mode with a hash:');
function toggleMode2(oldMode) {
const modeMap = {
'bar-chart': 'total-view',
'total-view': 'percentage-view',
'percentage-view': 'grid-view',
'grid-view': 'bar-chart',
}
return modeMap[oldMode];
}
console.info(toggleMode2('bar-chart'));
// total-view
console.info(toggleMode2('total-view'));
// percentage-view
console.info(toggleMode2('percentage-view'));
// grid-view
console.info(toggleMode2('grid-view'));
// bar-chart
console.log('\nToggle mode automated with a hash:');
function createToggle(allModes) {
const modeMap = {};
allModes.forEach(function(mode, index) {
const next = (index + 1) % allModes.length;
modeMap[mode] = allModes[next];
});
return function(oldMode) {
return modeMap[oldMode];
};
}
const allModes = ['bar-chart', 'total-view', 'percentage-view', 'grid-view'];
const toggleMode3 = createToggle(allModes);
console.info(toggleMode3('bar-chart'));
// total-view
console.info(toggleMode3('total-view'));
// percentage-view
console.info(toggleMode3('percentage-view'));
// grid-view
console.info(toggleMode3('grid-view'));
// bar-chart
|
import TimeField from 'ember-time-field/components/time-field';
export default TimeField; |
import EMPTY from '../utils/empty';
import acopy from '../utils/acopy';
export function RingBuffer(head, tail, length, array) {
this.head = head;
this.tail = tail;
this.length = length;
this.array = array;
}
RingBuffer.prototype = {
pop: function () {
var array = this.array,
tail = this.tail,
item;
if (this.length === 0) {
return EMPTY;
}
item = array[tail];
array[tail] = null;
this.tail = (tail + 1) % array.length;
this.length--;
return item;
},
unshift: function(item) {
var array = this.array,
head = this.head;
array[head] = item;
this.head = (head + 1) % array.length;
this.length++;
},
unboundedUnshift: function(item) {
if (this.length + 1 === this.array.length) {
this.resize();
}
this.unshift(item);
},
resize: function() {
var array = this.array,
newArraySize = array.length * 2,
newArray = new Array(newArraySize),
head = this.head,
tail = this.tail,
length = this.length;
if (tail < head) {
acopy(array, tail, newArray, 0, length);
this.tail = 0;
this.head = length;
this.array = newArray;
} else if (tail > head) {
acopy(array, tail, newArray, 0, array.length - tail);
acopy(array, 0, newArray, array.length - tail, head);
this.tail = 0;
this.head = length;
this.array = newArray;
} else if (tail === head) {
this.tail = 0;
this.head = 0;
this.array = newArray;
}
},
cleanup: function(predicate) {
var length = this.length;
for (var i = 0; i < length; i++) {
var item = this.pop();
if (predicate(item)) {
this.unshift(item);
}
}
}
}; |
const { expect } = require('chai');
const { init } = require('../../src');
describe('init()', () => {
it('requires swfClient', () => {
expect(() => init({})).to.throw('swfClient option is required');
});
});
|
/**
* mock.js 提供应用截获ajax请求,为脱离后台测试使用
* 模拟查询更改内存中mockData,并返回数据
*/
import { fetch } from 'mk-utils'
const mockData = fetch.mockData
function initMockData() {
if (!mockData.users) {
mockData.users = [{
id: 1,
mobile: 13334445556,
password: '1'
}]
}
}
fetch.mock('/v1/user/create', (option) => {
initMockData()
if (option.captcha != '123456') {
return { result: false, error: { message: '验证码错误,请重新获取验证码录入' } }
}
const id = mockData.users.length + 1
const v = { ...option, id }
mockData.users.push(v)
return { result: true, value: v }
})
fetch.mock('/v1/user/existsMobile', (mobile) => {
initMockData()
return { result: true, value: mockData.users.findIndex(o => o.mobile == mobile) != -1 }
})
fetch.mock('/v1/captcha/fetch', (option) => {
return { result: true, value: '123456' }
})
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EventStore = (function () {
function EventStore() {
this._events = [];
this._onEventStoredEvents = [];
}
EventStore.prototype.storeEvent = function (event) {
this._events.push(event);
this._onEventStoredEvents.forEach(function (callback) {
callback(event);
});
};
EventStore.prototype.replayEvents = function (finalTime, millisecondsInterval, hardReplay) {
if (hardReplay === void 0) { hardReplay = false; }
var self = this;
var eventsToReplay = self._events.filter(function (event) {
return finalTime == null
|| event.created == null
|| event.created.isBefore(finalTime);
});
function replayEvent(index) {
self._onEventStoredEvents.forEach(function (callback) {
callback(eventsToReplay[index]);
});
if (index + 1 == eventsToReplay.length) {
return;
}
if (millisecondsInterval) {
setTimeout(function () { return replayEvent(index + 1); }, millisecondsInterval);
}
else {
replayEvent(index + 1);
}
}
replayEvent(0);
if (hardReplay) {
self._events = eventsToReplay;
}
};
EventStore.prototype.replayEventsUpTo = function (domainEvent, millisecondsInterval, hardReplay, inclusive) {
if (hardReplay === void 0) { hardReplay = false; }
if (inclusive === void 0) { inclusive = true; }
var self = this;
var replayedEvents = [];
function replayEvent(index) {
if ((!inclusive) && (self._events[index] == domainEvent)) {
if (hardReplay) {
self._events = replayedEvents;
}
return;
}
self._onEventStoredEvents.forEach(function (callback) {
callback(self._events[index]);
});
replayedEvents.push(self._events[index]);
if (self._events[index] == domainEvent) {
if (hardReplay) {
self._events = replayedEvents;
}
return;
}
if (millisecondsInterval) {
setTimeout(function () { return replayEvent(index + 1); }, millisecondsInterval);
}
else {
replayEvent(index + 1);
}
}
replayEvent(0);
};
EventStore.prototype.onEventStored = function (callback) {
this._onEventStoredEvents.push(callback);
};
EventStore.prototype.removeOnEventStoredEvent = function (callback) {
this._onEventStoredEvents = this._onEventStoredEvents.filter(function (oese) { return oese != callback; });
};
EventStore.prototype.clearOnEventStoredEvents = function () {
this._onEventStoredEvents = [];
};
EventStore.prototype.getEventsForID = function (id, callback) {
callback(this._events.filter(function (a) { return a.aggregateID == id; }));
};
EventStore.prototype.getAllEvents = function () {
return this._events;
};
return EventStore;
}());
exports.EventStore = EventStore;
//# sourceMappingURL=eventstore.js.map |
/* jshint globalstrict: true, curly: false */
'use strict';
var iter = window.iter;
describe("join", function() {
it("given empty sequence returns empty string", function() {
var result = iter([]).join('xxx');
expect(result).toBe('');
});
it("given non empty sequence joins elements using given string separator", function() {
var result = iter([1,2,3]).join(':');
expect(result).toBe('1:2:3');
});
});
|
import React from 'react'
import PropTypes from 'prop-types'
const defaultStyles = {
position: 'relative',
padding: '0.5em'
}
export const Text = ({ text, style }) => !text ? null : (
<div style={{ ...defaultStyles, ...style }}>{ text }</div>
)
Text.propTypes = {
text: PropTypes.string,
style: PropTypes.object
}
|
var bull, cow, count, win, chance, placeno;
var word;
var used = new Array();
function guess(txt) {
var result = document.getElementById("indicate" + (count-1));
var gword = txt.value.toLowerCase();
bull = 0;
cow = 0;
var i,j,k;
var next = count + 1;
var appendText = '<tr id="row' + (count+1) + '"><td> <input id="txtGuess' + (count+1) + '" type="text" maxlength="6" placeholder="Chance ' + placeno + '" onblur="guess(this);" onkeypress="return runScript(event,this)" disabled/> </td><td id="indicate' + (count+1) + '"> </td></tr>'
if(gword.length == 6) {
if(spellcheck(gword)) {
displayContent(result.id,"Enter a proper word",0,"shake");
txt.focus();
}
else if ((used.indexOf(gword))>-1){
displayContent(result.id,"This word is already used!",0,"shake");
txt.focus();
}
else {
//------------------------ CORRECT GUESS ---------------------------
if(gword == word) {
win = 1;
displayWin(result,txt,chance)
}
//-----------------------------------------------------------------
else {
if(document.getElementById("txtGuess"+count)!=null) {
document.getElementById("txtGuess"+count).disabled = false;
document.getElementById("txtGuess"+count).focus();
}
count++;
var val=bullcow(gword,word);
bull = val[0];
cow = val[1];
//------------------ ENABLING NEXT CHANCE -------------------------
if(next<chance) {
displayContent("gameHeart",appendText,1);
effect("row"+(count),"fadeInDown");
placeno++;
}
used.push(gword);
//-----------------------------------------------------------------
//---------------------- DISPLAY RESULT ---------------------------
txt.disabled = true;
var inner = bull + " Bull, " + cow + " Cow";
displayContent(result.id,inner,0,"bounceInLeft");
displayContent("spanChance",(chance-(count-1)),0,"fadeIn");
//-----------------------------------------------------------------
//---------------------- COLORING CODES ---------------------------
colorLetters(gword,bull,cow);
//-----------------------------------------------------------------
//------------------- FINAL WRONG GUESS RESULT --------------------
if(((count)==(chance+1)) && (gword.length==6)) {
lastchance();
}
//-----------------------------------------------------------------
}
}
}
else if((txt.value.length == 0) && (result!=null) && (win==0)) {
displayContent(result.id,"Enter a 6 letter word",0,"shake");
txt.focus();
}
else {
txt.focus();
if((document.getElementById("txtGuess" + (next-1))!=null) && (win==0)) {
displayContent(result.id,"Enter a 6 letter word",0,"shake");
}
}
}
function setmoreChance() {
chance = chance+6;
$("#divFail").css("display","none");
var appendText = '<tr><td> <input id="txtGuess' + (count) + '" type="text" maxlength="6" placeholder="Chance ' + placeno + '" onblur="guess(this);" onkeypress="return runScript(event,this)"/> </td><td id="indicate' + (count) + '"> </td></tr>';
appendText += '<tr><td> <input id="txtGuess' + (count+1) + '" type="text" maxlength="6" placeholder="Chance ' + (placeno+1) + '" onblur="guess(this);" onkeypress="return runScript(event,this)" disabled/> </td><td id="indicate' + (count+1) + '"> </td></tr>';
displayContent("gameHeart",appendText,1);
$("#txtGuess" + count).trigger("focus");
count++;
placeno+=2;
runTimer();
runAddTime(0);
displayContent("spanChance",(chance-(count-1)),0,"fadeIn");
}
function setinitialValues(newWord) {
count = 1;
chance = 10;
win = 0;
word = newWord;
placeno=3;
used.length = 0;
}
function getwin() {
return win;
}
|
/**
* license inazumatv.com
* author (at)taikiken / htp://inazumatv.com
* date 2014/02/06 - 13:17
*
* Copyright (c) 2011-2014 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
*
*
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
/**
* global object
*
* @example
*
* <script type="text/javascript" src="/js/sagen-VERSION.min.js"
* id="sagen"
* data-orientation="true"
* data-android="true"
* data-ios="true"
* data-canvas="true">
* </script>
*
* ( function ( window ){
* "use strict";
* var Sagen = window.Sagen
* ;
*
* if ( Sagen.Browser.iOS.is() ) {
* // iOS
* }
*
* }( window ) );
*
*
* @module Sagen
* @type {object}
*/
var Sagen = {};
( function ( window, Sagen ){
"use strict";
// trim
// three.js
String.prototype.trim = String.prototype.trim || function () {
return this.replace( /^\s+|\s+$/g, '' );
};
// Array.isArray
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
/**
* @for Sagen
* @static
* @method hasClass
* @param {HTMLElement} element
* @param {String} class_name CSS class name
* @returns {boolean} 指定 CSS class が存在するか否かの真偽値を返します
*/
Sagen.hasClass = function( element, class_name ) {
var regex;
regex = new RegExp(class_name, 'i');
return !!element.className.match(regex);
};
/**
* @for Sagen
* @static
* @method addClass
* @param {HTMLElement} element 対象 tag element
* @param {String} class_name 追加 CSS class name, 1件だけ指定可能です
* @returns {string} 追加後の CSS class を返します
*/
Sagen.addClass = function( element, class_name ) {
if ( !Sagen.hasClass( element, class_name ) ) {
// class が無かったら
var className = element.className,
pre_space = "";
if ( className !== "" ) {
pre_space = " ";
}
return element.className += pre_space + class_name;
}
};
/**
*
* @for Sagen
* @static
* @method removeClass
* @param {HTMLElement} element 対象 tag element
* @param {String} class_name 削除 CSS class name, 1件だけ指定可能です
* @returns {string} 削除後の CSS class を返します
*/
Sagen.removeClass = function( element, class_name ) {
if ( Sagen.hasClass( element, class_name ) ) {
// class があれば
element.className = element.className.replace( class_name, "" ).trim().split( " " ).join( " " );
return element.className;
}
};
var data_set = ( function ( window ){
var document = window.document,
sagen = document.getElementById( "sagen" ),
data_orientation = false,
data_android = false,
data_ios = false,
data_canvas = false
;
if ( sagen ) {
if ( typeof sagen.dataset !== "undefined" ) {
// sagan.dataset defined
if ( typeof sagen.dataset.orientation !== "undefined" ) {
data_orientation = ( sagen.dataset.orientation.toLowerCase() === "true" );
}
if ( typeof sagen.dataset.android !== "undefined" ) {
data_android = ( sagen.dataset.android.toLowerCase() === "true" );
}
if ( typeof sagen.dataset.ios !== "undefined" ) {
data_ios = ( sagen.dataset.ios.toLowerCase() === "true" );
}
if ( typeof sagen.dataset.canvas !== "undefined" ) {
data_canvas = ( sagen.dataset.canvas.toLowerCase() === "true" );
}
} else {
var attributes = sagen.attributes,
attribute,
node_name;
for ( var j = attributes.length; --j >= 0; ) {
attribute = attributes[ j ];
node_name = attribute.nodeName.toLowerCase();
if ( node_name === 'data-orientation' ) {
data_orientation = attribute.nodeValue.toLowerCase() === "true";
} else if ( node_name === 'data-android' ) {
data_android = attribute.nodeValue.toLowerCase() === "true";
} else if ( node_name === 'data-ios' ) {
data_ios = attribute.nodeValue.toLowerCase() === "true";
} else if ( node_name === 'data-canvas' ) {
data_canvas = attribute.nodeValue.toLowerCase() === "true";
}
}
}
}
return {
orientation: data_orientation,
android: data_android,
ios: data_ios,
canvas: data_canvas
};
}( window ) );
/**
* @for Sagen
* @static
* @method orientation
* @returns {Boolean} orientation checkするか否かの真偽値
*/
Sagen.orientation = function (){
return data_set.orientation;
};
/**
* @for Sagen
* @static
* @method android
* @returns {Boolean} android checkするか否かの真偽値
*/
Sagen.android = function (){
return data_set.android;
};
/**
* @for Sagen
* @static
* @method ios
* @returns {Boolean} ios checkするか否かの真偽値
*/
Sagen.ios = function (){
return data_set.ios;
};
/**
* @for Sagen
* @static
* @method canvas
* @returns {Boolean} canvas checkするか否かの真偽値
*/
Sagen.canvas = function (){
return data_set.canvas;
};
}( window, Sagen ) );/**
* @module Sagen
*/
(function( Sagen ) {
"use strict";
/**
* Static class holding library specific information such as the version and buildDate of
* the library.
* @class Sagen
**/
var s = Sagen.build = Sagen.build || {};
/**
* The version string for this release.
* @property version
* @type String
* @static
**/
s.version = /*version*/"0.2.14"; // injected by build process
/**
* The build date for this release in UTC format.
* @property buildDate
* @type String
* @static
**/
s.buildDate = /*date*/"Wed, 07 May 2014 08:08:08 GMT"; // injected by build process
})( this.Sagen );
/**
* license inazumatv.com
* author (at)taikiken / http://inazumatv.com
* date 2013/12/13 - 14:26
*
* Copyright (c) 2011-2013 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
( function ( window, Sagen ){
"use strict";
// EventDispatcher class from EaselJS.
// Copyright (c) 2010 gskinner.com, inc.
// http://createjs.com/
/**
* The EventDispatcher provides methods for managing prioritized queues of event listeners and dispatching events. All
* {{#crossLink "DisplayObject"}}{{/crossLink}} classes dispatch events, as well as some of the utilities like {{#crossLink "Ticker"}}{{/crossLink}}.
*
* You can either extend this class or mix its methods into an existing prototype or instance by using the
* EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method.
*
* <h4>Example</h4>
* Add EventDispatcher capabilities to the "MyClass" class.
*
* EventDispatcher.initialize(MyClass.prototype);
*
* Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}).
*
* instance.addEventListener("eventName", handlerMethod);
* function handlerMethod(event) {
* console.log(event.target + " Was Clicked");
* }
*
* <b>Maintaining proper scope</b><br />
* When using EventDispatcher in a class, you may need to use <code>Function.bind</code> or another approach to
* maintain you method scope. Note that Function.bind is not supported in some older browsers.
*
* instance.addEventListener("click", handleClick.bind(this));
* function handleClick(event) {
* console.log("Method called in scope: " + this);
* }
*
* Please note that currently, EventDispatcher does not support event priority or bubbling. Future versions may add
* support for one or both of these features.
*
* @class EventDispatcher
* @constructor
**/
var EventDispatcher = function() {
this.initialize();
};
var p = EventDispatcher.prototype;
p.constructor = EventDispatcher;
/**
* Static initializer to mix in EventDispatcher methods.
* @method initialize
* @static
* @param {Object} [target] The target object to inject EventDispatcher methods into. This can be an instance or a
* prototype.
**/
EventDispatcher.initialize = function(target) {
target.addEventListener = p.addEventListener;
target.removeEventListener = p.removeEventListener;
target.removeAllEventListeners = p.removeAllEventListeners;
target.hasEventListener = p.hasEventListener;
target.dispatchEvent = p.dispatchEvent;
};
// private properties:
/**
* @protected
* @property _listeners
* @type Object
**/
p._listeners = null;
// constructor:
/**
* Initialization method.
* @method initialize
* @protected
**/
p.initialize = function() {};
// public methods:
/**
* Adds the specified event listener.
* @method addEventListener
* @param {String} type The string type of the event.
* @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
* the event is dispatched.
* @return {Function | Object} Returns the listener for chaining or assignment.
**/
p.addEventListener = function(type, listener) {
var listeners = this._listeners;
if (!listeners) { listeners = this._listeners = {}; }
else { this.removeEventListener(type, listener); }
var arr = listeners[type];
if (!arr) { arr = listeners[type] = []; }
arr.push(listener);
return listener;
};
/**
* Removes the specified event listener.
* @method removeEventListener
* @param {String} type The string type of the event.
* @param {Function | Object} listener The listener function or object.
**/
p.removeEventListener = function(type, listener) {
var listeners = this._listeners;
if (!listeners) { return; }
var arr = listeners[type];
if (!arr) { return; }
for (var i=0,l=arr.length; i<l; i++) {
if (arr[i] === listener) {
if (l===1) { delete(listeners[type]); } // allows for faster checks.
else { arr.splice(i,1); }
break;
}
}
};
/**
* Removes all listeners for the specified type, or all listeners of all types.
* @method removeAllEventListeners
* @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed.
**/
p.removeAllEventListeners = function(type) {
if (!type) { this._listeners = null; }
else if (this._listeners) { delete(this._listeners[type]); }
};
/**
* Dispatches the specified event.
* @method dispatchEvent
* @param {Object | String} eventObj An object with a "type" property, or a string type. If a string is used,
* dispatchEvent will construct a generic event object with "type" and "params" properties.
* @param {Object} [target] The object to use as the target property of the event object. This will default to the
* dispatching object.
* @return {Boolean} Returns true if any listener returned true.
**/
p.dispatchEvent = function(eventObj, target) {
var ret=false, listeners = this._listeners;
if (eventObj && listeners) {
if (typeof eventObj === "string") { eventObj = {type:eventObj}; }
var arr = listeners[eventObj.type];
if (!arr) { return ret; }
eventObj.target = target||this;
arr = arr.slice(); // to avoid issues with items being removed or added during the dispatch
for (var i=0,l=arr.length; i<l; i++) {
var o = arr[i];
if (o.handleEvent) { ret = ret||o.handleEvent(eventObj); }
else { ret = ret||o(eventObj); }
}
}
return !!ret;
};
/**
* Indicates whether there is at least one listener for the specified event type.
* @method hasEventListener
* @param {String} type The string type of the event.
* @return {Boolean} Returns true if there is at least one listener for the specified event.
**/
p.hasEventListener = function(type) {
var listeners = this._listeners;
return !!(listeners && listeners[type]);
};
/**
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[EventDispatcher]";
};
Sagen.EventDispatcher = EventDispatcher;
}( window, this.Sagen || {} ) );/**
* license inazumatv.com
* author (at)taikiken / http://inazumatv.com
* date 2013/12/13 - 14:34
*
* Copyright (c) 2011-2013 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
( function ( window, Sagen ){
"use strict";
/**
* @class EventObject
* @param {String} eventType Event Type
* @param {*} [params] String || Array eventHandler へ送る値をセット。複数の時は配列にセットする
* @constructor
*/
var EventObject = function ( eventType, params ){
if ( typeof params === "undefined" || params === null ) {
params = [];
} else if ( !Array.isArray( params ) ) {
// 配列へ
params = [ params ];
}
this.type = eventType;
this.params = params;
};
var p = EventObject.prototype;
p.constructor = EventObject;
/**
* パラメタ取出し
* @method getParams
* @returns {*} 配列を返します
*/
p.getParams = function (){
return this.params;
};
Sagen.EventObject = EventObject;
}( window, this.Sagen || {} ) );/**
* license inazumatv.com
* author (at)taikiken / http://inazumatv.com
* date 2013/12/12 - 17:25
*
* Copyright (c) 2011-2013 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*
* Browser class from inazumatv.util
*/
( function ( window, Sagen ){
"use strict";
var navigator = window.navigator,
_ua = navigator.userAgent,
_ie6 = !!_ua.match(/msie [6]/i),
_ie7 = !!_ua.match(/msie [7]/i),
_ie8 = !!_ua.match(/msie [8]/i),
_ie9 = !!_ua.match(/msie [9]/i),
_ie10 = !!_ua.match(/msie [10]/i),
_ie11 = !!_ua.match(/trident\/[7]/i) && !!_ua.match(/rv:[11]/i),
_ie = !!_ua.match(/msie/i) || _ie11,
_legacy = _ie6 || _ie7|| _ie8,
_ipad = !!_ua.match(/ipad/i),
_ipod = !!_ua.match(/ipod/i),
_iphone = !!_ua.match(/iphone/i) && !_ipad && !_ipod,
_ios = _ipad || _ipod || _iphone,
_android = !!_ua.match(/android/i),
_mobile = _ios || _android,
_chrome = !!_ua.match(/chrome/i),
_firefox = !!_ua.match(/firefox/i),
_safari = !!_ua.match(/safari/i),
_android_standard = _android && _safari && !!_ua.match(/version/i),
_touch = typeof window.ontouchstart !== "undefined",
_fullScreen = typeof navigator.standalone !== "undefined" ? navigator.standalone : false,
_android_phone = false,
_android_tablet = false,
_ios_version = -1,
_safari_version = -1,
_safari_versions = [ -1, 0, 0 ],
_ios_versions,
_android_version = -1,
_android_versions,
_chrome_version = -1,
_canvas = !!window.CanvasRenderingContext2D
;
if ( _android ) {
_android_phone = !!_ua.match(/mobile/i);
if ( !_android_phone ) {
_android_tablet = true;
}
}
if ( _android_standard ) {
_chrome = false;
_safari = false;
}
if ( _chrome ) {
_safari = false;
}
// private
// iOS version
// http://stackoverflow.com/questions/8348139/detect-_ios-version-less-than-5-with-javascript
/**
* iOS version detection
* @for Browser
* @method _iosVersion
* @returns {Array} iOS version 配列 3桁
* @private
*/
function _iosVersion () {
var v, versions = [ -1, 0, 0 ];
if ( _ios ) {
// supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
versions = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
_ios_version = parseFloat( versions[ 0 ] + "." + versions[ 1 ] + versions[ 2 ] );
}
return versions;
}
_ios_versions = _iosVersion();
/**
* Android version detection
* @for Browser
* @method _get_androidVersion
* @returns {Array} Android version 配列 3桁
* @private
*/
function _get_androidVersion () {
var v, versions = [ -1, 0, 0 ];
if ( _android ) {
v = (navigator.appVersion).match(/Android (\d+)\.(\d+)\.?(\d+)?/);
versions = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
_android_version = parseFloat( versions[ 0 ] + "." + versions[ 1 ] + versions[ 2 ] );
}
return versions;
}
_android_versions = _get_androidVersion();
// Safari version
/**
* Safari version detection
* @returns {Array} Safari version 配列 2桁~3桁
* @private
*/
function _safariVersion () {
var v, versions;
v = (navigator.appVersion).match(/Version\/(\d+)\.(\d+)\.?(\d+)?/);
versions = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
_safari_version = parseFloat( versions[ 0 ] + "." + versions[ 1 ] + versions[ 2 ] );
return versions;
}
if ( _safari && !_mobile ) {
// not _mobile and _safari
_safari_versions = _safariVersion();
}
function _chromeVersion () {
var v, versions;
v = (navigator.appVersion).match(/Chrome\/(\d+)\.(\d+)\.(\d+)\.?(\d+)?/);
versions = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3], 10), parseInt(v[4], 10)];
return versions.join( "." );
}
if (_chrome ) {
_chrome_version = _chromeVersion();
}
/**
* Browser 情報を管理します
* @class Browser
* @constructor
*/
var Browser = function () {
throw "Browser cannot be instantiated";
};
/**
*
* @type {{iOS: {is: Function, number: Function, major: Function, version: Function}, Android: {is: Function, number: Function, major: Function, version: Function}, IE: {is: Function, version: Function}, Chrome: {is: Function}, Safari: {is: Function}, Firefox: {is: Function}, _ie: Function, _ie6: Function, _ie7: Function, _ie8: Function, _ie9: Function, _ie10: Function, _ie11: Function, _chrome: Function, _firefox: Function, _safari: Function, _legacy: Function, _mobile: Function, _ios: Function, _ios_version: Function, _android_version: Function, _android_version_major: Function, _android_version_num: Function, _android: Function, _iphone: Function, _ipad: Function, _ipod: Function, hideURLBar: Function}}
*/
Browser = {
// new version
/**
* iOS に関する情報
* @for Browser
* @property iOS
* @type Object
* @static
*/
iOS: {
/**
* @for Browser.iOS
* @method is
* @returns {boolean} iOS か否かを返します
* @static
*/
is: function (){
return _ios;
},
/**
* @for Browser.iOS
* @method number
* @returns {Array} iOS version number を返します [ major, minor, build ]
* @static
*/
number: function (){
return _ios_versions;
},
/**
* @for Browser.iOS
* @method major
* @returns {Number} iOS major version number を返します
* @static
*/
major: function (){
return _ios_versions[ 0 ];
},
/**
* @for Browser.iOS
* @method version
* @returns {Number} iOS version を返します 9.99
* @static
*/
version: function (){
return _ios_version;
},
/**
* @for Browser.iOS
* @method iPhone
* @returns {Boolean} iPhone か否かを返します
* @static
*/
iPhone: function (){
return _iphone;
},
/**
* @for Browser.iOS
* @method iPad
* @returns {Boolean} iPad か否かを返します
* @static
*/
iPad: function (){
return _ipad;
},
/**
* @for Browser.iOS
* @method iPod
* @returns {Boolean} iPod か否かを返します
* @static
*/
iPod: function (){
return _ipod;
},
/**
* @for Browser.iOS
* @method fullScreen
* @returns {boolean} standalone mode か否かを返します
* @static
*/
fullScreen: function (){
return _fullScreen;
}
},
/**
* Android に関する情報
* @for Browser
* @property Android
* @type Object
* @static
*/
Android: {
/**
* @for Browser.Android
* @method is
* @returns {boolean} Android か否かを返します
* @static
*/
is: function (){
return _android;
},
/**
* @for Browser.Android
* @method number
* @returns {Array} Android version number を返します [ major, minor, build ]
* @static
*/
number: function (){
return _android_versions;
},
/**
* @for Browser.Android
* @method major
* @returns {Number} Android major version number を返します
* @static
*/
major: function (){
return _android_versions[ 0 ];
},
/**
* @for Browser.Android
* @method version
* @returns {Number} Android version を返します 9.99
* @static
*/
version: function (){
return _android_version;
},
/**
* @for Browser.Android
* @method phone
* @returns {boolean} Android Phone か否かを返します
* @static
*/
phone: function (){
return _android_phone;
},
/**
* @for Browser.Android
* @method tablet
* @returns {boolean} Android Tablet か否かを返します
* @static
*/
tablet: function (){
return _android_tablet;
},
/**
* @for Browser.Android
* @method standard
* @returns {boolean} Android standard Browser か否かを返します
* @static
*/
standard: function () {
return _android_standard;
}
},
/**
* IE に関する情報
* @for Browser
* @property IE
* @type Object
* @static
*/
IE: {
/**
* @for Browser.IE
* @method is
* @returns {boolean} IE か否かを返します
* @static
*/
is: function (){
return _ie;
},
/**
* @for Browser.IE
* @method is6
* @returns {boolean} IE 6 か否かを返します
*/
is6: function (){
return _ie6;
},
/**
* @for Browser.IE
* @method is7
* @returns {boolean} IE 7 か否かを返します
*/
is7: function (){
return _ie7;
},
/**
* @for Browser.IE
* @method is8
* @returns {boolean} IE 8 か否かを返します
*/
is8: function (){
return _ie8;
},
/**
* @for Browser.IE
* @method is9
* @returns {boolean} IE 9 か否かを返します
*/
is9: function (){
return _ie9;
},
/**
* @for Browser.IE
* @method is10
* @returns {boolean} IE 10 か否かを返します
*/
is10: function (){
return _ie10;
},
/**
* @for Browser.IE
* @method is11
* @returns {boolean} IE 11 か否かを返します
*/
is11: function (){
return _ie11;
},
/**
* @for Browser.IE
* @method _legacy
* @returns {boolean} IE 6 or 7 or 8 か否かを返します
*/
legacy: function (){
return _legacy;
},
/**
* @for Browser.IE
* @method version
* @returns {Number} IE version を返します int 6 ~ 11, IE 6 ~ IE 11 でない場合は -1 を返します
* @static
*/
version: function (){
var v = -1;
if ( _ie11 ) {
v = 11;
} else if ( _ie10 ) {
v = 10;
} else if ( _ie9 ) {
v = 9;
} else if ( _ie8 ) {
v = 8;
} else if ( _ie7 ) {
v = 7;
} else if ( _ie6 ) {
v = 6;
}
return v;
}
},
/**
* Chrome に関する情報
* @for Browser
* @property Chrome
* @type Object
* @static
*/
Chrome: {
/**
* @for Browser.Chrome
* @method is
* @returns {boolean} Chrome か否かを返します
* @static
*/
is: function (){
return _chrome;
},
/**
* @for Browser.Chrome
* @method version
* @returns {string}
*/
version: function () {
return _chrome_version;
}
},
/**
* Safari に関する情報
* @for Browser
* @property Safari
* @type Object
* @static
*/
Safari: {
/**
* @for Browser.Safari
* @method is
* @returns {boolean} Safari か否かを返します
* @static
*/
is: function (){
return _safari;
},
/**
* @for Browser.Safari
* @method number
* @returns {Array} Safari version number を返します [ major, minor, build ]
* @static
*/
number: function (){
return _safari_versions;
},
/**
* @for Browser.Safari
* @method major
* @returns {Number} Safari major version number を返します
* @static
*/
major: function (){
return _safari_versions[ 0 ];
},
/**
* @for Browser.Safari
* @method version
* @returns {Number} Safari version を返します 9.99
* @static
*/
version: function (){
return _safari_version;
}
},
/**
* Firefox に関する情報
* @for Browser
* @property Firefox
* @type Object
* @static
*/
Firefox: {
/**
* @for Browser.Firefox
* @method is
* @returns {boolean} Firefox か否かを返します
* @static
*/
is: function (){
return _firefox;
}
},
/**
* Touch action に関する情報
* @for Browser
* @property Touch
* @type Object
* @static
*/
Touch: {
/**
* @for Browser.Touch
* @method is
* @returns {boolean} Touch 可能か否かを返します
* @static
*/
is: function (){
return _touch;
}
},
/**
* Mobile action に関する情報
* @for Browser
* @property Mobile
* @type Object
* @static
*/
Mobile: {
/**
* @for Browser.Mobile
* @method is
* @returns {boolean} mobile(smart phone) か否かを返します
* @static
*/
is: function (){
return _mobile;
},
/**
* iPhone, Android phone. URL bar 下へスクロールさせます。<br>
* window.onload 後に実行します。<br>
* iOS 7 mobile Safari, Android Chrome and iOS Chrome では動作しません。
*
* function onLoad () {
* window.removeEventListener( "load", onLoad );
* Browser.Mobile.hideURLBar();
* }
* window.addEventListener( "load", onLoad, false );
*
* @for Browser.Mobile
* @method hideURLBar
* @static
*/
hideURLBar : function (){
setTimeout( function (){ scrollBy( 0, 1 ); }, 0);
},
/**
* @for Browser.Mobile
* @method phone
* @returns {boolean} Smart Phone(include iPod)か否かを返します
* @static
*/
phone: function (){
return _ipod || _iphone || _android_phone;
},
/**
* @for Browser.Mobile
* @method tablet
* @returns {boolean} tablet か否かを返します
* @static
*/
tablet: function (){
return _ipad || _android_tablet;
}
},
/**
* Canvas に関する情報
* @for Browser
* @property Canvas
* @type Object
* @static
*/
Canvas: {
/**
* @for Browser.Canvas
* @method is
* @returns {boolean} canvas 2D が使用可能か否かを返します
* @static
*/
is: function (){
return _canvas;
},
/**
* @for Browser.Canvas
* @method webgl
* @returns {boolean} canvas webgl 使用可能か否かを返します
* @static
*/
webgl: function (){
if ( !_canvas ) {
return false;
}
try {
return !!window.WebGLRenderingContext && !!document.createElement( 'canvas' ).getContext( 'experimental-webgl' );
} catch( e ) {
return false;
}
}
}
};
Sagen.Browser = Browser;
}( window, this.Sagen || {} ) );/**
* license inazumatv.com
* author (at)taikiken / htp://inazumatv.com
* date 2014/02/06 - 13:55
*
* Copyright (c) 2011-2014 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
( function ( window, Sagen ){
"use strict";
var document = window.document,
abs = window.Math.abs,
Browser = Sagen.Browser,
iOS = Browser.iOS,
Android = Browser.Android,
Canvas = Browser.Canvas,
EventDispatcher = Sagen.EventDispatcher,
EventObject = Sagen.EventObject,
_is_orientation_change = "onorientationchange" in window,
_is_orientation = "orientation" in window,
_orientation_event = _is_orientation_change ? "orientationchange" : "resize",
_element = document.documentElement,
_other = false,
_orientation_check = Sagen.orientation(),
use_matchmedia = typeof window.matchMedia !== "undefined"
;
function _initialize () {
var class_names = [],
number;
// write class
if ( iOS.is() ) {
// iOS
if ( iOS.iPad() ) {
// iPad
class_names.push( "ios" );
class_names.push( "ipad" );
class_names.push( "tablet" );
} else if ( iOS.iPod() ) {
// iPod
class_names.push( "ios" );
class_names.push( "ipod" );
class_names.push( "mobile" );
} else if ( iOS.iPhone() ) {
// iPhone
class_names.push( "ios" );
class_names.push( "iphone" );
class_names.push( "mobile" );
}
if ( iOS.fullScreen() ) {
// standalone
class_names.push( "standalone" );
}
// version
number = iOS.number();
class_names.push( "ios" + number.join("") );
class_names.push( "ios" + number[ 0 ] );
class_names.push( "ios" + number[ 0 ] + number[ 1 ] );
} else if ( Android.is() ) {
// Android
if ( Android.phone() ) {
// phone
class_names.push( "android" );
class_names.push( "mobile" );
} else if ( Android.tablet() ) {
// tablet
class_names.push( "android" );
class_names.push( "tablet" );
// hd tablet or not
if ( window.innerWidth >= 1024 && window.innerHeight >= 1024 ) {
class_names.push( "tablet-hd" );
}
}
// version
number = Android.number();
class_names.push( "android" + number.join( "" ) );
class_names.push( "android" + number[ 0 ] );
class_names.push( "android" + number[ 0 ] + number[ 1 ] );
} else {
// not iOS and not Android
class_names.push( "other" );
_other = true;
}
if ( Browser.Touch.is() ) {
// touch device
class_names.push( "touch" );
}
if ( _is_orientation_change ) {
// orientation change
class_names.push( "orientation-change" );
}
if ( _is_orientation ) {
// orientation
class_names.push( "orientation" );
}
_addClass( class_names.join( " " ) );
}
function _addClass ( class_name ) {
Sagen.addClass( _element, class_name );
}
function _removeClass ( class_name ) {
Sagen.removeClass( _element, class_name );
}
// ------------------
// for android tablet portrait check
function _android_portrait () {
var w = parseInt( window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, 10 ),
h = parseInt( window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight, 10 );
return h > w;
}
function _android_landscape () {
var w = parseInt( window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, 10 ),
h = parseInt( window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight, 10 );
return w > h;
}
// check portrait
function _portrait () {
return abs( window.orientation ) !== 90;
}
// check landscape
function _landscape () {
return abs( window.orientation ) === 90;
}
// event handler
function _width_onOrientation () {
var direction;
if ( _android_portrait() ) {
// portrait
_removeClass( "landscape" );
_addClass( "portrait" );
direction = "portrait";
} else {
// landscape
_removeClass( "portrait" );
_addClass( "landscape" );
direction = "landscape";
}
Device._onOrientation( direction );
}
function _onOrientation () {
if ( !_is_orientation ) {
_width_onOrientation();
return;
}
var direction = "";
function set_portrait () {
_removeClass( "landscape" );
_addClass( "portrait" );
direction = "portrait";
}
function set_landscape () {
_removeClass( "portrait" );
_addClass( "landscape" );
direction = "landscape";
}
if ( use_matchmedia ) {
if ( window.matchMedia( "(orientation: portrait)" ).matches ) {
// portrait
set_portrait();
} else {
// landscape
set_landscape();
}
} else {
// not matchMedia
if ( _portrait() ) {
// portrait
set_portrait();
} else if ( _landscape() ) {
// landscape
set_landscape();
}
}
Device._onOrientation( direction );
}
/**
* Device 情報に基づきhtml tagへCSSクラスネームを書き込みます
* @class Device
* @constructor
*/
var Device = function () {
throw "Device cannot be instantiated";
};
/**
* @for Viewport
* @property CHANGE_ORIENTATION
* @type {string}
* @static
*/
Device.CHANGE_ORIENTATION = "changeOrientation";
EventDispatcher.initialize( Device );
Device._onOrientation = function ( direction ){
Device.dispatchEvent( new EventObject( Device.CHANGE_ORIENTATION, [ direction ] ), this );
};
/**
* orientation 監視を開始します。
* data-orientation="true"だと自動で実行されます。
* @for Device
* @method listen
* @static
*/
Device.listen = function (){
// orientation check start
if ( typeof window.addEventListener !== "undefined" && !_other ) {
window.addEventListener( _orientation_event, _onOrientation, false );
}
};
/**
* orientation 監視を止めます。
* @for Device
* @method abort
* @static
*/
Device.abort = function (){
// orientation check stop
window.removeEventListener( _orientation_event, _onOrientation );
};
/**
* portraitか否かを返します。
* @for Device
* @method portrait
* @return {Boolean} portraitならばtrue
* @static
*/
Device.portrait = function (){
return _portrait();
};
/**
* landscapeか否かを返します。
* @for Device
* @method landscape
* @return {Boolean} landscapeならばtrue
* @static
*/
Device.landscape = function (){
return _landscape();
};
/**
* canvas, webglが使用可能かを調べcss classを書き込みます
* @for Device
* @method canvas
* @static
*/
Device.canvas = function (){
if ( Canvas.is() ) {
// canvas enable
_addClass( "canvas" );
if ( Canvas.webgl() ) {
_addClass( "webgl" );
}
}
};
/**
* 強制的にorientation eventを発火します。data-orientationがtrueになっている必要があります。
* @for Device
* @method fire
* @static
*/
Device.fire = function (){
if ( _orientation_check && !_other ) {
_onOrientation();
}
};
/**
* @for Device
* @method getElement
* @returns {HTMLElement} html tag element を返します
* @static
*/
Device.getElement = function () {
return _element;
};
Sagen.Device = Device;
// write action
_initialize();
if ( !_other ) {
_onOrientation();
} else {
_orientation_check = false;
}
if ( _orientation_check && !_other ) {
// orientation check
Device.listen();
}
if ( Sagen.canvas() ) {
Device.canvas();
}
}( window, this.Sagen || {} ) );/**
* license inazumatv.com
* author (at)taikiken / htp://inazumatv.com
* date 2014/02/06 - 13:30
*
* Copyright (c) 2011-2014 inazumatv.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
( function ( window, Sagen ){
"use strict";
var document = window.document,
Browser = Sagen.Browser,
_contents = [],
_viewport,
_content
;
// get viewport content
( function (){
var contents;
if ( typeof document.querySelector !== "undefined" ) {
_viewport = document.querySelector( "meta[name='viewport']" );
if ( _viewport ) {
_content = _viewport.content;
// ToDo
// for remove setting
// contents = _content.split( "," );
//
// for ( var i = 0, limit = contents.length; i < limit; i++ ) {
// var con = contents[ i ];
// _contents.push( con.split( " " ).join("") );
// }
}
}
}() );
/**
*
* @param {String} content
* @returns {HTMLElement}
* @private
*/
function _createMeta ( content ) {
var meta = document.createElement( "meta" );
meta.name = "viewport";
meta.content = content;
_viewport = meta;
return meta;
}
/**
* Viewport 情報を管理します
* @class Viewport
* @constructor
*/
var Viewport = function () {
throw "Viewport cannot be instantiated";
};
/**
* viewport へ設定を追加します
* @for Viewport
* @method add
* @param {String} option
* @static
*/
Viewport.add = function ( option ) {
if ( _viewport && _content && option ) {
_viewport.content = _viewport.content + ", " + option;
}
};
/**
* viewport へ設定を置き換えます
* @for Viewport
* @method replace
* @param {String} old_option 置換前の文字列
* @param {String} [new_option] 置換後の文字列 optional
* @static
*/
Viewport.replace = function ( old_option, new_option ){
new_option = new_option || "";
if ( _viewport && _content && old_option ) {
_viewport.content = _viewport.content.split( old_option ).join( new_option );
}
};
/**
* viewport タグを書き込みます
* @for Viewport
* @method write
* @param {String} viewport viewport content部Text
* @static
*/
Viewport.write = function ( viewport ) {
document.getElementsByTagName( "head" )[ 0 ].appendChild( _createMeta( viewport ) );
};
/**
* viewport content を全て書き換えます
* @for Viewport
* @method rewrite
* @param {string} content
* @static
*/
Viewport.rewrite = function ( content ){
_viewport.content = content;
};
/**
* @for Viewport
* @static
*/
Viewport.Android = {
/**
* target-densitydpi=device-dpi option を viewport content 属性に追加します
* @for Viewport.Android
* @method targetDensity
* @static
*/
targetDensity: function (){
Viewport.add( "target-densitydpi=device-dpi" );
}
};
/**
* @for Viewport
* @static
*/
Viewport.iOS = {
/**
* minimal-ui option を viewport content 属性に追加します
* @for Viewport.iOS
* @method minimalUI
* @static
*/
minimalUI: function (){
Viewport.add( "minimal-ui" );
}
};
/**
* @for Viewport
* @method getMeta
* @returns {DOMElement} meta: viewport DOMElement を返します
*/
Viewport.getMeta = function (){
return _viewport;
};
Sagen.Viewport = Viewport;
if ( Sagen.android() && !Browser.Chrome.is() ) {
// android viewport added
if ( Browser.Android.is() ) {
Viewport.Android.targetDensity();
}
}
if ( Sagen.ios() ) {
// iOS 7.1 viewport added
if ( Browser.iOS.is() && Browser.iOS.version() >= 7.1 ) {
Viewport.iOS.minimalUI();
}
}
}( window, this.Sagen || {} ) ); |
/* global Metro */
(function(Metro, $) {
'use strict';
var Utils = Metro.utils;
var cookieDisclaimerDefaults = {
name: 'cookies_accepted',
template: null,
templateSource: null,
acceptButton: '.cookie-accept-button',
cancelButton: '.cookie-cancel-button',
message: 'Our website uses cookies to monitor traffic on our website and ensure that we can provide our customers with the best online experience possible.',
duration: "30days",
clsContainer: "",
clsMessage: "",
clsButtons: "",
clsAcceptButton: "alert",
clsCancelButton: "",
onAccept: Metro.noop,
onDecline: Metro.noop
};
Metro.cookieDisclaimer = {
init: function(options){
var that = this, cookie = Metro.cookie;
this.options = $.extend({}, cookieDisclaimerDefaults, options);
this.disclaimer = $("<div>");
if (cookie.getCookie(this.options.name)) {
return ;
}
if (this.options.template) {
$.get(this.options.template).then(function(response){
that.create(response);
});
} else if (this.options.templateSource) {
this.create($(this.options.templateSource));
} else {
this.create();
}
},
create: function(html){
var cookie = Metro.cookie;
var o = this.options, wrapper = this.disclaimer, buttons;
wrapper
.addClass("cookie-disclaimer-block")
.addClass(o.clsContainer);
if (!html) {
buttons = $("<div>")
.addClass("cookie-disclaimer-actions")
.addClass(o.clsButtons)
.append( $('<button>').addClass('button cookie-accept-button').addClass(o.clsAcceptButton).html('Accept') )
.append( $('<button>').addClass('button cookie-cancel-button').addClass(o.clsCancelButton).html('Cancel') );
wrapper
.html( $("<div>").addClass(o.clsMessage).html(o.message) )
.append( $("<hr>").addClass('thin') )
.append(buttons);
} else if (html instanceof $) {
wrapper.append(html);
} else {
wrapper.html(html);
}
wrapper.appendTo($('body'));
wrapper.on(Metro.events.click, o.acceptButton, function(){
var dur = 0;
var durations = (""+o.duration).toArray(" ");
$.each(durations, function(){
var d = ""+this;
if (d.includes("day")) {
dur += parseInt(d)*24*60*60*1000;
} else
if (d.includes("hour")) {
dur += parseInt(d)*60*60*1000;
} else
if (d.includes("min")) {
dur += parseInt(d)*60*1000;
} else
if (d.includes("sec")) {
dur += parseInt(d)*1000;
} else {
dur += parseInt(d);
}
})
cookie.setCookie(o.name, true, dur);
Utils.exec(o.onAccept);
wrapper.remove();
});
wrapper.on(Metro.events.click, o.cancelButton, function(){
Utils.exec(o.onDecline);
wrapper.remove();
});
}
};
}(Metro, m4q)); |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Customer = mongoose.model('Customer'),
User = mongoose.model('User'),
Site = mongoose.model('Site'),
Channel = mongoose.model('Channel'),
ChannelController = require('./channel'),
UserController = require('./user'),
util = require('util'),
randomstring = require("randomstring"),
Q = require('q'),
_ = require('lodash');
/**
* Find Customer by id
*/
exports.customer = function(req, res, next, id) {
Customer.load(id, function(err, customer) {
if (err) return next(err);
if (!customer) return next(new Error('Failed to load customer ' + id));
req.customer = customer;
next();
});
};
/**
* Create an customer
*/
exports.create = function(req, res) {
var customer = new Customer(req.body);
customer.user = req.user;
customer.save(function(err, retCustomer) {
if (err) {
console.warn('create err:', err);
return res.status(400).json({
error: 'Cannot save the customer'
});
}
// Create a default channel for this customer
ChannelController.addDefChannelForCustomer(retCustomer,
function(err, channel) {
if (err) {
return res.status(400).json({
error: 'Cannot create the default channel'
});
};
res.json(retCustomer);
}
);
});
};
/**
* Update an customer
*/
exports.update = function(req, res) {
var customer = req.customer;
console.log('req.customer:', req.customer);
customer = _.extend(customer, req.body);
customer.save(function(err) {
if (err) {
return res.status(500).json({
error: err
});
}
res.json(customer);
});
};
/**
* Delete an customer
*/
exports.destroy = function(req, res) {
var customer = req.customer;
customer.remove(function(err) {
if (err) {
return res.status(500).json({
error: 'Cannot delete the customer'
});
}
res.json(customer);
});
};
/**
* Show an customer
*/
exports.show = function(req, res) {
//collect sites information
Site.find({
customer: req.customer
}).count()
.exec(function(err, count) {
if (err) {
console.error('find site error');
res.send(err, 500);
return;
};
//expand customer user info
UserController.loadUserInfo(req.customer)
.then(function(retUser) {
var jsonObj = req.customer.toJSON();
jsonObj['sitesCount'] = count;
jsonObj['user'] = retUser;
res.json(jsonObj);
}, function(err) {
console.error('load user info error');
res.send(err, 400);
return;
})
});
};
/**
* Show an customer's sites information
*/
exports.sites = function(req, res) {
//collect sites information
Site.find({
customer: req.customer
}).select('-__t -__v -deleteFlag')
.exec(function(err, sites) {
if (err) {
console.error('find site error');
res.send(err, 500);
return;
};
res.json(sites);
});
};
exports.sitesPaginate = function(req, res) {
req.checkQuery('pageNumber', 'invalid pageNumber').isInt();
req.checkQuery('pageSize', 'invalid pageSize').isInt();
var errors = req.validationErrors(true);
if (errors) {
res.send(errors, 400);
return;
}
var pageNumber = req.query.pageNumber,
pageSize = req.query.pageSize,
filterChannelName = req.query.channelName,
callback = function(error, pageCount, sites, itemCount) {
if (error) {
console.error(error);
res.status(500).json({
error: error
});
} else {
res.json({
pageCount: pageCount,
data: sites,
count: itemCount
});
}
};
var filterCond = filterChannelName ? {
customer: req.customer,
channelName: filterChannelName,
} : {
customer: req.customer,
};
Site.paginate(filterCond,
pageNumber, pageSize, callback, {
sortBy: '-created',
columns: '_id license.uuid siteName reference created deviceId deliveryInfo channel channelName channelType disable lastHeartbeat'
});
};
exports.addSite = function(req, res) {
req.body.customer = req.customer;
req.body.customerName = req.customer.brand;
ChannelController.getCustomerDefChannel(req.customer,
function(err, channel) {
if (err) {
console.warn('getCustomerDefChannel err:', err);
return res.status(400).json({
error: 'Cannot get CustomerDefChannel'
});
}
var siteObj = _.extend(req.body, {
channel: channel,
channelName: channel.name,
channelType: channel.type,
deviceId: randomstring.generate(10),
license: {
uuid: randomstring.generate(10)
}
});
// SiteController.create(req, res);
var site = new Site(siteObj);
site.save(function(err, retSite) {
if (err) {
console.warn('create err:', err);
return res.status(400).json({
error: 'Cannot save the site'
});
}
res.json(retSite);
});
});
};
function getSiteNum(customers) {
var deferred = Q.defer();
Site.aggregate([{
$match: {
customer: {
$in: _.map(customers, '_id')
}
}
}, {
$group: {
_id: '$customer',
count: {
$sum: 1
}
}
}])
.exec(function(err, result) {
console.log('result:', result);
if (err) {
deferred.reject(err);
return;
};
var customerSiteCountMap = {};
_.each(result, function(obj) {
customerSiteCountMap[obj._id] = obj.count;
})
var retCustomers = _.map(customers, function(customer) {
var ret = customer.toJSON();
ret.sitesCount = customerSiteCountMap[customer._id];
ret.sitesCount = ret.sitesCount ? ret.sitesCount: 0;
return ret;
});
deferred.resolve(retCustomers);
});
return deferred.promise;
}
/**
* List of Customers
*/
exports.paginate = function(req, res) {
req.checkQuery('pageNumber', 'invalid pageNumber').isInt();
req.checkQuery('pageSize', 'invalid pageSize').isInt();
var errors = req.validationErrors(true);
if (errors) {
res.send(errors, 400);
return;
}
var pageNumber = req.query.pageNumber,
pageSize = req.query.pageSize,
type = req.query.type,
callback = function(error, pageCount, customers, itemCount) {
if (error) {
console.error(error);
res.status(500).json({
error: error
});
return;
}
getSiteNum(customers)
.then(function(customersWithSitesCnt) {
res.json({
pageCount: pageCount,
data: customersWithSitesCnt,
count: itemCount
});
}, function(err) {
res.json({
getSiteNumErr: err
}, 400);
});
}
Customer.paginate({
deleteFlag: false
},
pageNumber, pageSize, callback, {
sortBy: '-created',
columns: '_id created logo name brand status industry'
});
};
exports.count = function(req, res, next) {
if (!('count' in req.query)) {
next();
return;
};
Customer.count(function(err, count) {
if (err) {
console.error('customer count error:', err);
return res.status(500).json({
error: 'count the customers error'
});
}
res.json({
count: count
});
return;
});
};
exports.analysis = function(req, res, next) {
console.log('increase:', req.query);
if (!('increase' in req.query)) {
next();
return;
};
req.checkQuery('startDate', 'invalid startDate').isDate();
req.checkQuery('endDate', 'invalid endDate').isDate();
var errors = req.validationErrors(true);
if (errors) {
res.send(errors, 400);
return;
}
Customer.where({
created: {
$gte: req.query.startDate,
$lte: req.query.endDate,
}
}).count(function(err, count) {
if (err) {
console.error('customer analysis error:', err);
return res.status(500).json({
error: 'count the analysis error'
});
}
res.json({
count: count
});
return;
});
return;
};
function getChannelsInfo(customers) {
var deferred = Q.defer();
var jsonObj, channelObj, customersMap = {};
_.each(customers, function(obj) {
jsonObj = obj.toJSON();
jsonObj.channels = [];
customersMap[jsonObj._id] = jsonObj;
})
Channel.find({})
.exec(function(err, channels) {
if (err) {
deferred.reject(err);
return;
};
_.each(channels, function(channel) {
channelObj = _.pick(channel, ['_id', 'name', 'type']);
jsonObj = customersMap[channel.customer];
jsonObj.channels.push(channelObj);
});
deferred.resolve(_.values(customersMap));
});
return deferred.promise;
}
exports.basicInfos = function(req, res, next) {
if (!('basicInfos' in req.query)) {
next();
return;
};
Customer.where({
deleteFlag: false
}).select('_id name brand logo').exec(function(err, customers) {
if (err) {
console.error('customer basicInfos error:', err);
return res.status(500).json({
error: 'count the basicInfos error'
});ba
}
getChannelsInfo(customers)
.then(function(valueArr) {
res.json(valueArr);
}, function(err) {
res.json({
getChannelsInfoErr: err
}, 400);
});
return;
});
};
exports.bindUser = function(req, res, next) {
// because we set our user.provider to local our models/user.js validation will always be true
req.assert('email', 'You must enter a valid email address').isEmail();
req.assert('password', 'Password must be between 8-20 characters long').len(8, 20);
var errors = req.validationErrors();
console.log(1.5, errors);
if (errors) {
return res.status(400).send(errors);
}
console.log(2);
var user = new User(req.body);
user.customer = req.customer;
user.provider = 'local';
user.username = user.email;
user.name = user.email;
user.roles = ['customer'];
user.save(function(err, retUser) {
console.log(3, err);
if (err) {
switch (err.code) {
case 11000:
case 11001:
res.status(400).json([{
msg: 'Username already taken',
param: 'username'
}]);
break;
default:
var modelErrors = [];
if (err.errors) {
for (var x in err.errors) {
modelErrors.push({
param: x,
msg: err.errors[x].message,
value: err.errors[x].value
});
}
res.status(400).json(modelErrors);
}
}
return;
}
res.json(retUser);
});
} |
'use strict';
/*!
* Copyright (c) 2014 Stefan Aichholzer <theaichholzer@gmail.com>
*
* 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.
*/
var salvus = {
/**
* Helper function to extract the properties if more than one is
* being expected to be handled.
*
* @param {String} elementum - The elements which are being read.
* @returns {Array} - Elements which have been found.
* @private
*/
extraho: function Salvus$extraho (elementum) {
var par = elementum.match(/\[([^\]]+)]|\(([^)]+)\)|{([^}]+)}/),
substantia;
if (par) {
substantia = {
semita: elementum.substr(0, elementum.search(/\(|\[|\{/)).split('.'),
elementum: {}
};
par = (par[1] || par[2] || par[3]).split(',');
par.forEach(function(pecunia) {
pecunia = pecunia.trim().split(':');
substantia.elementum[pecunia[0]] = pecunia[1];
});
}
return substantia;
},
/**
* Writes a value to the property. Nested properties will
* result in creating the nested objects and append the property where specified.
*
* @param {String | Array} elementum
* @returns {object} - The modified object with its new properties/value.
*/
noto: function Salvus$noto (elementum) {
if (!elementum) {
return this;
}
var sui = this,
semita,
multiSubstantia;
elementum = Array.isArray(elementum) ? elementum : elementum.split();
elementum.forEach(function(elementi) {
multiSubstantia = salvus.extraho(elementi);
if (multiSubstantia) {
semita = multiSubstantia.semita;
} else {
elementi = elementi.split(':');
semita = elementi[0].split('.');
}
for (var bona=0; bona < semita.length-1; ++bona) {
if (!sui[semita[bona]]) {
sui[semita[bona]] = {};
}
/*
This must be fixed to support multiple definitions of the same object
obj.noto(['name.last', 'name.first'])
Will create a double 'name' and it's not the desired behaviour.
*/
sui = sui[semita[bona]];
}
if (multiSubstantia) {
sui[semita[semita.length-1]] = sui[semita[semita.length-1]] || {};
for (var elemento in multiSubstantia.elementum) {
if (multiSubstantia.elementum.hasOwnProperty(elemento)) {
multiSubstantia.elementum[elemento] = multiSubstantia.elementum[elemento] === 'true'
? true
: multiSubstantia.elementum[elemento] === 'false' ? false : multiSubstantia.elementum[elemento];
sui[semita[semita.length-1]][elemento] = multiSubstantia.elementum[elemento];
}
}
} else {
elementi[1] = elementi[1] === 'true' ? true : elementi[1] === 'false' ? false : elementi[1];
sui[semita[semita.length-1]] = elementi[1];
}
});
return this;
},
/**
* Reads any property's value. Non-existent properties will return
* undefined.
*
* @param {String} elementum - The elements which are being read.
* @param {Boolean} refero - Identify the 'undefined' property trying to be accessed. Defaults to 'false'.
* @param {Boolean} stricto - Only actual values are returned, everything else will be 'undefined'. Defaults to 'false'.
* @param {String} intellego - Prepend this string to the undefined property. Requires 'refero' to be true. Defaults to '!!'.
* @returns {String | undefined} - The found value, 'undefined' or a string describing the 'undefined' property (Requires 'refero' to be true).
*/
lego: function Salvus$lego (elementum, refero, stricto, intellego) {
if (!elementum) {
return undefined;
}
var sui = this,
semita = elementum.split('.'),
valorem;
for (var bona = 0; bona < semita.length; ++bona) {
if (sui[semita[bona]] === null) {
valorem = stricto ? sui[semita[bona]] || false : null;
return valorem === null ? valorem : refero ? (intellego || '!!') + semita[bona] : undefined;
}
if (!stricto && typeof sui[semita[bona]] === 'boolean' && sui[semita[bona]] === false) {
return refero ? (intellego || '!!') + semita[bona] : false;
}
valorem = sui[semita[bona].trim()];
valorem = stricto ? valorem || false : (valorem || valorem === null) ? valorem : false;
if (valorem || valorem === null) {
sui = valorem;
} else {
return (refero) ? (intellego || '!!') + semita[bona] : undefined;
}
}
return valorem;
},
/**
* Removes all properties specified in elementum.
*
* @param {String | Array} elementum - Properties to remove
* @returns {object} - The cleaned object.
* @constructor
*/
erado: function Salvus$erado (elementum) {
if (!elementum) {
return this;
}
return this.noto(elementum).purgo(false, true);
},
/**
* Removes all empty properties -recursively- from the object.
* Properties which values are "undefined" or "null" will also
* be purged, this also includes empty objects and empty arrays.
*
* @param {object} - Passed-in on recursion only.
* @param {boolean} - Used internally to preseve `null` values.
* @returns {object} - The purged object.
*/
purgo: function Salvus$purgo (obj, salvo) {
var sui = obj || this,
isArray,
isEmptyArray,
isObject,
isEmptyObject;
for (var property in sui) {
if (sui.hasOwnProperty(property)) {
isArray = Array.isArray(sui[property]);
isEmptyArray = isArray && sui[property].length === 0;
isObject = !isArray && sui[property] && typeof sui[property] === 'object';
isEmptyObject = isObject && Object.keys(sui[property]).length === 0;
if (isObject && !isEmptyObject) {
salvus.purgo(sui[property], salvo);
} else if (!sui[property] || isEmptyArray || isEmptyObject) {
if (salvo && sui[property] === null) {
continue;
}
delete sui[property];
salvus.purgo(sui, salvo);
}
}
}
return sui;
}
};
module.exports = (function() {
Object.defineProperties(Object.prototype, {
noto: {
configurable: true,
enumerable: false,
value: salvus.noto
},
lego: {
configurable: true,
enumerable: false,
value: salvus.lego
},
erado: {
configurable: true,
enumerable: false,
value: salvus.erado
},
purgo: {
configurable: true,
enumerable: false,
value: salvus.purgo
}
});
})();
|
'use strict';
(function() {
var profileId = document.querySelector('#profile-id') || null;
var profileUsername = document.querySelector('#profile-username') || null;
var profileRepos = document.querySelector('#profile-repos') || null;
var displayName = document.querySelector('#display-name') || null;
var shareButton = document.querySelector('#shareButton') || null;
var poll = document.querySelector('#pollInfo') || null;
var apiUrl = appUrl + '/api/:id';
var shareUrl = appUrl + window.location.pathname;
function updateHtmlElement(data, element, userProperty) {
element.innerHTML = data[userProperty];
}
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('GET', apiUrl, function(data) {
var userObject = JSON.parse(data);
if (userObject.hasOwnProperty('error')) {
document.querySelector("#loginButton").innerHTML = '<a href="/login">Login</a>';
return;
} else {
document.querySelector("#loginButton").innerHTML = '<a href="/logout">Logout</a>'
document.querySelector("#profileLink").innerHTML = '<a href="/profile">Profile</a>'
document.querySelector("#newPollLink").innerHTML = '<a href="/new-poll">Create Poll</a>'
if (poll !== null) {
var output = "<div class='radio'>"
output += "<label><input type='radio' name='optradio' id='other' > Other </label> "
output += "<input type='text' name='optradio' />"
output += "</div>"
$('#pollEnding').prepend(output);
}
if (shareButton !== null) {
var shareOutput = '<a href="mailto:?subject=Check%20Out%20This%20Poll&body=Check%20Out%20This%20Poll%0A' + shareUrl + '"><i id="social-email" class="fa fa-envelope-o fa-2x" alt="Email Poll!" title="Email Poll!"></i></a>'
shareOutput += "<a href='https://www.facebook.com/sharer.php?u=" + shareUrl + "&t=Check out this poll!'><i id='social-fb' class='fa fa-facebook fa-2x' alt='Share poll on Facebook!' title='Share poll on Facebook!'></i></a>"
shareOutput += "<a href='https://twitter.com/share?text=Check out this poll!&url=" + shareUrl + "'><i id='social-tw' class='fa fa-twitter fa-2x' alt='Share poll on Twitter!' title='Share poll on Twitter!'></i></a>"
document.querySelector('#shareButton').innerHTML = shareOutput;
}
if (displayName !== null) {
updateHtmlElement(userObject, displayName, 'displayName');
}
if (profileId !== null) {
updateHtmlElement(userObject, profileId, 'id');
}
if (profileUsername !== null) {
updateHtmlElement(userObject, profileUsername, 'username');
}
if (profileRepos !== null) {
updateHtmlElement(userObject, profileRepos, 'publicRepos');
}
}
}))
})(); |
'use strict';
/*global SVG */
SVG.Longhole = SVG.invent({
create: 'g',
inherit: SVG.G,
extend: {
build: function(bits) {
var longholesPartsTC = this.doc().use('TC_Loading_Longholes_Parts', 'images/master.svg');
this.longholesTCLegs1 = this.doc().use('TC_Loading_Longholes_Legs_1', 'images/master.svg');
this.longholesTCLegs2 = this.doc().use('TC_Loading_Longholes_Legs_2', 'images/master.svg');
this.longholesTCLegs3 = this.doc().use('TC_Loading_Longholes_Legs_3', 'images/master.svg');
this.longholesTCLegs4 = this.doc().use('TC_Loading_Longholes_Legs_4', 'images/master.svg');
this.bits = bits;
this.bitsToX = 8.8;
this.bitsToY = -46.9;
this.t = 2000;
this.forwardPathMaster = [
5.4 // dynamite 1
, 7.3 // dynamite 2
];
this.forwardPath = [];
var longholesTCMan = this.doc()
.group()
.add(longholesPartsTC)
.add(this.longholesTCLegs1)
.add(this.longholesTCLegs2)
.add(this.longholesTCLegs3)
.add(this.longholesTCLegs4)
;
this.clip = this.doc()
.rect(50, 20)
.move(317, 480)
;
this.add(this.clip);
this.clipWith(this.clip);
this.body = this.doc()
.group()
.add(longholesTCMan)
;
this.add(this.body);
this.reset();
return this;
}
}
, construct: {
longhole: function(bits) {
return this.put(new SVG.Longhole).build(bits);
}
}
});
SVG.extend(SVG.Longhole, {
setForwardPathMaster: function(path) {
this.forwardPathMaster = path;
this.reset();
return this;
}
, setForwardPath: function() {
this.forwardPath = this.forwardPathMaster.slice();
return this;
}
, moveClip: function(x, y) {
this.clip.move(x, y);
return this;
}
, setBitsToX: function(n) {
this.bitsToX = n;
return this;
}
, setBitsToY: function(n) {
this.bitsToY = n;
return this;
}
, reset: function() {
this.setForwardPath();
this.goMax = this.forwardPath.length;
this.goCounter = 0;
this.bitIndex = 0;
this.showHoles();
return this;
}
, forward: function() {
return this.body
.animate(this.t)
.dx(this.forwardPath.shift())
;
}
, backward: function() {
return this.body
.animate(5000)
.x(0)
;
}
, holeIn: function() {
var bit = this.bits.get(this.bitIndex);
this.bitIndex++;
return bit
.animate(this.t)
.y(this.bitsToY)
.x(this.bitsToX)
;
}
, showHoles: function() {
this.bits.each(function() {
this.move(0, 0);
});
return this.bits.opacity(1);
}
, hideHoles: function() {
return this.bits.animate(1000, '>', 2000).opacity(0);
}
, isEnded: function() {
return this.goCounter > this.goMax;
}
, go: function() {
var self = this;
self.holeIn().after(function(){
self.goCounter++;
if (self.isEnded()) {
self.backward().after(function(){
self.hideHoles().after(function(){
self.reset();
self.go();
});
});
}
else {
self.forward().after(function(){
self.go();
});
}
});
}
});
|
export { default } from 'ember-buffered-proxy-component/components/buffered-proxy';
|
import { validator, buildValidations } from 'ember-cp-validations';
export default buildValidations({
name: validator('presence', true),
email: [
validator('format', { type: 'email' })
],
category: validator('presence', true)
});
|
'use strict';
angular.module('pets').directive('qr',[ '$http',
function($http) {
return {
templateUrl: '/modules/pets/views/qr.client.view.html',
restrict: 'E',
replace: true,
scope: {
pet: '='
},
link: function postLink(scope, element, attr) {
element.bind('click', function() {
var popupWin = window.open('', '_blank', 'width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><head></head><body onload="window.print()">' + element.html() + '</html>');
popupWin.document.close();
});
scope.svg = "";
$http.get('/qr/' + scope.pet.slug).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
scope.svg = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('ERROR');
});
}
};
}
]);
(function (angular) {
function printDirective() {
var printSection = document.getElementById('printSection');
// if there is no printing section, create one
if (!printSection) {
printSection = document.createElement('div');
printSection.id = 'printSection';
document.body.appendChild(printSection);
}
function link(scope, element, attrs) {
element.on('click', function () {
var elemToPrint = document.getElementById(attrs.printElementId);
if (elemToPrint) {
printElement(elemToPrint);
}
});
window.onafterprint = function () {
// clean the print section before adding new content
printSection.innerHTML = '';
}
}
function printElement(elem) {
// clones the element you want to print
var domClone = elem.cloneNode(true);
printSection.appendChild(domClone);
window.print();
}
return {
link: link,
restrict: 'A'
};
}
angular.module('core').directive('ngPrint', [printDirective]);
}(window.angular));;
|
(function() {
$(function() {
var offlineMode, time;
time = function() {
var d, utc;
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * 6));
};
offlineMode = function() {
var el;
el = document.getElementById("widlib");
if ((typeof ltie !== "undefined" && ltie !== null) || !client.loaded) {
return el.innerHTML = '<a href="http://gurman-ufa.ru" target="_blank"><img src="/images/offline.jpg"></a>';
}
};
setTimeout(function() {
return offlineMode();
}, 1500);
if (typeof ltie !== "undefined" && ltie !== null) {
return offlineMode();
} else {
return window.client = new Widlib.Client({
fallback: "/widlib",
templates: JST,
el: $('#widlib'),
firstPage: function() {
var h;
h = time().getHours();
if (h >= 10 && h < 21) {
return "start";
} else {
return "sleep";
}
},
pages: {
start: {
onBind: function() {
return this.app.loaded = true;
}
},
sleep: {
"extends": "start"
},
main: {
"extends": "common"
},
section: {
"extends": "plusminus",
local: ["setSection"],
setSection: function() {
this.sectionID = this.session.submits.main || this.session.submits.start;
this.sectionName = this.session.data.sections[this.sectionID];
return this.currentSection = _(this.session.data.products).where({
section: this.sectionID
});
},
onEnter: function() {
this.extendsProducts();
this.setSection();
return true;
}
},
cart: {
"extends": "plusminus",
local: ["cart"],
onEnter: function() {
this.sumtrigger = 0;
this.extendsProducts();
return this.cart()[0];
}
},
form: {
"extends": "common",
local: ["submitForm"],
remote: ["onSubmitServer"],
submitForm: function() {
return $("form[wl-submit]").submit();
},
onSubmit: function(options) {
if (options.to !== "finish") {
return options.to;
}
if (!options.data.form.address || !options.data.form.phone) {
return false;
}
return Q(this.onSubmitServer(_(options.data.form).extend({
products: this.cart()
}))).then(function() {
return options.to;
});
}
},
finish: {
"extends": "common",
local: ['clear'],
onLeave: function() {
this.clear();
return true;
},
clear: function() {
var _this = this;
return _(this.session.data.products).each(function(product) {
return product.quantity = 0;
});
}
},
details: {
"extends": "common",
backStack: false,
onEnter: function() {
console.log("");
return this.product = _(this.session.data.products).findWhere({
id: this.session.submits.detailsShow
});
}
},
info: {
"extends": "common",
backStack: false
},
common: {
local: ['sum', 'sumStr', 'cart'],
onBind: function() {
rivets.bind(this.session.el, this);
if (_(['section', 'cart', 'form', 'finish']).contains(this.name)) {
return yaCounter23446726.reachGoal(this.name, {
order_price: this.sum(),
currency: "RUR",
exchange_rate: 1,
goods: this.cart()
});
}
},
sum: function(products) {
if (products == null) {
products = this.session.data.products;
}
return _(products).reduce(function(sum, product) {
return sum + product.quantity * product.price;
}, 0);
},
sumStr: function() {
var ret;
ret = this.sum();
if (ret > 0) {
return "" + ret + " руб";
} else {
return "";
}
},
cart: function() {
return _(this.session.data.products).filter(function(product) {
return product.quantity;
});
}
},
plusminus: {
"extends": "common",
local: ['extendsProducts'],
extendsProducts: function() {
var _this = this;
this.sumtrigger = 0;
return _(this.session.data.products).each(function(product) {
product.plus = function(event) {
product.quantity++;
event.preventDefault();
return _this.sumtrigger++;
};
product.minus = function(evetn) {
if (product.quantity) {
product.quantity--;
}
event.preventDefault();
return _this.sumtrigger++;
};
product.smallImage = function() {
return "/images/35/" + product.id + ".png";
};
product.bigImage = function() {
return "/images/200-90/" + product.id + ".png";
};
return product.quantity || (product.quantity = 0);
});
},
onEnter: function() {
this.extendsProducts();
return true;
}
}
},
data: {
sections: {
pancakes: 'Блины',
rolls: 'Роллы',
salads: 'Салаты',
hot: 'Горячее',
desserts: 'Десерты',
beverages: 'Напитки'
},
products: [
{
id: 'wo',
section: 'pancakes',
price: 35,
name: 'Блины без начинки'
}, {
id: 'wquark',
section: 'pancakes',
price: 50,
name: 'Блины с творогом'
}, {
id: 'wchicken',
section: 'pancakes',
price: 65,
name: 'Блины с курицей'
}, {
id: 'wmeat',
section: 'pancakes',
price: 70,
name: 'Блины с мясом'
}, {
id: 'california',
section: 'rolls',
price: 250,
name: 'Калифорния'
}, {
id: 'canada',
section: 'rolls',
price: 270,
name: 'Канада'
}, {
id: 'philadelphia',
section: 'rolls',
price: 250,
name: 'Филадельфия'
}, {
id: 'kunsei',
section: 'rolls',
price: 200,
name: 'Кунсей'
}, {
id: 'olivier',
section: 'salads',
price: 85,
name: 'Оливье'
}, {
id: 'herring',
section: 'salads',
price: 70,
name: 'Сельдь под шубой'
}, {
id: 'ceasar',
section: 'salads',
price: 140,
name: 'Цезарь с курицей'
}, {
id: 'greek',
section: 'salads',
price: 120,
name: 'Греческий'
}, {
id: 'pascarbonara',
section: 'hot',
price: 170,
name: 'Паста Карбонара'
}, {
id: 'passalmon',
section: 'hot',
price: 195,
name: 'Паста с лососем'
}, {
id: 'wokchicken',
section: 'hot',
price: 140,
name: 'Лапша китайская с курицей'
}, {
id: 'wokveggie',
section: 'hot',
price: 110,
name: 'Лапша китайская с овощами'
}, {
id: 'maminwhole',
section: 'desserts',
price: 550,
name: 'Торт "Мамин" целиком'
}, {
id: 'maminpiece',
section: 'desserts',
price: 105,
name: 'Торт "Мамин" кусочек'
}, {
id: 'honeywhole',
section: 'desserts',
price: 520,
name: 'Торт "Медовый" целиком'
}, {
id: 'honeypiece',
section: 'desserts',
price: 80,
name: 'Торт "Медовый" кусочек'
}, {
id: 'cowberry',
section: 'beverages',
price: 69,
name: 'Брусничный морс 0,5л'
}, {
id: 'cranberry',
section: 'beverages',
price: 69,
name: 'Клюквенный морс 0,5л'
}, {
id: 'cherry',
section: 'beverages',
price: 69,
name: 'Вишневый морс 0,5л'
}, {
id: 'mojito',
section: 'beverages',
price: 69,
name: 'Мохито (б/а) 0,33л'
}
]
}
});
}
});
}).call(this);
|
'use strict';
/* Controllers */
(function(module) {
module.controller('AboutCtrl', ['$timeout', '$scope', function($timeout, $scope) {
}]);
})(window.CtrlModule); |
export default function sleep (ms = 10) {
return new Promise((resolve, reject) => setTimeout(resolve, ms))
}
|
(function(){
'use strict';
angular
.module('events.auth')
.config(FacebookConfig);
FacebookConfig.$inject = ['FacebookProvider'];
function FacebookConfig (FacebookProvider) {
FacebookProvider.setSdkVersion('v2.3');
FacebookProvider.init('590352944439692');
}
})();
|
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "cs",
likelySubtags: {
cs: "cs-Latn-CZ"
},
identity: {
language: "cs"
},
territory: "CZ",
numbers: {
currencies: {
ADP: {
displayName: "andorrská peseta",
"displayName-count-one": "andorrská peseta",
"displayName-count-few": "andorrské pesety",
"displayName-count-many": "andorrské pesety",
"displayName-count-other": "andorrských peset",
symbol: "ADP"
},
AED: {
displayName: "SAE dirham",
"displayName-count-one": "SAE dirham",
"displayName-count-few": "SAE dirhamy",
"displayName-count-many": "SAE dirhamu",
"displayName-count-other": "SAE dirhamů",
symbol: "AED"
},
AFA: {
displayName: "afghánský afghán (1927–2002)",
"displayName-count-one": "afghánský afghán (1927–2002)",
"displayName-count-few": "afghánské afghány (1927–2002)",
"displayName-count-many": "afghánského afghánu (1927–2002)",
"displayName-count-other": "afghánských afghánů (1927–2002)",
symbol: "AFA"
},
AFN: {
displayName: "afghánský afghán",
"displayName-count-one": "afghánský afghán",
"displayName-count-few": "afghánské afghány",
"displayName-count-many": "afghánského afghánu",
"displayName-count-other": "afghánských afghánů",
symbol: "AFN"
},
ALK: {
displayName: "albánský lek (1946–1965)",
"displayName-count-one": "albánský lek (1946–1965)",
"displayName-count-few": "albánské leky (1946–1965)",
"displayName-count-many": "albánského leku (1946–1965)",
"displayName-count-other": "albánských leků (1946–1965)",
symbol: "ALK"
},
ALL: {
displayName: "albánský lek",
"displayName-count-one": "albánský lek",
"displayName-count-few": "albánské leky",
"displayName-count-many": "albánského leku",
"displayName-count-other": "albánských leků",
symbol: "ALL"
},
AMD: {
displayName: "arménský dram",
"displayName-count-one": "arménský dram",
"displayName-count-few": "arménské dramy",
"displayName-count-many": "arménského dramu",
"displayName-count-other": "arménských dramů",
symbol: "AMD"
},
ANG: {
displayName: "nizozemskoantilský gulden",
"displayName-count-one": "nizozemskoantilský gulden",
"displayName-count-few": "nizozemskoantilské guldeny",
"displayName-count-many": "nizozemskoantilského guldenu",
"displayName-count-other": "nizozemskoantilských guldenů",
symbol: "ANG"
},
AOA: {
displayName: "angolská kwanza",
"displayName-count-one": "angolská kwanza",
"displayName-count-few": "angolské kwanzy",
"displayName-count-many": "angolské kwanzy",
"displayName-count-other": "angolských kwanz",
symbol: "AOA",
"symbol-alt-narrow": "Kz"
},
AOK: {
displayName: "angolská kwanza (1977–1991)",
"displayName-count-one": "angolská kwanza (1977–1991)",
"displayName-count-few": "angolské kwanzy (1977–1991)",
"displayName-count-many": "angolské kwanzy (1977–1991)",
"displayName-count-other": "angolských kwanz (1977–1991)",
symbol: "AOK"
},
AON: {
displayName: "angolská kwanza (1990–2000)",
"displayName-count-one": "angolská kwanza (1990–2000)",
"displayName-count-few": "angolské kwanzy (1990–2000)",
"displayName-count-many": "angolské kwanzy (1990–2000)",
"displayName-count-other": "angolských kwanz (1990–2000)",
symbol: "AON"
},
AOR: {
displayName: "angolská kwanza (1995–1999)",
"displayName-count-one": "angolská nový kwanza (1995–1999)",
"displayName-count-few": "angolská kwanza (1995–1999)",
"displayName-count-many": "angolské kwanzy (1995–1999)",
"displayName-count-other": "angolských kwanz (1995–1999)",
symbol: "AOR"
},
ARA: {
displayName: "argentinský austral",
"displayName-count-one": "argentinský austral",
"displayName-count-few": "argentinské australy",
"displayName-count-many": "argentinského australu",
"displayName-count-other": "argentinských australů",
symbol: "ARA"
},
ARL: {
displayName: "argentinské peso ley (1970–1983)",
"displayName-count-one": "argentinské peso ley (1970–1983)",
"displayName-count-few": "argentinská pesa ley (1970–1983)",
"displayName-count-many": "argentinského pesa ley (1970–1983)",
"displayName-count-other": "argentinských pes ley (1970–1983)",
symbol: "ARL"
},
ARM: {
displayName: "argentinské peso (1881–1970)",
"displayName-count-one": "argentinské peso (1881–1970)",
"displayName-count-few": "argentinská pesa (1881–1970)",
"displayName-count-many": "argentinského pesa (1881–1970)",
"displayName-count-other": "argentinských pes (1881–1970)",
symbol: "ARM"
},
ARP: {
displayName: "argentinské peso (1983–1985)",
"displayName-count-one": "argentinské peso (1983–1985)",
"displayName-count-few": "argentinská pesa (1983–1985)",
"displayName-count-many": "argentinského pesa (1983–1985)",
"displayName-count-other": "argentinských pes (1983–1985)",
symbol: "ARP"
},
ARS: {
displayName: "argentinské peso",
"displayName-count-one": "argentinské peso",
"displayName-count-few": "argentinská pesa",
"displayName-count-many": "argentinského pesa",
"displayName-count-other": "argentinských pes",
symbol: "ARS",
"symbol-alt-narrow": "$"
},
ATS: {
displayName: "rakouský šilink",
"displayName-count-one": "rakouský šilink",
"displayName-count-few": "rakouské šilinky",
"displayName-count-many": "rakouského šilinku",
"displayName-count-other": "rakouských šilinků",
symbol: "ATS"
},
AUD: {
displayName: "australský dolar",
"displayName-count-one": "australský dolar",
"displayName-count-few": "australské dolary",
"displayName-count-many": "australského dolaru",
"displayName-count-other": "australských dolarů",
symbol: "AU$",
"symbol-alt-narrow": "$"
},
AWG: {
displayName: "arubský zlatý",
"displayName-count-one": "arubský zlatý",
"displayName-count-few": "arubské zlaté",
"displayName-count-many": "arubského zlatého",
"displayName-count-other": "arubských zlatých",
symbol: "AWG"
},
AZM: {
displayName: "ázerbájdžánský manat (1993–2006)",
"displayName-count-one": "ázerbájdžánský manat (1993–2006)",
"displayName-count-few": "ázerbájdžánské manaty (1993–2006)",
"displayName-count-many": "ázerbájdžánského manatu (1993–2006)",
"displayName-count-other": "ázerbájdžánských manatů (1993–2006)",
symbol: "AZM"
},
AZN: {
displayName: "ázerbájdžánský manat",
"displayName-count-one": "ázerbájdžánský manat",
"displayName-count-few": "ázerbájdžánské manaty",
"displayName-count-many": "ázerbájdžánského manatu",
"displayName-count-other": "ázerbájdžánských manatů",
symbol: "AZN"
},
BAD: {
displayName: "bosenský dinár (1992–1994)",
"displayName-count-one": "bosenský dinár (1992–1994)",
"displayName-count-few": "bosenské dináry (1992–1994)",
"displayName-count-many": "bosenského dináru (1992–1994)",
"displayName-count-other": "bosenských dinárů (1992–1994)",
symbol: "BAD"
},
BAM: {
displayName: "bosenská konvertibilní marka",
"displayName-count-one": "bosenská konvertibilní marka",
"displayName-count-few": "bosenské konvertibilní marky",
"displayName-count-many": "bosenské konvertibilní marky",
"displayName-count-other": "bosenských konvertibilních marek",
symbol: "BAM",
"symbol-alt-narrow": "KM"
},
BAN: {
displayName: "bosenský nový dinár (1994–1997)",
"displayName-count-one": "bosenský nový dinár (1994–1997)",
"displayName-count-few": "bosenské nové dináry (1994–1997)",
"displayName-count-many": "bosenského nového dináru (1994–1997)",
"displayName-count-other": "bosenských nových dinárů (1994–1997)",
symbol: "BAN"
},
BBD: {
displayName: "barbadoský dolar",
"displayName-count-one": "barbadoský dolar",
"displayName-count-few": "barbadoské dolary",
"displayName-count-many": "barbadoského dolaru",
"displayName-count-other": "barbadoských dolarů",
symbol: "BBD",
"symbol-alt-narrow": "$"
},
BDT: {
displayName: "bangladéšská taka",
"displayName-count-one": "bangladéšská taka",
"displayName-count-few": "bangladéšské taky",
"displayName-count-many": "bangladéšské taky",
"displayName-count-other": "bangladéšských tak",
symbol: "BDT",
"symbol-alt-narrow": "৳"
},
BEC: {
displayName: "belgický konvertibilní frank",
"displayName-count-one": "belgický konvertibilní frank",
"displayName-count-few": "belgické konvertibilní franky",
"displayName-count-many": "belgického konvertibilního franku",
"displayName-count-other": "belgických konvertibilních franků",
symbol: "BEC"
},
BEF: {
displayName: "belgický frank",
"displayName-count-one": "belgický frank",
"displayName-count-few": "belgické franky",
"displayName-count-many": "belgického franku",
"displayName-count-other": "belgických franků",
symbol: "BEF"
},
BEL: {
displayName: "belgický finanční frank",
"displayName-count-one": "belgický finanční frank",
"displayName-count-few": "belgické finanční franky",
"displayName-count-many": "belgického finančního franku",
"displayName-count-other": "belgických finančních franků",
symbol: "BEL"
},
BGL: {
displayName: "BGL",
symbol: "BGL"
},
BGM: {
displayName: "BGM",
symbol: "BGM"
},
BGN: {
displayName: "bulharský lev",
"displayName-count-one": "bulharský lev",
"displayName-count-few": "bulharské lvy",
"displayName-count-many": "bulharského lva",
"displayName-count-other": "bulharských lvů",
symbol: "BGN"
},
BGO: {
displayName: "bulharský lev (1879–1952)",
"displayName-count-one": "bulharský lev (1879–1952)",
"displayName-count-few": "bulharské leva (1879–1952)",
"displayName-count-many": "bulharského leva (1879–1952)",
"displayName-count-other": "bulharských leva (1879–1952)",
symbol: "BGO"
},
BHD: {
displayName: "bahrajnský dinár",
"displayName-count-one": "bahrajnský dinár",
"displayName-count-few": "bahrajnské dináry",
"displayName-count-many": "bahrajnského dináru",
"displayName-count-other": "bahrajnských dinárů",
symbol: "BHD"
},
BIF: {
displayName: "burundský frank",
"displayName-count-one": "burundský frank",
"displayName-count-few": "burundské franky",
"displayName-count-many": "burundského franku",
"displayName-count-other": "burundských franků",
symbol: "BIF"
},
BMD: {
displayName: "bermudský dolar",
"displayName-count-one": "bermudský dolar",
"displayName-count-few": "bermudské dolary",
"displayName-count-many": "bermudského dolaru",
"displayName-count-other": "bermudských dolarů",
symbol: "BMD",
"symbol-alt-narrow": "$"
},
BND: {
displayName: "brunejský dolar",
"displayName-count-one": "brunejský dolar",
"displayName-count-few": "brunejské dolary",
"displayName-count-many": "brunejského dolaru",
"displayName-count-other": "brunejských dolarů",
symbol: "BND",
"symbol-alt-narrow": "$"
},
BOB: {
displayName: "bolivijský boliviano",
"displayName-count-one": "bolivijský boliviano",
"displayName-count-few": "bolivijské bolivianos",
"displayName-count-many": "bolivijského boliviana",
"displayName-count-other": "bolivijských bolivianos",
symbol: "BOB",
"symbol-alt-narrow": "Bs"
},
BOL: {
displayName: "bolivijský boliviano (1863–1963)",
"displayName-count-one": "bolivijský boliviano (1863–1963)",
"displayName-count-few": "bolivijské bolivianos (1863–1963)",
"displayName-count-many": "bolivijského boliviana (1863–1963)",
"displayName-count-other": "bolivijských bolivianos (1863–1963)",
symbol: "BOL"
},
BOP: {
displayName: "bolivijské peso",
"displayName-count-one": "bolivijské peso",
"displayName-count-few": "bolivijská pesa",
"displayName-count-many": "bolivijského pesa",
"displayName-count-other": "bolivijských pes",
symbol: "BOP"
},
BOV: {
displayName: "bolivijský mvdol",
"displayName-count-one": "bolivijský mvdol",
"displayName-count-few": "bolivijské mvdoly",
"displayName-count-many": "bolivijského mvdolu",
"displayName-count-other": "bolivijských mvdolů",
symbol: "BOV"
},
BRB: {
displayName: "brazilské nové cruzeiro (1967–1986)",
"displayName-count-one": "brazilské nové cruzeiro (1967–1986)",
"displayName-count-few": "brazilská nová cruzeira (1967–1986)",
"displayName-count-many": "brazilského nového cruzeira (1967–1986)",
"displayName-count-other": "brazilských nových cruzeir (1967–1986)",
symbol: "BRB"
},
BRC: {
displayName: "brazilské cruzado (1986–1989)",
"displayName-count-one": "brazilské cruzado (1986–1989)",
"displayName-count-few": "brazilská cruzada (1986–1989)",
"displayName-count-many": "brazilského cruzada (1986–1989)",
"displayName-count-other": "brazilských cruzad (1986–1989)",
symbol: "BRC"
},
BRE: {
displayName: "brazilské cruzeiro (1990–1993)",
"displayName-count-one": "brazilské cruzeiro (1990–1993)",
"displayName-count-few": "brazilská cruzeira (1990–1993)",
"displayName-count-many": "brazilského cruzeira (1990–1993)",
"displayName-count-other": "brazilských cruzeir (1990–1993)",
symbol: "BRE"
},
BRL: {
displayName: "brazilský real",
"displayName-count-one": "brazilský real",
"displayName-count-few": "brazilské realy",
"displayName-count-many": "brazilského realu",
"displayName-count-other": "brazilských realů",
symbol: "R$",
"symbol-alt-narrow": "R$"
},
BRN: {
displayName: "brazilské nové cruzado (1989–1990)",
"displayName-count-one": "brazilské nové cruzado (1989–1990)",
"displayName-count-few": "brazilská nová cruzada (1989–1990)",
"displayName-count-many": "brazilského nového cruzada (1989–1990)",
"displayName-count-other": "brazilských nových cruzad (1989–1990)",
symbol: "BRN"
},
BRR: {
displayName: "brazilské cruzeiro (1993–1994)",
"displayName-count-one": "brazilské cruzeiro (1993–1994)",
"displayName-count-few": "brazilská cruzeira (1993–1994)",
"displayName-count-many": "brazilského cruzeira (1993–1994)",
"displayName-count-other": "brazilských cruzeir (1993–1994)",
symbol: "BRR"
},
BRZ: {
displayName: "brazilské cruzeiro (1942–1967)",
"displayName-count-one": "brazilské cruzeiro (1942–1967)",
"displayName-count-few": "brazilská cruzeira (1942–1967)",
"displayName-count-many": "brazilského cruzeira (1942–1967)",
"displayName-count-other": "brazilských cruzeir (1942–1967)",
symbol: "BRZ"
},
BSD: {
displayName: "bahamský dolar",
"displayName-count-one": "bahamský dolar",
"displayName-count-few": "bahamské dolary",
"displayName-count-many": "bahamského dolaru",
"displayName-count-other": "bahamských dolarů",
symbol: "BSD",
"symbol-alt-narrow": "$"
},
BTN: {
displayName: "bhútánský ngultrum",
"displayName-count-one": "bhútánský ngultrum",
"displayName-count-few": "bhútánské ngultrumy",
"displayName-count-many": "bhútánského ngultrumu",
"displayName-count-other": "bhútánských ngultrumů",
symbol: "BTN"
},
BUK: {
displayName: "barmský kyat",
"displayName-count-one": "barmský kyat",
"displayName-count-few": "barmské kyaty",
"displayName-count-many": "barmského kyatu",
"displayName-count-other": "barmských kyatů",
symbol: "BUK"
},
BWP: {
displayName: "botswanská pula",
"displayName-count-one": "botswanská pula",
"displayName-count-few": "botswanské puly",
"displayName-count-many": "botswanské puly",
"displayName-count-other": "botswanských pul",
symbol: "BWP",
"symbol-alt-narrow": "P"
},
BYB: {
displayName: "běloruský rubl (1994–1999)",
"displayName-count-one": "běloruský rubl (1994–1999)",
"displayName-count-few": "běloruské rubly (1994–1999)",
"displayName-count-many": "běloruského rublu (1994–1999)",
"displayName-count-other": "běloruských rublů (1994–1999)",
symbol: "BYB"
},
BYN: {
displayName: "běloruský rubl",
"displayName-count-one": "běloruský rubl",
"displayName-count-few": "běloruské rubly",
"displayName-count-many": "běloruského rublu",
"displayName-count-other": "běloruských rublů",
symbol: "BYN",
"symbol-alt-narrow": "р."
},
BYR: {
displayName: "běloruský rubl (2000–2016)",
"displayName-count-one": "běloruský rubl (2000–2016)",
"displayName-count-few": "běloruské rubly (2000–2016)",
"displayName-count-many": "běloruského rublu (2000–2016)",
"displayName-count-other": "běloruských rublů (2000–2016)",
symbol: "BYR"
},
BZD: {
displayName: "belizský dolar",
"displayName-count-one": "belizský dolar",
"displayName-count-few": "belizské dolary",
"displayName-count-many": "belizského dolaru",
"displayName-count-other": "belizských dolarů",
symbol: "BZD",
"symbol-alt-narrow": "$"
},
CAD: {
displayName: "kanadský dolar",
"displayName-count-one": "kanadský dolar",
"displayName-count-few": "kanadské dolary",
"displayName-count-many": "kanadského dolaru",
"displayName-count-other": "kanadských dolarů",
symbol: "CA$",
"symbol-alt-narrow": "$"
},
CDF: {
displayName: "konžský frank",
"displayName-count-one": "konžský frank",
"displayName-count-few": "konžské franky",
"displayName-count-many": "konžského franku",
"displayName-count-other": "konžských franků",
symbol: "CDF"
},
CHE: {
displayName: "švýcarské WIR-euro",
"displayName-count-one": "švýcarské WIR-euro",
"displayName-count-few": "švýcarská WIR-eura",
"displayName-count-many": "švýcarského WIR-eura",
"displayName-count-other": "švýcarských WIR-eur",
symbol: "CHE"
},
CHF: {
displayName: "švýcarský frank",
"displayName-count-one": "švýcarský frank",
"displayName-count-few": "švýcarské franky",
"displayName-count-many": "švýcarského franku",
"displayName-count-other": "švýcarských franků",
symbol: "CHF"
},
CHW: {
displayName: "švýcarský WIR-frank",
"displayName-count-one": "švýcarský WIR-frank",
"displayName-count-few": "švýcarské WIR-franky",
"displayName-count-many": "švýcarského WIR-franku",
"displayName-count-other": "švýcarských WIR-franků",
symbol: "CHW"
},
CLE: {
displayName: "chilské escudo",
"displayName-count-one": "chilské escudo",
"displayName-count-few": "chilská escuda",
"displayName-count-many": "chilského escuda",
"displayName-count-other": "chilských escud",
symbol: "CLE"
},
CLF: {
displayName: "chilská účetní jednotka (UF)",
"displayName-count-one": "chilská účetní jednotka (UF)",
"displayName-count-few": "chilské účetní jednotky (UF)",
"displayName-count-many": "chilské účetní jednotky (UF)",
"displayName-count-other": "chilských účetních jednotek (UF)",
symbol: "CLF"
},
CLP: {
displayName: "chilské peso",
"displayName-count-one": "chilské peso",
"displayName-count-few": "chilská pesa",
"displayName-count-many": "chilského pesa",
"displayName-count-other": "chilských pes",
symbol: "CLP",
"symbol-alt-narrow": "$"
},
CNY: {
displayName: "čínský jüan",
"displayName-count-one": "čínský jüan",
"displayName-count-few": "čínské jüany",
"displayName-count-many": "čínského jüanu",
"displayName-count-other": "čínských jüanů",
symbol: "CN¥",
"symbol-alt-narrow": "¥"
},
COP: {
displayName: "kolumbijské peso",
"displayName-count-one": "kolumbijské peso",
"displayName-count-few": "kolumbijská pesa",
"displayName-count-many": "kolumbijského pesa",
"displayName-count-other": "kolumbijských pes",
symbol: "COP",
"symbol-alt-narrow": "$"
},
COU: {
displayName: "kolumbijská jednotka reálné hodnoty",
"displayName-count-one": "kolumbijská jednotka reálné hodnoty",
"displayName-count-few": "kolumbijské jednotky reálné hodnoty",
"displayName-count-many": "kolumbijské jednotky reálné hodnoty",
"displayName-count-other": "kolumbijských jednotek reálné hodnoty",
symbol: "COU"
},
CRC: {
displayName: "kostarický colón",
"displayName-count-one": "kostarický colón",
"displayName-count-few": "kostarické colóny",
"displayName-count-many": "kostarického colónu",
"displayName-count-other": "kostarických colónů",
symbol: "CRC",
"symbol-alt-narrow": "₡"
},
CSD: {
displayName: "srbský dinár (2002–2006)",
"displayName-count-one": "srbský dinár (2002–2006)",
"displayName-count-few": "srbské dináry (2002–2006)",
"displayName-count-many": "srbského dináru (2002–2006)",
"displayName-count-other": "srbských dinárů (2002–2006)",
symbol: "CSD"
},
CSK: {
displayName: "československá koruna",
"displayName-count-one": "československá koruna",
"displayName-count-few": "československé koruny",
"displayName-count-many": "československé koruny",
"displayName-count-other": "československých korun",
symbol: "Kčs"
},
CUC: {
displayName: "kubánské konvertibilní peso",
"displayName-count-one": "kubánské konvertibilní peso",
"displayName-count-few": "kubánská konvertibilní pesa",
"displayName-count-many": "kubánského konvertibilního pesa",
"displayName-count-other": "kubánských konvertibilních pes",
symbol: "CUC",
"symbol-alt-narrow": "$"
},
CUP: {
displayName: "kubánské peso",
"displayName-count-one": "kubánské peso",
"displayName-count-few": "kubánská pesa",
"displayName-count-many": "kubánského pesa",
"displayName-count-other": "kubánských pes",
symbol: "CUP",
"symbol-alt-narrow": "$"
},
CVE: {
displayName: "kapverdské escudo",
"displayName-count-one": "kapverdské escudo",
"displayName-count-few": "kapverdská escuda",
"displayName-count-many": "kapverdského escuda",
"displayName-count-other": "kapverdských escud",
symbol: "CVE"
},
CYP: {
displayName: "kyperská libra",
"displayName-count-one": "kyperská libra",
"displayName-count-few": "kyperské libry",
"displayName-count-many": "kyperské libry",
"displayName-count-other": "kyperských liber",
symbol: "CYP"
},
CZK: {
displayName: "česká koruna",
"displayName-count-one": "česká koruna",
"displayName-count-few": "české koruny",
"displayName-count-many": "české koruny",
"displayName-count-other": "českých korun",
symbol: "Kč",
"symbol-alt-narrow": "Kč"
},
DDM: {
displayName: "východoněmecká marka",
"displayName-count-one": "východoněmecká marka",
"displayName-count-few": "východoněmecké marky",
"displayName-count-many": "východoněmecké marky",
"displayName-count-other": "východoněmeckých marek",
symbol: "DDM"
},
DEM: {
displayName: "německá marka",
"displayName-count-one": "německá marka",
"displayName-count-few": "německé marky",
"displayName-count-many": "německé marky",
"displayName-count-other": "německých marek",
symbol: "DEM"
},
DJF: {
displayName: "džibutský frank",
"displayName-count-one": "džibutský frank",
"displayName-count-few": "džibutské franky",
"displayName-count-many": "džibutského franku",
"displayName-count-other": "džibutských franků",
symbol: "DJF"
},
DKK: {
displayName: "dánská koruna",
"displayName-count-one": "dánská koruna",
"displayName-count-few": "dánské koruny",
"displayName-count-many": "dánské koruny",
"displayName-count-other": "dánských korun",
symbol: "DKK",
"symbol-alt-narrow": "kr"
},
DOP: {
displayName: "dominikánské peso",
"displayName-count-one": "dominikánské peso",
"displayName-count-few": "dominikánská pesa",
"displayName-count-many": "dominikánského pesa",
"displayName-count-other": "dominikánských pes",
symbol: "DOP",
"symbol-alt-narrow": "$"
},
DZD: {
displayName: "alžírský dinár",
"displayName-count-one": "alžírský dinár",
"displayName-count-few": "alžírské dináry",
"displayName-count-many": "alžírského dináru",
"displayName-count-other": "alžírských dinárů",
symbol: "DZD"
},
ECS: {
displayName: "ekvádorský sucre",
"displayName-count-one": "ekvádorský sucre",
"displayName-count-few": "ekvádorské sucre",
"displayName-count-many": "ekvádorského sucre",
"displayName-count-other": "ekvádorských sucre",
symbol: "ECS"
},
ECV: {
displayName: "ekvádorská jednotka konstantní hodnoty",
"displayName-count-one": "ekvádorská jednotka konstantní hodnoty",
"displayName-count-few": "ekvádorské jednotky konstantní hodnoty",
"displayName-count-many": "ekvádorské jednotky konstantní hodnoty",
"displayName-count-other": "ekvádorských jednotek konstantní hodnoty",
symbol: "ECV"
},
EEK: {
displayName: "estonská koruna",
"displayName-count-one": "estonská koruna",
"displayName-count-few": "estonské koruny",
"displayName-count-many": "estonské koruny",
"displayName-count-other": "estonských korun",
symbol: "EEK"
},
EGP: {
displayName: "egyptská libra",
"displayName-count-one": "egyptská libra",
"displayName-count-few": "egyptské libry",
"displayName-count-many": "egyptské libry",
"displayName-count-other": "egyptských liber",
symbol: "EGP",
"symbol-alt-narrow": "E£"
},
ERN: {
displayName: "eritrejská nakfa",
"displayName-count-one": "eritrejská nakfa",
"displayName-count-few": "eritrejské nakfy",
"displayName-count-many": "eritrejské nakfy",
"displayName-count-other": "eritrejských nakf",
symbol: "ERN"
},
ESA: {
displayName: "španělská peseta („A“ účet)",
"displayName-count-one": "španělská peseta („A“ účet)",
"displayName-count-few": "španělské pesety („A“ účet)",
"displayName-count-many": "španělské pesety („A“ účet)",
"displayName-count-other": "španělských peset („A“ účet)",
symbol: "ESA"
},
ESB: {
displayName: "španělská peseta (konvertibilní účet)",
"displayName-count-one": "španělská peseta (konvertibilní účet)",
"displayName-count-few": "španělské pesety (konvertibilní účet)",
"displayName-count-many": "španělské pesety (konvertibilní účet)",
"displayName-count-other": "španělských peset (konvertibilní účet)",
symbol: "ESB"
},
ESP: {
displayName: "španělská peseta",
"displayName-count-one": "španělská peseta",
"displayName-count-few": "španělské pesety",
"displayName-count-many": "španělské pesety",
"displayName-count-other": "španělských peset",
symbol: "ESP",
"symbol-alt-narrow": "₧"
},
ETB: {
displayName: "etiopský birr",
"displayName-count-one": "etiopský birr",
"displayName-count-few": "etiopské birry",
"displayName-count-many": "etiopského birru",
"displayName-count-other": "etiopských birrů",
symbol: "ETB"
},
EUR: {
displayName: "euro",
"displayName-count-one": "euro",
"displayName-count-few": "eura",
"displayName-count-many": "eura",
"displayName-count-other": "eur",
symbol: "€",
"symbol-alt-narrow": "€"
},
FIM: {
displayName: "finská marka",
"displayName-count-one": "finská marka",
"displayName-count-few": "finské marky",
"displayName-count-many": "finské marky",
"displayName-count-other": "finských marek",
symbol: "FIM"
},
FJD: {
displayName: "fidžijský dolar",
"displayName-count-one": "fidžijský dolar",
"displayName-count-few": "fidžijské dolary",
"displayName-count-many": "fidžijského dolaru",
"displayName-count-other": "fidžijských dolarů",
symbol: "FJD",
"symbol-alt-narrow": "$"
},
FKP: {
displayName: "falklandská libra",
"displayName-count-one": "falklandská libra",
"displayName-count-few": "falklandské libry",
"displayName-count-many": "falklandské libry",
"displayName-count-other": "falklandských liber",
symbol: "FKP",
"symbol-alt-narrow": "£"
},
FRF: {
displayName: "francouzský frank",
"displayName-count-one": "francouzský frank",
"displayName-count-few": "francouzské franky",
"displayName-count-many": "francouzského franku",
"displayName-count-other": "francouzských franků",
symbol: "FRF"
},
GBP: {
displayName: "britská libra",
"displayName-count-one": "britská libra",
"displayName-count-few": "britské libry",
"displayName-count-many": "britské libry",
"displayName-count-other": "britských liber",
symbol: "£",
"symbol-alt-narrow": "£"
},
GEK: {
displayName: "gruzínské kuponové lari",
"displayName-count-one": "gruzínské kuponové lari",
"displayName-count-few": "gruzínské kuponové lari",
"displayName-count-many": "gruzínského kuponového lari",
"displayName-count-other": "gruzínských kuponových lari",
symbol: "GEK"
},
GEL: {
displayName: "gruzínské lari",
"displayName-count-one": "gruzínské lari",
"displayName-count-few": "gruzínské lari",
"displayName-count-many": "gruzínského lari",
"displayName-count-other": "gruzínských lari",
symbol: "GEL",
"symbol-alt-narrow": "₾",
"symbol-alt-variant": "₾"
},
GHC: {
displayName: "ghanský cedi (1979–2007)",
"displayName-count-one": "ghanský cedi (1979–2007)",
"displayName-count-few": "ghanské cedi (1979–2007)",
"displayName-count-many": "ghanského cedi (1979–2007)",
"displayName-count-other": "ghanských cedi (1979–2007)",
symbol: "GHC"
},
GHS: {
displayName: "ghanský cedi",
"displayName-count-one": "ghanský cedi",
"displayName-count-few": "ghanské cedi",
"displayName-count-many": "ghanského cedi",
"displayName-count-other": "ghanských cedi",
symbol: "GHS"
},
GIP: {
displayName: "gibraltarská libra",
"displayName-count-one": "gibraltarská libra",
"displayName-count-few": "gibraltarské libry",
"displayName-count-many": "gibraltarské libry",
"displayName-count-other": "gibraltarských liber",
symbol: "GIP",
"symbol-alt-narrow": "£"
},
GMD: {
displayName: "gambijský dalasi",
"displayName-count-one": "gambijský dalasi",
"displayName-count-few": "gambijské dalasi",
"displayName-count-many": "gambijského dalasi",
"displayName-count-other": "gambijských dalasi",
symbol: "GMD"
},
GNF: {
displayName: "guinejský frank",
"displayName-count-one": "guinejský frank",
"displayName-count-few": "guinejské franky",
"displayName-count-many": "guinejského franku",
"displayName-count-other": "guinejských franků",
symbol: "GNF",
"symbol-alt-narrow": "FG"
},
GNS: {
displayName: "guinejský syli",
"displayName-count-one": "guinejský syli",
"displayName-count-few": "guinejské syli",
"displayName-count-many": "guinejského syli",
"displayName-count-other": "guinejských syli",
symbol: "GNS"
},
GQE: {
displayName: "rovníkovoguinejský ekwele",
"displayName-count-one": "rovníkovoguinejský ekwele",
"displayName-count-few": "rovníkovoguinejské ekwele",
"displayName-count-many": "rovníkovoguinejského ekwele",
"displayName-count-other": "rovníkovoguinejských ekwele",
symbol: "GQE"
},
GRD: {
displayName: "řecká drachma",
"displayName-count-one": "řecká drachma",
"displayName-count-few": "řecké drachmy",
"displayName-count-many": "řecké drachmy",
"displayName-count-other": "řeckých drachem",
symbol: "GRD"
},
GTQ: {
displayName: "guatemalský quetzal",
"displayName-count-one": "guatemalský quetzal",
"displayName-count-few": "guatemalské quetzaly",
"displayName-count-many": "guatemalského quetzalu",
"displayName-count-other": "guatemalských quetzalů",
symbol: "GTQ",
"symbol-alt-narrow": "Q"
},
GWE: {
displayName: "portugalskoguinejské escudo",
"displayName-count-one": "portugalskoguinejské escudo",
"displayName-count-few": "portugalskoguinejská escuda",
"displayName-count-many": "portugalskoguinejského escuda",
"displayName-count-other": "portugalskoguinejských escud",
symbol: "GWE"
},
GWP: {
displayName: "guinejsko-bissauské peso",
"displayName-count-one": "guinejsko-bissauské peso",
"displayName-count-few": "guinejsko-bissauská pesa",
"displayName-count-many": "guinejsko-bissauského pesa",
"displayName-count-other": "guinejsko-bissauských pes",
symbol: "GWP"
},
GYD: {
displayName: "guyanský dolar",
"displayName-count-one": "guyanský dolar",
"displayName-count-few": "guyanské dolary",
"displayName-count-many": "guyanského dolaru",
"displayName-count-other": "guyanských dolarů",
symbol: "GYD",
"symbol-alt-narrow": "$"
},
HKD: {
displayName: "hongkongský dolar",
"displayName-count-one": "hongkongský dolar",
"displayName-count-few": "hongkongské dolary",
"displayName-count-many": "hongkongského dolaru",
"displayName-count-other": "hongkongských dolarů",
symbol: "HK$",
"symbol-alt-narrow": "$"
},
HNL: {
displayName: "honduraská lempira",
"displayName-count-one": "honduraská lempira",
"displayName-count-few": "honduraské lempiry",
"displayName-count-many": "honduraské lempiry",
"displayName-count-other": "honduraských lempir",
symbol: "HNL",
"symbol-alt-narrow": "L"
},
HRD: {
displayName: "chorvatský dinár",
"displayName-count-one": "chorvatský dinár",
"displayName-count-few": "chorvatské dináry",
"displayName-count-many": "chorvatského dináru",
"displayName-count-other": "chorvatských dinárů",
symbol: "HRD"
},
HRK: {
displayName: "chorvatská kuna",
"displayName-count-one": "chorvatská kuna",
"displayName-count-few": "chorvatské kuny",
"displayName-count-many": "chorvatské kuny",
"displayName-count-other": "chorvatských kun",
symbol: "HRK",
"symbol-alt-narrow": "kn"
},
HTG: {
displayName: "haitský gourde",
"displayName-count-one": "haitský gourde",
"displayName-count-few": "haitské gourde",
"displayName-count-many": "haitského gourde",
"displayName-count-other": "haitských gourde",
symbol: "HTG"
},
HUF: {
displayName: "maďarský forint",
"displayName-count-one": "maďarský forint",
"displayName-count-few": "maďarské forinty",
"displayName-count-many": "maďarského forintu",
"displayName-count-other": "maďarských forintů",
symbol: "HUF",
"symbol-alt-narrow": "Ft"
},
IDR: {
displayName: "indonéská rupie",
"displayName-count-one": "indonéská rupie",
"displayName-count-few": "indonéské rupie",
"displayName-count-many": "indonéské rupie",
"displayName-count-other": "indonéských rupií",
symbol: "IDR",
"symbol-alt-narrow": "Rp"
},
IEP: {
displayName: "irská libra",
"displayName-count-one": "irská libra",
"displayName-count-few": "irské libry",
"displayName-count-many": "irské libry",
"displayName-count-other": "irských liber",
symbol: "IEP"
},
ILP: {
displayName: "izraelská libra",
"displayName-count-one": "izraelská libra",
"displayName-count-few": "izraelské libry",
"displayName-count-many": "izraelské libry",
"displayName-count-other": "izraelských liber",
symbol: "ILP"
},
ILR: {
displayName: "izraelský šekel (1980–1985)",
"displayName-count-one": "izraelský šekel (1980–1985)",
"displayName-count-few": "izraelské šekely (1980–1985)",
"displayName-count-many": "izraelského šekelu (1980–1985)",
"displayName-count-other": "izraelských šekelů (1980–1985)",
symbol: "ILR"
},
ILS: {
displayName: "izraelský nový šekel",
"displayName-count-one": "izraelský nový šekel",
"displayName-count-few": "izraelské nové šekely",
"displayName-count-many": "izraelského nového šekelu",
"displayName-count-other": "izraelských nový šekelů",
symbol: "ILS",
"symbol-alt-narrow": "₪"
},
INR: {
displayName: "indická rupie",
"displayName-count-one": "indická rupie",
"displayName-count-few": "indické rupie",
"displayName-count-many": "indické rupie",
"displayName-count-other": "indických rupií",
symbol: "INR",
"symbol-alt-narrow": "₹"
},
IQD: {
displayName: "irácký dinár",
"displayName-count-one": "irácký dinár",
"displayName-count-few": "irácké dináry",
"displayName-count-many": "iráckého dináru",
"displayName-count-other": "iráckých dinárů",
symbol: "IQD"
},
IRR: {
displayName: "íránský rijál",
"displayName-count-one": "íránský rijál",
"displayName-count-few": "íránské rijály",
"displayName-count-many": "íránského rijálu",
"displayName-count-other": "íránských rijálů",
symbol: "IRR"
},
ISJ: {
displayName: "islandská koruna (1918–1981)",
"displayName-count-one": "islandská koruna (1918–1981)",
"displayName-count-few": "islandské koruny (1918–1981)",
"displayName-count-many": "islandské koruny (1918–1981)",
"displayName-count-other": "islandských korun (1918–1981)",
symbol: "ISJ"
},
ISK: {
displayName: "islandská koruna",
"displayName-count-one": "islandská koruna",
"displayName-count-few": "islandské koruny",
"displayName-count-many": "islandské koruny",
"displayName-count-other": "islandských korun",
symbol: "ISK",
"symbol-alt-narrow": "kr"
},
ITL: {
displayName: "italská lira",
"displayName-count-one": "italská lira",
"displayName-count-few": "italské liry",
"displayName-count-many": "italské liry",
"displayName-count-other": "italských lir",
symbol: "ITL"
},
JMD: {
displayName: "jamajský dolar",
"displayName-count-one": "jamajský dolar",
"displayName-count-few": "jamajské dolary",
"displayName-count-many": "jamajského dolaru",
"displayName-count-other": "jamajských dolarů",
symbol: "JMD",
"symbol-alt-narrow": "$"
},
JOD: {
displayName: "jordánský dinár",
"displayName-count-one": "jordánský dinár",
"displayName-count-few": "jordánské dináry",
"displayName-count-many": "jordánského dináru",
"displayName-count-other": "jordánských dinárů",
symbol: "JOD"
},
JPY: {
displayName: "japonský jen",
"displayName-count-one": "japonský jen",
"displayName-count-few": "japonské jeny",
"displayName-count-many": "japonského jenu",
"displayName-count-other": "japonských jenů",
symbol: "JP¥",
"symbol-alt-narrow": "¥"
},
KES: {
displayName: "keňský šilink",
"displayName-count-one": "keňský šilink",
"displayName-count-few": "keňské šilinky",
"displayName-count-many": "keňského šilinku",
"displayName-count-other": "keňských šilinků",
symbol: "KES"
},
KGS: {
displayName: "kyrgyzský som",
"displayName-count-one": "kyrgyzský som",
"displayName-count-few": "kyrgyzské somy",
"displayName-count-many": "kyrgyzského somu",
"displayName-count-other": "kyrgyzských somů",
symbol: "KGS"
},
KHR: {
displayName: "kambodžský riel",
"displayName-count-one": "kambodžský riel",
"displayName-count-few": "kambodžské riely",
"displayName-count-many": "kambodžského rielu",
"displayName-count-other": "kambodžských rielů",
symbol: "KHR",
"symbol-alt-narrow": "៛"
},
KMF: {
displayName: "komorský frank",
"displayName-count-one": "komorský frank",
"displayName-count-few": "komorské franky",
"displayName-count-many": "komorského franku",
"displayName-count-other": "komorských franků",
symbol: "KMF",
"symbol-alt-narrow": "CF"
},
KPW: {
displayName: "severokorejský won",
"displayName-count-one": "severokorejský won",
"displayName-count-few": "severokorejské wony",
"displayName-count-many": "severokorejského wonu",
"displayName-count-other": "severokorejských wonů",
symbol: "KPW",
"symbol-alt-narrow": "₩"
},
KRH: {
displayName: "jihokorejský hwan (1953–1962)",
"displayName-count-one": "jihokorejský hwan (1953–1962)",
"displayName-count-few": "jihokorejské hwany (1953–1962)",
"displayName-count-many": "jihokorejského hwanu (1953–1962)",
"displayName-count-other": "jihokorejských hwanů (1953–1962)",
symbol: "KRH"
},
KRO: {
displayName: "jihokorejský won (1945–1953)",
"displayName-count-one": "jihokorejský won (1945–1953)",
"displayName-count-few": "jihokorejské wony (1945–1953)",
"displayName-count-many": "jihokorejského wonu (1945–1953)",
"displayName-count-other": "jihokorejských wonů (1945–1953)",
symbol: "KRO"
},
KRW: {
displayName: "jihokorejský won",
"displayName-count-one": "jihokorejský won",
"displayName-count-few": "jihokorejské wony",
"displayName-count-many": "jihokorejského wonu",
"displayName-count-other": "jihokorejských wonů",
symbol: "₩",
"symbol-alt-narrow": "₩"
},
KWD: {
displayName: "kuvajtský dinár",
"displayName-count-one": "kuvajtský dinár",
"displayName-count-few": "kuvajtské dináry",
"displayName-count-many": "kuvajtského dináru",
"displayName-count-other": "kuvajtských dinárů",
symbol: "KWD"
},
KYD: {
displayName: "kajmanský dolar",
"displayName-count-one": "kajmanský dolar",
"displayName-count-few": "kajmanské dolary",
"displayName-count-many": "kajmanského dolaru",
"displayName-count-other": "kajmanských dolarů",
symbol: "KYD",
"symbol-alt-narrow": "$"
},
KZT: {
displayName: "kazašské tenge",
"displayName-count-one": "kazašské tenge",
"displayName-count-few": "kazašské tenge",
"displayName-count-many": "kazašského tenge",
"displayName-count-other": "kazašských tenge",
symbol: "KZT",
"symbol-alt-narrow": "₸"
},
LAK: {
displayName: "laoský kip",
"displayName-count-one": "laoský kip",
"displayName-count-few": "laoské kipy",
"displayName-count-many": "laoského kipu",
"displayName-count-other": "laoských kipů",
symbol: "LAK",
"symbol-alt-narrow": "₭"
},
LBP: {
displayName: "libanonská libra",
"displayName-count-one": "libanonská libra",
"displayName-count-few": "libanonské libry",
"displayName-count-many": "libanonské libry",
"displayName-count-other": "libanonských liber",
symbol: "LBP",
"symbol-alt-narrow": "L£"
},
LKR: {
displayName: "srílanská rupie",
"displayName-count-one": "srílanská rupie",
"displayName-count-few": "srílanské rupie",
"displayName-count-many": "srílanské rupie",
"displayName-count-other": "srílanských rupií",
symbol: "LKR",
"symbol-alt-narrow": "Rs"
},
LRD: {
displayName: "liberijský dolar",
"displayName-count-one": "liberijský dolar",
"displayName-count-few": "liberijské dolary",
"displayName-count-many": "liberijského dolaru",
"displayName-count-other": "liberijských dolarů",
symbol: "LRD",
"symbol-alt-narrow": "$"
},
LSL: {
displayName: "lesothský loti",
"displayName-count-one": "lesothský loti",
"displayName-count-few": "lesothské maloti",
"displayName-count-many": "lesothského loti",
"displayName-count-other": "lesothských maloti",
symbol: "LSL"
},
LTL: {
displayName: "litevský litas",
"displayName-count-one": "litevský litas",
"displayName-count-few": "litevské lity",
"displayName-count-many": "litevského litu",
"displayName-count-other": "litevských litů",
symbol: "LTL",
"symbol-alt-narrow": "Lt"
},
LTT: {
displayName: "litevský talonas",
"displayName-count-one": "litevský talonas",
"displayName-count-few": "litevské talony",
"displayName-count-many": "litevského talonu",
"displayName-count-other": "litevských talonů",
symbol: "LTT"
},
LUC: {
displayName: "lucemburský konvertibilní frank",
"displayName-count-one": "lucemburský konvertibilní frank",
"displayName-count-few": "lucemburské konvertibilní franky",
"displayName-count-many": "lucemburského konvertibilního franku",
"displayName-count-other": "lucemburských konvertibilních franků",
symbol: "LUC"
},
LUF: {
displayName: "lucemburský frank",
"displayName-count-one": "lucemburský frank",
"displayName-count-few": "lucemburské franky",
"displayName-count-many": "lucemburského franku",
"displayName-count-other": "lucemburských franků",
symbol: "LUF"
},
LUL: {
displayName: "lucemburský finanční frank",
"displayName-count-one": "lucemburský finanční frank",
"displayName-count-few": "lucemburské finanční franky",
"displayName-count-many": "lucemburského finančního franku",
"displayName-count-other": "lucemburských finančních franků",
symbol: "LUL"
},
LVL: {
displayName: "lotyšský lat",
"displayName-count-one": "lotyšský lat",
"displayName-count-few": "lotyšské laty",
"displayName-count-many": "lotyšského latu",
"displayName-count-other": "lotyšských latů",
symbol: "LVL",
"symbol-alt-narrow": "Ls"
},
LVR: {
displayName: "lotyšský rubl",
"displayName-count-one": "lotyšský rubl",
"displayName-count-few": "lotyšské rubly",
"displayName-count-many": "lotyšského rublu",
"displayName-count-other": "lotyšských rublů",
symbol: "LVR"
},
LYD: {
displayName: "libyjský dinár",
"displayName-count-one": "libyjský dinár",
"displayName-count-few": "libyjské dináry",
"displayName-count-many": "libyjského dináru",
"displayName-count-other": "libyjských dinárů",
symbol: "LYD"
},
MAD: {
displayName: "marocký dinár",
"displayName-count-one": "marocký dinár",
"displayName-count-few": "marocké dináry",
"displayName-count-many": "marockého dináru",
"displayName-count-other": "marockých dinárů",
symbol: "MAD"
},
MAF: {
displayName: "marocký frank",
"displayName-count-one": "marocký frank",
"displayName-count-few": "marocké franky",
"displayName-count-many": "marockého franku",
"displayName-count-other": "marockých franků",
symbol: "MAF"
},
MCF: {
displayName: "monacký frank",
"displayName-count-one": "monacký frank",
"displayName-count-few": "monacké franky",
"displayName-count-many": "monackého franku",
"displayName-count-other": "monackých franků",
symbol: "MCF"
},
MDC: {
displayName: "moldavský kupon",
"displayName-count-one": "moldavský kupon",
"displayName-count-few": "moldavské kupony",
"displayName-count-many": "moldavského kuponu",
"displayName-count-other": "moldavských kuponů",
symbol: "MDC"
},
MDL: {
displayName: "moldavský leu",
"displayName-count-one": "moldavský leu",
"displayName-count-few": "moldavské lei",
"displayName-count-many": "moldavského leu",
"displayName-count-other": "moldavských lei",
symbol: "MDL"
},
MGA: {
displayName: "madagaskarský ariary",
"displayName-count-one": "madagaskarský ariary",
"displayName-count-few": "madagaskarské ariary",
"displayName-count-many": "madagaskarského ariary",
"displayName-count-other": "madagaskarských ariary",
symbol: "MGA",
"symbol-alt-narrow": "Ar"
},
MGF: {
displayName: "madagaskarský frank",
"displayName-count-one": "madagaskarský frank",
"displayName-count-few": "madagaskarské franky",
"displayName-count-many": "madagaskarského franku",
"displayName-count-other": "madagaskarských franků",
symbol: "MGF"
},
MKD: {
displayName: "makedonský denár",
"displayName-count-one": "makedonský denár",
"displayName-count-few": "makedonské denáry",
"displayName-count-many": "makedonského denáru",
"displayName-count-other": "makedonských denárů",
symbol: "MKD"
},
MKN: {
displayName: "makedonský denár (1992–1993)",
"displayName-count-one": "makedonský denár (1992–1993)",
"displayName-count-few": "makedonské denáry (1992–1993)",
"displayName-count-many": "makedonského denáru (1992–1993)",
"displayName-count-other": "makedonských denárů (1992–1993)",
symbol: "MKN"
},
MLF: {
displayName: "malijský frank",
"displayName-count-one": "malijský frank",
"displayName-count-few": "malijské franky",
"displayName-count-many": "malijského franku",
"displayName-count-other": "malijských franků",
symbol: "MLF"
},
MMK: {
displayName: "myanmarský kyat",
"displayName-count-one": "myanmarský kyat",
"displayName-count-few": "myanmarské kyaty",
"displayName-count-many": "myanmarského kyatu",
"displayName-count-other": "myanmarských kyatů",
symbol: "MMK",
"symbol-alt-narrow": "K"
},
MNT: {
displayName: "mongolský tugrik",
"displayName-count-one": "mongolský tugrik",
"displayName-count-few": "mongolské tugriky",
"displayName-count-many": "mongolského tugriku",
"displayName-count-other": "mongolských tugriků",
symbol: "MNT",
"symbol-alt-narrow": "₮"
},
MOP: {
displayName: "macajská pataca",
"displayName-count-one": "macajská pataca",
"displayName-count-few": "macajské patacy",
"displayName-count-many": "macajské patacy",
"displayName-count-other": "macajských patac",
symbol: "MOP"
},
MRO: {
displayName: "mauritánská ouguiya",
"displayName-count-one": "mauritánská ouguiya",
"displayName-count-few": "mauritánské ouguiye",
"displayName-count-many": "mauritánské ouguiye",
"displayName-count-other": "mauritánských ouguiyí",
symbol: "MRO"
},
MTL: {
displayName: "maltská lira",
"displayName-count-one": "maltská lira",
"displayName-count-few": "maltské liry",
"displayName-count-many": "maltské liry",
"displayName-count-other": "maltských lir",
symbol: "MTL"
},
MTP: {
displayName: "maltská libra",
"displayName-count-one": "maltská libra",
"displayName-count-few": "maltské libry",
"displayName-count-many": "maltské libry",
"displayName-count-other": "maltských liber",
symbol: "MTP"
},
MUR: {
displayName: "mauricijská rupie",
"displayName-count-one": "mauricijská rupie",
"displayName-count-few": "mauricijské rupie",
"displayName-count-many": "mauricijské rupie",
"displayName-count-other": "mauricijských rupií",
symbol: "MUR",
"symbol-alt-narrow": "Rs"
},
MVP: {
displayName: "maledivská rupie (1947–1981)",
"displayName-count-one": "maledivská rupie (1947–1981)",
"displayName-count-few": "maledivské rupie (1947–1981)",
"displayName-count-many": "maledivské rupie (1947–1981)",
"displayName-count-other": "maledivských rupií (1947–1981)",
symbol: "MVP"
},
MVR: {
displayName: "maledivská rupie",
"displayName-count-one": "maledivská rupie",
"displayName-count-few": "maledivské rupie",
"displayName-count-many": "maledivské rupie",
"displayName-count-other": "maledivských rupií",
symbol: "MVR"
},
MWK: {
displayName: "malawijská kwacha",
"displayName-count-one": "malawijská kwacha",
"displayName-count-few": "malawijské kwachy",
"displayName-count-many": "malawijské kwachy",
"displayName-count-other": "malawijských kwach",
symbol: "MWK"
},
MXN: {
displayName: "mexické peso",
"displayName-count-one": "mexické peso",
"displayName-count-few": "mexická pesa",
"displayName-count-many": "mexického pesa",
"displayName-count-other": "mexických pes",
symbol: "MX$",
"symbol-alt-narrow": "$"
},
MXP: {
displayName: "mexické stříbrné peso (1861–1992)",
"displayName-count-one": "mexické stříbrné peso (1861–1992)",
"displayName-count-few": "mexická stříbrná pesa (1861–1992)",
"displayName-count-many": "mexického stříbrného pesa (1861–1992)",
"displayName-count-other": "mexických stříbrných pes (1861–1992)",
symbol: "MXP"
},
MXV: {
displayName: "mexická investiční jednotka",
"displayName-count-one": "mexická investiční jednotka",
"displayName-count-few": "mexické investiční jednotky",
"displayName-count-many": "mexické investiční jednotky",
"displayName-count-other": "mexických investičních jednotek",
symbol: "MXV"
},
MYR: {
displayName: "malajsijský ringgit",
"displayName-count-one": "malajsijský ringgit",
"displayName-count-few": "malajsijské ringgity",
"displayName-count-many": "malajsijského ringgitu",
"displayName-count-other": "malajsijských ringgitů",
symbol: "MYR",
"symbol-alt-narrow": "RM"
},
MZE: {
displayName: "mosambický escudo",
"displayName-count-one": "mosambický escudo",
"displayName-count-few": "mosambická escuda",
"displayName-count-many": "mosambického escuda",
"displayName-count-other": "mosambických escud",
symbol: "MZE"
},
MZM: {
displayName: "mosambický metical (1980–2006)",
"displayName-count-one": "mosambický metical (1980–2006)",
"displayName-count-few": "mosambické meticaly (1980–2006)",
"displayName-count-many": "mosambického meticalu (1980–2006)",
"displayName-count-other": "mosambických meticalů (1980–2006)",
symbol: "MZM"
},
MZN: {
displayName: "mozambický metical",
"displayName-count-one": "mozambický metical",
"displayName-count-few": "mozambické meticaly",
"displayName-count-many": "mozambického meticalu",
"displayName-count-other": "mozambických meticalů",
symbol: "MZN"
},
NAD: {
displayName: "namibijský dolar",
"displayName-count-one": "namibijský dolar",
"displayName-count-few": "namibijské dolary",
"displayName-count-many": "namibijského dolaru",
"displayName-count-other": "namibijských dolarů",
symbol: "NAD",
"symbol-alt-narrow": "$"
},
NGN: {
displayName: "nigerijská naira",
"displayName-count-one": "nigerijská naira",
"displayName-count-few": "nigerijské nairy",
"displayName-count-many": "nigerijské nairy",
"displayName-count-other": "nigerijských nair",
symbol: "NGN",
"symbol-alt-narrow": "₦"
},
NIC: {
displayName: "nikaragujská córdoba (1988–1991)",
"displayName-count-one": "nikaragujská córdoba (1988–1991)",
"displayName-count-few": "nikaragujské córdoby (1988–1991)",
"displayName-count-many": "nikaragujské córdoby (1988–1991)",
"displayName-count-other": "nikaragujských córdob (1988–1991)",
symbol: "NIC"
},
NIO: {
displayName: "nikaragujská córdoba",
"displayName-count-one": "nikaragujská córdoba",
"displayName-count-few": "nikaragujské córdoby",
"displayName-count-many": "nikaragujské córdoby",
"displayName-count-other": "nikaragujských córdob",
symbol: "NIO",
"symbol-alt-narrow": "C$"
},
NLG: {
displayName: "nizozemský gulden",
"displayName-count-one": "nizozemský gulden",
"displayName-count-few": "nizozemské guldeny",
"displayName-count-many": "nizozemského guldenu",
"displayName-count-other": "nizozemských guldenů",
symbol: "NLG"
},
NOK: {
displayName: "norská koruna",
"displayName-count-one": "norská koruna",
"displayName-count-few": "norské koruny",
"displayName-count-many": "norské koruny",
"displayName-count-other": "norských korun",
symbol: "NOK",
"symbol-alt-narrow": "kr"
},
NPR: {
displayName: "nepálská rupie",
"displayName-count-one": "nepálská rupie",
"displayName-count-few": "nepálské rupie",
"displayName-count-many": "nepálské rupie",
"displayName-count-other": "nepálských rupií",
symbol: "NPR",
"symbol-alt-narrow": "Rs"
},
NZD: {
displayName: "novozélandský dolar",
"displayName-count-one": "novozélandský dolar",
"displayName-count-few": "novozélandské dolary",
"displayName-count-many": "novozélandského dolaru",
"displayName-count-other": "novozélandských dolarů",
symbol: "NZ$",
"symbol-alt-narrow": "$"
},
OMR: {
displayName: "ománský rijál",
"displayName-count-one": "ománský rijál",
"displayName-count-few": "ománské rijály",
"displayName-count-many": "ománského rijálu",
"displayName-count-other": "ománských rijálů",
symbol: "OMR"
},
PAB: {
displayName: "panamská balboa",
"displayName-count-one": "panamská balboa",
"displayName-count-few": "panamské balboy",
"displayName-count-many": "panamské balboy",
"displayName-count-other": "panamských balboí",
symbol: "PAB"
},
PEI: {
displayName: "peruánská inti",
"displayName-count-one": "peruánská inti",
"displayName-count-few": "peruánské inti",
"displayName-count-many": "peruánské inti",
"displayName-count-other": "peruánských inti",
symbol: "PEI"
},
PEN: {
displayName: "peruánský sol",
"displayName-count-one": "peruánský sol",
"displayName-count-few": "peruánské soly",
"displayName-count-many": "peruánského solu",
"displayName-count-other": "peruánských solů",
symbol: "PEN"
},
PES: {
displayName: "peruánský sol (1863–1965)",
"displayName-count-one": "peruánský sol (1863–1965)",
"displayName-count-few": "peruánské soly (1863–1965)",
"displayName-count-many": "peruánského solu (1863–1965)",
"displayName-count-other": "peruánských solů (1863–1965)",
symbol: "PES"
},
PGK: {
displayName: "papuánská nová kina",
"displayName-count-one": "papuánská nová kina",
"displayName-count-few": "papuánské nové kiny",
"displayName-count-many": "papuánské nové kiny",
"displayName-count-other": "papuánských nových kin",
symbol: "PGK"
},
PHP: {
displayName: "filipínské peso",
"displayName-count-one": "filipínské peso",
"displayName-count-few": "filipínská pesa",
"displayName-count-many": "filipínského pesa",
"displayName-count-other": "filipínských pes",
symbol: "PHP",
"symbol-alt-narrow": "₱"
},
PKR: {
displayName: "pákistánská rupie",
"displayName-count-one": "pákistánská rupie",
"displayName-count-few": "pákistánské rupie",
"displayName-count-many": "pákistánské rupie",
"displayName-count-other": "pákistánských rupií",
symbol: "PKR",
"symbol-alt-narrow": "Rs"
},
PLN: {
displayName: "polský zlotý",
"displayName-count-one": "polský zlotý",
"displayName-count-few": "polské zloté",
"displayName-count-many": "polského zlotého",
"displayName-count-other": "polských zlotých",
symbol: "PLN",
"symbol-alt-narrow": "zł"
},
PLZ: {
displayName: "polský zlotý (1950–1995)",
"displayName-count-one": "polský zlotý (1950–1995)",
"displayName-count-few": "polské zloté (1950–1995)",
"displayName-count-many": "polského zlotého (1950–1995)",
"displayName-count-other": "polských zlotých (1950–1995)",
symbol: "PLZ"
},
PTE: {
displayName: "portugalské escudo",
"displayName-count-one": "portugalské escudo",
"displayName-count-few": "portugalská escuda",
"displayName-count-many": "portugalského escuda",
"displayName-count-other": "portugalských escud",
symbol: "PTE"
},
PYG: {
displayName: "paraguajské guarani",
"displayName-count-one": "paraguajské guarani",
"displayName-count-few": "paraguajská guarani",
"displayName-count-many": "paraguajského guarani",
"displayName-count-other": "paraguajských guarani",
symbol: "PYG",
"symbol-alt-narrow": "₲"
},
QAR: {
displayName: "katarský rijál",
"displayName-count-one": "katarský rijál",
"displayName-count-few": "katarské rijály",
"displayName-count-many": "katarského rijálu",
"displayName-count-other": "katarských rijálů",
symbol: "QAR"
},
RHD: {
displayName: "rhodéský dolar",
"displayName-count-one": "rhodéský dolar",
"displayName-count-few": "rhodéské dolary",
"displayName-count-many": "rhodéského dolaru",
"displayName-count-other": "rhodéských dolarů",
symbol: "RHD"
},
ROL: {
displayName: "rumunské leu (1952–2006)",
"displayName-count-one": "rumunské leu (1952–2006)",
"displayName-count-few": "rumunské lei (1952–2006)",
"displayName-count-many": "rumunského leu (1952–2006)",
"displayName-count-other": "rumunských lei (1952–2006)",
symbol: "ROL"
},
RON: {
displayName: "rumunský leu",
"displayName-count-one": "rumunský leu",
"displayName-count-few": "rumunské lei",
"displayName-count-many": "rumunského leu",
"displayName-count-other": "rumunských lei",
symbol: "RON",
"symbol-alt-narrow": "L"
},
RSD: {
displayName: "srbský dinár",
"displayName-count-one": "srbský dinár",
"displayName-count-few": "srbské dináry",
"displayName-count-many": "srbského dináru",
"displayName-count-other": "srbských dinárů",
symbol: "RSD"
},
RUB: {
displayName: "ruský rubl",
"displayName-count-one": "ruský rubl",
"displayName-count-few": "ruské rubly",
"displayName-count-many": "ruského rublu",
"displayName-count-other": "ruských rublů",
symbol: "RUB",
"symbol-alt-narrow": "₽"
},
RUR: {
displayName: "ruský rubl (1991–1998)",
"displayName-count-one": "ruský rubl (1991–1998)",
"displayName-count-few": "ruské rubly (1991–1998)",
"displayName-count-many": "ruského rublu (1991–1998)",
"displayName-count-other": "ruských rublů (1991–1998)",
symbol: "RUR",
"symbol-alt-narrow": "р."
},
RWF: {
displayName: "rwandský frank",
"displayName-count-one": "rwandský frank",
"displayName-count-few": "rwandské franky",
"displayName-count-many": "rwandského franku",
"displayName-count-other": "rwandských franků",
symbol: "RWF",
"symbol-alt-narrow": "RF"
},
SAR: {
displayName: "saúdský rijál",
"displayName-count-one": "saúdský rijál",
"displayName-count-few": "saúdské rijály",
"displayName-count-many": "saúdského rijálu",
"displayName-count-other": "saúdských rijálů",
symbol: "SAR"
},
SBD: {
displayName: "šalamounský dolar",
"displayName-count-one": "šalamounský dolar",
"displayName-count-few": "šalamounské dolary",
"displayName-count-many": "šalamounského dolaru",
"displayName-count-other": "šalamounských dolarů",
symbol: "SBD",
"symbol-alt-narrow": "$"
},
SCR: {
displayName: "seychelská rupie",
"displayName-count-one": "seychelská rupie",
"displayName-count-few": "seychelské rupie",
"displayName-count-many": "seychelské rupie",
"displayName-count-other": "seychelských rupií",
symbol: "SCR"
},
SDD: {
displayName: "súdánský dinár (1992–2007)",
"displayName-count-one": "súdánský dinár (1992–2007)",
"displayName-count-few": "súdánské dináry (1992–2007)",
"displayName-count-many": "súdánského dináru (1992–2007)",
"displayName-count-other": "súdánských dinárů (1992–2007)",
symbol: "SDD"
},
SDG: {
displayName: "súdánská libra",
"displayName-count-one": "súdánská libra",
"displayName-count-few": "súdánské libry",
"displayName-count-many": "súdánské libry",
"displayName-count-other": "súdánských liber",
symbol: "SDG"
},
SDP: {
displayName: "súdánská libra (1957–1998)",
"displayName-count-one": "súdánská libra (1957–1998)",
"displayName-count-few": "súdánské libry (1957–1998)",
"displayName-count-many": "súdánské libry (1957–1998)",
"displayName-count-other": "súdánských liber (1957–1998)",
symbol: "SDP"
},
SEK: {
displayName: "švédská koruna",
"displayName-count-one": "švédská koruna",
"displayName-count-few": "švédské koruny",
"displayName-count-many": "švédské koruny",
"displayName-count-other": "švédských korun",
symbol: "SEK",
"symbol-alt-narrow": "kr"
},
SGD: {
displayName: "singapurský dolar",
"displayName-count-one": "singapurský dolar",
"displayName-count-few": "singapurské dolary",
"displayName-count-many": "singapurského dolaru",
"displayName-count-other": "singapurských dolarů",
symbol: "SGD",
"symbol-alt-narrow": "$"
},
SHP: {
displayName: "svatohelenská libra",
"displayName-count-one": "svatohelenská libra",
"displayName-count-few": "svatohelenské libry",
"displayName-count-many": "svatohelenské libry",
"displayName-count-other": "svatohelenských liber",
symbol: "SHP",
"symbol-alt-narrow": "£"
},
SIT: {
displayName: "slovinský tolar",
"displayName-count-one": "slovinský tolar",
"displayName-count-few": "slovinské tolary",
"displayName-count-many": "slovinského tolaru",
"displayName-count-other": "slovinských tolarů",
symbol: "SIT"
},
SKK: {
displayName: "slovenská koruna",
"displayName-count-one": "slovenská koruna",
"displayName-count-few": "slovenské koruny",
"displayName-count-many": "slovenské koruny",
"displayName-count-other": "slovenských korun",
symbol: "SKK"
},
SLL: {
displayName: "sierro-leonský leone",
"displayName-count-one": "sierro-leonský leone",
"displayName-count-few": "sierro-leonské leone",
"displayName-count-many": "sierro-leonského leone",
"displayName-count-other": "sierro-leonských leone",
symbol: "SLL"
},
SOS: {
displayName: "somálský šilink",
"displayName-count-one": "somálský šilink",
"displayName-count-few": "somálské šilinky",
"displayName-count-many": "somálského šilinku",
"displayName-count-other": "somálských šilinků",
symbol: "SOS"
},
SRD: {
displayName: "surinamský dolar",
"displayName-count-one": "surinamský dolar",
"displayName-count-few": "surinamské dolary",
"displayName-count-many": "surinamského dolaru",
"displayName-count-other": "surinamských dolarů",
symbol: "SRD",
"symbol-alt-narrow": "$"
},
SRG: {
displayName: "surinamský zlatý",
"displayName-count-one": "surinamský zlatý",
"displayName-count-few": "surinamské zlaté",
"displayName-count-many": "surinamského zlatého",
"displayName-count-other": "surinamských zlatých",
symbol: "SRG"
},
SSP: {
displayName: "jihosúdánská libra",
"displayName-count-one": "jihosúdánská libra",
"displayName-count-few": "jihosúdánské libry",
"displayName-count-many": "jihosúdánské libry",
"displayName-count-other": "jihosúdánských liber",
symbol: "SSP",
"symbol-alt-narrow": "£"
},
STD: {
displayName: "svatotomášská dobra",
"displayName-count-one": "svatotomášská dobra",
"displayName-count-few": "svatotomášské dobry",
"displayName-count-many": "svatotomášské dobry",
"displayName-count-other": "svatotomášských dober",
symbol: "STD",
"symbol-alt-narrow": "Db"
},
SUR: {
displayName: "sovětský rubl",
"displayName-count-one": "sovětský rubl",
"displayName-count-few": "sovětské rubly",
"displayName-count-many": "sovětského rublu",
"displayName-count-other": "sovětských rublů",
symbol: "SUR"
},
SVC: {
displayName: "salvadorský colón",
"displayName-count-one": "salvadorský colón",
"displayName-count-few": "salvadorské colóny",
"displayName-count-many": "salvadorského colónu",
"displayName-count-other": "salvadorských colónů",
symbol: "SVC"
},
SYP: {
displayName: "syrská libra",
"displayName-count-one": "syrská libra",
"displayName-count-few": "syrské libry",
"displayName-count-many": "syrské libry",
"displayName-count-other": "syrských liber",
symbol: "SYP",
"symbol-alt-narrow": "£"
},
SZL: {
displayName: "svazijský lilangeni",
"displayName-count-one": "svazijský lilangeni",
"displayName-count-few": "svazijské emalangeni",
"displayName-count-many": "svazijského lilangeni",
"displayName-count-other": "svazijských emalangeni",
symbol: "SZL"
},
THB: {
displayName: "thajský baht",
"displayName-count-one": "thajský baht",
"displayName-count-few": "thajské bahty",
"displayName-count-many": "thajského bahtu",
"displayName-count-other": "thajských bahtů",
symbol: "THB",
"symbol-alt-narrow": "฿"
},
TJR: {
displayName: "tádžický rubl",
"displayName-count-one": "tádžický rubl",
"displayName-count-few": "tádžické rubly",
"displayName-count-many": "tádžického rublu",
"displayName-count-other": "tádžických rublů",
symbol: "TJR"
},
TJS: {
displayName: "tádžické somoni",
"displayName-count-one": "tádžické somoni",
"displayName-count-few": "tádžická somoni",
"displayName-count-many": "tádžického somoni",
"displayName-count-other": "tádžických somoni",
symbol: "TJS"
},
TMM: {
displayName: "turkmenský manat (1993–2009)",
"displayName-count-one": "turkmenský manat (1993–2009)",
"displayName-count-few": "turkmenské manaty (1993–2009)",
"displayName-count-many": "turkmenského manatu (1993–2009)",
"displayName-count-other": "turkmenských manatů (1993–2009)",
symbol: "TMM"
},
TMT: {
displayName: "turkmenský manat",
"displayName-count-one": "turkmenský manat",
"displayName-count-few": "turkmenské manaty",
"displayName-count-many": "turkmenského manatu",
"displayName-count-other": "turkmenských manatů",
symbol: "TMT"
},
TND: {
displayName: "tuniský dinár",
"displayName-count-one": "tuniský dinár",
"displayName-count-few": "tuniské dináry",
"displayName-count-many": "tuniského dináru",
"displayName-count-other": "tuniských dinárů",
symbol: "TND"
},
TOP: {
displayName: "tonžská paanga",
"displayName-count-one": "tonžská paanga",
"displayName-count-few": "tonžské paangy",
"displayName-count-many": "tonžské paangy",
"displayName-count-other": "tonžských paang",
symbol: "TOP",
"symbol-alt-narrow": "T$"
},
TPE: {
displayName: "timorské escudo",
"displayName-count-one": "timorské escudo",
"displayName-count-few": "timorská escuda",
"displayName-count-many": "timorského escuda",
"displayName-count-other": "timorských escud",
symbol: "TPE"
},
TRL: {
displayName: "turecká lira (1922–2005)",
"displayName-count-one": "turecká lira (1922–2005)",
"displayName-count-few": "turecké liry (1922–2005)",
"displayName-count-many": "turecké liry (1922–2005)",
"displayName-count-other": "tureckých lir (1922–2005)",
symbol: "TRL"
},
TRY: {
displayName: "turecká lira",
"displayName-count-one": "turecká lira",
"displayName-count-few": "turecké liry",
"displayName-count-many": "turecké liry",
"displayName-count-other": "tureckých lir",
symbol: "TRY",
"symbol-alt-narrow": "₺",
"symbol-alt-variant": "TL"
},
TTD: {
displayName: "trinidadský dolar",
"displayName-count-one": "trinidadský dolar",
"displayName-count-few": "trinidadské dolary",
"displayName-count-many": "trinidadského dolaru",
"displayName-count-other": "trinidadských dolarů",
symbol: "TTD",
"symbol-alt-narrow": "$"
},
TWD: {
displayName: "tchajwanský dolar",
"displayName-count-one": "tchajwanský dolar",
"displayName-count-few": "tchajwanské dolary",
"displayName-count-many": "tchajwanského dolaru",
"displayName-count-other": "tchajwanských dolarů",
symbol: "NT$",
"symbol-alt-narrow": "NT$"
},
TZS: {
displayName: "tanzanský šilink",
"displayName-count-one": "tanzanský šilink",
"displayName-count-few": "tanzanské šilinky",
"displayName-count-many": "tanzanského šilinku",
"displayName-count-other": "tanzanských šilinků",
symbol: "TZS"
},
UAH: {
displayName: "ukrajinská hřivna",
"displayName-count-one": "ukrajinská hřivna",
"displayName-count-few": "ukrajinské hřivny",
"displayName-count-many": "ukrajinské hřivny",
"displayName-count-other": "ukrajinských hřiven",
symbol: "UAH",
"symbol-alt-narrow": "₴"
},
UAK: {
displayName: "ukrajinský karbovanec",
"displayName-count-one": "ukrajinský karbovanec",
"displayName-count-few": "ukrajinské karbovance",
"displayName-count-many": "ukrajinského karbovance",
"displayName-count-other": "ukrajinských karbovanců",
symbol: "UAK"
},
UGS: {
displayName: "ugandský šilink (1966–1987)",
"displayName-count-one": "ugandský šilink (1966–1987)",
"displayName-count-few": "ugandské šilinky (1966–1987)",
"displayName-count-many": "ugandského šilinku (1966–1987)",
"displayName-count-other": "ugandských šilinků (1966–1987)",
symbol: "UGS"
},
UGX: {
displayName: "ugandský šilink",
"displayName-count-one": "ugandský šilink",
"displayName-count-few": "ugandské šilinky",
"displayName-count-many": "ugandského šilinku",
"displayName-count-other": "ugandských šilinků",
symbol: "UGX"
},
USD: {
displayName: "americký dolar",
"displayName-count-one": "americký dolar",
"displayName-count-few": "americké dolary",
"displayName-count-many": "amerického dolaru",
"displayName-count-other": "amerických dolarů",
symbol: "US$",
"symbol-alt-narrow": "$"
},
USN: {
displayName: "americký dolar (příští den)",
"displayName-count-one": "americký dolar (příští den)",
"displayName-count-few": "americké dolary (příští den)",
"displayName-count-many": "amerického dolaru (příští den)",
"displayName-count-other": "amerických dolarů (příští den)",
symbol: "USN"
},
USS: {
displayName: "americký dolar (týž den)",
"displayName-count-one": "americký dolar (týž den)",
"displayName-count-few": "americké dolary (týž den)",
"displayName-count-many": "amerického dolaru (týž den)",
"displayName-count-other": "amerických dolarů (týž den)",
symbol: "USS"
},
UYI: {
displayName: "uruguayské peso (v indexovaných jednotkách)",
"displayName-count-one": "uruguayské peso (v indexovaných jednotkách)",
"displayName-count-few": "uruguayská pesa (v indexovaných jednotkách)",
"displayName-count-many": "uruguayského pesa (v indexovaných jednotkách)",
"displayName-count-other": "uruguayských pes (v indexovaných jednotkách)",
symbol: "UYI"
},
UYP: {
displayName: "uruguayské peso (1975–1993)",
"displayName-count-one": "uruguayské peso (1975–1993)",
"displayName-count-few": "uruguayská pesa (1975–1993)",
"displayName-count-many": "uruguayského pesa (1975–1993)",
"displayName-count-other": "uruguayských pes (1975–1993)",
symbol: "UYP"
},
UYU: {
displayName: "uruguayské peso",
"displayName-count-one": "uruguayské peso",
"displayName-count-few": "uruguayská pesa",
"displayName-count-many": "uruguayského pesa",
"displayName-count-other": "uruguayských pes",
symbol: "UYU",
"symbol-alt-narrow": "$"
},
UZS: {
displayName: "uzbecký sum",
"displayName-count-one": "uzbecký sum",
"displayName-count-few": "uzbecké sumy",
"displayName-count-many": "uzbeckého sumu",
"displayName-count-other": "uzbeckých sumů",
symbol: "UZS"
},
VEB: {
displayName: "venezuelský bolívar (1871–2008)",
"displayName-count-one": "venezuelský bolívar (1871–2008)",
"displayName-count-few": "venezuelské bolívary (1871–2008)",
"displayName-count-many": "venezuelského bolívaru (1871–2008)",
"displayName-count-other": "venezuelských bolívarů (1871–2008)",
symbol: "VEB"
},
VEF: {
displayName: "venezuelský bolívar",
"displayName-count-one": "venezuelský bolívar",
"displayName-count-few": "venezuelské bolívary",
"displayName-count-many": "venezuelského bolívaru",
"displayName-count-other": "venezuelských bolívarů",
symbol: "VEF",
"symbol-alt-narrow": "Bs"
},
VND: {
displayName: "vietnamský dong",
"displayName-count-one": "vietnamský dong",
"displayName-count-few": "vietnamské dongy",
"displayName-count-many": "vietnamského dongu",
"displayName-count-other": "vietnamských dongů",
symbol: "VND",
"symbol-alt-narrow": "₫"
},
VNN: {
displayName: "vietnamský dong (1978–1985)",
"displayName-count-one": "vietnamský dong (1978–1985)",
"displayName-count-few": "vietnamské dongy (1978–1985)",
"displayName-count-many": "vietnamského dongu (1978–1985)",
"displayName-count-other": "vietnamských dongů (1978–1985)",
symbol: "VNN"
},
VUV: {
displayName: "vanuatský vatu",
"displayName-count-one": "vanuatský vatu",
"displayName-count-few": "vanuatské vatu",
"displayName-count-many": "vanuatského vatu",
"displayName-count-other": "vanuatských vatu",
symbol: "VUV"
},
WST: {
displayName: "samojská tala",
"displayName-count-one": "samojská tala",
"displayName-count-few": "samojské taly",
"displayName-count-many": "samojské taly",
"displayName-count-other": "samojských tal",
symbol: "WST"
},
XAF: {
displayName: "CFA/BEAC frank",
"displayName-count-one": "CFA/BEAC frank",
"displayName-count-few": "CFA/BEAC franky",
"displayName-count-many": "CFA/BEAC franku",
"displayName-count-other": "CFA/BEAC franků",
symbol: "FCFA"
},
XAG: {
displayName: "stříbro",
"displayName-count-one": "trojská unce stříbra",
"displayName-count-few": "trojské unce stříbra",
"displayName-count-many": "trojské unce stříbra",
"displayName-count-other": "trojských uncí stříbra",
symbol: "XAG"
},
XAU: {
displayName: "zlato",
"displayName-count-one": "trojská unce zlata",
"displayName-count-few": "trojské unce zlata",
"displayName-count-many": "trojské unce zlata",
"displayName-count-other": "trojských uncí zlata",
symbol: "XAU"
},
XBA: {
displayName: "evropská smíšená jednotka",
"displayName-count-one": "evropská smíšená jednotka",
"displayName-count-few": "evropské smíšené jednotky",
"displayName-count-many": "evropské smíšené jednotky",
"displayName-count-other": "evropských smíšených jednotek",
symbol: "XBA"
},
XBB: {
displayName: "evropská peněžní jednotka",
"displayName-count-one": "evropská peněžní jednotka",
"displayName-count-few": "evropské peněžní jednotky",
"displayName-count-many": "evropské peněžní jednotky",
"displayName-count-other": "evropských peněžních jednotek",
symbol: "XBB"
},
XBC: {
displayName: "evropská jednotka účtu 9 (XBC)",
"displayName-count-one": "evropská jednotka účtu 9 (XBC)",
"displayName-count-few": "evropské jednotky účtu 9 (XBC)",
"displayName-count-many": "evropské jednotky účtu 9 (XBC)",
"displayName-count-other": "evropských jednotek účtu 9 (XBC)",
symbol: "XBC"
},
XBD: {
displayName: "evropská jednotka účtu 17 (XBD)",
"displayName-count-one": "evropská jednotka účtu 17 (XBD)",
"displayName-count-few": "evropské jednotky účtu 17 (XBD)",
"displayName-count-many": "evropské jednotky účtu 17 (XBD)",
"displayName-count-other": "evropských jednotek účtu 17 (XBD)",
symbol: "XBD"
},
XCD: {
displayName: "východokaribský dolar",
"displayName-count-one": "východokaribský dolar",
"displayName-count-few": "východokaribské dolary",
"displayName-count-many": "východokaribského dolaru",
"displayName-count-other": "východokaribských dolarů",
symbol: "EC$",
"symbol-alt-narrow": "$"
},
XDR: {
displayName: "SDR",
symbol: "XDR"
},
XEU: {
displayName: "evropská měnová jednotka",
"displayName-count-one": "ECU",
"displayName-count-few": "ECU",
"displayName-count-many": "ECU",
"displayName-count-other": "ECU",
symbol: "ECU"
},
XFO: {
displayName: "francouzský zlatý frank",
"displayName-count-one": "francouzský zlatý frank",
"displayName-count-few": "francouzské zlaté franky",
"displayName-count-many": "francouzského zlatého franku",
"displayName-count-other": "francouzských zlatých franků",
symbol: "XFO"
},
XFU: {
displayName: "francouzský UIC frank",
"displayName-count-one": "francouzský UIC frank",
"displayName-count-few": "francouzské UIC franky",
"displayName-count-many": "francouzského UIC franku",
"displayName-count-other": "francouzských UIC franků",
symbol: "XFU"
},
XOF: {
displayName: "CFA/BCEAO frank",
"displayName-count-one": "CFA/BCEAO frank",
"displayName-count-few": "CFA/BCEAO franky",
"displayName-count-many": "CFA/BCEAO franku",
"displayName-count-other": "CFA/BCEAO franků",
symbol: "CFA"
},
XPD: {
displayName: "palladium",
"displayName-count-one": "trojská unce palladia",
"displayName-count-few": "trojské unce palladia",
"displayName-count-many": "trojské unce palladia",
"displayName-count-other": "trojských uncí palladia",
symbol: "XPD"
},
XPF: {
displayName: "CFP frank",
"displayName-count-one": "CFP frank",
"displayName-count-few": "CFP franky",
"displayName-count-many": "CFP franku",
"displayName-count-other": "CFP franků",
symbol: "CFPF"
},
XPT: {
displayName: "platina",
"displayName-count-one": "trojská unce platiny",
"displayName-count-few": "trojské unce platiny",
"displayName-count-many": "trojské unce platiny",
"displayName-count-other": "trojských uncí platiny",
symbol: "XPT"
},
XRE: {
displayName: "kód fondů RINET",
symbol: "XRE"
},
XSU: {
displayName: "sucre",
"displayName-count-one": "sucre",
"displayName-count-few": "sucre",
"displayName-count-many": "sucre",
"displayName-count-other": "sucre",
symbol: "XSU"
},
XTS: {
displayName: "kód zvlášť vyhrazený pro testovací účely",
"displayName-count-one": "kód zvlášť vyhrazený pro testovací účely",
"displayName-count-few": "kódy zvlášť vyhrazené pro testovací účely",
"displayName-count-many": "kódu zvlášť vyhrazeného pro testovací účely",
"displayName-count-other": "kódů zvlášť vyhrazených pro testovací účely",
symbol: "XTS"
},
XUA: {
displayName: "XUA",
symbol: "XUA"
},
XXX: {
displayName: "neznámá měna",
"displayName-count-one": "neznámá měna",
"displayName-count-few": "neznámá měna",
"displayName-count-many": "neznámá měna",
"displayName-count-other": "neznámá měna",
symbol: "XXX"
},
YDD: {
displayName: "jemenský dinár",
"displayName-count-one": "jemenský dinár",
"displayName-count-few": "jemenské dináry",
"displayName-count-many": "jemenského dináru",
"displayName-count-other": "jemenských dinárů",
symbol: "YDD"
},
YER: {
displayName: "jemenský rijál",
"displayName-count-one": "jemenský rijál",
"displayName-count-few": "jemenské rijály",
"displayName-count-many": "jemenského rijálu",
"displayName-count-other": "jemenských rijálů",
symbol: "YER"
},
YUD: {
displayName: "jugoslávský dinár (1966–1990)",
"displayName-count-one": "jugoslávský dinár (1966–1990)",
"displayName-count-few": "jugoslávské dináry (1966–1990)",
"displayName-count-many": "jugoslávského dináru (1966–1990)",
"displayName-count-other": "jugoslávských dinárů (1966–1990)",
symbol: "YUD"
},
YUM: {
displayName: "jugoslávský nový dinár (1994–2002)",
"displayName-count-one": "jugoslávský nový dinár (1994–2002)",
"displayName-count-few": "jugoslávské nové dináry (1994–2002)",
"displayName-count-many": "jugoslávského nového dináru (1994–2002)",
"displayName-count-other": "jugoslávských nových dinárů (1994–2002)",
symbol: "YUM"
},
YUN: {
displayName: "jugoslávský konvertibilní dinár (1990–1992)",
"displayName-count-one": "jugoslávský konvertibilní dinár (1990–1992)",
"displayName-count-few": "jugoslávské konvertibilní dináry (1990–1992)",
"displayName-count-many": "jugoslávského konvertibilního dináru (1990–1992)",
"displayName-count-other": "jugoslávských konvertibilních dinárů (1990–1992)",
symbol: "YUN"
},
YUR: {
displayName: "jugoslávský reformovaný dinár (1992–1993)",
"displayName-count-one": "jugoslávský reformovaný dinár (1992–1993)",
"displayName-count-few": "jugoslávské reformované dináry (1992–1993)",
"displayName-count-many": "jugoslávského reformovaného dináru (1992–1993)",
"displayName-count-other": "jugoslávských reformovaných dinárů (1992–1993)",
symbol: "YUR"
},
ZAL: {
displayName: "jihoafrický finanční rand",
"displayName-count-one": "jihoafrický finanční rand",
"displayName-count-few": "jihoafrické finanční randy",
"displayName-count-many": "jihoafrického finančního randu",
"displayName-count-other": "jihoafrických finančních randů",
symbol: "ZAL"
},
ZAR: {
displayName: "jihoafrický rand",
"displayName-count-one": "jihoafrický rand",
"displayName-count-few": "jihoafrické randy",
"displayName-count-many": "jihoafrického randu",
"displayName-count-other": "jihoafrických randů",
symbol: "ZAR",
"symbol-alt-narrow": "R"
},
ZMK: {
displayName: "zambijská kwacha (1968–2012)",
"displayName-count-one": "zambijská kwacha (1968–2012)",
"displayName-count-few": "zambijské kwachy (1968–2012)",
"displayName-count-many": "zambijské kwachy (1968–2012)",
"displayName-count-other": "zambijských kwach (1968–2012)",
symbol: "ZMK"
},
ZMW: {
displayName: "zambijská kwacha",
"displayName-count-one": "zambijská kwacha",
"displayName-count-few": "zambijské kwachy",
"displayName-count-many": "zambijské kwachy",
"displayName-count-other": "zambijských kwach",
symbol: "ZMW",
"symbol-alt-narrow": "ZK"
},
ZRN: {
displayName: "zairský nový zaire (1993–1998)",
"displayName-count-one": "zairský nový zaire (1993–1998)",
"displayName-count-few": "zairské nové zairy (1993–1998)",
"displayName-count-many": "zairského nového zairu (1993–1998)",
"displayName-count-other": "zairských nových zairů (1993–1998)",
symbol: "ZRN"
},
ZRZ: {
displayName: "zairský zaire (1971–1993)",
"displayName-count-one": "zairský zaire (1971–1993)",
"displayName-count-few": "zairské zairy (1971–1993)",
"displayName-count-many": "zairského zairu (1971–1993)",
"displayName-count-other": "zairských zairů (1971–1993)",
symbol: "ZRZ"
},
ZWD: {
displayName: "zimbabwský dolar (1980–2008)",
"displayName-count-one": "zimbabwský dolar (1980–2008)",
"displayName-count-few": "zimbabwské dolary (1980–2008)",
"displayName-count-many": "zimbabwského dolaru (1980–2008)",
"displayName-count-other": "zimbabwských dolarů (1980–2008)",
symbol: "ZWD"
},
ZWL: {
displayName: "zimbabwský dolar (2009)",
"displayName-count-one": "zimbabwský dolar (2009)",
"displayName-count-few": "zimbabwské dolary (2009)",
"displayName-count-many": "zimbabwského dolaru (2009)",
"displayName-count-other": "zimbabwských dolarů (2009)",
symbol: "ZWL"
},
ZWR: {
displayName: "zimbabwský dolar (2008)",
"displayName-count-one": "zimbabwský dolar (2008)",
"displayName-count-few": "zimbabwské dolary (2008)",
"displayName-count-many": "zimbabwského dolaru (2008)",
"displayName-count-other": "zimbabwských dolarů (2008)",
symbol: "ZWR"
}
},
localeCurrency: "CZK"
}
});
|
if (typeof Object.assign !== 'function') {
(() => {
Object.assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
const output = Object(target);
for (let index = 1; index < arguments.length; index++) {
const source = arguments[index];
if (source !== undefined && source !== null) {
for (const nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
|
export const u1F494 = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M1308 1837q-2 55-2 111l1 27v88q0 44-6 66.5t-15 22.5q-11 0-37.5-25.5T1213 2094l-73-55q-57-43-118.5-78T897 1893l-127-64q-277-141-392.5-311T262 1138q0-202 123-336t325-134q103 0 177 32t125.5 56 92.5 77l36 49q10 11 22.5 28t12.5 35q0 21-63.5 80.5T1049 1106q0 14 34.5 49.5t94.5 86.5l24 20q23 20 36.5 36t13.5 29q0 17-38.5 68.5t-56 73-17.5 41.5q0 33 48 77.5t85 75 37 64.5q0 55-2 110zm917-330.5Q2113 1673 1870.5 1815T1528 2042l-35 31q-18 16-31 25.5t-23 22.5l-19 21q-10 11-19.5 18.5t-19.5 7.5q-11 0-15-7.5t-4-17.5q0-16 8-35t35-131.5 40.5-152.5 13.5-71q0-50-40.5-109t-59.5-87-19-42q0-30 83.5-86t83.5-84q0-19-14-37l-26-32q-23-29-44.5-57.5T1381 1161l-23-30q-13-15-13-32 0-25 62.5-52.5t65.5-29.5l26-10q29-11 48-23.5t19-27.5q0-25-28-83.5t-28-74.5q0-9 4-11t57.5-38.5 135-71.5 182.5-35q195 0 321.5 140t126.5 342q0 216-112 382.5z"},"children":[]}]}; |
"use strict";
var moment = require("../../");
var helpers = require("../helpers/helpers");
exports.utc = {
utc : function (test) {
moment.tz.add([
"TestUTC/Pacific|PST|80|0|",
"TestUTC/Eastern|EST|50|0|"
]);
var m = moment("2014-07-10 12:00:00+00:00"),
localFormat = m.format(),
localOffset = helpers.getUTCOffset(m);
m.tz("TestUTC/Pacific");
test.equal(helpers.getUTCOffset(m), -480, "Should change the offset when using moment.fn.tz");
test.equal(m.format(), "2014-07-10T04:00:00-08:00", "Should change the offset when using moment.fn.tz");
m.utc();
moment.updateOffset(m);
test.equal(helpers.getUTCOffset(m), 0, "Should set the offset to +00:00 when using moment.fn.utc");
test.equal(m.format(), "2014-07-10T12:00:00Z", "Should change the offset when using moment.fn.utc");
m.tz("TestUTC/Eastern");
test.equal(helpers.getUTCOffset(m), -300, "Should change the offset when using moment.fn.tz");
test.equal(m.format(), "2014-07-10T07:00:00-05:00", "Should change the offset when using moment.fn.tz");
m.utc();
moment.updateOffset(m);
test.equal(helpers.getUTCOffset(m), 0, "Should set the offset to +00:00 when using moment.fn.utc");
test.equal(m.format(), "2014-07-10T12:00:00Z", "Should change the offset when using moment.fn.utc");
m.local();
moment.updateOffset(m);
test.equal(helpers.getUTCOffset(m), localOffset, "Should reset the offset to local time when using moment.fn.local");
test.equal(m.format(), localFormat, "Should reset the offset to local time when using moment.fn.local");
m = moment('2017-01-01T00:00:00');
var utcWallTimeFormat = m.clone().utcOffset('-05:00', true).format();
m.tz('America/New_York', true);
test.equal(m.format(), utcWallTimeFormat, "Should change the offset while keeping wall time when passing an optional parameter to moment.fn.tz");
test.done();
}
};
|
/**
*
* LocaleToggle
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = <option>--</option>;
// If we have items, render them
if (props.values) {
content = props.values.map(value =>
<ToggleOption key={value} value={value} message={props.messages[value]} />
);
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: PropTypes.func,
values: PropTypes.array,
value: PropTypes.string,
messages: PropTypes.object,
};
export default Toggle;
|
import { Router as router } from 'express';
import passport from 'passport';
import csrf from 'csurf';
import userCtrl from './controllers/userCtrl';
import taskCtrl from './controllers/taskCtrl';
import auth from './middleware/auth';
const runningOnOpenshift = process.env.OPENSHIFT_EXAMPLE || false;
const routes = router();
const csrfProtection = csrf({
cookie: {
httpOnly: true,
secure: runningOnOpenshift ? true : false
}
});
routes.use((req, res, next) => {
res.locals.req = req;
next();
});
// Checks whether the user is authenticated, if so - redirects to /tasks
// Otherwise redirects to /login
routes.get('/', auth.requiresLogin, (req, res) => {
res.redirect('/tasks');
});
routes.get('/login', csrfProtection, userCtrl.login.get);
routes.post('/login', csrfProtection, passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true
}), userCtrl.login.post);
routes.get('/logout', userCtrl.logout.get);
routes.get('/signup', csrfProtection, userCtrl.signup.get);
routes.post('/signup', csrfProtection, userCtrl.signup.post);
routes.get('/tasks', auth.requiresLogin, taskCtrl.get);
routes.post('/tasks', auth.requiresLogin, taskCtrl.create);
routes.put('/tasks/:id', auth.requiresLogin, taskCtrl.update);
routes.delete('/tasks/:id', auth.requiresLogin, taskCtrl.remove);
routes.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if (err.code === 'EBADCSRFTOKEN') {
res.status(403);
return res.render('error', { err });
}
res.status(500);
res.render('error', { err });
});
routes.use((req, res) => {
res.status(404);
res.render('error', {
err: '404 Not Found'
});
});
export default routes;
|
import fs from 'fs';
import gulp from 'gulp';
import onlyScripts from './util/scriptFilter';
const tasks = fs.readdirSync('./gulp/tasks/').filter(onlyScripts);
// Ensure process ends after all Gulp tasks are finished
gulp.on('stop', function () {
if ( !global.isWatching ) {
process.nextTick(function () {
process.exit(0);
});
}
});
tasks.forEach((task) => {
require('./tasks/' + task);
});
//////////////////////////////////
// import gulp from 'gulp';
// import browserSync from 'browser-sync';
// import nodemon from 'gulp-nodemon';
//
// // we'd need a slight delay to reload browsers
// // connected to browser-sync after restarting nodemon
// var BROWSER_SYNC_RELOAD_DELAY = 500;
//
// gulp.task('nodemon', function (cb) {
// var called = false;
// return nodemon({
//
// // nodemon our expressjs server
// script: 'appfart.js',
//
// // watch core server file(s) that require server restart on change
// watch: ['appfart.js']
// })
// .on('start', function onStart() {
// // ensure start only got called once
// if (!called) { cb(); }
// called = true;
// })
// .on('restart', function onRestart() {
// // reload connected browsers after a slight delay
// setTimeout(function reload() {
// browserSync.reload({
// stream: false
// });
// }, BROWSER_SYNC_RELOAD_DELAY);
// });
// });
//
// gulp.task('browser-sync', ['nodemon'], function () {
//
// // for more browser-sync config options: http://www.browsersync.io/docs/options/
// browserSync({
//
// // informs browser-sync to proxy our expressjs app which would run at the following location
// proxy: 'http://localhost:3000',
//
// // informs browser-sync to use the following port for the proxied app
// // notice that the default port is 3000, which would clash with our expressjs
// port: 4000,
//
// // open the proxied app in chrome
// browser: ['google-chrome']
// });
// });
//
// gulp.task('js', function () {
// return gulp.src('public/**/*.js')
// // do stuff to JavaScript files
// //.pipe(uglify())
// //.pipe(gulp.dest('...'));
// });
//
// gulp.task('css', function () {
// return gulp.src('public/**/*.css')
// .pipe(browserSync.reload({ stream: true }));
// })
//
// gulp.task('bs-reload', function () {
// browserSync.reload();
// });
//
// gulp.task('default', ['browser-sync'], function () {
// gulp.watch('public/**/*.js', ['js', browserSync.reload]);
// gulp.watch('public/**/*.css', ['css']);
// gulp.watch('public/**/*.html', ['bs-reload']);
// });
|
import React from 'react';
import PropTypes from 'prop-types';
import {TapAnimationContent} from '../TapAnimation/TapAnimation';
export class MZButton extends React.Component {
render() {
let className = 'mz-button ' + this.props.className;
return <button onClick={this.props.onClick} className={className} disabled={this.props.disabled}>
<TapAnimationContent>
{this.props.children}
</TapAnimationContent>
</button>
}
}
MZButton.propTypes = {
className: PropTypes.string,
onClick: PropTypes.func
};
MZButton.defaultProps = {
className: ''
}; |
// https://github.com/jacwright/date.format
define('date.format', function() {
Date.shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
Date.longMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Date.shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
Date.longDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// defining patterns
var replaceChars = {
// Day
d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
D: function() { return Date.shortDays[this.getDay()]; },
j: function() { return this.getDate(); },
l: function() { return Date.longDays[this.getDay()]; },
N: function() { return (this.getDay() == 0 ? 7 : this.getDay()); },
S: function() { var d = this.getDate();return (d % 10 == 1 && d != 11 ? 'st' : (d % 10 == 2 && d != 12 ? 'nd' : (d % 10 == 3 && d != 13 ? 'rd' : 'th'))); },
w: function() { return this.getDay(); },
z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
// Week
W: function() {
var target = new Date(this.valueOf());
var dayNr = (this.getDay() + 6) % 7;
target.setDate(target.getDate() - dayNr + 3);
var firstThursday = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - target) / 604800000);
},
// Month
F: function() { return Date.longMonths[this.getMonth()]; },
m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
M: function() { return Date.shortMonths[this.getMonth()]; },
n: function() { return this.getMonth() + 1; },
t: function() {
var year = this.getFullYear(), nextMonth = this.getMonth() + 1;
if (nextMonth === 12) {
year = year++;
nextMonth = 0;
}
return new Date(year, nextMonth, 0).getDate();
},
// Year
L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); }, // Fixed now
o: function() { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
Y: function() { return this.getFullYear(); },
y: function() { return ('' + this.getFullYear()).substr(2); },
// Time
a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
g: function() { return this.getHours() % 12 || 12; },
G: function() { return this.getHours(); },
h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?
'0' : '')) + m; },
// Timezone
e: function() { return /\((.*)\)/.exec(new Date().toString())[1]; },
I: function() {
var DST = null;
for (var i = 0; i < 12; ++i) {
var d = new Date(this.getFullYear(), i, 1);
var offset = d.getTimezoneOffset();
if (DST === null) DST = offset;
else if (offset < DST) { DST = offset; break; } else if (offset > DST) break;
}
return (this.getTimezoneOffset() == DST) | 0;
},
O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
T: function() { return this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); },
Z: function() { return -this.getTimezoneOffset() * 60; },
// Full Date/Time
c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
r: function() { return this.toString(); },
U: function() { return this.getTime() / 1000; }
};
// Simulates PHP's date function
Date.prototype.format = function(format) {
var date = this;
return format.replace(/(\\?)(.)/g, function(_, esc, chr) {
return (esc === '' && replaceChars[chr]) ? replaceChars[chr].call(date) : chr;
});
};
Date.setLocalization = function(monthNames, dayNames) {
if (monthNames) {
Date.longMonths = monthNames;
for (var i = 0; i < monthNames.length; i += 1) {
Date.shortMonths[i] = monthNames[i].substr(0, 3);
}
}
if (dayNames) {
Date.longDays = dayNames;
for (var i = 0; i < dayNames.length; i += 1) {
Date.shortDays[i] = dayNames[i].substr(0, 3);
}
}
};
}); |
const Context = require('../semantic/context.js');
class Program {
constructor(block) {
this.block = block;
}
toString() {
return `(Program ${this.block.toString()})`;
}
analyze(context = Context.INITIAL) {
return this.block.analyze(context);
}
}
module.exports = Program;
|
var gulp = require("gulp");
var uglify = require("gulp-uglify");
var concat = require("gulp-concat");
var lint = require("gulp-eslint");
var rename = require("gulp-rename");
var config = require("../config");
gulp.task("scripts", ["scripts:lint", "scripts:build"]);
gulp.task("scripts:lint", function() {
return gulp.src(config.scripts.src)
.pipe(lint())
.pipe(lint.format())
.pipe(lint.failAfterError());
});
gulp.task("scripts:build", function() {
return gulp.src(config.scripts.src)
.pipe(concat(config.scripts.name))
.pipe(gulp.dest(config.scripts.dest))
.pipe(rename({
suffix: ".min"
}))
.pipe(uglify())
.pipe(gulp.dest(config.scripts.dest))
});
gulp.task("scripts:libs", function() {
return gulp.src(config.libs.src)
.pipe(concat(config.libs.name))
.pipe(gulp.dest(config.libs.dest))
.pipe(rename({
suffix: ".min"
}))
.pipe(uglify())
.pipe(gulp.dest(config.dest))
});
|
import { factory } from '../../utils/factory';
var name = 'parser';
var dependencies = ['typed', 'Parser'];
export var createParser =
/* #__PURE__ */
factory(name, dependencies, function (_ref) {
var typed = _ref.typed,
Parser = _ref.Parser;
/**
* Create a parser. The function creates a new `math.Parser` object.
*
* Syntax:
*
* math.parser()
*
* Examples:
*
* const parser = new math.parser()
*
* // evaluate expressions
* const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5
* const b = parser.evaluate('sqrt(-4)') // 2i
* const c = parser.evaluate('2 inch in cm') // 5.08 cm
* const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476
*
* // define variables and functions
* parser.evaluate('x = 7 / 2') // 3.5
* parser.evaluate('x + 3') // 6.5
* parser.evaluate('function f(x, y) = x^y') // f(x, y)
* parser.evaluate('f(2, 3)') // 8
*
* // get and set variables and functions
* const x = parser.get('x') // 7
* const f = parser.get('f') // function
* const g = f(3, 2) // 9
* parser.set('h', 500)
* const i = parser.evaluate('h / 2') // 250
* parser.set('hello', function (name) {
* return 'hello, ' + name + '!'
* })
* parser.evaluate('hello("user")') // "hello, user!"
*
* // clear defined functions and variables
* parser.clear()
*
* See also:
*
* evaluate, compile, parse
*
* @return {Parser} Parser
*/
return typed(name, {
'': function _() {
return new Parser();
}
});
}); |
var updateRegion = {
region: function() {
// resets
$('region_label').hide();
$('region_select').hide();
// performs update of region
var country = this.getValue();
var label = RegionUpdaterCountries.get(this.getValue());
if (label) {
label = label.get("label");
if (label=="null") {
label=""
} else {
var regions = RegionUpdaterCountries.get(country).get("regions");
}
$('region_label').innerHTML = label;
$('region_label').show();
var return_choices = '<option>Choose a selection</option>';
var choices = regions.each(function(s) {
return_choices += '<option>' + s + '</option>';
});
$('region_select').innerHTML = return_choices;
$('region_select').show();
} else {
return false;
}
}
};
function RegionSelect() {
$('country_selector').observe('change', updateRegion.region);
};
Event.observe(window, 'load', RegionSelect); |
getTimelineData = function() {
var dxs = Session.get("patientDiagnoses");
var timelineData = [];
var pt = Session.get("patient");
if (!pt || !getPatientDob()) return;
var dobMs = getPatientDob().getTime();
var twoMosAgoMs = new Date().getTime() - 5.25949e9;
var earliestTime = dobMs;
if (dobMs < twoMosAgoMs) earliestTime = twoMosAgoMs;
var beginning = new Date().getTime();
var ending = earliestTime;
var monthFormat = d3.time.format("%-m/%y");
for (var di in dxs) {
var dx = dxs[di];
var start = earliestTime;
if (dx.startDate && dx.startDate.getTime() > earliestTime) {
start = dx.startDate.getTime();
}
if (start < beginning) beginning = start;
var end = new Date().getTime();
if (dx.endDate) {
end = dx.endDate.getTime();
}
if (end > ending) ending = end;
var label = dx.objName;
if (dx.startDate) label += " (started " + monthFormat(dx.startDate) + ")";
var obj = {
id: dx._id,
label: label,
times: [{
"starting_time": start,
"ending_time": end
}]
};
//console.log("getTimelineData object: " + JSON.stringify(obj));
timelineData.push(obj);
}
return {
data: timelineData,
beginning: beginning,
ending: ending
};
};
timelineChart = null;
Tracker.autorun(function () {
var timelineDataObj = getTimelineData();
//console.log("timeline Tracker.autorun: timelineChart?" + (! timelineChart) + "; timelineDataObj=" + JSON.stringify(timelineDataObj));
if (!timelineChart) return;
timelineChart.beginning(timelineDataObj.beginning);
timelineChart.ending(timelineDataObj.ending);
if (!timelineDataObj.data || !timelineDataObj.data.length) return;
d3.select("#timeline").selectAll("g").remove();
d3.select("#timeline").selectAll("svg").remove();
//d3.select("#timeline").remove();
timelineChart = d3.timeline()
.stack()
.tickFormat({
format: d3.time.format("%-m/%y"),
tickTime: d3.time.months,
tickInterval: 1,
tickSize: 5
})
.itemHeight(15)
.margin({left:100, top: 0, right: 0, bottom: 200})
.orient("bottom")
.width(1200);
console.log("PLOTTING: " + JSON.stringify(timelineDataObj));
var svg = d3.select("#timeline")
.append("svg")
.attr("width", "800")
.datum(timelineDataObj.data)
.call(timelineChart);
//d3.select("#timeline").selectAll("g").remove();
});
Template.timeline.rendered = function() {
timelineChart = d3.timeline()
.stack()
.tickFormat({
format: d3.time.format("%-m/%y"),
tickTime: d3.time.months,
tickInterval: 1,
tickSize: 5
})
.itemHeight(15)
.margin({left:100, top: 0, right: 0, bottom: 200})
.orient("bottom")
.width(1200);
};
//.rotateTicks(90)
//.showToday()
//.relativeTime() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.